From e7dee32fec5df48aeeb771a3334fec54c8c8b257 Mon Sep 17 00:00:00 2001 From: shilei <798989044@qq.com> Date: Mon, 29 Sep 2025 10:43:32 +0800 Subject: [PATCH] =?UTF-8?q?=E8=B6=85=E5=8F=91=E4=BA=8C=E5=BC=80=E4=BB=A3?= =?UTF-8?q?=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../WEB-INF/prop/hrm_fadada.properties | 24 + .../WEB-INF/prop/hrm_kqreport.properties | 59 + .../WEB-INF/prop/hrm_zhongkong.properties | 52 + 领悦二开new/interface/fdd/do.jsp | 323 ++ 领悦二开new/interface/lingyue/DemoTest.jsp | 226 + 领悦二开new/interface/lingyue/bb.jsp | 492 ++ 领悦二开new/interface/lingyue/cc.jsp | 410 ++ .../interface/lingyue/controle_leave.jsp | 44 + 领悦二开new/interface/lingyue/dd.jsp | 2578 +++++++++ 领悦二开new/interface/lingyue/do.jsp | 39 + .../interface/lingyue/initSubAndDeptCode.jsp | 103 + 领悦二开new/interface/lingyue/initZkkq.jsp | 254 + 领悦二开new/interface/lingyue/re_user.jsp | 332 ++ .../interface/lingyue/repairKqAttendInfos.jsp | 92 + 领悦二开new/interface/lingyue/syntest.jsp | 423 ++ .../api/hrm/service/HrmResourceAddService.java | 1100 ++++ .../api/hrm/service/HrmResourceBaseService.java | 3635 ++++++++++++ .../src/com/api/lingyue/SynOtherKqInfoApi.java | 16 + .../hrm/cmd/organization/AddDepartmentCmd.java | 231 + .../hrm/cmd/organization/AddSubCompanyCmd.java | 245 + .../hrm/cmd/organization/CancelDepartmentCmd.java | 175 + .../hrm/cmd/organization/CancelSubCompanyCmd.java | 165 + .../hrm/cmd/organization/DelDepartmentCmd.java | 182 + .../hrm/cmd/organization/DelSubCompanyCmd.java | 205 + .../hrm/cmd/organization/EditDepartmentCmd.java | 282 + .../hrm/cmd/organization/EditSubCompanyCmd.java | 223 + .../src/com/engine/kq/bean/KQBalanceOfLeave.java | 497 ++ .../src/com/engine/kq/bean/KQChildrenBean.java | 46 + .../src/com/engine/kq/bean/KqLockAttenda.java | 74 + .../com/engine/kq/biz/KQBalanceOfLeaveBiz.java | 4908 +++++++++++++++++ .../src/com/engine/kq/biz/KQChildrenComInfo.java | 81 + .../src/com/engine/kq/biz/KQFormatBiz.java | 339 ++ .../src/com/engine/kq/biz/KQFormatData.java | 1698 ++++++ .../src/com/engine/kq/biz/KQFormatShiftRule.java | 562 ++ .../src/com/engine/kq/biz/KQFormatSignData.java | 758 +++ .../src/com/engine/kq/biz/KQGroupBiz.java | 714 +++ .../src/com/engine/kq/biz/KQGroupComInfo.java | 466 ++ .../com/engine/kq/biz/KQGroupMemberComInfo.java | 981 ++++ .../src/com/engine/kq/biz/KQHolidaySetBiz.java | 499 ++ .../src/com/engine/kq/biz/KQLeaveRulesBiz.java | 1307 +++++ .../com/engine/kq/biz/KQLeaveRulesComInfo.java | 319 ++ .../engine/kq/biz/KQLeaveRulesDetailComInfo.java | 1329 +++++ .../src/com/engine/kq/biz/KQOvertimeRulesBiz.java | 1054 ++++ .../src/com/engine/kq/biz/KQReportBiz.java | 3653 ++++++++++++ .../com/engine/kq/biz/KQScheduleSignImport.java | 877 +++ .../engine/kq/biz/KQScheduleSignImportJob.java | 30 + .../engine/kq/biz/KQShiftManagementComInfo.java | 814 +++ .../com/engine/kq/biz/KQShiftScheduleComInfo.java | 179 + .../src/com/engine/kq/biz/KQWorkTime.java | 471 ++ .../biz/chain/cominfo/ShiftInfoCominfoBean.java | 521 ++ .../kq/biz/chain/shiftinfo/ShiftInfoBean.java | 804 +++ .../com/engine/kq/cmd/report/ExportExcelCmd.java | 954 ++++ .../com/engine/kq/cmd/report/GetKQReportCmd.java | 1004 ++++ .../engine/kq/entity/KQBalanceOfLeaveEntity.java | 234 + .../src/com/engine/kq/entity/KQGroupEntity.java | 235 + .../kq/entity/KQOvertimeRulesDetailEntity.java | 253 + .../engine/kq/entity/KQScheduleSignEntity.java | 107 + .../com/engine/kq/entity/KQShiftRuleEntity.java | 189 + .../src/com/engine/kq/entity/WorkTimeEntity.java | 220 + .../engine/kq/jucailin/genid/DefaultWorker.java | 52 + .../com/engine/kq/jucailin/genid/IdGenerator.java | 16 + .../com/engine/kq/jucailin/genid/SnowflakeId.java | 93 + .../src/com/engine/kq/jucailin/genid/Worker.java | 5 + .../com/engine/kq/jucailin/util/KQDateUtil.java | 19 + .../src/com/engine/kq/util/ExcelUtil.java | 829 +++ .../src/com/engine/kq/util/KQLockAttendaUtil.java | 1382 +++++ .../kq/util/lingyuewuye/ExpirationDateMethod.java | 44 + .../engine/kq/util/lingyuewuye/NianJiaUtil.java | 80 + .../src/com/engine/lingyue/util/KqUtil.java | 2253 ++++++++ .../engine/lingyue/web/SynOtherKqInfoAction.java | 165 + 领悦二开new/src/com/fage/DemoTest.java | 551 ++ 领悦二开new/src/com/lingyue/util/KqUtil.java | 812 +++ .../lingyue/action/SynAddUserAction.java | 120 + .../lingyue/action/SynDeleteUserAction.java | 74 + .../lingyue/action/SynTransUserAction.java | 142 + .../lingyue/job/SynDeleteUserToZkJob.java | 211 + .../interfaces/lingyue/job/SynNewUserToZkJob.java | 96 + .../interfaces/lingyue/job/SynOtherKqInfoJob.java | 129 + .../lingyue/job/SynSubcomDeptUserInfoJob.java | 94 + .../lingyue/job/SyncKqDataFromZKJob.java | 309 ++ .../weaver/interfaces/lingyue/util/HttpUtil.java | 528 ++ 81 files changed, 46091 insertions(+) create mode 100644 领悦二开new/WEB-INF/prop/hrm_fadada.properties create mode 100644 领悦二开new/WEB-INF/prop/hrm_kqreport.properties create mode 100644 领悦二开new/WEB-INF/prop/hrm_zhongkong.properties create mode 100644 领悦二开new/interface/fdd/do.jsp create mode 100644 领悦二开new/interface/lingyue/DemoTest.jsp create mode 100644 领悦二开new/interface/lingyue/bb.jsp create mode 100644 领悦二开new/interface/lingyue/cc.jsp create mode 100644 领悦二开new/interface/lingyue/controle_leave.jsp create mode 100644 领悦二开new/interface/lingyue/dd.jsp create mode 100644 领悦二开new/interface/lingyue/do.jsp create mode 100644 领悦二开new/interface/lingyue/initSubAndDeptCode.jsp create mode 100644 领悦二开new/interface/lingyue/initZkkq.jsp create mode 100644 领悦二开new/interface/lingyue/re_user.jsp create mode 100644 领悦二开new/interface/lingyue/repairKqAttendInfos.jsp create mode 100644 领悦二开new/interface/lingyue/syntest.jsp create mode 100644 领悦二开new/src/com/api/hrm/service/HrmResourceAddService.java create mode 100644 领悦二开new/src/com/api/hrm/service/HrmResourceBaseService.java create mode 100644 领悦二开new/src/com/api/lingyue/SynOtherKqInfoApi.java create mode 100644 领悦二开new/src/com/engine/hrm/cmd/organization/AddDepartmentCmd.java create mode 100644 领悦二开new/src/com/engine/hrm/cmd/organization/AddSubCompanyCmd.java create mode 100644 领悦二开new/src/com/engine/hrm/cmd/organization/CancelDepartmentCmd.java create mode 100644 领悦二开new/src/com/engine/hrm/cmd/organization/CancelSubCompanyCmd.java create mode 100644 领悦二开new/src/com/engine/hrm/cmd/organization/DelDepartmentCmd.java create mode 100644 领悦二开new/src/com/engine/hrm/cmd/organization/DelSubCompanyCmd.java create mode 100644 领悦二开new/src/com/engine/hrm/cmd/organization/EditDepartmentCmd.java create mode 100644 领悦二开new/src/com/engine/hrm/cmd/organization/EditSubCompanyCmd.java create mode 100644 领悦二开new/src/com/engine/kq/bean/KQBalanceOfLeave.java create mode 100644 领悦二开new/src/com/engine/kq/bean/KQChildrenBean.java create mode 100644 领悦二开new/src/com/engine/kq/bean/KqLockAttenda.java create mode 100644 领悦二开new/src/com/engine/kq/biz/KQBalanceOfLeaveBiz.java create mode 100644 领悦二开new/src/com/engine/kq/biz/KQChildrenComInfo.java create mode 100644 领悦二开new/src/com/engine/kq/biz/KQFormatBiz.java create mode 100644 领悦二开new/src/com/engine/kq/biz/KQFormatData.java create mode 100644 领悦二开new/src/com/engine/kq/biz/KQFormatShiftRule.java create mode 100644 领悦二开new/src/com/engine/kq/biz/KQFormatSignData.java create mode 100644 领悦二开new/src/com/engine/kq/biz/KQGroupBiz.java create mode 100644 领悦二开new/src/com/engine/kq/biz/KQGroupComInfo.java create mode 100644 领悦二开new/src/com/engine/kq/biz/KQGroupMemberComInfo.java create mode 100644 领悦二开new/src/com/engine/kq/biz/KQHolidaySetBiz.java create mode 100644 领悦二开new/src/com/engine/kq/biz/KQLeaveRulesBiz.java create mode 100644 领悦二开new/src/com/engine/kq/biz/KQLeaveRulesComInfo.java create mode 100644 领悦二开new/src/com/engine/kq/biz/KQLeaveRulesDetailComInfo.java create mode 100644 领悦二开new/src/com/engine/kq/biz/KQOvertimeRulesBiz.java create mode 100644 领悦二开new/src/com/engine/kq/biz/KQReportBiz.java create mode 100644 领悦二开new/src/com/engine/kq/biz/KQScheduleSignImport.java create mode 100644 领悦二开new/src/com/engine/kq/biz/KQScheduleSignImportJob.java create mode 100644 领悦二开new/src/com/engine/kq/biz/KQShiftManagementComInfo.java create mode 100644 领悦二开new/src/com/engine/kq/biz/KQShiftScheduleComInfo.java create mode 100644 领悦二开new/src/com/engine/kq/biz/KQWorkTime.java create mode 100644 领悦二开new/src/com/engine/kq/biz/chain/cominfo/ShiftInfoCominfoBean.java create mode 100644 领悦二开new/src/com/engine/kq/biz/chain/shiftinfo/ShiftInfoBean.java create mode 100644 领悦二开new/src/com/engine/kq/cmd/report/ExportExcelCmd.java create mode 100644 领悦二开new/src/com/engine/kq/cmd/report/GetKQReportCmd.java create mode 100644 领悦二开new/src/com/engine/kq/entity/KQBalanceOfLeaveEntity.java create mode 100644 领悦二开new/src/com/engine/kq/entity/KQGroupEntity.java create mode 100644 领悦二开new/src/com/engine/kq/entity/KQOvertimeRulesDetailEntity.java create mode 100644 领悦二开new/src/com/engine/kq/entity/KQScheduleSignEntity.java create mode 100644 领悦二开new/src/com/engine/kq/entity/KQShiftRuleEntity.java create mode 100644 领悦二开new/src/com/engine/kq/entity/WorkTimeEntity.java create mode 100644 领悦二开new/src/com/engine/kq/jucailin/genid/DefaultWorker.java create mode 100644 领悦二开new/src/com/engine/kq/jucailin/genid/IdGenerator.java create mode 100644 领悦二开new/src/com/engine/kq/jucailin/genid/SnowflakeId.java create mode 100644 领悦二开new/src/com/engine/kq/jucailin/genid/Worker.java create mode 100644 领悦二开new/src/com/engine/kq/jucailin/util/KQDateUtil.java create mode 100644 领悦二开new/src/com/engine/kq/util/ExcelUtil.java create mode 100644 领悦二开new/src/com/engine/kq/util/KQLockAttendaUtil.java create mode 100644 领悦二开new/src/com/engine/kq/util/lingyuewuye/ExpirationDateMethod.java create mode 100644 领悦二开new/src/com/engine/kq/util/lingyuewuye/NianJiaUtil.java create mode 100644 领悦二开new/src/com/engine/lingyue/util/KqUtil.java create mode 100644 领悦二开new/src/com/engine/lingyue/web/SynOtherKqInfoAction.java create mode 100644 领悦二开new/src/com/fage/DemoTest.java create mode 100644 领悦二开new/src/com/lingyue/util/KqUtil.java create mode 100644 领悦二开new/src/weaver/interfaces/lingyue/action/SynAddUserAction.java create mode 100644 领悦二开new/src/weaver/interfaces/lingyue/action/SynDeleteUserAction.java create mode 100644 领悦二开new/src/weaver/interfaces/lingyue/action/SynTransUserAction.java create mode 100644 领悦二开new/src/weaver/interfaces/lingyue/job/SynDeleteUserToZkJob.java create mode 100644 领悦二开new/src/weaver/interfaces/lingyue/job/SynNewUserToZkJob.java create mode 100644 领悦二开new/src/weaver/interfaces/lingyue/job/SynOtherKqInfoJob.java create mode 100644 领悦二开new/src/weaver/interfaces/lingyue/job/SynSubcomDeptUserInfoJob.java create mode 100644 领悦二开new/src/weaver/interfaces/lingyue/job/SyncKqDataFromZKJob.java create mode 100644 领悦二开new/src/weaver/interfaces/lingyue/util/HttpUtil.java diff --git a/领悦二开new/WEB-INF/prop/hrm_fadada.properties b/领悦二开new/WEB-INF/prop/hrm_fadada.properties new file mode 100644 index 0000000..c23159a --- /dev/null +++ b/领悦二开new/WEB-INF/prop/hrm_fadada.properties @@ -0,0 +1,24 @@ +# ӿurl +fadada_url=http://172.18.3.51:8072 + +# Խ appid +fadada_appid=100003 + +# Խ secret +fadada_secret=Sq3xcgWquEA56XU3hY4AGKsj + +# + +# + +# + +# + +# + +# + +# + +# \ No newline at end of file diff --git a/领悦二开new/WEB-INF/prop/hrm_kqreport.properties b/领悦二开new/WEB-INF/prop/hrm_kqreport.properties new file mode 100644 index 0000000..4515f60 --- /dev/null +++ b/领悦二开new/WEB-INF/prop/hrm_kqreport.properties @@ -0,0 +1,59 @@ +# \u75C5\u5047 7 \u5E74\u5047 2 \u4EA7\u5047 8 \u966A\u4EA7\u5047 9 \u5A5A\u5047 10 \u4E27\u5047 11 \u5DE5\u4F24\u5047 13 \u63A2\u4EB2\u5047 14 \u8C03\u4F11\u5047 15 +halfday_leave_ids=7,2,9,10,11,14,15 + +# \u54FA\u4E73\u5047 \u5047\u671F\u7C7B\u578Bid 12 +breastfeed_leave_id=12 + +# \u4E8B\u5047 \u5047\u671F\u7C7B\u578Bid +leaveabsencetype=6 + +# \u75C5\u5047 \u5047\u671F\u7C7B\u578Bid +sickleavetype=7 + +# \u5E74\u5047 \u5047\u671F\u7C7B\u578Bid +annualleavetype=2 + +# \u966A\u4EA7\u5047 \u5047\u671F\u7C7B\u578Bid +paternityleavetype=9 + +# \u5A5A\u5047 \u5047\u671F\u7C7B\u578Bid +marriageleavetype=10 + +# \u4E27\u5047 \u5047\u671F\u7C7B\u578Bid +bereavementleavetype=11 + +# \u63A2\u4EB2\u5047 \u5047\u671F\u7C7B\u578Bid +homeleavetype=14 + +# \u8C03\u4F11\u5047 \u5047\u671F\u7C7B\u578Bid +compensatory_leave_id=15 + +# \u4EA7\u5047 \u5047\u671F\u7C7B\u578Bid +maternity_leave_id=8 + +# \u5DE5\u4F24\u5047 \u5047\u671F\u7C7B\u578Bid +injuryLeave_leave_id=13 + +# \u7247\u533A \u4EBA\u5458\u5361\u7247\u81EA\u5B9A\u4E49\u5B57\u6BB5 +area_fieldid=field137 + +# \u5C97\u4F4D\u540D\u79F0 \u4EBA\u5458\u5361\u7247\u81EA\u5B9A\u4E49\u5B57\u6BB5 +position_fieldid=field128 + +# \u4F11\u606F\u73ED\u6B21 id +rest_serial_id=191 + +rest2_serial_id=2 + +# \u96C6\u56E2\u603B\u90E8\u884C\u653F\u73ED\u6B21 \u8003\u52E4\u7EC4id +the_top_groupid=209 + +# \u8F6C\u6B63\u65E5\u671F \u5DE5\u4F5C\u4FE1\u606F \u81EA\u5B9A\u4E49\u5B57\u6BB5id +zzrq_fieldid=field14 + +# \u79BB\u804C\u65E5\u671F \u5DE5\u4F5C\u4FE1\u606F \u81EA\u5B9A\u4E49\u5B57\u6BB5id +lzrq_fieldid=field49 + + + + diff --git a/领悦二开new/WEB-INF/prop/hrm_zhongkong.properties b/领悦二开new/WEB-INF/prop/hrm_zhongkong.properties new file mode 100644 index 0000000..bf3ef63 --- /dev/null +++ b/领悦二开new/WEB-INF/prop/hrm_zhongkong.properties @@ -0,0 +1,52 @@ +# \uFFFD\uFFFD\u0221\uFFFD\uFFFD\uFFFD\u0432\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u03E2 \uFFFD\u04FF\uFFFDurl +get_all_dept_url=http://222.212.88.118:8989/api/v2/department/get/ + +# \uFFFD\uFFFD\u0221\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u0531\uFFFD\uFFFD\u03E2 \uFFFD\u04FF\uFFFDurl +get_all_user_url=http://222.212.88.118:8989/api/v2/employee/get/ + +# \uFFFD\u04FF\uFFFD\u01BE\u05A4 key +key=56b2gxturpnypuumxq4bpwhrj1_82cpu0nqwrslzkgzp + +# \uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u00B2\uFFFD\uFFFD\uFFFD \uFFFD\u04FF\uFFFDurl +add_update_dept_url=http://222.212.88.118:8989/api/v2/department/update/ + +# \u027E\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD \uFFFD\u04FF\uFFFDurl +delete_dept_url=http://222.212.88.118:8989/api/v2/department/delete/ + +# \uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u0531 \uFFFD\u04FF\uFFFDurl +add_update_user_url=http://222.212.88.118:8989/api/v2/employee/update/ + +# \uFFFD\uFFFD\u0531\uFFFD\uFFFD\u05B0 \uFFFD\u04FF\uFFFDurl +leave_user_url=http://222.212.88.118:8989/api/v2/employee/leave/ + +# \u027E\uFFFD\uFFFD\uFFFD\uFFFD\u0531 \uFFFD\u04FF\uFFFDurl +#delete_user_url=http://222.212.88.118:8989/api/v2/employee/delete/ + +# \uFFFD\uFFFD\u0221\uFFFD\uFFFD\uFFFD\u06BC\uFFFD\u00BC \uFFFD\u04FF\uFFFDurl +get_kqinfo_url=http://222.212.88.118:8989/api/v2/transaction/get/ + +# \uFFFD\u043F\u063F\uFFFD\uFFFD\u06BB\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD \u0123\uFFFD\uFFFDid +zkkqjkqsj_formmodeid=38 + +# \uFFFD\uFFFD\uFFFD\u06BF\uFFFD\uFFFD\uFFFD \uFFFD\u0536\uFFFD\uFFFD\uFFFD\uFFFD\u05B6\uFFFDid +kq_fieldid=field38 + +# \uFFFD\uFFFD\uFFFD\uFFFD +kq_number=2000 + +# \uFFFD\uFFFD\u0531\uFFFD\uFFFD\uFFFD\uFFFD\u05B0\uFFFD\uFFFD\u03E2 \uFFFD\uFFFD\uFFFD\u0331\uFFFD\uFFFD\uFFFD +newuser_table=formtable_main_118 + +# \uFFFD\uFFFD\u05B0\u0237\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD \uFFFD\uFFFD\uFFFD\uFFFD +deleteuser_table=formtable_main_72 + +# HR\u036C\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u043F\u063F\uFFFD\uFFFD\u06BB\uFFFD\uFFFD\uFFFD\u00BC\uFFFD\uFFFD \u0123\uFFFD\uFFFDid +hrtozkkqj_formmodeid=103 + +lzyy_fieldid=8900 + +sfhl_fieldid=field150 + +restore_user_url=http://222.212.88.118:8989/api/v2/employee/restore/ + +zksfhf_fieldid=field151 \ No newline at end of file diff --git a/领悦二开new/interface/fdd/do.jsp b/领悦二开new/interface/fdd/do.jsp new file mode 100644 index 0000000..a857a15 --- /dev/null +++ b/领悦二开new/interface/fdd/do.jsp @@ -0,0 +1,323 @@ +<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> +<%@page import="weaver.general.Util"%> +<%@ page import="weaver.conn.RecordSet" %> +<%@ page import="weaver.general.TimeUtil" %> +<%@ page import="com.alibaba.fastjson.JSONObject" %> +<%@ page import="java.util.*" %> +<%@ page import="com.alibaba.fastjson.JSONArray" %> +<%@ page import="java.text.SimpleDateFormat" %> +<%@ page import="java.text.ParseException" %> +<%@ page import="org.apache.http.client.methods.CloseableHttpResponse" %> +<%@ page import="org.apache.http.impl.client.CloseableHttpClient" %> +<%@ page import="org.apache.http.impl.client.HttpClients" %> +<%@ page import="org.apache.http.client.methods.HttpPost" %> +<%@ page import="org.apache.http.entity.StringEntity" %> +<%@ page import="org.apache.http.HttpEntity" %> +<%@ page import="org.apache.http.util.EntityUtils" %> +<%@ page import="java.io.IOException" %> +<%@ page import="com.fdd.utils.HttpUtil" %> +<%@ page import="com.fdd.dto.BaseDTO" %> +<%@ page import="com.fdd.utils.SignTypeEnum" %> +<%@ page import="com.fdd.utils.SignUtil" %> +<%@ page import="java.sql.Timestamp" %> +<%@ page import="java.text.DateFormat" %> +<%@ page import="weaver.file.Prop" %> +<%@ page import="java.net.URLEncoder" %> +<%@ page import="java.io.UnsupportedEncodingException" %> +<%@ page import="sun.misc.BASE64Encoder" %> +<%@ page import="com.alibaba.fastjson.JSON" %> +<%@ page import="java.security.MessageDigest" %> +<%@ page import="java.security.NoSuchAlgorithmException" %> + +<% + int sum = 0; + + String type = Util.null2String(request.getParameter("type")); + String account = Util.null2String(request.getParameter("account")); + String adminAccountId = ""; + String companyName = ""; + + String data = registerAccount(type,account,adminAccountId,companyName); + + sum++; + +%> + +<%! + RecordSet rst = new RecordSet(); + + /** + * 项目部署后向项目经理申请对接Api的APPID + */ + private String APPID = rst.getPropValue("hrm_fadada", "fadada_appid"); + /** + * 项目部署后向项目经理申请对接Api的APPSECRET + */ + private String APPSECRET = rst.getPropValue("hrm_fadada", "fadada_secret"); + /** + * 项目部署后,对外访问的域名 + */ + private String FDDHOST = rst.getPropValue("hrm_fadada", "fadada_url"); + + /** + * 注册账号 + */ + public String registerAccount(String type, String account, String adminAccountId, String companyName) { + Map map = new HashMap();// 业务参数都放在这里 + map.put("type", type); + map.put("account", account); + map.put("adminAccountId", adminAccountId); + map.put("companyName", companyName); + String rep = request("/account/register", map, "POST"); + rst.writeLog("[ApiUtil.registerAccount]:注册账号接口返回参数:" + rep); + JSONObject jsonObject = JSONObject.parseObject(rep); + String data = jsonObject.getString("data"); + return data; + } + + /** + * 实名认证状态查询 + * @param type 类型 1 为个人,2为企业。 + */ + public String personCertificationStatus(String type, String customerId) { + Map map = new HashMap();// 业务参数都放在这里 + map.put("customerId", customerId); + String rep = ""; + if ("1".equals(type)) { + rep = request("/certification/person/get-status", map, "POST"); + } else if ("2".equals(type)) { + + rep = request("/certification/company/get-status", map, "POST"); + } + rst.writeLog("[ApiUtil.personCertificationStatus]实名认证状态查询接口返回参数:" + rep); + return rep; + } + + /** + * @param url + * @param map + */ + public String request(String url, Map map, String type) { + String response = ""; + try { + rst.writeLog("[ApiUtil.request]:接口传入业务参数:" + map.toString()); + Map params = getParams(map); + rst.writeLog("[ApiUtil.request]:接口传入共通参数:" + params); + if ("POST".equals(type)) { + response = HttpUtil.postUrlAsJson(FDDHOST + url, params, "UTF-8"); + } else if ("GET".equals(type)) { + response = getGetUrl(FDDHOST + url, params, "UTF-8"); + } + } catch (Exception e) { + rst.writeLog("[ApiUtil.request]:错误信息:" + e.getMessage()); + } + return response; + } + + public Map getParams(Map map) { + Map params = null; + try { + String timestamp = getTimeStamp();// 获取时间戳 + BaseDTO baseDTO = new BaseDTO(); + baseDTO.setSignType(SignTypeEnum.SHA256.getValue()); + baseDTO.setTimestamp(timestamp); + baseDTO.setAppId(APPID); + baseDTO.setAppSecret(APPSECRET); + String bizContent = bizContent(map);// 把所有业务参数 + String sign = getSign(baseDTO.getAppId(), baseDTO.getAppSecret(), baseDTO.getSignType(), + baseDTO.getTimestamp(), bizContent);// 生成签名 + params = new HashMap(8); + params.put("appId", APPID); + params.put("signType", SignTypeEnum.SHA256.getValue()); + params.put("sign", sign); + params.put("timestamp", timestamp); + params.put("bizContent", bizContent); + } catch (Exception e) { + rst.writeLog("[ApiUtil.getParams]:错误信息:" + e.getMessage()); + } + return params; + } + + /** + * 根据数据获取签名 + * + * @param appId + * @param appKey + * @param signType + * @param timestamp + * @param bizContent + * @return java.lang.String + * @author zhangq2@fadada.com + * @date 2019/1/2 + */ + public static String getSign(String appId, String appKey, String signType, String timestamp, String bizContent) + throws Exception { + // 可以优化 + Map map = new HashMap(10); + map.put("appId", appId); + map.put("signType", signType); + map.put("timestamp", timestamp); + map.put("bizContent", bizContent); + + List list = new ArrayList(map.keySet()); + Collections.sort(list); + StringBuilder builder = new StringBuilder(); + for (String key : list) { + Object value = map.get(key); + if (null != value && !"".equals(value)) { + builder.append(key).append("=").append(value).append("&"); + } + } + String content = builder.substring(0, builder.length() - 1); + String sign = ""; + switch (SignTypeEnum.valueOf(signType)) { + case SHA256: + String sha256 = CryptTool.sha256(CryptTool.sha256(content) + appKey); + sign = CryptTool.encryptBASE64(sha256.getBytes("UTF-8")); + break; + case SHA1: + String sha1 = CryptTool.sha1(CryptTool.sha1(content) + appKey); + sign = CryptTool.encryptBASE64(sha1.getBytes("UTF-8")); + break; + case MD5: + String md5 = CryptTool.md5(CryptTool.md5(content) + appKey); + sign = CryptTool.encryptBASE64(md5.getBytes("UTF-8")); + break; + default: + break; + } + return sign.trim(); + } + + /** + * 获取时间戳 + * + * @return + */ + public String getTimeStamp() { + Timestamp ts = new Timestamp(System.currentTimeMillis()); + DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + return sdf.format(ts); + } + + /** + * 获取手动签署地址 + */ + public String getGetUrl(String url, Map params, String encode) { + StringBuffer buf = new StringBuffer(url); + if (params != null) { + // 地址增加?或者& + String flag = (url.indexOf('?') == -1) ? "?" : "&"; + // 添加参数 + for (String name : params.keySet()) { + buf.append(flag); + buf.append(name); + buf.append("="); + try { + String param = params.get(name).toString(); + if (param == null) { + param = ""; + } + buf.append(URLEncoder.encode(param, encode)); + } catch (UnsupportedEncodingException e) { + } + flag = "&"; + } + } + return buf.toString(); + } + + /** + * 将字符串转为base-64编码 + * @param s + * @return + */ + public static String toBase64(String s) { + if (s == null) { + return s; + } + try { + BASE64Encoder base64Encoder = new BASE64Encoder(); + return base64Encoder.encode(s.getBytes("UTF-8")); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + return s; + } + } + + /** + * 利用java原生的摘要实现SHA256加密 + * @param str 加密后的报文 + * @return + */ + public static String String2SHA256StrJava(String str){ + MessageDigest messageDigest; + String encodeStr = ""; + try { + messageDigest = MessageDigest.getInstance("SHA-256"); + messageDigest.update(str.getBytes("UTF-8")); + encodeStr = byte2Hex(messageDigest.digest()); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + return encodeStr; + } + + /** + * 将byte转为16进制 + * @param bytes + * @return + */ + private static String byte2Hex(byte[] bytes){ + StringBuffer stringBuffer = new StringBuffer(); + String temp = null; + for (int i=0;i + + + + + + +

Congratulation Mode 666666 !

+ +

sum <%=sum%>

+ +

data <%=data%>

+ + \ No newline at end of file diff --git a/领悦二开new/interface/lingyue/DemoTest.jsp b/领悦二开new/interface/lingyue/DemoTest.jsp new file mode 100644 index 0000000..f06857e --- /dev/null +++ b/领悦二开new/interface/lingyue/DemoTest.jsp @@ -0,0 +1,226 @@ +<%@ page import="weaver.general.Util" %> +<%@ page import="java.math.BigDecimal" %> +<%@ page contentType="text/html; charset=UTF-8" %> + + +<% + int nodeid = Util.getIntValue(request.getParameter("nodeid"));//流程的节点id + bb.writeLog("========== 加班申请流程 nodeid ============"+ nodeid); + String sql = "select isstart from workflow_nodebase where id = " + nodeid; + rs.execute(sql); + rs.next(); + int isstart = Util.getIntValue(rs.getString("isstart"));//判断是否是流程创建节点 1:是 0:否 +%> + \ No newline at end of file diff --git a/领悦二开new/interface/lingyue/bb.jsp b/领悦二开new/interface/lingyue/bb.jsp new file mode 100644 index 0000000..45e7658 --- /dev/null +++ b/领悦二开new/interface/lingyue/bb.jsp @@ -0,0 +1,492 @@ +<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> +<%@page import="weaver.general.Util"%> +<%@ page import="weaver.conn.RecordSet" %> +<%@ page import="weaver.general.TimeUtil" %> +<%@ page import="com.alibaba.fastjson.JSONObject" %> +<%@ page import="java.util.*" %> +<%@ page import="com.alibaba.fastjson.JSONArray" %> +<%@ page import="org.apache.http.client.methods.CloseableHttpResponse" %> +<%@ page import="org.apache.http.impl.client.CloseableHttpClient" %> +<%@ page import="org.apache.http.impl.client.HttpClients" %> +<%@ page import="org.apache.http.client.methods.HttpPost" %> +<%@ page import="org.apache.http.entity.StringEntity" %> +<%@ page import="org.apache.http.HttpEntity" %> +<%@ page import="org.apache.http.util.EntityUtils" %> +<%@ page import="java.io.IOException" %> +<%@ page import="com.google.common.collect.Maps" %> +<%@ page import="com.google.common.collect.Lists" %> +<%@ page import="weaver.interfaces.lingyue.util.HttpUtil" %> +<%@ page import="com.engine.kq.biz.KQFormatBiz" %> +<%@ page import="com.engine.kq.timer.KQTaskBean" %> +<%@ page import="com.engine.kq.wfset.util.SplitActionUtil" %> +<%@ page import="com.engine.kq.timer.KQQueue" %> +<%@ page import="weaver.formmode.setup.ModeRightInfo" %> + +<% + int sum = 0; + + String startdate = request.getParameter("startdate"); + String starttime = request.getParameter("starttime"); + String enddate = request.getParameter("enddate"); + String endtime = request.getParameter("endtime"); + + String startTime = startdate + " "+ starttime; + String endTime = enddate + " "+ endtime; + + List lsFormatData = new ArrayList<>(); + JSONObject json_main = new JSONObject(); + List> lsParams = new ArrayList<>(); + try { + int index = 1; + json_main.put("starttime", startTime); + json_main.put("endtime", endTime); + json_main.put("number", 2000); + + SynKqData(lsFormatData,index,json_main); + + Map> overtimeMap = Maps.newHashMap(); + List overtimeList = Lists.newArrayList(); + List formatParams = null; + List> lsFormatParams = new ArrayList<>(); + List delParams = null; + List> lsDelParams = new ArrayList<>(); + + for(int i=0;lsFormatData!=null&&i(); + String[] formatData = Util.splitString(lsFormatData.get(i),"|"); + String date_1 = HttpUtil.addDateDay(formatData[1],-1); + formatParams.add(formatData[0]); + formatParams.add(date_1); + lsFormatParams.add(formatParams); + + formatParams = new ArrayList<>(); + formatParams.add(formatData[0]); + formatParams.add(formatData[1]); + lsFormatParams.add(formatParams); + + delParams = new ArrayList<>(); + delParams.add(formatData[0]); + delParams.add(formatData[1]); + delParams.add(formatData[2]); + lsDelParams.add(delParams); + + String resourceId = formatData[0]; + String kqdate = formatData[1]; + if(overtimeMap.containsKey(resourceId)){ + List tmp_overtimeList = overtimeMap.get(resourceId); + if(!tmp_overtimeList.contains(kqdate)){ + tmp_overtimeList.add(kqdate); + } + }else{ + if(!overtimeList.contains(kqdate)){ + overtimeList.add(kqdate); + } + overtimeMap.put(resourceId, overtimeList); + } + } + + new KQFormatBiz().format(lsFormatParams); + //处理加班生成 + List tasks = new ArrayList<>(); + for(Map.Entry> mme: overtimeMap.entrySet()){ + String resid = mme.getKey(); + List overList = mme.getValue(); + for(String date : overList){ + SplitActionUtil.pushOverTimeTasks(date,date,resid,tasks); + } + } + if(!tasks.isEmpty()){ + KQQueue.writeTasks(tasks); + } + + }catch (Exception e){ + e.printStackTrace(); + } + + int num = lsFormatData.size(); + int num2 = lsParams.size(); + + sum++; + +%> + +<%! + public void SynKqData(List lsFormatData, int index, JSONObject json_main){ + RecordSet rs = new RecordSet(); + RecordSet rs1 = new RecordSet(); + RecordSet rs2 = new RecordSet(); + RecordSet rst = new RecordSet(); + String currentdate = TimeUtil.getCurrentDateString(); + String currenttime = TimeUtil.getOnlyCurrentTimeString(); + String currentdatetime = currentdate + " " + currenttime; + + Map headers = new HashMap<>(); + String key = rs.getPropValue("hrm_zhongkong","key"); + String get_kqinfo_url = rs.getPropValue("hrm_zhongkong","get_kqinfo_url"); + int zkkqjkqsj_formmodeid = Util.getIntValue(rs.getPropValue("hrm_zhongkong","zkkqjkqsj_formmodeid")); + int creater = 1; + + boolean bool = false; + + get_kqinfo_url = get_kqinfo_url + "?key=" + key; + List> lsParams = new ArrayList<>(); + List idList = new ArrayList<>(); + json_main.put("id",index); + + rs.writeLog("============= SynKqData json_main =============== "+ json_main); + + String result = httpPostKqData(get_kqinfo_url,headers,json_main.toString(),"utf-8"); + if(result != null && !"".equals(result)) { + JSONObject json1 = JSONObject.parseObject(result); + String items = json1.getString("items").toString(); + JSONArray data_jsonArray = JSONArray.parseArray(items); + rs.writeLog("============= SynKqData data_jsonArray =============== "+ data_jsonArray); + if (data_jsonArray.size() > 1) { + bool = true; + for (int i = 0; i < data_jsonArray.size(); i++) { + JSONObject jsonObject = JSONObject.parseObject(data_jsonArray.get(i).toString()); + + String lsh = ""; + String pin = ""; + String ename = ""; + String deptnumber = ""; + String deptname = ""; + String checktime = ""; + String sn = ""; + String alias = ""; + String verify = ""; + String stateno = ""; + String state = ""; + + if (jsonObject.containsKey("id")) { + lsh = jsonObject.get("id").toString(); + idList.add(lsh); + } + if (jsonObject.containsKey("pin")) { + pin = jsonObject.get("pin").toString(); + } + if (jsonObject.containsKey("ename")) { + ename = jsonObject.get("ename").toString(); + } + if (jsonObject.containsKey("deptnumber")) { + deptnumber = jsonObject.get("deptnumber").toString(); + } + if (jsonObject.containsKey("deptname")) { + deptname = jsonObject.get("deptname").toString(); + } + if (jsonObject.containsKey("checktime")) { + checktime = jsonObject.get("checktime").toString(); + } + if (jsonObject.containsKey("sn")) { + sn = jsonObject.get("sn").toString(); + } + if (jsonObject.containsKey("alias")) { + alias = jsonObject.get("alias").toString(); + } + if (jsonObject.containsKey("verify")) { + verify = jsonObject.get("verify").toString(); + } + if (jsonObject.containsKey("stateno")) { + stateno = jsonObject.get("stateno").toString(); + } + if (jsonObject.containsKey("state")) { + state = jsonObject.get("state").toString(); + } + + String userid = getUserIdByPin(pin); + rs.writeLog("====================== userid =============== "+ userid); + if(userid != null && !"".equals(userid)){ + String signDate = ""; + String signTime = ""; + int usertype = 1; + int signType = 1; + int isincom = 1; + String signfrom = "OutDataSourceSyn"; + String addr = ""; + int isimport = 1; + + signDate = checktime.substring(0, 10); + signTime = checktime.substring(11, 19); + signType = 1; + + List params = new ArrayList<>(); + params.add(userid); + params.add(usertype); + params.add(signType); + params.add(signDate); + params.add(signTime); + params.add(""); + params.add(isincom); + params.add(isimport); + params.add(signfrom); + params.add(""); + params.add(""); + params.add(addr); + params.add("中控考勤机数据同步"); + lsParams.add(params); + String formatData = userid + "|" + signDate + "|" + signTime; + if (!lsFormatData.contains(formatData)) { + lsFormatData.add(formatData); + } + + boolean isdelte = deleteByInfo(userid,signDate,signTime); + boolean isok = InsertByInfo(userid,usertype,signDate,signTime,"",isincom,isimport,signfrom,"","",addr,"中控考勤机数据同步"); + rs.writeLog("isdelte:" + isdelte+" isok:"+isok); + + rs1.executeQuery("select * from uf_zkkqjkqsj where lsh = ?",lsh); + //不存在 + if(!rs1.next()) { + int billid = -1; + String uuid = UUID.randomUUID().toString(); + boolean exeRes = rst.executeUpdate("insert into uf_zkkqjkqsj(lsh,verify,checktime,sn,alias,pin,ename,deptnumber,deptname,stateno,state,modedatacreater,modedatacreatedate,modedatacreatetime,formmodeid,modeuuid) values(?,?,?,?,?,?,?,?," + + "?,?,?,?,?,?,?,?)", + new Object[]{lsh, verify, checktime, sn, alias, pin, ename, deptnumber, deptname, stateno, state, creater, currentdate, currenttime, zkkqjkqsj_formmodeid, uuid}); + if (exeRes) { + //重构权限 + rs2.executeQuery(" select id from uf_zkkqjkqsj where modeuuid=? ", new Object[]{uuid}); + rs2.next(); + billid = rs2.getInt("id"); + ModeRightInfo moderight = new ModeRightInfo(); + moderight.editModeDataShare(creater, zkkqjkqsj_formmodeid, billid); + } + } + } + } + }else{ + JSONObject jsonObject = JSONObject.parseObject(data_jsonArray.get(0).toString()); + + String lsh = ""; + String pin = ""; + String ename = ""; + String deptnumber = ""; + String deptname = ""; + String checktime = ""; + String sn = ""; + String alias = ""; + String verify = ""; + String stateno = ""; + String state = ""; + + if (jsonObject.containsKey("id")) { + lsh = jsonObject.get("id").toString(); + idList.add(lsh); + } + if (jsonObject.containsKey("pin")) { + pin = jsonObject.get("pin").toString(); + } + if (jsonObject.containsKey("ename")) { + ename = jsonObject.get("ename").toString(); + } + if (jsonObject.containsKey("deptnumber")) { + deptnumber = jsonObject.get("deptnumber").toString(); + } + if (jsonObject.containsKey("deptname")) { + deptname = jsonObject.get("deptname").toString(); + } + if (jsonObject.containsKey("checktime")) { + checktime = jsonObject.get("checktime").toString(); + } + if (jsonObject.containsKey("sn")) { + sn = jsonObject.get("sn").toString(); + } + if (jsonObject.containsKey("alias")) { + alias = jsonObject.get("alias").toString(); + } + if (jsonObject.containsKey("verify")) { + verify = jsonObject.get("verify").toString(); + } + if (jsonObject.containsKey("stateno")) { + stateno = jsonObject.get("stateno").toString(); + } + if (jsonObject.containsKey("state")) { + state = jsonObject.get("state").toString(); + } + + String userid = getUserIdByPin(pin); + if(userid != null && !"".equals(userid)){ + String signDate = ""; + String signTime = ""; + int usertype = 1; + int signType = 1; + int isincom = 1; + String signfrom = "OutDataSourceSyn"; + String addr = ""; + int isimport = 1; + + signDate = checktime.substring(0, 10); + signTime = checktime.substring(11, 19); + signType = 1; + + List params = new ArrayList<>(); + params.add(userid); + params.add(usertype); + params.add(signType); + params.add(signDate); + params.add(signTime); + params.add(""); + params.add(isincom); + params.add(isimport); + params.add(signfrom); + params.add(""); + params.add(""); + params.add(addr); + params.add("中控考勤机数据同步"); + lsParams.add(params); + String formatData = userid + "|" + signDate + "|" + signTime; + if (!lsFormatData.contains(formatData)) { + lsFormatData.add(formatData); + } + + boolean isdelte = deleteByInfo(userid,signDate,signTime); + boolean isok = InsertByInfo(userid,usertype,signDate,signTime,"",isincom,isimport,signfrom,"","",addr,"中控考勤机数据同步"); + rs.writeLog("isdelte:" + isdelte+"isok:"+isok); + + rs1.executeQuery("select * from uf_zkkqjkqsj where lsh = ?",lsh); + //不存在 + if(!rs1.next()) { + int billid = -1; + String uuid = UUID.randomUUID().toString(); + boolean exeRes = rst.executeUpdate("insert into uf_zkkqjkqsj(lsh,verify,checktime,sn,alias,pin,ename,deptnumber,deptname,stateno,state,modedatacreater,modedatacreatedate,modedatacreatetime,formmodeid,modeuuid) values(?,?,?,?,?,?,?,?," + + "?,?,?,?,?,?,?,?)", + new Object[]{lsh, verify, checktime, sn, alias, pin, ename, deptnumber, deptname, stateno, state, creater, currentdate, currenttime, zkkqjkqsj_formmodeid, uuid}); + if (exeRes) { + //重构权限 + rs2.executeQuery(" select id from uf_zkkqjkqsj where modeuuid=? ", new Object[]{uuid}); + rs2.next(); + billid = rs2.getInt("id"); + ModeRightInfo moderight = new ModeRightInfo(); + moderight.editModeDataShare(creater, zkkqjkqsj_formmodeid, billid); + } + } + } + } + } + if(bool){ + index = Integer.parseInt(Collections.max(idList)); + json_main.put("id",index); + SynKqData(lsFormatData,index,json_main); + } + } + + /** + * post 请求 json格式 + * @param url + * @param headers + * @param stringJson + * @param encode + * @return + */ + public static String httpPostKqData(String url, Map headers, String stringJson, String encode){ + String result = ""; + if(encode == null){ + encode = "utf-8"; + } + RecordSet rs = new RecordSet(); + String content = null; + CloseableHttpResponse httpResponse = null; + CloseableHttpClient closeableHttpClient = null; + try { + closeableHttpClient = HttpClients.createDefault(); + HttpPost httpost = new HttpPost(url); + //设置header + httpost.setHeader("Content-type", "application/json"); + if (headers != null && headers.size() > 0) { + for (Map.Entry entry : headers.entrySet()) { + httpost.setHeader(entry.getKey(),entry.getValue()); + } + } + //组织请求参数 + StringEntity stringEntity = new StringEntity(stringJson, encode); + httpost.setEntity(stringEntity); + //响应信息 + httpResponse = closeableHttpClient.execute(httpost); + if(httpResponse != null) { + HttpEntity entity = httpResponse.getEntity(); + content = EntityUtils.toString(entity, encode); + if (content != null && !"".equals(content)) { + JSONObject json = JSONObject.parseObject(content); +// rs.writeLog("============= pushInfo json =================== " + json); + int success = Integer.parseInt(json.getString("ret")); + String data = json.getString("data").toString(); + // 成功的 + if(success == 0){ + result = json.getString("data").toString(); + } + } + } + } catch (Exception e) { + e.printStackTrace(); + rs.writeLog(e); + }finally{ + try { + httpResponse.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + try { //关闭连接、释放资源 + closeableHttpClient.close(); + } catch (IOException e) { + e.printStackTrace(); + } + return result; + } + + /** + * 删除 + * @param userId + * @param signdate + * @param signtime + */ + public static Boolean deleteByInfo(String userId,String signdate,String signtime){ + RecordSet rs = new RecordSet(); + String sql = "delete from hrmschedulesign where signfrom='OutDataSourceSyn' and userid =? and signdate = ? and signtime = ? "; + boolean isdelete = rs.executeUpdate(sql,userId,signdate,signtime); + return isdelete; + } + + /** + * 新增 + * @param userId + * @param signdate + * @param signtime + */ + public static Boolean InsertByInfo(String userId,Integer usertype,String signdate,String signtime,String clientaddress,Integer isincom,Integer isimport,String signfrom,String longitude,String latitude,String addr,String memo){ + RecordSet rs = new RecordSet(); + String sql = " insert into HrmScheduleSign (userid, usertype, signdate, signtime, clientaddress, isincom, isimport, signfrom, longitude, latitude, addr,memo) " + + " values(?,?,?,?,?,?,?,?,?,?,?,?)"; + boolean isok = rs.executeUpdate(sql,userId,usertype,signdate,signtime,clientaddress,isincom,isimport,signfrom,longitude,latitude,addr,memo); + return isok; + } + + /** + * 根据 自定义 考勤卡号 获取 人员id + * @param fieldvalue + * @return + */ + public static String getUserIdByPin(String fieldvalue){ + String result = ""; + RecordSet rs = new RecordSet(); + String kq_fieldid = rs.getPropValue("hrm_zhongkong","kq_fieldid"); + rs.executeQuery("select a.id from cus_fielddata a,hrmresource b where a.id=b.id and a.scope = 'HrmCustomFieldByInfoType' and a.scopeid = -1 and "+ kq_fieldid +" = ?",fieldvalue); + rs.writeLog("select a.id from cus_fielddata a,hrmresource b where a.id=b.id and a.scope = 'HrmCustomFieldByInfoType' and a.scopeid = -1 and "+ kq_fieldid +" = "+ fieldvalue); + if(rs.next()){ + result = com.wbi.util.Util.null2String(rs.getString("id")); + } + return result; + } +%> + + + + + +

Congratulation Mode 666666 !

+ +

lsFormatData <%=num%>

+ +

lsParams <%=num2%>

+ +

sum <%=sum%>

+ + diff --git a/领悦二开new/interface/lingyue/cc.jsp b/领悦二开new/interface/lingyue/cc.jsp new file mode 100644 index 0000000..0da3fbd --- /dev/null +++ b/领悦二开new/interface/lingyue/cc.jsp @@ -0,0 +1,410 @@ +<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> +<%@page import="weaver.general.Util"%> +<%@ page import="weaver.conn.RecordSet" %> +<%@ page import="weaver.general.TimeUtil" %> +<%@ page import="com.alibaba.fastjson.JSONObject" %> +<%@ page import="java.util.*" %> +<%@ page import="com.alibaba.fastjson.JSONArray" %> +<%@ page import="org.apache.http.client.methods.CloseableHttpResponse" %> +<%@ page import="org.apache.http.impl.client.CloseableHttpClient" %> +<%@ page import="org.apache.http.impl.client.HttpClients" %> +<%@ page import="org.apache.http.client.methods.HttpPost" %> +<%@ page import="org.apache.http.entity.StringEntity" %> +<%@ page import="org.apache.http.HttpEntity" %> +<%@ page import="org.apache.http.util.EntityUtils" %> +<%@ page import="java.io.IOException" %> +<%@ page import="com.google.common.collect.Maps" %> +<%@ page import="com.google.common.collect.Lists" %> +<%@ page import="weaver.interfaces.lingyue.util.HttpUtil" %> +<%@ page import="com.engine.kq.biz.KQFormatBiz" %> +<%@ page import="com.engine.kq.timer.KQTaskBean" %> +<%@ page import="com.engine.kq.wfset.util.SplitActionUtil" %> +<%@ page import="com.engine.kq.timer.KQQueue" %> +<%@ page import="weaver.formmode.setup.ModeRightInfo" %> +<%@ page import="weaver.common.DateUtil" %> +<%@ page import="weaver.hrm.common.Tools" %> +<%@ page import="weaver.conn.BatchRecordSet" %> +<%@ page import="com.engine.kq.bean.ImportSetting" %> +<%@ page import="com.engine.kq.entity.KQScheduleSignEntity" %> +<%@ page import="java.text.DateFormat" %> +<%@ page import="java.text.SimpleDateFormat" %> +<%@ page import="weaver.conn.RecordSetDataSource" %> +<%@ page import="java.sql.Timestamp" %> +<%@ page import="weaver.common.StringUtil" %> +<%@ page import="weaver.hrm.User" %> +<%@ page import="com.engine.kq.util.KQDurationCalculatorUtil" %> + +<% + int sum = 0; + + int userlanguage = 7; //登录语言 + + String userId = request.getParameter("userid"); + String beginDate = request.getParameter("fromdate"); + String endDate = request.getParameter("todate"); + + User user = new User(Integer.parseInt(userId)); + + String username = user.getLastname(); + + rs.writeLog("考勤机同步:importData:开始>>>>>>beginDate>>"+beginDate+">>>>>endDate>>>>"+endDate+">>>>>>"+ DateUtil.getFullDate()); + RecordSet delrs = new RecordSet(); + String sql = ""; + endDate = Tools.getDate(endDate, 1); + BatchRecordSet bRs = new BatchRecordSet(); + List> lsParams = new ArrayList<>(); + List params = null; + + List> lsDelParams = new ArrayList<>(); + List delParams = null; + + List lsFormatData = new ArrayList<>(); + List> lsFormatParams = new ArrayList<>(); + List formatParams = null; + + Map> users = getUsers(userlanguage); + Map loginidMap = users.get("loginidMap"); + Map lastnameMap = users.get("lastnameMap"); + Map workcodeMap = users.get("workcodeMap"); + List keymap = new ArrayList<>(); + + + List lsImportSetting = new ArrayList<>(); + ImportSetting importSetting = null; + sql = " select datasourceid, loginid, workcode, lastname, signdate, signtime, tablename, clientaddress,longitude,latitude,addr,memo " + + " from HrmScheduleSignSet "; + rs.execute(sql); + while (rs.next()) { + importSetting = new ImportSetting(); + importSetting.setDatasourceid(Util.null2String(rs.getString("datasourceid")).trim()); + importSetting.setLoginid(Util.null2String(rs.getString("loginid")).trim()); + importSetting.setWorkcode(Util.null2String(rs.getString("workcode")).trim()); + importSetting.setLastname(Util.null2String(rs.getString("lastname")).trim()); + importSetting.setSigndate(Util.null2String(rs.getString("signdate")).trim()); + importSetting.setSigntime(Util.null2String(rs.getString("signtime")).trim()); + importSetting.setTablename(Util.null2String(rs.getString("tablename")).trim()); + importSetting.setClientaddress(Util.null2String(rs.getString("clientaddress")).trim()); + importSetting.setLongitude(Util.null2String(rs.getString("longitude")).trim()); + importSetting.setLatitude(Util.null2String(rs.getString("latitude")).trim()); + importSetting.setAddr(Util.null2String(rs.getString("addr")).trim()); + importSetting.setMemo(Util.null2String(rs.getString("memo")).trim()); + lsImportSetting.add(importSetting); + } + List lsKQScheduleSignData = new ArrayList<>(); + KQScheduleSignEntity kqScheduleSignData = null; + for (int i = 0; lsImportSetting != null && i < lsImportSetting.size(); i++) { + try { + importSetting = lsImportSetting.get(i); + String datasourceid = importSetting.getDatasourceid(); + String loginid = importSetting.getLoginid(); + String workcode = importSetting.getWorkcode(); + String lastname = importSetting.getLastname(); + String signdate = importSetting.getSigndate(); + String signtime = importSetting.getSigntime(); + String tablename = importSetting.getTablename(); + String clientaddress = importSetting.getClientaddress(); + String longitude = importSetting.getLongitude(); + String latitude = importSetting.getLatitude(); + String addr = importSetting.getAddr(); + String memo = importSetting.getMemo(); + + DateFormat df = new SimpleDateFormat("HH:mm:ss"); + + sql = " select * from " + tablename + " where oary = '"+userId+"' and modedatacreatedate >= '" + beginDate + "' and modedatacreatedate < '" + endDate + "' order by modedatacreatedate,modedatacreatetime "; + + //有遇到外部同步,上面的【conn = ds.getConnection();】这个阻塞住,导致下面的同步不执行,下面的用法和集成领导确认 + RecordSetDataSource rsds = new RecordSetDataSource(datasourceid); + + rsds.execute(sql); + + List noRepertSynData = new ArrayList<>(); + while (rsds.next()) { + String tmpLoginid = ""; + String tmpWorkcode = ""; + String tmpLastname = ""; + String tmpSigndate = ""; + String tmpSigntime = ""; + String tmpClientaddress = ""; + String tmpLongitude = ""; + String tmpLatitude = ""; + String tmpAddr = ""; + String tmpMemo = ""; + String tmpCreatedate = ""; + + if (loginid.length() > 0) tmpLoginid = Util.null2String(rsds.getString(loginid)).trim(); + if (workcode.length() > 0) tmpWorkcode = Util.null2String(rsds.getString(workcode)).trim(); + if (lastname.length() > 0) tmpLastname = Util.null2String(rsds.getString(lastname)).trim(); + if (signdate.length() > 0) tmpSigndate = Util.null2String(rsds.getString(signdate)).trim(); + if (clientaddress.length() > 0) + tmpClientaddress = Util.null2String(rsds.getString(clientaddress)); + if (longitude.length() > 0) tmpLongitude = Util.null2String(rsds.getString(longitude)).trim(); + if (latitude.length() > 0) tmpLatitude = Util.null2String(rsds.getString(latitude)).trim(); + if (addr.length() > 0) tmpAddr = Util.null2String(rsds.getString(addr)).trim(); + if (memo.length() > 0) tmpMemo = Util.null2String(rsds.getString(memo)).trim(); + tmpCreatedate = Util.null2String(rsds.getString("modedatacreatedate")).trim(); + + if (signtime.length() > 0) { + tmpSigntime = Util.null2String(rsds.getString(signtime)).trim(); + //判断tmpSigntime格式 08:21:11 如果为长格式需要格式化 + if (tmpSigntime.length() > 8) { + if(tmpSigntime.length()<16){//有遇到signtime格式为hh:mm:ss.0000的格式导致同步不成功 + tmpSigntime = tmpSigntime.substring(0,8); + }else{//比如上yyyy-mm-dd hh:mm的格式走原逻辑 + tmpSigntime = df.format(Timestamp.valueOf(tmpSigntime)); + } + } else if (tmpSigntime.length() < 8) { + //不带秒的情况 自动补齐 + tmpSigntime += ":00"; + } + } else { + tmpSigntime = ""; + } + + if (tmpSigndate.length() > 10) { + //如果时间为长格式,从signdate字段中格式化时间 + if (tmpSigndate.length() == 16) { + //不带秒的情况 自动补齐 + tmpSigndate += ":00"; + } + if (tmpSigntime.length() == 0) {//以signtime字段为有限 + tmpSigndate = tmpSigndate.length()>19?tmpSigndate.substring(0,19):tmpSigndate; + tmpSigntime = df.format(Timestamp.valueOf(tmpSigndate)); + } + tmpSigndate = Tools.formatDate(tmpSigndate, "yyyy-MM-dd"); + } + + //如果时间格式不带秒补齐 + if (tmpSigntime.length() <= 5) { + tmpSigntime += ":00"; + } + + kqScheduleSignData = new KQScheduleSignEntity(); + kqScheduleSignData.setLoginid(tmpLoginid); + kqScheduleSignData.setWorkcode(tmpWorkcode); + kqScheduleSignData.setLastname(tmpLastname); + kqScheduleSignData.setSigndate(tmpSigndate); + kqScheduleSignData.setSigntime(tmpSigntime); + kqScheduleSignData.setClientaddress(tmpClientaddress); + kqScheduleSignData.setLongitude(tmpLongitude); + kqScheduleSignData.setLatitude(tmpLatitude); + kqScheduleSignData.setAddr(tmpAddr); + kqScheduleSignData.setMemo(tmpMemo); + kqScheduleSignData.setCreatedate(tmpCreatedate); + lsKQScheduleSignData.add(kqScheduleSignData); + } + } catch (Exception e) { + rs.writeLog(e); + } + } + List noRepertSynData = new ArrayList<>(); + for (int i = 0; lsKQScheduleSignData != null && i < lsKQScheduleSignData.size(); i++) { + kqScheduleSignData = lsKQScheduleSignData.get(i); + String tmpLoginid = kqScheduleSignData.getLoginid(); + String tmpWorkcode = kqScheduleSignData.getWorkcode(); + String tmpLastname = kqScheduleSignData.getLastname(); + String tmpSigndate = kqScheduleSignData.getSigndate(); + String tmpSigntime = kqScheduleSignData.getSigntime(); + String tmpClientaddress = kqScheduleSignData.getClientaddress(); + String tmpLongitude = kqScheduleSignData.getLongitude(); + String tmpLatitude = kqScheduleSignData.getLatitude(); + String tmpAddr = kqScheduleSignData.getAddr(); + String tmpMemo = kqScheduleSignData.getMemo(); + String tmpCreatedate = kqScheduleSignData.getCreatedate(); + int userid = 0; + if (Util.null2String(tmpLoginid).length() > 0) { + userid = StringUtil.parseToInt(loginidMap.get(tmpLoginid), 0); + } + if (userid == 0 && Util.null2String(tmpWorkcode).length() > 0) { + userid = StringUtil.parseToInt(workcodeMap.get(tmpWorkcode), 0); + } + if (userid == 0 && Util.null2String(tmpLastname).length() > 0) { + userid = StringUtil.parseToInt(lastnameMap.get(tmpLastname), 0); + } + + if (userid <= 0) { + rs.writeLog("人员id未找到>>>>>>>>>>" + JSONObject.toJSONString(kqScheduleSignData)); + continue; + } + String dkParamData = userid + "#" + tmpCreatedate + "#" + tmpSigntime; + if (noRepertSynData.contains(dkParamData)) { + continue; + } + noRepertSynData.add(dkParamData); + params = new ArrayList<>(); + params.add(userid); + params.add(1); + params.add(tmpSigndate); + params.add(tmpSigntime); + params.add(tmpClientaddress); + params.add(1); + params.add(1); + params.add("OutDataSourceSyn"); + params.add(tmpLongitude); + params.add(tmpLatitude); + params.add(tmpAddr); + params.add(tmpMemo); + params.add(tmpCreatedate); + lsParams.add(params); + + String belongDate = getBelongDate(new User(userid), tmpCreatedate, tmpSigntime); + + String formatData = userid + "|" + tmpCreatedate+ "|" + belongDate; + if (!lsFormatData.contains(formatData)) { + lsFormatData.add(formatData); + } + } + + Map> overtimeMap = Maps.newHashMap(); + List overtimeList = Lists.newArrayList(); + //刷新报表数据 + for (int i = 0; lsFormatData != null && i < lsFormatData.size(); i++) { + formatParams = new ArrayList<>(); + String key = lsFormatData.get(i);//String formatData = userid + "|" + tmpSigndate; + String[] formatData = Util.splitString(lsFormatData.get(i), "|"); + String date_1 = DateUtil.addDate(formatData[1], -1); + formatParams.add(formatData[0]); + formatParams.add(date_1); + lsFormatParams.add(formatParams); + + formatParams = new ArrayList<>(); + formatParams.add(formatData[0]); + formatParams.add(formatData[1]); + lsFormatParams.add(formatParams); + + if (!keymap.contains(key)) { + keymap.add(key); + delParams = new ArrayList<>(); + delParams.add(formatData[0]); + delParams.add(formatData[1]); + lsDelParams.add(delParams); + } + + String resourceId = formatData[0]; + String kqdate = formatData[1]; + String belongDate = formatData[2]; + if (overtimeMap.containsKey(resourceId)) { + List tmp_overtimeList = overtimeMap.get(resourceId); + if (!tmp_overtimeList.contains(kqdate)) { + tmp_overtimeList.add(kqdate); + if(!kqdate.equals(belongDate)) { + tmp_overtimeList.add(belongDate); + } + } + } else { + if (!overtimeList.contains(kqdate)) { + overtimeList.add(kqdate); + if(!kqdate.equals(belongDate)) { + overtimeList.add(belongDate); + } + } + overtimeMap.put(resourceId, overtimeList); + } + } + + rs.writeLog("同步之前删除数据:"+ JSONObject.toJSONString(lsDelParams)); + rs.writeLog("同步插入数据:"+ JSONObject.toJSONString(lsParams)); + + //删除本次同步数据 + sql = " delete from hrmschedulesign where signfrom='OutDataSourceSyn' and userid =? and (createdate = ? or createdate is null) "; + bRs.executeBatchSql(sql, lsDelParams); + + + sql = " insert into HrmScheduleSign (userid, usertype, signdate, signtime, clientaddress, isincom, isimport, signfrom, longitude, latitude, addr,memo, createdate) " + + " values(?,?,?,?,?,?,?,?,?,?,?,?,?)"; + bRs.executeBatchSql(sql, lsParams); + + new KQFormatBiz().format(lsFormatParams, 12); + + //处理加班生成 + List tasks = new ArrayList<>(); + for (Map.Entry> mme : overtimeMap.entrySet()) { + String resid = mme.getKey(); + List overList = mme.getValue(); + for (String date : overList) { + SplitActionUtil.pushOverTimeTasks(date, date, resid, tasks); + } + } + if (!tasks.isEmpty()) { + KQQueue.writeTasks(tasks); + } + + + int size = lsKQScheduleSignData.size(); + sum++; + +%> + +<%! + private String getBelongDate(User user, String curDate, String signDateTime) { + String belongDate = curDate; + Map todayLineMap = KQDurationCalculatorUtil.getWorkButton(user, curDate,true); + if(todayLineMap != null) { + List> preInfo = (ArrayList>)todayLineMap.get("pre_signTime"); + if(preInfo != null) { + for(Map entry : preInfo) { + String pre_endtime_across = entry.get("endtime_across"); + String pre_endtime = entry.get("endtime"); + String signEndInfo = "1".equals(pre_endtime_across) ? (curDate+" "+pre_endtime+":00") : (DateUtil.addDate(curDate,-1)+" "+pre_endtime+":00"); + String signOutDateTime = signDateTime; + if(signOutDateTime.compareTo(signEndInfo) < 0) { + belongDate = DateUtil.addDate(curDate, -1); + } + } + } + } + return belongDate; + } + + public Map> getUsers(int language) { + RecordSet rs = new RecordSet(); + String sql = "select id,loginid,lastname,workcode from hrmresource where status in(0,1,2,3,5)"; + if (Util.isEnableMultiLang()) { + if (rs.getDBType().equalsIgnoreCase("sqlserver")) { + sql = "select id,loginid,ltrim(rtrim(dbo.convToMultiLang(ltrim(rtrim(lastname)),"+language+"))) as lastname,workcode from hrmresource where status in(0,1,2,3,5)"; + } else { + sql = "select id,loginid,ltrim(rtrim(convToMultiLang(ltrim(rtrim(lastname)),"+language+"))) as lastname,workcode from hrmresource where status in(0,1,2,3,5)"; + } + } + + Map> users = new HashMap>(); + rs.execute(sql); + Map loginidMap = new HashMap(); + Map lastnameMap = new HashMap(); + Map workcodeMap = new HashMap(); + String resourceId = "", loginid = "",lastname = "", workcode = ""; + while (rs.next()) { + if (StringUtil.isNull(resourceId = StringUtil.vString(rs.getString("id")))) continue; + loginid = StringUtil.vString(rs.getString("loginid")); + if (StringUtil.isNull(loginid)){ + }else{ + loginidMap.put(loginid, resourceId); + } + if (StringUtil.isNotNull(lastname = StringUtil.vString(rs.getString("lastname")))) lastnameMap.put(lastname, resourceId); + if (StringUtil.isNotNull(workcode = StringUtil.vString(rs.getString("workcode")))) workcodeMap.put(workcode, resourceId); + } + users.put("loginidMap", loginidMap); + users.put("lastnameMap", lastnameMap); + users.put("workcodeMap", workcodeMap); + return users; + } +%> + + + + + +

Congratulation Mode 666666 !

+ +

以下是 <%=username%> 的 相关数据展示

+ +

size <%=size%>

+ +

需要同步到原始打卡记录表的数据 <%=JSONObject.toJSONString(lsKQScheduleSignData)%>

+ +

同步之前删除数据:<%=JSONObject.toJSONString(lsDelParams)%>

+ +

同步插入数据 <%=JSONObject.toJSONString(lsParams)%>

+ +

sum <%=sum%>

+ + diff --git a/领悦二开new/interface/lingyue/controle_leave.jsp b/领悦二开new/interface/lingyue/controle_leave.jsp new file mode 100644 index 0000000..4ecc0af --- /dev/null +++ b/领悦二开new/interface/lingyue/controle_leave.jsp @@ -0,0 +1,44 @@ +<%@ page import="weaver.general.Util" %> +<%@ page contentType="text/html; charset=UTF-8" %> + + +<% + int nodeid = Util.getIntValue(request.getParameter("nodeid"));//流程的节点id + bb.writeLog("========== 请假流程 nodeid ============"+ nodeid); + String sql = "select isstart from workflow_nodebase where id = " + nodeid; + rs.execute(sql); + rs.next(); + int isstart = Util.getIntValue(rs.getString("isstart"));//判断是否是流程创建节点 1:是 0:否 +%> + \ No newline at end of file diff --git a/领悦二开new/interface/lingyue/dd.jsp b/领悦二开new/interface/lingyue/dd.jsp new file mode 100644 index 0000000..d18ee99 --- /dev/null +++ b/领悦二开new/interface/lingyue/dd.jsp @@ -0,0 +1,2578 @@ +<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> +<%@page import="weaver.general.Util"%> +<%@ page import="java.math.BigDecimal" %> +<%@ page import="weaver.conn.RecordSet" %> +<%@ page import="com.engine.kq.util.KQDurationCalculatorUtil" %> +<%@ page import="weaver.hrm.User" %> +<%@ page import="java.util.*" %> +<%@ page import="java.time.format.DateTimeFormatter" %> +<%@ page import="java.time.LocalDate" %> +<%@ page import="org.apache.commons.lang.StringUtils" %> +<%@ page import="java.text.SimpleDateFormat" %> +<%@ page import="java.text.ParseException" %> +<%@ page import="weaver.hrm.company.SubCompanyComInfo" %> +<%@ page import="com.engine.kq.entity.KQGroupEntity" %> +<%@ page import="com.engine.kq.biz.KQGroupMemberComInfo" %> +<%@ page import="com.engine.kq.biz.KQUnitBiz" %> +<%@ page import="com.engine.kq.biz.KQLeaveRulesComInfo" %> +<%@ page import="com.engine.lingyue.util.KqUtil" %> +<%@ page import="weaver.hrm.company.DepartmentComInfo" %> +<%@ page import="com.engine.kq.biz.KQWorkTime" %> +<%@ page import="com.engine.kq.entity.WorkTimeEntity" %> + + +<% + int sum = 0; + String id = Util.null2String(request.getParameter("userid")); + String fromDate = Util.null2String(request.getParameter("fromdate")); + String toDate = Util.null2String(request.getParameter("todate")); + + User user = new User(Integer.parseInt(id)); + + String username = user.getLastname(); + +// 薪资调整日期 + String salaryAdjustDate = getSalaryAdjustDate(fromDate,toDate,id); + + //事假 + int leaveabsencetype = Util.getIntValue(rs.getPropValue("hrm_kqreport","leaveabsencetype")); + //病假 + int sickleavetype = Util.getIntValue(rs.getPropValue("hrm_kqreport","sickleavetype")); + //年假 + int annualleavetype = Util.getIntValue(rs.getPropValue("hrm_kqreport","annualleavetype")); + //陪产假 + int paternityleavetype = Util.getIntValue(rs.getPropValue("hrm_kqreport","paternityleavetype")); + //婚假 + int marriageleavetype = Util.getIntValue(rs.getPropValue("hrm_kqreport","marriageleavetype")); + //丧假 + int bereavementleavetype = Util.getIntValue(rs.getPropValue("hrm_kqreport","bereavementleavetype")); + //探亲假 + int homeleavetype = Util.getIntValue(rs.getPropValue("hrm_kqreport","homeleavetype")); + //哺乳假 + int breastfeedleavetype = Util.getIntValue(rs.getPropValue("hrm_kqreport","breastfeed_leave_id")); + //调休假 + int compensatoryleavetype = Util.getIntValue(rs.getPropValue("hrm_kqreport","compensatory_leave_id")); + //产假 + int maternityleavetype = Util.getIntValue(rs.getPropValue("hrm_kqreport","maternity_leave_id")); + + //班次id + String serialid = getSerialId(fromDate,toDate,id); + + //入职日期 + String companystartdate = getCompanyStartDate(id); + + //转正日期 + String comfirmdate = getComfirmDate(id); + + //异动日期 + String transactiondate = getTransactionDate(fromDate,toDate,id); + + //离职日期 + String terminationdate = getTerminationDate(id); + + //是否请了产假 + boolean boo1l = checkIsRestLeaveDay(fromDate,id); + + //片区 + String area = getArea(id); + + //日期范围内是否有异动 + boolean hasTransaction = checkHasTransactionDate(fromDate,toDate,id); + + //分部 + String subcompany = getSubcompany(fromDate,toDate,id); + + //部门 + String department = getDepartment(fromDate,toDate,id); + + String position_fieldid = rs.getPropValue("hrm_kqreport","position_fieldid"); + + String gwid = getSnapShotData("FIELD128",fromDate,toDate,id); + + //岗位名称 + String positionname = getPosition(fromDate,toDate,id); + + // 休息班 天数 + String restdays = getRestSerialDaysAfter(fromDate,toDate,id); + + //应出勤天数 + String requiredworkdays = KQDurationCalculatorUtil.getDurationRound(String.valueOf(getWorkDays(fromDate,toDate,id))); + + //实际出勤天数(薪酬调整前) + String attenddaysbeforesalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(getAttendDaysBeforeSalary(fromDate,toDate,id))); + + //事假天数(薪酬调整前) + String leaveabsencedaysbeforesalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(getBeforeSalaryLeaveDays(leaveabsencetype,fromDate,toDate,id))); + + //病假天数(薪酬调整前) + String sickleavedaysbeforesalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(getBeforeSalaryLeaveDays(sickleavetype,fromDate,toDate,id))); + + //年假(薪酬调整前) + String annualleavedaysbeforesalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(getBeforeSalaryLeaveDays(annualleavetype,fromDate,toDate,id))); + + //陪产假(薪酬调整前) + String paternityleavedaysbeforesalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(getBeforeSalaryLeaveDays(paternityleavetype,fromDate,toDate,id))); + + //婚假(薪酬调整前) + String marriageleavedaysbeforesalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(getBeforeSalaryLeaveDays(marriageleavetype,fromDate,toDate,id))); + + //丧假(薪酬调整前) + String bereavementleavedaysbeforesalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(getBeforeSalaryLeaveDays(bereavementleavetype,fromDate,toDate,id))); + + //探亲假(薪酬调整前) + String homeleavedaysbeforesalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(getBeforeSalaryLeaveDays(homeleavetype,fromDate,toDate,id))); + + //哺乳假(薪酬调整前) + String breastfeedleavedaysbeforesalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(getBeforeSalaryLeaveDays(breastfeedleavetype,fromDate,toDate,id))); + + //调休假(薪酬调整前) + String compensatoryleavedaysbeforesalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(getBeforeSalaryLeaveDays(compensatoryleavetype,fromDate,toDate,id))); + + //产假(薪酬调整前) + String maternityleavedaysbeforesalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(getBeforeSalaryLeaveDays(maternityleavetype,fromDate,toDate,id))); + + //旷工天数(薪酬调整前) + String absenteeismdaysbeforesalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(getAbsenteeismDaysBeforeSalaryBefore(fromDate,toDate,id))); + + //旷工天数(薪酬调整前)总计 + String absenteeismdayscountbeforesalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(getAbsenteeismDaysCountAfterSalary(fromDate,toDate,id))); + + //每次漏签计0.5天旷工 + String forgotcheckabsenteeismdays = KQDurationCalculatorUtil.getDurationRound(String.valueOf(getForgotCheckAbsenteeismDaysAfter(fromDate,toDate,id))); + + //严重迟到/早退每次计0.5天旷工 + String gravebelateleaveearlydays = KQDurationCalculatorUtil.getDurationRound(String.valueOf(getGraveBeLateLeaveEarlyDaysAfter(fromDate,toDate,id))); + + //实际出勤天数(薪酬调整后) + String attendDaysAfterSalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(getAttendDaysAfterSalary(fromDate,toDate,id))); + + //事假天数(薪酬调整后) + String leaveabsencedaysaftersalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(getAfterSalaryLeaveDays(leaveabsencetype,fromDate,toDate,id))); + + //病假天数(薪酬调整后) + String sickleavedaysaftersalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(getAfterSalaryLeaveDays(sickleavetype,fromDate,toDate,id))); + + //年假(薪酬调整后) + String annualleavedaysaftersalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(getAfterSalaryLeaveDays(annualleavetype,fromDate,toDate,id))); + + //陪产假(薪酬调整后) + String paternityleavedaysaftersalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(getAfterSalaryLeaveDays(paternityleavetype,fromDate,toDate,id))); + + //婚假(薪酬调整后) + String marriageleavedaysaftersalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(getAfterSalaryLeaveDays(marriageleavetype,fromDate,toDate,id))); + + //丧假(薪酬调整后) + String bereavementleavedaysaftersalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(getAfterSalaryLeaveDays(bereavementleavetype,fromDate,toDate,id))); + + //探亲假(薪酬调整后) + String homeleavedaysaftersalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(getAfterSalaryLeaveDays(homeleavetype,fromDate,toDate,id))); + + //哺乳假(薪酬调整后) + String breastfeedleavedaysaftersalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(getAfterSalaryLeaveDays(breastfeedleavetype,fromDate,toDate,id))); + + //调休假(薪酬调整后) + String compensatoryleavedaysaftersalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(getAfterSalaryLeaveDays(compensatoryleavetype,fromDate,toDate,id))); + + //产假(薪酬调整后) + String maternityleavedaysaftersalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(getAfterSalaryLeaveDays(maternityleavetype,fromDate,toDate,id))); + + //旷工天数(薪酬调整后) + String absenteeismdaysaftersalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(getAbsenteeismDaysAfterSalaryAfter(fromDate,toDate,id))); + +// 旷工天数(薪酬调整后)总计 +// String absenteeismdayscountaftersalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(getAbsenteeismDaysCountAfterSalary(fromDate,toDate,id))); + + //旷工次数 + String absenteeismdays = KQDurationCalculatorUtil.getDurationRound(String.valueOf(getAbsenteeismDays(fromDate,toDate,id))); + + String workdays = "0"; + String attendancedays = "0"; + rs.executeQuery("select sum(workdays)as workdays,sum(attendancedays)as days from kq_format_total " + + " where resourceid = ? and kqdate >= ? and kqdate <= ? and attendanceMins is not null and attendanceMins > 0",id,fromDate,toDate); + while(rs.next()){ + workdays = Util.null2o(rs.getString("workdays")); + attendancedays = Util.null2o(rs.getString("days")); + } + + String publicHolidays = "0"; + + rs.executeQuery("select distinct groupid from kq_format_total " + + " where resourceid = ? and kqdate >= ? and kqdate <= ?",id,fromDate,toDate); + while(rs.next()){ + String groupid = Util.null2String(rs.getString("groupid")); + // 法定(公众假日)天数 + publicHolidays = getPublicHolidays(companystartdate,fromDate,toDate,groupid,id); + } + + int positionRank = getPositionRank(getPositionRankId(fromDate,toDate,id)); + + String serial_hours = getHoursBySerial(serialid); + + // 假期 天数 + String attendLeaveDays = getAttendLeaveDaysAfter(fromDate,toDate,id); + + // 获取 产假天数(薪酬用) + double maternityLeaveDaySalary = getMaternityLeaveDaySalary(fromDate,toDate,id); + + // 产假 + String maternity_leave_id = rs.getPropValue("hrm_kqreport","maternity_leave_id"); + + // 工伤假 + String injuryLeave_leave_id = rs.getPropValue("hrm_kqreport","injuryLeave_leave_id"); + + // 工伤假 薪酬有用 + double injuryLeaveDaysSalary = getInjuryLeaveDaySalary(fromDate,toDate,id); + + // 格式化日期 + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + rs.executeQuery("select distinct groupid,kqdate from kq_format_total " + + " where resourceid = ? and kqdate >= ? and kqdate <= ?",id,fromDate,toDate); + rs.next(); + //考勤组 id + String groupid = rs.getPropValue("hrm_kqreport","the_top_groupid"); + + // 周六或周日天数 + String weekdays = "0"; + // 【周一到周五】产假天数 + String workdayss= "0"; + // 【周一到周五】调配休息日产假天数 + String allocateRestDays = "0"; + // 【周六周日】调配工作日产假天数 + String allocateWorkDays = "0"; + + String[] dateStartArr = parseDate(fromDate); + String[] dateEndtArr = parseDate(toDate); + LocalDate startDate = LocalDate.of(Integer.parseInt(dateStartArr[0]), Integer.parseInt(dateStartArr[1]), Integer.parseInt(dateStartArr[2])); + LocalDate endDate = LocalDate.of(Integer.parseInt(dateEndtArr[0]), Integer.parseInt(dateEndtArr[1]), Integer.parseInt(dateEndtArr[2])); + // 遍历日期范围 + for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) { + // 输出格式化后的日期字符串 + String dateString = date.format(formatter); + // 是 周六或 周日 + if (isSaturdayOrSunday(dateString)) { + //是调配工作日 + if (isAllocateWorkDay(groupid, dateString)) { + String leaveDays = getLeaveTypeDays(maternity_leave_id,dateString,dateString,id); + if(floatCompare(leaveDays,"0") > 0) { + allocateWorkDays = floatAdd(allocateWorkDays, leaveDays); + } + }// 是 调配休息日 + } else { + // 是 调配休息日 + if(isAllocateRestDay(groupid,dateString)){ + String leaveDays = getLeaveTypeDays(maternity_leave_id,dateString,dateString,id); + if(floatCompare(leaveDays,"0") > 0) { + allocateRestDays = floatAdd(allocateRestDays, leaveDays); + } + }else { + String leaveDays = getLeaveTypeDays(maternity_leave_id, dateString, dateString, id); + if (floatCompare(leaveDays, "0") > 0) { + workdayss = floatAdd(workdayss, leaveDays); + } + } + } + } + + + sum++; + +%> + +<%! + + /** + * 获取 工伤假 薪酬用 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static double getInjuryLeaveDaySalary(String fromdate, String todate,String userid){ + double result = 0.00; + RecordSet rs = new RecordSet(); + //职级 + int positionRank = getPositionRank(getPositionRankId(fromdate,todate,userid)); + // 产假 + String injuryLeave_leave_id = rs.getPropValue("hrm_kqreport","injuryLeave_leave_id"); + + if (positionRank == 1 || positionRank == 2) { + result = Double.valueOf(getLeaveTypeDays(injuryLeave_leave_id,fromdate,todate,userid)); + }else{ + result = Double.valueOf(getLeaveDaysSalary(injuryLeave_leave_id,fromdate,todate,userid)); + } + return result; + } + + /** + * 获取 假天数(薪酬用) + * @param leaveType + * @param fromDate + * @param toDate + * @param userid + * @return + */ + public static String getLeaveDaysSalary(String leaveType,String fromDate, String toDate,String userid){ + String result = "0"; + RecordSet rs = new RecordSet(); + // 格式化日期 + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + rs.executeQuery("select distinct groupid,kqdate from kq_format_total " + + " where resourceid = ? and kqdate >= ? and kqdate <= ?",userid,fromDate,toDate); + rs.next(); + //考勤组 id +// String groupid = Util.null2String(rs.getString("groupid")); + + String groupid = rs.getPropValue("hrm_kqreport","the_top_groupid"); + + // 休息班次 + String rest_serial_id = rs.getPropValue("hrm_kqreport","rest_serial_id"); + + // 周六或周日天数 + String weekdays = "0"; + // 周一到周五天数 + String workdays = "0"; + // 调配休息日天数 + String allocateRestDays = "0"; + // 调配工作日天数 + String allocateWorkDays = "0"; + + String[] dateStartArr = parseDate(fromDate); + String[] dateEndtArr = parseDate(toDate); + LocalDate startDate = LocalDate.of(Integer.parseInt(dateStartArr[0]), Integer.parseInt(dateStartArr[1]), Integer.parseInt(dateStartArr[2])); + LocalDate endDate = LocalDate.of(Integer.parseInt(dateEndtArr[0]), Integer.parseInt(dateEndtArr[1]), Integer.parseInt(dateEndtArr[2])); + // 遍历日期范围 + for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) { + // 输出格式化后的日期字符串 + String dateString = date.format(formatter); +// // 是 周六或 周日 +// if (isSaturdayOrSunday(dateString)) { +// //是调配工作日、是公众假日 +// if (isAllocateWorkDay(groupid, dateString) || isAllocateHolidayDay(groupid, dateString)) { +// String leaveDays = getLeaveTypeDays(leaveType,dateString,dateString,userid); +// if(floatCompare(leaveDays,"0") > 0) { +// allocateWorkDays = floatAdd(allocateWorkDays, leaveDays); +// } +// } +// } else { +// // 是 调配休息日 +// if(isAllocateRestDay(groupid,dateString)){ +// String leaveDays = getLeaveTypeDays(leaveType,dateString,dateString,userid); +// if(floatCompare(leaveDays,"0") > 0) { +// allocateRestDays = floatAdd(allocateRestDays, leaveDays); +// } +// }else { +// String leaveDays = getLeaveTypeDays(leaveType, dateString, dateString, userid); +// if (floatCompare(leaveDays, "0") > 0) { +// workdays = floatAdd(workdays, leaveDays); +// } +// } +// } + KQWorkTime kqWorkTime = new KQWorkTime(); + WorkTimeEntity workTimeEntity = kqWorkTime.getWorkTime(userid, dateString); + String searIdFrom = workTimeEntity.getSerialId(); + if(searIdFrom != null && !"".equals(searIdFrom)){ + //当天请了产假 + if(checkHasMaternityLeave(leaveType,dateString,userid)){ + //非休息班次 + if(!rest_serial_id.equals(searIdFrom)){ + result = floatAdd(result, "1"); + } + } + } + } +// result = floatAdd(result,floatAdd(workdays,allocateWorkDays)); + return result; + } + + /** + * 获取 产假天数(薪酬用) + * @param leaveType + * @param fromDate + * @param toDate + * @param userid + * @return + */ + public static String getRestLeaveDaysSalary(String leaveType,String fromDate, String toDate,String userid){ + String result = "0"; + RecordSet rs = new RecordSet(); + // 格式化日期 + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + rs.executeQuery("select distinct groupid,kqdate from kq_format_total " + + " where resourceid = ? and kqdate >= ? and kqdate <= ?",userid,fromDate,toDate); + rs.next(); + //考勤组 id +// String groupid = Util.null2String(rs.getString("groupid")); + + String groupid = rs.getPropValue("hrm_kqreport","the_top_groupid"); + + // 休息班次 + String rest_serial_id = rs.getPropValue("hrm_kqreport","rest_serial_id"); + + // 周六或周日天数 + String weekdays = "0"; + // 周一到周五天数 + String workdays = "0"; + // 调配休息日天数 + String allocateRestDays = "0"; + // 调配工作日天数 + String allocateWorkDays = "0"; + + String[] dateStartArr = parseDate(fromDate); + String[] dateEndtArr = parseDate(toDate); + LocalDate startDate = LocalDate.of(Integer.parseInt(dateStartArr[0]), Integer.parseInt(dateStartArr[1]), Integer.parseInt(dateStartArr[2])); + LocalDate endDate = LocalDate.of(Integer.parseInt(dateEndtArr[0]), Integer.parseInt(dateEndtArr[1]), Integer.parseInt(dateEndtArr[2])); + // 遍历日期范围 + for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) { + // 输出格式化后的日期字符串 + String dateString = date.format(formatter); +// // 是 周六或 周日 +// if (isSaturdayOrSunday(dateString)) { +// //是调配工作日、是公众假日 +// if (isAllocateWorkDay(groupid, dateString) || isAllocateHolidayDay(groupid, dateString)) { +// String leaveDays = getLeaveTypeDays(leaveType,dateString,dateString,userid); +// if(floatCompare(leaveDays,"0") > 0) { +// allocateWorkDays = floatAdd(allocateWorkDays, leaveDays); +// } +// } +// } else { +// // 是 调配休息日 +// if(isAllocateRestDay(groupid,dateString)){ +// String leaveDays = getLeaveTypeDays(leaveType,dateString,dateString,userid); +// if(floatCompare(leaveDays,"0") > 0) { +// allocateRestDays = floatAdd(allocateRestDays, leaveDays); +// } +// }else { +// String leaveDays = getLeaveTypeDays(leaveType, dateString, dateString, userid); +// if (floatCompare(leaveDays, "0") > 0) { +// workdays = floatAdd(workdays, leaveDays); +// } +// } +// } + KQWorkTime kqWorkTime = new KQWorkTime(); + WorkTimeEntity workTimeEntity = kqWorkTime.getWorkTime(userid, dateString); + String searIdFrom = workTimeEntity.getSerialId(); + if(searIdFrom != null && !"".equals(searIdFrom)){ + //当天请了产假 + if(checkHasMaternityLeave(leaveType,dateString,userid)) { + //非休息班次 + if (!rest_serial_id.equals(searIdFrom)) { + result = floatAdd(result, "1"); + } + } + } + } +// result = floatAdd(result,floatAdd(workdays,allocateWorkDays)); + return result; + } + + /** + * 获取 日期范围内 假期天数 + * @param leaveType + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static String getLeaveTypeDays(String leaveType,String fromdate, String todate,String userid){ + String result = "0"; + RecordSet rs = new RecordSet(); + + String halfdays = "0"; + String halfbackdays = "0"; + + // 假 时长 + rs.executeQuery("select sum(duration) as count from kq_flow_split_leave where belongdate >= ? and belongdate <= ? and newleavetype in ("+ leaveType +") and resourceid = ? ",fromdate,todate,userid); + while(rs.next()){ + halfdays = Util.null2o(rs.getString("count")); + } + + // 销假时长 + rs.executeQuery("select sum(duration) as count from kq_flow_split_leaveback where belongdate >= ? and belongdate <= ? and newleavetype in ("+ leaveType +") and resourceid = ? ",fromdate,todate,userid); + while(rs.next()){ + halfbackdays = Util.null2o(rs.getString("count")); + } + + result = floatSubtract(halfdays,halfbackdays); + + return result; + } + + /** + * 判断日期范围内是否 有产假 + * @param leaveType + * @param fromdate + * @param userid + * @return + */ + public static boolean checkHasMaternityLeave(String leaveType,String fromdate,String userid){ + boolean bool = false; + String result = "0"; + RecordSet rs = new RecordSet(); + + String halfdays = "0"; + String halfbackdays = "0"; + + // 假 时长 + rs.executeQuery("select sum(duration) as count from kq_flow_split_leave where belongdate = ? and newleavetype in ("+ leaveType +") and resourceid = ? ",fromdate,userid); + while(rs.next()){ + halfdays = Util.null2o(rs.getString("count")); + } + + // 销假时长 + rs.executeQuery("select sum(duration) as count from kq_flow_split_leaveback where belongdate = ? and newleavetype in ("+ leaveType +") and resourceid = ? ",fromdate,userid); + while(rs.next()){ + halfbackdays = Util.null2o(rs.getString("count")); + } + + result = floatSubtract(halfdays,halfbackdays); + if(floatCompare(result,"0") > 0){ + bool = true; + } + return bool; + } + + /** + * 获取 产假天数(薪酬用) + * 职级为1和2:取标准产假天数 + * 职级不是1和2:【周一到周五】产假天数+【周六周日】调配工作日产假天数-【周一到周五】调配休息日产假天数 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static double getMaternityLeaveDaySalary(String fromdate, String todate,String userid){ + double result = 0.00; + RecordSet rs = new RecordSet(); + //职级 + int positionRank = getPositionRank(getPositionRankId(fromdate,todate,userid)); + // 产假 + String maternity_leave_id = rs.getPropValue("hrm_kqreport","maternity_leave_id"); + + if (positionRank == 1 || positionRank == 2) { + result = Double.valueOf(getLeaveTypeDays(maternity_leave_id,fromdate,todate,userid)); + }else{ + result = Double.valueOf(getRestLeaveDaysSalary(maternity_leave_id,fromdate,todate,userid)); + } + return result; + } + + /** + * 计算两个时间字符串日期的相差天数 + * + * @param sStartDate 字符串时间1 + * @param sEndDate 字符串时间2 + * @return 相差时间 + */ + public static int getDays(String sStartDate, String sEndDate) { + int days = 0; + try { + if (!"".equals(sStartDate) && !"".equals(sEndDate)) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + Date date1 = sdf.parse(sStartDate); + Date date2 = sdf.parse(sEndDate); + + long Days = (date2.getTime() - date1.getTime()) / (24*3600*1000); + if(Days < 0){ + days = 0; + }else{ + days = (int)Days+1; + } + } + }catch (Exception e){ + e.printStackTrace(); + } + return days; + } + + /** + * 计算天数 + * @param date1 日期 + * @param date2 日期 + * @return 天数 + */ + public static int calculateDays(Date date1, Date date2) { + Calendar cal1 = Calendar.getInstance(); + cal1.setTime(date1); + Calendar cal2 = Calendar.getInstance(); + cal2.setTime(date2); + int day1 = cal1.get(Calendar.DAY_OF_YEAR); + int day2 = cal2.get(Calendar.DAY_OF_YEAR); + int year1 = cal1.get(Calendar.YEAR); + int year2 = cal2.get(Calendar.YEAR); + if (year1 != year2) {//不同 年 + int timeDistance = 0; + if (year1 < year2) {//后面日期年大于前面日期 + for (int i = year1; i < year2; i++) { + if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {//闰年 + timeDistance += 366; + } else {//不是闰年 + timeDistance += 365; + } + } + } else { + for (int i = year2; i < year1; i++) { + if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {//闰年 + timeDistance += 366; + } else {//不是闰年 + timeDistance += 365; + timeDistance = 0 - timeDistance; + } + } + } + return timeDistance + (day2 - day1); + } else {//同一年 + return day2 - day1; + } + } + + /** + * @param a 任意数 + * @return 是 + */ + private static String isZero(String a) { + if (a==null || "".equals(a)) { + a = "0"; + } + return a; + } + + /** + * 大小比较 + * + * @param a + * @param b + * @return -1 小于 0 等于 1 大于 + */ + public static int floatCompare(String a, String b) { + a = isZero(a); + b = isZero(b); + BigDecimal bg1 = new BigDecimal(a); + BigDecimal bg2 = new BigDecimal(b); + return bg1.compareTo(bg2); + } + + /** + * 方法描述 : 对两个字符串进行金额的相加 + * @param a + * @param b + * @return + * String + */ + public static String floatAdd(String a, String b) { + a=a.equals("")?"0":a; + b=b.equals("")?"0":b; + BigDecimal bg1 = new BigDecimal(a); + BigDecimal bg2 = new BigDecimal(b); + BigDecimal bd = bg1.add(bg2); + return bd.toString(); + } + + /** + * + * 方法描述 : 对两个字符串进行金额的相减 + * @param a + * @param b + * @return + * String + */ + public static String floatSubtract(String a, String b) { + a=a.equals("")?"0":a; + b=b.equals("")?"0":b; + BigDecimal bg1 = new BigDecimal(a); + BigDecimal bg2 = new BigDecimal(b); + BigDecimal bd = bg1.subtract(bg2); + return bd.toString(); + } + + /** + * + * 方法描述 : 对两个字符串进行金额的相乘 + * @param a + * @param b + * @return + * String + */ + public static String floatMultiply(String a, String b) { + a=a.equals("")?"0":a; + b=b.equals("")?"0":b; + BigDecimal bg1 = new BigDecimal(a); + BigDecimal bg2 = new BigDecimal(b); + BigDecimal bd = bg1.multiply(bg2).setScale(4, BigDecimal.ROUND_HALF_UP); + return bd.toString(); + } + + /** + * + * 方法描述 : 对两个字符串进行金额的相除(默认保留两位小数) + * @param a + * @param b + * @return + * String + */ + public static String floatDivide(String a, String b) { + a=a.equals("")?"0":a; + b=b.equals("")?"0":b; + BigDecimal bg1 = new BigDecimal(a); + BigDecimal bg2 = new BigDecimal(b); + BigDecimal bd = bg1.divide(bg2, 2, BigDecimal.ROUND_HALF_UP); + return bd.toString(); + } + + /** + * 判断当月有几天 + * @param Year int 2020 + * @param Month int 8 + * @return + */ + public static int getMonthDays(String Year, String Month) { + int year = Integer.parseInt(Year); + int month = Integer.parseInt(Month); + if (month == 2) { + if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) { + return 29; + } else { + return 28; + } + } else if (month == 4 || month == 6 || month == 9 || month == 11) { + return 30; + } else { + return 31; + } + } + + /** + * 比较时间的大小 + * @param a + * @param b + * @return + * @throws ParseException + */ + public static boolean compareDate(String a, String b){ + boolean bool = false; + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + try { + long t1 = sdf.parse(a).getTime(); + long t2 = sdf.parse(b).getTime(); + if (t1 >= t2) { + bool = true; + } + return bool; + }catch (Exception e){ + e.printStackTrace(); + } + return bool; + } + + /** + * 获取 旷工天数(薪酬调整前) + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static double getAbsenteeismDaysBeforeSalaryBefore(String fromdate, String todate,String userid){ + double result = 0.00; + RecordSet rs = new RecordSet(); + // 薪资调整日期 + String salaryAdjustDate = getSalaryAdjustDate(fromdate,todate,userid); + if(salaryAdjustDate != null && !"".equals(salaryAdjustDate)){ + if(belongCalendar(salaryAdjustDate,fromdate,todate)) { + rs.executeQuery("select sum(absenteeism) as days from kq_format_total " + + " where resourceid = ? and kqdate >= ? and kqdate < ? ", userid, fromdate, salaryAdjustDate); + while (rs.next()) { + result = Util.getDoubleValue(rs.getString("days"), 0.00); + } + } +// rs.executeQuery("select sum(absenteeism) as days from kq_format_total "+ +// " where resourceid = ? and kqdate >= ? and kqdate < ? ",userid,fromdate,salaryAdjustDate); +// while(rs.next()){ +// result = Util.getDoubleValue(rs.getString("days"),0.00); +// } + } + return result; + } + + /** + * 获取 旷工天数(薪酬调整后) + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static double getAbsenteeismDaysAfterSalaryAfter(String fromdate, String todate,String userid){ + double result = 0.00; + RecordSet rs = new RecordSet(); + // 薪资调整日期 + String salaryAdjustDate = getSalaryAdjustDate(fromdate,todate,userid); + if(salaryAdjustDate != null && !"".equals(salaryAdjustDate)){ + if(belongCalendar(salaryAdjustDate,fromdate,todate)) { + rs.executeQuery("select sum(absenteeism) as days from kq_format_total " + + " where resourceid = ? and kqdate >= ? and kqdate <= ? ", userid, salaryAdjustDate, todate); + while (rs.next()) { + result = Util.getDoubleValue(rs.getString("days"), 0.00); + } + }else{ + rs.executeQuery("select sum(absenteeism) as days from kq_format_total " + + " where resourceid = ? and kqdate >= ? and kqdate <= ? ", userid, fromdate, todate); + while (rs.next()) { + result = Util.getDoubleValue(rs.getString("days"), 0.00); + } + } + }else{ + rs.executeQuery("select sum(absenteeism) as days from kq_format_total "+ + " where resourceid = ? and kqdate >= ? and kqdate <= ? ",userid,fromdate,todate); + while(rs.next()){ + result = Util.getDoubleValue(rs.getString("days"),0.00); + } + } + return result; + } + + /** + * 获取 旷工次数 调整前旷工天数+调整后旷工天数 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static double getAbsenteeismDays(String fromdate, String todate,String userid){ + // 调整前旷工天数 + double absenteeismDaysBeforeSalary = getAbsenteeismDaysBeforeSalaryBefore(fromdate,todate,userid); + // 调整后旷工天数 + double absenteeismDaysAfterSalary = getAbsenteeismDaysAfterSalaryAfter(fromdate,todate,userid); + // 漏签、 计0.5天旷工 + double forgotcheckabsenteeismdays = getForgotCheckAbsenteeismDaysAfter(fromdate,todate,userid); + // 严重迟到、严重早退 计0.5天旷工 + double gravebelateleaveearlydays = getGraveBeLateLeaveEarlyDaysAfter(fromdate,todate,userid); + + return absenteeismDaysBeforeSalary + absenteeismDaysAfterSalary + forgotcheckabsenteeismdays + gravebelateleaveearlydays; + } + + /** + * 获取 每次漏签、严重迟到、严重早退 计0.5天旷工 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static double getForgotCheckAbsenteeismDaysBefore(String fromdate, String todate,String userid){ + double result = 0.00; + RecordSet rs = new RecordSet(); + rs.executeQuery("select sum(forgotCheck)+sum(forgotBeginWorkCheck) as count from kq_format_total "+ + " where resourceid = ? and kqdate >= ? and kqdate < ? ",userid,fromdate,todate); + while(rs.next()){ + String count = Util.null2o(rs.getString("count")); + result = Double.valueOf(floatMultiply(count,"0.5")); + } + return result; + } + + /** + * 获取 每次漏签、严重迟到、严重早退 计0.5天旷工 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static double getForgotCheckAbsenteeismDaysAfter(String fromdate, String todate,String userid){ + double result = 0.00; + RecordSet rs = new RecordSet(); + rs.executeQuery("select sum(forgotCheck)+sum(forgotBeginWorkCheck) as count from kq_format_total "+ + " where resourceid = ? and kqdate >= ? and kqdate <= ? ",userid,fromdate,todate); + while(rs.next()){ + String count = Util.null2o(rs.getString("count")); + result = Double.valueOf(floatMultiply(count,"0.5")); + } + return result; + } + + /** + * 获取 每次严重迟到/早退 0.5天旷工 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static double getGraveBeLateLeaveEarlyDaysBefore(String fromdate, String todate,String userid){ + double result = 0.00; + RecordSet rs = new RecordSet(); + rs.executeQuery("select sum(gravebelate)+sum(graveleaveearly) as count from kq_format_total "+ + " where resourceid = ? and kqdate >= ? and kqdate <= ? ",userid,fromdate,todate); + while(rs.next()){ + String count = Util.null2o(rs.getString("count")); + result = Double.valueOf(floatMultiply(count,"0.5")); + } + return result; + } + + /** + * 获取 每次严重迟到/早退 0.5天旷工 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static double getGraveBeLateLeaveEarlyDaysAfter(String fromdate, String todate,String userid){ + double result = 0.00; + RecordSet rs = new RecordSet(); + rs.executeQuery("select sum(gravebelate)+sum(graveleaveearly) as count from kq_format_total "+ + " where resourceid = ? and kqdate >= ? and kqdate <= ? ",userid,fromdate,todate); + while(rs.next()){ + String count = Util.null2o(rs.getString("count")); + result = Double.valueOf(floatMultiply(count,"0.5")); + } + return result; + } + + /** + * 获取 旷工天数(薪酬调整前)总计 取薪酬调动日期调整前的旷工天数(旷工+漏签+严重迟到/早退) + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static double getAbsenteeismDaysCountBeforeSalary(String fromdate, String todate,String userid){ + double result = 0.00; + + // 薪酬调动日期调整前的旷工天数 +// double absenteeismDaysBeforeSalary = getAbsenteeismDaysAfterSalaryAfter(fromdate, todate, userid); + // 每次漏签计0.5天旷工 + double forgotDays = getForgotCheckAbsenteeismDaysBefore(fromdate, todate, userid); + // 每次 严重迟到/早退每次计0.5天旷工 + double belateearlydays = getGraveBeLateLeaveEarlyDaysBefore(fromdate, todate, userid); + +// result = Double.valueOf(floatAdd(String.valueOf(absenteeismDaysBeforeSalary), floatAdd(String.valueOf(forgotDays), String.valueOf(belateearlydays)))); + result = Double.valueOf(floatAdd(String.valueOf(forgotDays), String.valueOf(belateearlydays))); + return result; + } + + /** + * 获取 旷工天数(薪酬调整后)总计 取薪酬调动日期调整前的旷工天数(旷工+漏签+严重迟到/早退) + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static double getAbsenteeismDaysCountAfterSalary(String fromdate, String todate,String userid){ + double result = 0.00; + + // 薪酬调动日期调整前的旷工天数 + double absenteeismDaysBeforeSalary = getAbsenteeismDaysAfterSalaryAfter(fromdate, todate, userid); + // 每次漏签计0.5天旷工 + double forgotDays = getForgotCheckAbsenteeismDaysBefore(fromdate, todate, userid); + // 每次 严重迟到/早退每次计0.5天旷工 + double belateearlydays = getGraveBeLateLeaveEarlyDaysBefore(fromdate, todate, userid); + + result = Double.valueOf(floatAdd(String.valueOf(absenteeismDaysBeforeSalary), floatAdd(String.valueOf(forgotDays), String.valueOf(belateearlydays)))); + return result; + } + + /** + * 获取 法定(公众假日)天数 + * @param companystartdate + * @param fromDate + * @param toDate + * @param groupid + * @return + */ + public static String getPublicHolidays(String companystartdate,String fromDate, String toDate,String groupid,String userid){ + String result = "0"; + RecordSet rs = new RecordSet(); + // 产假 + String maternity_leave_id = rs.getPropValue("hrm_kqreport","maternity_leave_id"); + // 工伤假 + String injuryLeave_leave_id = rs.getPropValue("hrm_kqreport","injuryLeave_leave_id"); + // 离职日期 + String terminationdate = getTerminationDate(userid); + if(compareDate(toDate,terminationdate)){ + toDate = terminationdate; + } + rs.executeQuery("select * from KQ_HolidaySet where holidayDate between ? and ? and changeType=1 and groupid = ?",fromDate,toDate,groupid); + while(rs.next()){ + String holidayDate = Util.null2String(rs.getString("holidayDate")); + //产假天数 + String maternityLeaveTypeDay = getLeaveTypeDays(maternity_leave_id,holidayDate,holidayDate,userid); + //工伤假天数 + String injuryLeaveLeaveTypeDay = getLeaveTypeDays(injuryLeave_leave_id,holidayDate,holidayDate,userid); + if(compareDate(holidayDate,companystartdate)){ + result = floatAdd(result,"1"); + } + if(floatCompare(maternityLeaveTypeDay,"0")==1){ + result = floatSubtract(result,"1"); + } + if(floatCompare(injuryLeaveLeaveTypeDay,"0")==1){ + result = floatSubtract(result,"1"); + } + } + return result; + } + + /** + * 获取 入职日期 = 人力资源表 companystartdate 字段 + * @param userid + * @return + */ + public static String getCompanyStartDate(String userid){ + String result = ""; + RecordSet rs = new RecordSet(); + rs.executeQuery("select companystartdate from hrmresource where id = ?",userid); + if(rs.next()){ + result = Util.null2String(rs.getString("companystartdate")); + } + return result; + } + + /** + * 获取 转正日期 + * @param userid + * @return + */ + public static String getComfirmDate(String userid){ + String result = ""; + RecordSet rs = new RecordSet(); + String zzrq_fieldid = rs.getPropValue("hrm_kqreport","zzrq_fieldid"); + String zzrq = getWorkCusFieldValue(userid,zzrq_fieldid); + if(zzrq != null && !"".equals(zzrq)){ + result = zzrq; + } + return result; + } + + /** + * 获取 工作信息里的 自定义字段的 值 + * @param userid + * @return + */ + public static String getWorkCusFieldValue(String userid,String fieldid){ + String result = ""; + RecordSet rs = new RecordSet(); + rs.executeQuery("select "+ fieldid +" from cus_fielddata where scope='HrmCustomFieldByInfoType' and scopeid='3' and id=?",userid); + if(rs.next()){ + result = Util.null2String(rs.getString(fieldid)); + } + return result; + } + + /** + * 获取 分部 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static String getSubcompany(String fromdate,String todate,String userid){ + String result = ""; + RecordSet rs = new RecordSet(); + //日期范围内是否有异动 + boolean hasTransaction = checkHasTransactionDate(fromdate,todate,userid); + if(hasTransaction){ + String fieldid = getSnapShotData("SUBCOMPANYID1",fromdate,todate,userid); + result = new SubCompanyComInfo().getSubCompanyname(fieldid); + }else { + rs.executeQuery("select subcompanyid1 from hrmresource where id = ?", userid); + if (rs.next()) { + String subcomid = Util.null2String(rs.getString("subcompanyid1")); + result = new SubCompanyComInfo().getSubCompanyname(subcomid); + } + + } + return result; + } + + /** + * 获取 部门 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static String getDepartment(String fromdate,String todate,String userid){ + String result = ""; + RecordSet rs = new RecordSet(); + //日期范围内是否有异动 + boolean hasTransaction = checkHasTransactionDate(fromdate,todate,userid); + if(hasTransaction){ + String fieldid = getSnapShotData("DEPARTMENTID",fromdate,todate,userid); + result = new DepartmentComInfo().getDepartmentname(fieldid); + }else { + rs.executeQuery("select departmentid from hrmresource where id = ?", userid); + if (rs.next()) { + String subcomid = Util.null2String(rs.getString("departmentid")); + result = new DepartmentComInfo().getDepartmentname(subcomid); + } + } + return result; + } + + /** + * 获取 异动日期 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static String getTransactionDate(String fromdate,String todate,String userid){ + String result = ""; + RecordSet rs = new RecordSet(); + rs.executeQuery("select top 1 ydsj from formtable_main_75 where ygxm = ? and ydsj >= ? and ydsj <= ? order by ydsj desc",userid,fromdate,todate); + if(rs.next()){ + result = Util.null2String(rs.getString("ydsj")); + } + return result; + } + + /** + * 获取 离职日期 + * @param userid + * @return + */ + public static String getTerminationDate(String userid){ + String result = ""; + RecordSet rs = new RecordSet(); + String lzrq_fieldid = rs.getPropValue("hrm_kqreport","lzrq_fieldid"); + String lzrq = getWorkCusFieldValue(userid,lzrq_fieldid); + if(lzrq != null && !"".equals(lzrq)){ + result = lzrq; + } + return result; + } + + /** + * 获取 片区 + * @param userid + * @return + */ + public static String getArea(String userid){ + String result = ""; + RecordSet rs = new RecordSet(); + String area_fieldid = rs.getPropValue("hrm_kqreport","area_fieldid"); + // 片区 + rs.executeQuery("select distinct "+ area_fieldid +" from cus_fielddata where scope='HrmCustomFieldByInfoType' and scopeid=-1 and id = ?",userid); + if(rs.next()){ + String areaid = Util.null2String(rs.getString(area_fieldid)); + if(areaid != null && !"".equals(areaid)){ + result = new SubCompanyComInfo().getSubCompanyname(areaid); + } + } + return result; + } + + /** + * 获取 岗位名称 + * @param areaid + * @return + */ + public static String getPositionName(String areaid){ + String result = ""; + RecordSet rs = new RecordSet(); + rs.executeQuery("select * from uf_xcbz where id = ?",areaid); + if(rs.next()){ + result = Util.null2String(rs.getString("gwmc")); + } + return result; + } + + /** + * 获取 岗位名称 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static String getPosition(String fromdate,String todate,String userid){ + String result = ""; + RecordSet rs = new RecordSet(); + String position_fieldid = rs.getPropValue("hrm_kqreport","position_fieldid"); + //日期范围内是否有异动 + boolean hasTransaction = checkHasTransactionDate(fromdate,todate,userid); + if(hasTransaction){ + String fieldid = getSnapShotData("FIELD128",fromdate,todate,userid); + result = getPositionName(fieldid); + }else { + // 岗位名称 + rs.executeQuery("select distinct " + position_fieldid + " from cus_fielddata where scope='HrmCustomFieldByInfoType' and scopeid=-1 and id = ?", userid); + if (rs.next()) { + String positionid = Util.null2String(rs.getString(position_fieldid)); + if (positionid != null && !"".equals(positionid)) { + result = getPositionName(positionid); + } + } + } + return result; + } + + /** + * 获取 快照 里的 字段信息 + * @param type + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static String getSnapShotData(String type,String fromdate,String todate,String userid){ + String result = ""; + RecordSet rs = new RecordSet(); + rs.executeQuery("select "+type+" from hrsa_hrm_snapshot where employee_id = ? and cast(snapshot_time as DATE) between ? and ? ",userid,fromdate,todate); + if(rs.next()){ + result = Util.null2String(rs.getString(type)); + } + return result; + } + + /** + * 获取 日期范围内是否有异动 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static boolean checkHasTransactionDate(String fromdate,String todate,String userid){ + boolean result = false; + RecordSet rs = new RecordSet(); + rs.executeQuery("select top 1 ydsj from formtable_main_75 where ygxm = ? and ydsj >= ? and ydsj <= ? order by ydsj desc",userid,fromdate,todate); + if(rs.next()){ + result = true; + } + return result; + } + + /** + * 获取 职等职级 id + * @param userid + */ + public static int getPositionRankId(String fromdate,String todate,String userid){ + int result = 0; + RecordSet rs = new RecordSet(); + //日期范围内是否有异动 + boolean hasTransaction = checkHasTransactionDate(fromdate,todate,userid); + if(hasTransaction){ + String fieldid = getSnapShotData("FIELD1",fromdate,todate,userid); + if (fieldid != null && !"".equals(fieldid)) { + result = Integer.parseInt(fieldid.split("_")[1]); + } + }else { + rs.executeQuery("select field1 from cus_fielddata where scope='HrmCustomFieldByInfoType' and scopeid=-1 and field1 is not null and field1 <> '' and id = ?", userid); + if (rs.next()) { + String field1 = Util.null2String(rs.getString("field1")); + if (field1 != null && !"".equals(field1)) { + result = Integer.parseInt(field1.split("_")[1]); + } + } + } + return result; + } + + /** + * 获取 岗位职级 + * @param mxid + * @return + */ + public static int getPositionRank(int mxid){ + int result = 0; + RecordSet rs = new RecordSet(); + rs.executeQuery("select gwzj from uf_zdzj_new where id = ?",mxid); + if(rs.next()){ + result = Util.getIntValue(rs.getString("gwzj")); + } + return result; + } + + /** + * 获取 应出勤天数 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static double getWorkDays(String fromdate,String todate,String userid){ + double result = 0.00; + int positionRank = getPositionRank(getPositionRankId(fromdate,todate,userid)); + // 对于职级为1和2的员工,应出勤天数默认为当月自然日的总天数 + // 对于不是这两个职级的员工,应出勤天数为:应出勤天数+法定节假日天数;若当月无法定节假日,就默认应出勤天数 + if(positionRank == 1 || positionRank == 2 || positionRank == 0){ + result = Double.valueOf(getDays(fromdate,todate)); + }else{ + result = Double.valueOf(getSpecialWorkDays(fromdate,todate,userid)); + } + return result; + } + + /** + * 应出勤天数为:应出勤天数+法定节假日天数;若当月无法定节假日,就默认应出勤天数 + * 周一到周五的天数 + 周六周日的调配工作日 - 周一到周五的调配休息日 = 最终的天数 + * @param fromDate + * @param toDate + * @param userid + * @return + */ + public static String getSpecialWorkDays(String fromDate,String toDate,String userid){ + String result = "0"; + RecordSet rs = new RecordSet(); + String groupid = rs.getPropValue("hrm_kqreport","the_top_groupid"); + // 周六或周日天数 + String weekdays = "0"; + // 周一到周五天数 + String workdays = "0"; + // 调配休息日天数 + String allocateRestDays = "0"; + // 调配工作日天数 + String allocateWorkDays = "0"; + // 格式化日期 + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); +// rs.executeQuery("select distinct groupid,kqdate from kq_format_total " + +// " where resourceid = ? and kqdate >= ? and kqdate <= ?",userid,fromDate,toDate); +// while(rs.next()){ +// // +// String dateString = Util.null2String(rs.getString("kqdate")); +// // 是 周六或 周日 +// if (isSaturdayOrSunday(dateString)) { +// //是调配工作日 +// if (isAllocateWorkDay(groupid, dateString)) { +// allocateWorkDays = floatAdd(allocateWorkDays,"1"); +// } +// //是公众假日 +// if(isAllocateHolidayDay(groupid, dateString)){ +// allocateWorkDays = floatAdd(allocateWorkDays,"1"); +// } +// } else { +// // 是 调配休息日 +// if(isAllocateRestDay(groupid,dateString)){ +// allocateRestDays = floatAdd(allocateRestDays,"1"); +// } +// workdays = floatAdd(workdays,"1"); +// } +// } + + String[] dateStartArr = parseDate(fromDate); + String[] dateEndtArr = parseDate(toDate); + LocalDate startDate = LocalDate.of(Integer.parseInt(dateStartArr[0]), Integer.parseInt(dateStartArr[1]), Integer.parseInt(dateStartArr[2])); + LocalDate endDate = LocalDate.of(Integer.parseInt(dateEndtArr[0]), Integer.parseInt(dateEndtArr[1]), Integer.parseInt(dateEndtArr[2])); + // 遍历日期范围 + for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) { + // 输出格式化后的日期字符串 + String dateString = date.format(formatter); + // 是 周六或 周日 + if (isSaturdayOrSunday(dateString)) { + //是调配工作日 + if (isAllocateWorkDay(groupid, dateString)) { + allocateWorkDays = floatAdd(allocateWorkDays,"1"); + } + //是公众假日 + if(isAllocateHolidayDay(groupid, dateString)){ + allocateWorkDays = floatAdd(allocateWorkDays,"1"); + } + } else { + // 是 调配休息日 + if(isAllocateRestDay(groupid,dateString)){ + allocateRestDays = floatAdd(allocateRestDays,"1"); + } + workdays = floatAdd(workdays,"1"); + } + } + result = floatAdd(result,floatSubtract(floatAdd(workdays,allocateWorkDays),allocateRestDays)); + return result; + } + + /** + * 获取 薪酬调整日期、转正日期、入职日期 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static String getSalaryAdjustDate(String fromdate,String todate,String userid){ + String result = ""; + RecordSet rs = new RecordSet(); + RecordSet rs1 = new RecordSet(); + RecordSet rs2 = new RecordSet(); + String txrq = ""; + String zzrq = ""; + String rzrq = ""; + rs.executeQuery("select txrq from uf_ygxcda where yg = ? and txrq >= ? and txrq <= ? and dxyy != '入职' ",userid,fromdate,todate); + if(rs.next()){ + txrq = Util.null2String(rs.getString("txrq")); + } + rs1.executeQuery("select shjg as zzrq from uf_ygzzxx where lczt = '2' and xm = ? ",userid); + if(rs1.next()){ + zzrq = Util.null2String(rs1.getString("zzrq")); + } + rs2.executeQuery("select companystartdate from hrmresource where id = ?",userid); + if(rs2.next()){ + rzrq = Util.null2String(rs2.getString("companystartdate")); + } + if(txrq != null && !"".equals(txrq)){ + result = txrq; + }else if(zzrq != null && !"".equals(zzrq)){ + result = zzrq; + }else if(rzrq != null && !"".equals(rzrq)){ + result = rzrq; + } + return result; + } + + /** + * 获取 指定假期的时长 + * @param type + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static String getLeaveDaysBefore(int type,String fromdate,String todate,String userid){ + String result = "0"; + RecordSet rs = new RecordSet(); + String halfdays = "0"; + String halfbackdays = "0"; + // 假期 时长 + rs.executeQuery("select sum(duration) as count from kq_flow_split_leave where belongdate >= ? and belongdate < ? and newleavetype in ("+ type +") and resourceid = ? ",fromdate,todate,userid); + while(rs.next()){ + halfdays = Util.null2o(rs.getString("count")); + } + // 销假时长 + rs.executeQuery("select sum(duration) as count from kq_flow_split_leaveback where belongdate >= ? and belongdate < ? and newleavetype in ("+ type +") and resourceid = ? ",fromdate,todate,userid); + while(rs.next()){ + halfbackdays = Util.null2o(rs.getString("count")); + } + result = floatSubtract(halfdays,halfbackdays); + return result; + } + + /** + * 获取 指定假期的时长 + * @param type + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static String getLeaveDaysAfter(int type,String fromdate,String todate,String userid){ + String result = "0"; + RecordSet rs = new RecordSet(); + String halfdays = "0"; + String halfbackdays = "0"; + KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo(); + // 假期 时长 + rs.executeQuery("select resourceid, newleavetype, durationrule, sum(duration) as val from kq_flow_split_leave where belongdate >= ? and belongdate <= ? and newleavetype in ("+ type +") and resourceid = ? " + + " group by resourceid, newleavetype, durationrule",fromdate,todate,userid); + while(rs.next()){ + String newleavetype = rs.getString("newleavetype"); + String durationrule = rs.getString("durationrule"); + double value = rs.getDouble("val")<0?0:rs.getDouble("val"); + double proportion = Util.getDoubleValue(kqLeaveRulesComInfo.getProportion(newleavetype)); + if(KQUnitBiz.isLeaveHour(newleavetype, kqLeaveRulesComInfo)){//按小时 + if(!KQUnitBiz.isLeaveHour(durationrule)){ + if(proportion>0) value = value*proportion; + } + }else{//按天 + if(KQUnitBiz.isLeaveHour(durationrule)){ + if(proportion>0) value = value/proportion; + } + } + halfdays = String.valueOf(value); + } + // 销假时长 + rs.executeQuery("select resourceid, newleavetype, durationrule, sum(duration) as val from kq_flow_split_leaveback where belongdate >= ? and belongdate <= ? and newleavetype in ("+ type +") and resourceid = ? " + + " group by resourceid, newleavetype, durationrule",fromdate,todate,userid); + while(rs.next()){ + String newleavetype = rs.getString("newleavetype"); + String durationrule = rs.getString("durationrule"); + double value = rs.getDouble("val")<0?0:rs.getDouble("val"); + double proportion = Util.getDoubleValue(kqLeaveRulesComInfo.getProportion(newleavetype)); + if(KQUnitBiz.isLeaveHour(newleavetype, kqLeaveRulesComInfo)){//按小时 + if(!KQUnitBiz.isLeaveHour(durationrule)){ + if(proportion>0) value = value*proportion; + } + }else{//按天 + if(KQUnitBiz.isLeaveHour(durationrule)){ + if(proportion>0) value = value/proportion; + } + } + halfbackdays = String.valueOf(value); + } + result = floatSubtract(halfdays,halfbackdays); + return result; + } + + /** + * 获取 哺乳假的假期的时长 + * @param type + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static String getBreastfeedLeaveDays(int type,String fromdate,String todate,String userid){ + String result = "0"; + RecordSet rs1 = new RecordSet(); + String breastfeeddays = "0"; + String breastfeedbackdays = "0"; + //班次id + String serialid = getSerialId(fromdate,todate,userid); + String serialHours = getHoursBySerial(serialid); + + // 哺乳假 时长 + rs1.executeQuery("select sum(duration) as count from kq_flow_split_leave where belongDate >= ? and belongdate <= ? and newleavetype in ("+ type +") and resourceid = ? group by resourceid",fromdate,todate,userid); + while(rs1.next()){ + breastfeeddays = Util.null2o(rs1.getString("count")); + } + // 哺乳假 销假时长 + rs1.executeQuery("select sum(duration) as count from kq_flow_split_leave where belongDate >= ? and belongdate <= ? and newleavetype in ("+ type +") and resourceid = ? group by resourceid",fromdate,todate,userid); + while(rs1.next()){ + breastfeedbackdays = Util.null2o(rs1.getString("count")); + } + String breastdays = floatSubtract(breastfeeddays,breastfeedbackdays); + + if(floatCompare(serialHours,"0") > 0) { + String breadt_days = floatDivide(breastdays, serialHours); + result = floatAdd(result, breadt_days); + } + return result; + } + + /** + * 获取班次对应的工作时长 分钟数 转换为 小时 + * @param serialid + * @return + */ + public static String getHoursBySerial(String serialid){ + String result = ""; + RecordSet rs = new RecordSet(); + rs.executeQuery("select * from kq_ShiftManagement where id=?",serialid); + if(rs.next()) { + String worktime = Util.null2o(rs.getString("worktime")); + result = floatDivide(worktime,"60"); + } + return result; + } + + /** + * 获取 实际出勤天数(薪酬调整前) + * 对于职级为1和2的员工,实际出勤天数(标准)+带薪假(病、年、产、陪产、婚、丧、探亲、哺乳、调休)+迟到小时数(换算成班次所在天数)-每次漏签、严重迟到、严重早退 计0.5天旷工+休息班次 + * 对于不是这两个职级的员工,实际出勤天数(标准)+带薪假(病、年、产、陪产、婚、丧、探亲、哺乳、调休)+迟到小时数(换算成班次所在天数)-每次漏签、严重迟到、严重早退 计0.5天旷工+公众假日(当前日期范围内要有班次的) + * 病假 按半天请假 + * 年假 按半天请假 + * 产假 按半天请假 + * 陪产假 按半天请假 + * 婚假 按半天请假 + * 丧假 按半天请假 + * 探亲假 按半天请假 + * 哺乳假 按小时请假 + * 调休假 按半天请假 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static double getAttendDaysBeforeSalary(String fromdate,String todate,String userid){ + double result = 0.00; + RecordSet rs = new RecordSet(); + String attendancedays = "0"; + String publicHolidays = "0"; + // 入职日期 + String companystartdate = getCompanyStartDate(userid); + int positionRank = getPositionRank(getPositionRankId(fromdate,todate,userid)); + // 薪资调整日期 + String salaryAdjustDate = getSalaryAdjustDate(fromdate,todate,userid); + if(salaryAdjustDate != null && !"".equals(salaryAdjustDate)){ + if(belongCalendarBefore(salaryAdjustDate,fromdate,todate)) { + // 实际出勤天数(标准) + rs.executeQuery("select sum(attendancedays)as days from kq_format_total " + + " where resourceid = ? and kqdate >= ? and kqdate < ? and attendanceMins is not null and attendanceMins > 0 and absenteeismmins = 0", userid, fromdate, salaryAdjustDate); + while (rs.next()) { + attendancedays = Util.null2o(rs.getString("days")); + } + rs.writeLog("========= 实际出勤天数(薪酬调整前) 实际出勤天数 ======== "+ attendancedays); + + // 法定(公众假日)天数 + rs.executeQuery("select distinct groupid from kq_format_total " + + " where resourceid = ? and kqdate >= ? and kqdate < ?", userid, fromdate, todate); + while (rs.next()) { + String groupid = Util.null2String(rs.getString("groupid")); + // 法定(公众假日)天数 + publicHolidays = getPublicHolidays(companystartdate, fromdate, salaryAdjustDate, groupid, userid); + } + rs.writeLog("========= 实际出勤天数(薪酬调整前) 法定(公众假日)天数 ======== "+ publicHolidays); + + // 休息班 天数 + String restdays = getRestSerialDaysBefore(fromdate, salaryAdjustDate, userid); + + rs.writeLog("========= 实际出勤天数(薪酬调整前) 休息班 天数 ======== "+ restdays); + + // 假期 天数 + String attendLeaveDays = getAttendLeaveDaysBefore(fromdate, salaryAdjustDate, userid); + + rs.writeLog("========= 实际出勤天数(薪酬调整前) 假期 天数 ======== "+ attendLeaveDays); + + String days = floatAdd(attendancedays, attendLeaveDays); + + // 每次漏签、 计0.5天旷工 天数 + String forgotdays = String.valueOf(getAbsenteeismDaysCountBeforeSalary(fromdate, salaryAdjustDate, userid)); + days = floatSubtract(days, forgotdays); + + // 对于职级为1和2的员工,实际出勤天数(标准)+带薪假(病、年、产、陪产、婚、丧、探亲、哺乳、调休)+迟到小时数(换算成班次所在天数)-漏签次数*0.5+休息班次 + // 对于不是这两个职级的员工,实际出勤天数(标准)+带薪假(病、年、产、陪产、婚、丧、探亲、哺乳、调休)+迟到小时数(换算成班次所在天数)-漏签次数*0.5+公众假日(当前日期范围内要有班次的) + if (positionRank == 1 || positionRank == 2) { + result = Double.valueOf(floatAdd(days,restdays)); + } else if (positionRank == 0) { + result = Double.valueOf(floatSubtract(attendLeaveDays, forgotdays)); + } else { + result = Double.valueOf(floatAdd(days, publicHolidays)); + } + } + } + if(result < 0){ + result = 0.00; + } + return result; + } + + /** + * 获取 请假 时长 + * @param fromDate + * @param toDate + * @param userid + * @return + */ + public static String getLeaveHours(String fromDate, String toDate,String userid){ + String result = "0"; + RecordSet rs = new RecordSet(); + String serialid = getSerialId(fromDate,toDate,userid); + String serial_hours = getHoursBySerial(serialid); + rs.executeQuery("select SUM(duration)as count,durationrule,resourceid from kq_flow_split_leave where 1=1 and belongdate between ? and ? and resourceid = ? group by durationrule,resourceid",fromDate,toDate,userid); + while(rs.next()){ + String count = Util.null2o(rs.getString("count")); + // 1-按天请假、2-按半天请假、3-按小时请假、4-按整天请假、5-按半小时请假、6-按整小时请假 + int durationrule = Util.getIntValue(rs.getString("durationrule")); + // 按天,需要 乘以 每天的班次的小时 + if(durationrule == 1 || durationrule == 2 || durationrule == 4){ + result = floatMultiply(count,serial_hours); + }else{ +// // 按小时 +// if(durationrule == 3){ + result = count; + } + } + return result; + } + + /** + * 获取 实际出勤天数(薪酬调整后) + * 对于职级为1和2的员工,实际出勤天数(标准)+带薪假(病、年、产、陪产、婚、丧、探亲、哺乳、调休)+迟到小时数(换算成班次所在天数)-漏签次数*0.5+休息班次 + * 对于不是这两个职级的员工,实际出勤天数(标准)+带薪假(病、年、产、陪产、婚、丧、探亲、哺乳、调休)+迟到小时数(换算成班次所在天数)-漏签次数*0.5+公众假日(当前日期范围内要有班次的) + * 病假 按半天请假 + * 年假 按半天请假 + * 产假 按半天请假 + * 陪产假 按半天请假 + * 婚假 按半天请假 + * 丧假 按半天请假 + * 探亲假 按半天请假 + * 哺乳假 按小时请假 + * 调休假 按半天请假 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static double getAttendDaysAfterSalary(String fromdate,String todate,String userid){ + double result = 0.00; + RecordSet rs = new RecordSet(); + String attendancedays = "0"; + String publicHolidays = "0"; + // 应出勤天数 + double requiredworkdays = 0.00; + int positionRank = getPositionRank(getPositionRankId(fromdate,todate,userid)); + // 入职日期 + String companystartdate = getCompanyStartDate(userid); + String salaryattencedays = "0"; + rs.executeQuery("select sum(attendancedays)as days from kq_format_total " + + " where resourceid = ? and kqdate >= ? and kqdate <= ? and attendanceMins is not null and attendanceMins > 0 and absenteeismmins = 0",userid,fromdate,todate); + while(rs.next()){ + attendancedays = Util.null2o(rs.getString("days")); + } + // 薪资调整日期 + String salaryAdjustDate = getSalaryAdjustDate(fromdate,todate,userid); + rs.writeLog("========= 薪资调整日期 ======== "+ salaryAdjustDate); + // 应出勤天数 + requiredworkdays = getWorkDays(fromdate, todate, userid); + if(salaryAdjustDate != null && !"".equals(salaryAdjustDate)){ + if(belongCalendar(salaryAdjustDate,fromdate,todate)) { + + rs.writeLog("========= 应出勤天数 ======== "+ requiredworkdays); + + rs.executeQuery("select sum(attendancedays)as days from kq_format_total " + + " where resourceid = ? and kqdate >= ? and kqdate <= ? and attendanceMins is not null and attendanceMins > 0 and absenteeismmins = 0", userid, salaryAdjustDate, todate); + while (rs.next()) { + salaryattencedays = Util.null2o(rs.getString("days")); + } + rs.writeLog("========= 实际出勤天数 ======== "+ salaryattencedays); + + // 法定(公众假日)天数 + rs.executeQuery("select distinct groupid from kq_format_total " + + " where resourceid = ? and kqdate >= ? and kqdate <= ?", userid, fromdate, todate); + while (rs.next()) { + String groupid = Util.null2String(rs.getString("groupid")); + // 法定(公众假日)天数 + publicHolidays = getPublicHolidays(companystartdate, salaryAdjustDate, todate, groupid, userid); + } + rs.writeLog("========= 法定(公众假日)天数 ======== "+ publicHolidays); + + // 休息班 天数 + String restdays = getRestSerialDaysAfter(salaryAdjustDate, todate, userid); + rs.writeLog("========= 休息班 天数 ======== "+ restdays); + + // 假期 天数 + String attendLeaveDays = getAttendLeaveDaysAfter(salaryAdjustDate, todate, userid); + rs.writeLog("========= 假期 天数 ======== "+ attendLeaveDays); + + String days = floatAdd(salaryattencedays, attendLeaveDays); + +// // 迟到 天数 +// String latedays = getLateDaysAfter(salaryAdjustDate, todate, userid); +// days = floatAdd(days, latedays); +// +// // 早退 天数 +// String leaveearlydays = getLeaveEarlyDaysAfter(fromdate, salaryAdjustDate, userid); +// days = floatAdd(days, leaveearlydays); + + // 漏签 天数 + String forgotdays = String.valueOf(getAbsenteeismDaysCountBeforeSalary(salaryAdjustDate, todate, userid)); + days = floatSubtract(days, forgotdays); + +// // 严重迟到/严重早退 天数 +// String gravelateleavedays = String.valueOf(getGraveBeLateLeaveEarlyDaysAfter(salaryAdjustDate, todate, userid)); +// days = floatSubtract(days, gravelateleavedays); + + if (positionRank == 1 || positionRank == 2) { + result = Double.valueOf(floatAdd(days,restdays)); + } else { + if(positionRank == 0){ + result = Double.valueOf(days); + }else { + result = Double.valueOf(floatAdd(days, publicHolidays)); + } + } + }else{ + // 应出勤天数 + requiredworkdays = getWorkDays(fromdate,todate,userid); + + // 法定(公众假日)天数 + rs.executeQuery("select distinct groupid from kq_format_total " + + " where resourceid = ? and kqdate >= ? and kqdate <= ?",userid,fromdate,todate); + while(rs.next()){ + String groupid = Util.null2String(rs.getString("groupid")); + // 法定(公众假日)天数 + publicHolidays = getPublicHolidays(companystartdate,fromdate,todate,groupid,userid); + } + // 休息班 天数 + String restdays = getRestSerialDaysAfter(fromdate,todate,userid); + rs.writeLog("========= 休息班 天数 ======== "+ restdays); + + // 假期 天数 + String attendLeaveDays = getAttendLeaveDaysAfter(fromdate,todate,userid); + rs.writeLog("========= 假期 天数 ======== "+ attendLeaveDays); + + String days = floatAdd(attendancedays,attendLeaveDays); + +// // 迟到 天数 +// String latedays = getLateDaysAfter(fromdate,todate,userid); +// days = floatAdd(days,latedays); +// +// // 早退 天数 +// String leaveearlydays = getLeaveEarlyDaysAfter(fromdate,todate,userid); +// days = floatAdd(days,leaveearlydays); + + // 漏签 天数 + String forgotdays = String.valueOf(getAbsenteeismDaysCountBeforeSalary(fromdate,todate,userid)); + days = floatSubtract(days,forgotdays); + +// // 严重迟到/严重早退 天数 +// String gravelateleavedays = String.valueOf(getGraveBeLateLeaveEarlyDaysAfter(fromdate,todate,userid)); +// days = floatSubtract(days,gravelateleavedays); + + if(positionRank == 1 || positionRank == 2){ + result = Double.valueOf(floatAdd(days,restdays)); + }else{ + if(positionRank == 0){ + result = Double.valueOf(days); + }else { + result = Double.valueOf(floatAdd(days, publicHolidays)); + } + } + } + }else{ + // 应出勤天数 + requiredworkdays = getWorkDays(fromdate,todate,userid); + + // 法定(公众假日)天数 + rs.executeQuery("select distinct groupid from kq_format_total " + + " where resourceid = ? and kqdate >= ? and kqdate <= ?",userid,fromdate,todate); + while(rs.next()){ + String groupid = Util.null2String(rs.getString("groupid")); + // 法定(公众假日)天数 + publicHolidays = getPublicHolidays(companystartdate,fromdate,todate,groupid,userid); + } + // 休息班 天数 + String restdays = getRestSerialDaysAfter(fromdate,todate,userid); + + // 假期 天数 + String attendLeaveDays = getAttendLeaveDaysAfter(fromdate,todate,userid); + + String days = floatAdd(attendancedays,attendLeaveDays); + +// // 迟到 天数 +// String latedays = getLateDaysAfter(fromdate,todate,userid); +// days = floatAdd(days,latedays); +// +// // 早退 天数 +// String leaveearlydays = getLeaveEarlyDaysAfter(fromdate,todate,userid); +// days = floatAdd(days,leaveearlydays); + + // 漏签 天数 + String forgotdays = String.valueOf(getAbsenteeismDaysCountBeforeSalary(fromdate,todate,userid)); + days = floatSubtract(days,forgotdays); + +// // 严重迟到/严重早退 天数 +// String gravelateleavedays = String.valueOf(getGraveBeLateLeaveEarlyDaysAfter(fromdate,todate,userid)); +// days = floatSubtract(days,gravelateleavedays); + + if(positionRank == 1 || positionRank == 2){ + result = Double.valueOf(floatAdd(days,restdays)); + }else{ + if(positionRank == 0){ + result = Double.valueOf(days); + }else { + result = Double.valueOf(floatAdd(days, publicHolidays)); + } + } + } + + //实际出勤天数(薪酬调整前) + double attenddaysbeforesalary = getAttendDaysBeforeSalary(fromdate,todate,userid); + // 大于 应出勤天数 + if(result > requiredworkdays){ + result = requiredworkdays; + }else{ + if(attenddaysbeforesalary+result > requiredworkdays){ + double chae = attenddaysbeforesalary+result-requiredworkdays; + result = result - chae; + } + } + return result; + } + + /** + * 判断 当天是否请了产假 + * @param date + * @param userid + * @return + */ + public static boolean checkIsRestLeaveDay(String date,String userid){ + boolean bool = false; + RecordSet rs = new RecordSet(); + // 产假 + String maternity_leave_id = rs.getPropValue("hrm_kqreport","maternity_leave_id"); + rs.executeQuery("select id from kq_flow_split_leave where belongdate = ? and newleavetype in ("+ maternity_leave_id +") and resourceid = ? ",date,userid); + while(rs.next()){ + bool = true; + } + return bool; + } + + /** + * 获取 请假天数 + * + * 病假 按半天请假 + * 年假 按半天请假 + * 产假 按半天请假 + * 陪产假 按半天请假 + * 婚假 按半天请假 + * 丧假 按半天请假 + * 探亲假 按半天请假 + * 哺乳假 按小时请假 + * 调休假 按半天请假 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static String getAttendLeaveDaysBefore(String fromdate,String todate,String userid){ + String result = "0"; + RecordSet rs = new RecordSet(); + RecordSet rs1 = new RecordSet(); + String halfdays = "0"; + String halfbackdays = "0"; + String breastfeeddays = "0"; + String breastfeedbackdays = "0"; + // 病假 年假 产假 陪产假 婚假 丧假 探亲假 调休假 + String halfday_leave_ids = rs.getPropValue("hrm_kqreport","halfday_leave_ids"); + // 哺乳假 + String breastfeed_leave_id = rs.getPropValue("hrm_kqreport","breastfeed_leave_id"); + + // 病假 年假 陪产假 婚假 丧假 探亲假 时长 + rs.executeQuery("select sum(duration) as count from kq_flow_split_leave where belongdate >= ? and belongdate < ? and newleavetype in ("+ halfday_leave_ids +") and resourceid = ? ",fromdate,todate,userid); + while(rs.next()){ + halfdays = Util.null2o(rs.getString("count")); + } + + // 病假 年假 陪产假 婚假 丧假 探亲假 销假时长 + rs.executeQuery("select sum(duration) as count from kq_flow_split_leaveback where belongdate >= ? and belongdate < ? and newleavetype in ("+ halfday_leave_ids +") and resourceid = ? ",fromdate,todate,userid); + while(rs.next()){ + halfbackdays = Util.null2o(rs.getString("count")); + } + + result = floatSubtract(halfdays,halfbackdays); + +// //班次id +// String serialid = getSerialId(fromdate,todate,userid); +// String serialHours = getHoursBySerial(serialid); +// +// // 哺乳假 时长 +// rs1.executeQuery("select sum(duration) as count from kq_flow_split_leave where belongDate >= ? and belongdate < ? and newleavetype in ("+ breastfeed_leave_id +") and resourceid = ? group by resourceid",fromdate,todate,userid); +// while(rs1.next()){ +// breastfeeddays = Util.null2o(rs1.getString("count")); +// } +// // 哺乳假 销假时长 +// rs1.executeQuery("select sum(duration) as count from kq_flow_split_leave where belongDate >= ? and belongdate < ? and newleavetype in ("+ breastfeed_leave_id +") and resourceid = ? group by resourceid",fromdate,todate,userid); +// while(rs1.next()){ +// breastfeedbackdays = Util.null2o(rs1.getString("count")); +// } +// +// String breastdays = floatSubtract(breastfeeddays,breastfeedbackdays); +// +// if(floatCompare(serialHours,"0") > 0){ +// String breadt_days = floatDivide(breastdays,serialHours); +// result = floatAdd(result,breadt_days); +// } + + return result; + } + + /** + * 获取 请假天数 + * + * 病假 按半天请假 + * 年假 按半天请假 + * 产假 按半天请假 + * 陪产假 按半天请假 + * 婚假 按半天请假 + * 丧假 按半天请假 + * 探亲假 按半天请假 + * 哺乳假 按小时请假 + * 调休假 按半天请假 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static String getAttendLeaveDaysAfter(String fromdate,String todate,String userid){ + String result = "0"; + RecordSet rs = new RecordSet(); + RecordSet rs1 = new RecordSet(); + String halfdays = "0"; + String halfbackdays = "0"; + String breastfeeddays = "0"; + String breastfeedbackdays = "0"; + // 病假 年假 产假 陪产假 婚假 丧假 探亲假 调休假 + String halfday_leave_ids = rs.getPropValue("hrm_kqreport","halfday_leave_ids"); + // 哺乳假 + String breastfeed_leave_id = rs.getPropValue("hrm_kqreport","breastfeed_leave_id"); + + // 病假 年假 陪产假 婚假 丧假 探亲假 时长 + rs.executeQuery("select sum(duration) as count from kq_flow_split_leave where belongdate >= ? and belongdate <= ? and newleavetype in ("+ halfday_leave_ids +") and resourceid = ? ",fromdate,todate,userid); + while(rs.next()){ + halfdays = Util.null2o(rs.getString("count")); + } + + // 病假 年假 陪产假 婚假 丧假 探亲假 销假时长 + rs.executeQuery("select sum(duration) as count from kq_flow_split_leaveback where belongdate >= ? and belongdate <= ? and newleavetype in ("+ halfday_leave_ids +") and resourceid = ? ",fromdate,todate,userid); + while(rs.next()){ + halfbackdays = Util.null2o(rs.getString("count")); + } + + result = floatSubtract(halfdays,halfbackdays); + +// //班次id +// String serialid = getSerialId(fromdate,todate,userid); +// String serialHours = getHoursBySerial(serialid); +// +// // 哺乳假 时长 +// rs1.executeQuery("select sum(duration) as count from kq_flow_split_leave where belongDate >= ? and belongdate <= ? and newleavetype in ("+ breastfeed_leave_id +") and resourceid = ? group by resourceid",fromdate,todate,userid); +// while(rs1.next()){ +// breastfeeddays = Util.null2o(rs1.getString("count")); +// } +// // 哺乳假 销假时长 +// rs1.executeQuery("select sum(duration) as count from kq_flow_split_leaveback where belongDate >= ? and belongdate <= ? and newleavetype in ("+ breastfeed_leave_id +") and resourceid = ? group by resourceid",fromdate,todate,userid); +// while(rs1.next()){ +// breastfeedbackdays = Util.null2o(rs1.getString("count")); +// } +// +// String breastdays = floatSubtract(breastfeeddays,breastfeedbackdays); +// +// if(floatCompare(serialHours,"0") > 0){ +// String breadt_days = floatDivide(breastdays,serialHours); +// result = floatAdd(result,breadt_days); +// } + + return result; + } + + /** + * 获取 假期天数(调薪前) + * @param leavetype + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static double getBeforeSalaryLeaveDays(int leavetype,String fromdate,String todate,String userid){ + double result = 0.00; + // 薪资调整日期 + String salaryAdjustDate = getSalaryAdjustDate(fromdate,todate,userid); + if(salaryAdjustDate != null && !"".equals(salaryAdjustDate)){ + if(belongCalendar(salaryAdjustDate,fromdate,todate)) { + String leavedays = getLeaveDaysBefore(leavetype, fromdate, salaryAdjustDate, userid); + result = Double.valueOf(leavedays); + } + } + return result; + } + + /** + * 获取 假期天数(调薪后) + * @param leavetype + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static double getAfterSalaryLeaveDays(int leavetype,String fromdate,String todate,String userid){ + double result = 0.00; + // 薪资调整日期 + String salaryAdjustDate = getSalaryAdjustDate(fromdate,todate,userid); + if(salaryAdjustDate != null && !"".equals(salaryAdjustDate)){ + if(belongCalendar(salaryAdjustDate,fromdate,todate)) { + String leavedays = getLeaveDaysAfter(leavetype, salaryAdjustDate, todate, userid); + result = Double.valueOf(leavedays); + }else{ + String leavedays = getLeaveDaysAfter(leavetype, fromdate, todate, userid); + result = Double.valueOf(leavedays); + } + }else{ + String leavedays = getLeaveDaysAfter(leavetype,fromdate,todate,userid); + result = Double.valueOf(leavedays); + } + return result; + } + + /** + * 获取 迟到 天数 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static String getLateDaysBefore(String fromdate,String todate,String userid){ + String result = "0"; + RecordSet rs = new RecordSet(); + String serialid = getSerialId(fromdate,todate,userid); + String serial_hours = getHoursBySerial(serialid); + // 迟到 + rs.executeQuery("select sum(belatemins) as count from kq_format_total where kqdate >= ? and kqdate < ? and resourceid = ? ",fromdate,todate,userid); + while(rs.next()){ + String latemins = Util.null2o(rs.getString("count")); + String latehours = floatDivide(latemins,"60"); + if(floatCompare(serial_hours,"0") > 0){ + result = floatDivide(latehours,serial_hours); + } + } + return result; + } + + /** + * 获取 迟到 天数 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static String getLateDaysAfter(String fromdate,String todate,String userid){ + String result = "0"; + RecordSet rs = new RecordSet(); + String serialid = getSerialId(fromdate,todate,userid); + String serial_hours = getHoursBySerial(serialid); + // 迟到 + rs.executeQuery("select sum(belatemins) as count from kq_format_total where kqdate >= ? and kqdate <= ? and resourceid = ? ",fromdate,todate,userid); + while(rs.next()){ + String latemins = Util.null2o(rs.getString("count")); + String latehours = floatDivide(latemins,"60"); + if(floatCompare(serial_hours,"0") > 0){ + result = floatDivide(latehours,serial_hours); + } + } + return result; + } + + /** + * 获取 早退 天数 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static String getLeaveEarlyDaysBefore(String fromdate,String todate,String userid){ + String result = "0"; + RecordSet rs = new RecordSet(); + String serialid = getSerialId(fromdate,todate,userid); + String serial_hours = getHoursBySerial(serialid); + // 早退 + rs.executeQuery("select sum(leaveearlymins) as count from kq_format_total where kqdate >= ? and kqdate < ? and resourceid = ? ",fromdate,todate,userid); + while(rs.next()){ + String latemins = Util.null2o(rs.getString("count")); + String latehours = floatDivide(latemins,"60"); + if(floatCompare(serial_hours,"0") > 0){ + result = floatDivide(latehours,serial_hours); + } + } + return result; + } + + /** + * 获取 早退 天数 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static String getLeaveEarlyDaysAfter(String fromdate,String todate,String userid){ + String result = "0"; + RecordSet rs = new RecordSet(); + String serialid = getSerialId(fromdate,todate,userid); + String serial_hours = getHoursBySerial(serialid); + // 早退 + rs.executeQuery("select sum(leaveearlymins) as count from kq_format_total where kqdate >= ? and kqdate <= ? and resourceid = ? ",fromdate,todate,userid); + while(rs.next()){ + String latemins = Util.null2o(rs.getString("count")); + String latehours = floatDivide(latemins,"60"); + if(floatCompare(serial_hours,"0") > 0){ + result = floatDivide(latehours,serial_hours); + } + } + return result; + } + + /** + * 获取 休息班次 天数 + * @param fromDate + * @param toDate + * @param userid + * @return + */ + public static String getRestSerialDaysBefore(String fromDate, String toDate,String userid){ + String result = "0"; + RecordSet rs = new RecordSet(); + KQGroupMemberComInfo groupMemberComInfo = new KQGroupMemberComInfo(); + String rest_serial_id = rs.getPropValue("hrm_kqreport","rest_serial_id"); + String rest2_serial_id = rs.getPropValue("hrm_kqreport","rest2_serial_id"); + rs.executeQuery("select count(resourceid) as count from kq_format_detail where kqdate >= ? and kqdate < ? and resourceid = ? and serialid = ?",fromDate,toDate,userid,rest_serial_id); + while(rs.next()){ + result = Util.null2o(rs.getString("count")); + } + rs.executeQuery("select * from kq_format_total " + + " where resourceid = ? and kqdate >= ? and kqdate <= ? and serialid = ?",userid,fromDate,toDate,rest2_serial_id); + while(rs.next()) { + String groupid = Util.null2String(rs.getString("groupid")); + String kqdate = Util.null2String(rs.getString("kqdate")); + KQGroupEntity kqGroupEntity = groupMemberComInfo.getUserKQGroupInfo(userid,kqdate); + if(kqGroupEntity!=null) { + String kqtype = kqGroupEntity.getKqtype(); + //固定班制 + if ("1".equals(kqtype)) { + if (isHolidayOrRelaxDay(groupid, kqdate)) { + result = floatAdd(result, "1"); + } + } + } + } + return result; + } + + /** + * 获取 休息班次 天数 + * @param fromDate + * @param toDate + * @param userid + * @return + */ + public static String getRestSerialDaysAfter(String fromDate, String toDate,String userid){ + String result = "0"; + RecordSet rs = new RecordSet(); + KQGroupMemberComInfo groupMemberComInfo = new KQGroupMemberComInfo(); + String rest_serial_id = rs.getPropValue("hrm_kqreport","rest_serial_id"); + String rest2_serial_id = rs.getPropValue("hrm_kqreport","rest2_serial_id"); + rs.executeQuery("select * from kq_format_detail where kqdate >= ? and kqdate <= ? and resourceid = ? and serialid = ? ",fromDate,toDate,userid,rest_serial_id); + while(rs.next()){ + String kqdate = Util.null2String(rs.getString("kqdate")); + //不是请了产假 + if(!checkIsRestLeaveDay(kqdate,userid)){ + result = floatAdd(result, "1"); + } + } + rs.executeQuery("select * from kq_format_total " + + " where resourceid = ? and kqdate >= ? and kqdate <= ? and serialid = ?",userid,fromDate,toDate,rest2_serial_id); + while(rs.next()) { + String groupid = Util.null2String(rs.getString("groupid")); + String kqdate = Util.null2String(rs.getString("kqdate")); + KQGroupEntity kqGroupEntity = groupMemberComInfo.getUserKQGroupInfo(userid,kqdate); + if(kqGroupEntity!=null) { + String kqtype = kqGroupEntity.getKqtype(); + //固定班制 + if ("1".equals(kqtype)) { + if (isHolidayOrRelaxDay(groupid, kqdate)) { + //不是请了产假 + if(!checkIsRestLeaveDay(kqdate,userid)){ + result = floatAdd(result, "1"); + } + } + } + } + } + return result; + } + + /** + * 获取 班次id + * @param fromDate + * @param toDate + * @param userid + * @return + */ + public static String getSerialId(String fromDate, String toDate,String userid){ + String result = ""; + RecordSet rs = new RecordSet(); + rs.executeQuery("select distinct a.serialid from kq_format_total a,kq_ShiftManagement b " + + " where a.serialid=b.id and a.resourceid = ? and a.kqdate >= ? and a.kqdate <= ? and b.is_rest=0 ",userid,fromDate,toDate); + while(rs.next()){ + result = Util.null2String(rs.getString("serialid")); + } + return result; + } + + /** + * 判断 指定天数 是否是 公众假日 true 是 false 否 + * @param groupid + * @param date + * @return + */ + public static boolean isHolidayOrRelaxDay(String groupid,String date){ + boolean bool = false; + RecordSet rs = new RecordSet(); + rs.executeQuery("select * from kq_HolidaySet where groupid=? and holidayDate=?",groupid,date); + while(rs.next()){ + // 1-公众假日 2-调配工作日 3-调配休息日 + int changeType = Util.getIntValue(rs.getString("changeType")); + if(changeType == 1 || changeType == 3){ + bool = true; + } + } + return bool; + } + + /** + * 判断 指定天数 是否是 调配休息日 true 是 false 否 + * @param groupid + * @param date + * @return + */ + public static boolean isAllocateRestDay(String groupid,String date){ + boolean bool = false; + RecordSet rs = new RecordSet(); + rs.executeQuery("select * from kq_HolidaySet where groupid=? and holidayDate=?",groupid,date); + while(rs.next()){ + // 1-公众假日 2-调配工作日 3-调配休息日 + int changeType = Util.getIntValue(rs.getString("changeType")); + if(changeType == 3){ + bool = true; + } + } + return bool; + } + + /** + * 判断 指定天数 是否是 调配工作日 true 是 false 否 + * @param groupid + * @param date + * @return + */ + public static boolean isAllocateWorkDay(String groupid,String date){ + boolean bool = false; + RecordSet rs = new RecordSet(); + rs.executeQuery("select * from kq_HolidaySet where groupid=? and holidayDate=?",groupid,date); + while(rs.next()){ + // 1-公众假日 2-调配工作日 3-调配休息日 + int changeType = Util.getIntValue(rs.getString("changeType")); + if(changeType == 2){ + bool = true; + } + } + return bool; + } + + /** + * 判断 指定天数 是否是 调配工作日 true 是 false 否 + * @param groupid + * @param date + * @return + */ + public static boolean isAllocateHolidayDay(String groupid,String date){ + boolean bool = false; + RecordSet rs = new RecordSet(); + rs.executeQuery("select * from kq_HolidaySet where groupid=? and holidayDate=?",groupid,date); + while(rs.next()){ + // 1-公众假日 2-调配工作日 3-调配休息日 + int changeType = Util.getIntValue(rs.getString("changeType")); + if(changeType == 1){ + bool = true; + } + } + return bool; + } + + private static String[] parseDate(String date){ + if (StringUtils.isEmpty(date)) { + return new String[]{"1990", "1", "1"}; + } + try { + String[] split = date.split("-"); + List list = new ArrayList<>(Arrays.asList(split)); + // 只有年 + if (list.size() == 1) { + // 添加月 + list.add("1"); + // 添加日 + list.add("1"); + + } + // 只有年月 + else if (list.size() == 2) { + list.add("1"); + } + return list.toArray(new String[]{}); + }catch (Exception e){ + e.printStackTrace(); + } + return null; + } + + /** + * 判断 日期是否是 周六 或 周日 + * @param dateString + * @return + */ + public static boolean isSaturdayOrSunday(String dateString) { + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); + Date date = null; + boolean flag = false; + try { + date = format.parse(dateString); + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK); + if(dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY){ + flag = true; + } + } catch (ParseException e) { + e.printStackTrace(); + } + return flag; + } + + /** + * 判断一个时间是否在一个时间段内 + * + * @param nowTimee 指定时间 + * @param beginTimee 开始时间 + * @param endTimee 结束时间 + */ + public static boolean belongCalendarBefore(String nowTimee, String beginTimee, String endTimee) { + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); + Date nowTime = null; + Date beginTime = null; + Date endTime = null; + boolean b = false; + try { + nowTime = format.parse(nowTimee); + beginTime = format.parse(beginTimee); + endTime = format.parse(endTimee); + + Calendar date = Calendar.getInstance(); + date.setTime(nowTime); + Calendar begin = Calendar.getInstance(); + begin.setTime(beginTime); + Calendar end = Calendar.getInstance(); + end.setTime(endTime); + + if(nowTimee.equals(endTimee)){ + b = true; + }else if(date.after(begin) && date.before(end)){//在时间段内 + b = true; + } + } catch (Exception ex) { + ex.printStackTrace(); + } + return b; + } + + /** + * 判断一个时间是否在一个时间段内 + * + * @param nowTimee 指定时间 + * @param beginTimee 开始时间 + * @param endTimee 结束时间 + */ + public static boolean belongCalendar(String nowTimee, String beginTimee, String endTimee) { + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); + Date nowTime = null; + Date beginTime = null; + Date endTime = null; + boolean b = false; + try { + nowTime = format.parse(nowTimee); + beginTime = format.parse(beginTimee); + endTime = format.parse(endTimee); + + Calendar date = Calendar.getInstance(); + date.setTime(nowTime); + Calendar begin = Calendar.getInstance(); + begin.setTime(beginTime); + Calendar end = Calendar.getInstance(); + end.setTime(endTime); + + if(nowTimee.equals(endTimee) || nowTimee.equals(beginTimee)){ + b = true; + }else if(date.after(begin) && date.before(end)){//在时间段内 + b = true; + } + } catch (Exception ex) { + ex.printStackTrace(); + } + return b; + } + +%> + + + + + +

以下是 <%=username%> 的 相关数据展示

+ +

职级 <%=positionRank%>

+ +

班次id <%=serialid%>

+ +

【周一到周五】产假天数 <%=workdayss%>

+ +

【周一到周五】调配休息日产假天数 <%=allocateRestDays%>

+ +

【周六周日】调配工作日产假天数 <%=allocateWorkDays%>

+ +

产假天数(薪酬用) <%=maternityLeaveDaySalary%>

+ +

工伤假天数(薪酬用) <%=injuryLeaveDaysSalary%>

+ +

片区 <%=area%>

+ +

日期范围内是否有异动 <%=hasTransaction%>

+ +

分部 <%=subcompany%>

+ +

部门 <%=department%>

+ +

gwid <%=gwid%>

+ + +

岗位名称 <%=positionname%>

+ +

是否请了产假 <%=boo1l%>

+ +

入职日期 <%=companystartdate%>

+ +

转正日期 <%=comfirmdate%>

+ +

异动日期 <%=transactiondate%>

+ +

离职日期 <%=terminationdate%>

+ +

休息班天数 <%=restdays%>

+ +

标准的应出勤天数 <%=workdays%>

+ +

标准的实际出勤天数 <%=attendancedays%>

+ +

应出勤天数 <%=requiredworkdays%>

+ +

法定(公众假日)天数 <%=publicHolidays%>

+ +

薪资调整日期、转正日期、入职日期 <%=salaryAdjustDate%>

+ +

实际出勤天数(薪酬调整前) <%=attenddaysbeforesalary%>

+ +

实际出勤天数(薪酬调整后) <%=attendDaysAfterSalary%>

+ +

事假天数(薪酬调整前) <%=leaveabsencedaysbeforesalary%>

+ +

事假天数(薪酬调整后) <%=leaveabsencedaysaftersalary%>

+ +

病假天数(薪酬调整前) <%=sickleavedaysbeforesalary%>

+ +

病假天数(薪酬调整后) <%=sickleavedaysaftersalary%>

+ +

年假天数(薪酬调整前) <%=annualleavedaysbeforesalary%>

+ +

年假天数(薪酬调整后) <%=annualleavedaysaftersalary%>

+ +

陪产假天数(薪酬调整前) <%=paternityleavedaysbeforesalary%>

+ +

陪产假天数(薪酬调整后) <%=paternityleavedaysaftersalary%>

+ +

婚假天数(薪酬调整前) <%=marriageleavedaysbeforesalary%>

+ +

婚假天数(薪酬调整后) <%=marriageleavedaysaftersalary%>

+ +

丧假(薪酬调整前) <%=bereavementleavedaysbeforesalary%>

+ +

丧假天数(薪酬调整后) <%=bereavementleavedaysaftersalary%>

+ +

探亲假天数(薪酬调整前) <%=homeleavedaysbeforesalary%>

+ +

探亲假天数(薪酬调整后) <%=homeleavedaysaftersalary%>

+ +

哺乳假天数(薪酬调整前) <%=breastfeedleavedaysbeforesalary%>

+ +

哺乳假天数(薪酬调整后) <%=breastfeedleavedaysaftersalary%>

+ +

调休假天数(薪酬调整前) <%=compensatoryleavedaysbeforesalary%>

+ +

调休假天数(薪酬调整后) <%=compensatoryleavedaysaftersalary%>

+ +

产假天数(薪酬调整前) <%=maternityleavedaysbeforesalary%>

+ +

产假天数(薪酬调整后) <%=maternityleavedaysaftersalary%>

+ +

旷工天数(薪酬调整前) <%=absenteeismdaysbeforesalary%>

+ +

旷工天数(薪酬调整后) <%=absenteeismdaysaftersalary%>

+ +

旷工总计 <%=absenteeismdayscountbeforesalary%>

+ +<%--

旷工天数(薪酬调整后)总计 <%=absenteeismdayscountaftersalary%>

--%> + +

每次漏签计0.5天旷工 <%=forgotcheckabsenteeismdays%>

+ +

严重迟到/早退每次计0.5天旷工 <%=gravebelateleaveearlydays%>

+ +

旷工次数 <%=absenteeismdays%>

+ +

attendLeaveDays <%=attendLeaveDays%>

+ + \ No newline at end of file diff --git a/领悦二开new/interface/lingyue/do.jsp b/领悦二开new/interface/lingyue/do.jsp new file mode 100644 index 0000000..f01b8a8 --- /dev/null +++ b/领悦二开new/interface/lingyue/do.jsp @@ -0,0 +1,39 @@ +<%@ page import="com.alibaba.fastjson.JSONObject" %> +<%@ page import="com.alibaba.fastjson.JSONArray" %> +<%@ page import="weaver.general.Util" %> +<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> + +<% + int sum = 0; + + JSONObject json = new JSONObject(); + + JSONArray array = new JSONArray(); + + rs.executeQuery("select top 10 * from uf_kqjysdkjl"); + while(rs.next()){ + JSONObject jsonObject = new JSONObject(); + + String modedatacreatedate = Util.null2String(rs.getString("modedatacreatedate")); + + String modedatacreatetime = Util.null2String(rs.getString("modedatacreatetime")); + + jsonObject.put("modedatacreatedate",modedatacreatedate); + jsonObject.put("modedatacreatetime",modedatacreatetime); + + array.add(jsonObject); + } + + json.put("key",array); + +%> + + + +

Congratulation Mode 666666 !

+ +

sum <%=sum%>

+ +

json <%=json%>

+ + \ No newline at end of file diff --git a/领悦二开new/interface/lingyue/initSubAndDeptCode.jsp b/领悦二开new/interface/lingyue/initSubAndDeptCode.jsp new file mode 100644 index 0000000..12faff6 --- /dev/null +++ b/领悦二开new/interface/lingyue/initSubAndDeptCode.jsp @@ -0,0 +1,103 @@ +<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> +<%@page import="weaver.general.Util"%> +<%@ page import="java.math.BigDecimal" %> + + + + +<% + int sub_sum = 0; + + int dept_sum = 0; + + String lsh = "1"; + + rs.executeQuery("select * from hrmsubcompany where canceled is null order by showOrderOfTree"); + while(rs.next()){ + String mxid = Util.null2String(rs.getString("id")); + String newlsh = ""; + if(lsh.length() == 1){ + newlsh = "LY000"+lsh; + } + if(lsh.length() == 2){ + newlsh = "LY00"+lsh; + } + if(lsh.length() == 3){ + newlsh = "LY0"+lsh; + } + if(lsh.length() == 4){ + newlsh = "LY"+lsh; + } + boolean bool = rst.executeUpdate("update hrmsubcompany set subcompanycode=? where id = ?",newlsh,mxid); + if(bool){ + lsh = floatAdd(lsh,"1"); + sub_sum++; + } + + String lshh = "1"; + rs1.executeQuery("select * from hrmdepartment where canceled is null and subcompanyid1=? order by showOrderOfTree",mxid); + while(rs1.next()){ + String deptid = Util.null2String(rs1.getString("id")); + String newlshh = ""; + if(lshh.length() == 1){ + newlshh = newlsh+"000"+lshh; + } + if(lshh.length() == 2){ + newlshh = newlsh+"00"+lshh; + } + if(lshh.length() == 3){ + newlshh = newlsh+"0"+lshh; + } + if(lshh.length() == 4){ + newlshh = newlsh+lshh; + } + boolean booll = rss.executeUpdate("update hrmdepartment set departmentcode=? where id = ?",newlshh,deptid); + if(booll){ + lshh = floatAdd(lshh,"1"); + dept_sum++; + } + } + + } + + + + + + + + + +%> + +<%! + /** + * 方法描述 : 对两个字符串进行金额的相加 + * @param a + * @param b + * @return + * String + */ + public static String floatAdd(String a, String b) { + a=a.equals("")?"0":a; + b=b.equals("")?"0":b; + BigDecimal bg1 = new BigDecimal(a); + BigDecimal bg2 = new BigDecimal(b); + BigDecimal bd = bg1.add(bg2); + return bd.toString(); + } + +%> + + + + + + +

Congratulation Mode 666666 !

+ +

分部的 <%=sub_sum%>

+ +

部门的 <%=dept_sum%>

+ + \ No newline at end of file diff --git a/领悦二开new/interface/lingyue/initZkkq.jsp b/领悦二开new/interface/lingyue/initZkkq.jsp new file mode 100644 index 0000000..b7c33fb --- /dev/null +++ b/领悦二开new/interface/lingyue/initZkkq.jsp @@ -0,0 +1,254 @@ +<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> +<%@page import="weaver.general.Util"%> +<%@ page import="com.alibaba.fastjson.JSONObject" %> +<%@ page import="com.alibaba.fastjson.JSONArray" %> +<%@ page import="java.util.*" %> +<%@ page import="weaver.formmode.setup.ModeRightInfo" %> +<%@ page import="weaver.general.BaseBean" %> +<%@ page import="weaver.conn.RecordSet" %> +<%@ page import="org.apache.http.client.methods.CloseableHttpResponse" %> +<%@ page import="org.apache.http.impl.client.CloseableHttpClient" %> +<%@ page import="org.apache.http.impl.client.HttpClients" %> +<%@ page import="org.apache.http.client.methods.HttpPost" %> +<%@ page import="org.apache.http.entity.StringEntity" %> +<%@ page import="org.apache.http.HttpEntity" %> +<%@ page import="org.apache.http.util.EntityUtils" %> +<%@ page import="java.io.IOException" %> +<%@ page import="com.time.util.DateUtil" %> +<%@ page import="weaver.conn.BatchRecordSet" %> + + + +<% + int sum = 0; + + // 2024-08-01 第一条数据的 流水号 + + String index = "18190783"; + + int kq_number = 1; + + // 杨观明 id 14911 + String userid = "14765"; + + String url = Util.null2String(rs.getPropValue("hrm_zhongkong", "get_kqinfo_url")); + + String key = rs.getPropValue("hrm_zhongkong","key"); + url = url + "?key=" + key; + //考勤原始记录表模块id + String formmodeid = Util.null2String(rs.getPropValue("hrm_zhongkong", "zkkqjkqsj_formmodeid")); + String modedatacreater = "1"; //模块创建人id + String modedatacreatertype = "0"; //创建人类型(插入默认值0即可) + String modedatacreatedate = DateUtil.getCurrentTime("yyyy-MM-dd"); + String modedatacreatetime = DateUtil.getCurrentTime("HH:mm:ss"); + + List recordList = new ArrayList<>(); + + recordList.add("333"); + + Map userMap = getUserMap(userid); + + List> plist = new ArrayList<>(); + + rs.writeLog("SyncKqDataFromZKJob plist1:" + plist.size()); + rs.writeLog("SyncKqDataFromZKJob userMap:" + userMap.size()); + rs.writeLog("SyncKqDataFromZKJob recordList:" + recordList.size()); + + getTrafficRecords(plist,recordList,userMap,formmodeid, modedatacreater, modedatacreatertype, modedatacreatedate, modedatacreatetime, url, kq_number, index); + + rs.writeLog("SyncKqDataFromZKJob plist2:" + plist.size()); + + //批量插入建模数据 + StringBuffer sb = new StringBuffer(); + sb.append("insert into uf_kqjysdkjl("); + sb.append("MODEUUID,formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime,"); + sb.append("oary,kqsjid,pin,ename,deptnumber,deptname,checkdate,checktime,sn,alias"); + sb.append(")values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); + + BatchRecordSet batchRecordSet = new BatchRecordSet(); + batchRecordSet.executeBatchSql(sb.toString(), plist); + + + + //权限重构 + String sql = "select id from uf_kqjysdkjl where modedatacreatedate = '" + modedatacreatedate + "' and modedatacreatetime='" + modedatacreatetime + "'"; + rs.execute(sql); + while (rs.next()) { + int billid = Integer.parseInt(rs.getString("id")); + ModeRightInfo info = new ModeRightInfo(); + info.setNewRight(true); + info.rebuildModeDataShareByEdit(1, Integer.parseInt(formmodeid), billid); + } + + sum ++; + +%> + +<%! + /** + * 人员id以及自定义考勤编号字段 + * + * @return + */ + private static Map getUserMap(String userid) { + Map map = new HashMap<>(); + RecordSet rs = new RecordSet(); + String kq_fieldid = rs.getPropValue("hrm_zhongkong","kq_fieldid"); + String sql = "select a.id,b."+kq_fieldid+" as kqbh from hrmresource a left join cus_fielddata b on a.id=b.id where b.scope='HrmCustomFieldByInfoType' and a.status < 4 and b.scopeid=-1 and (b."+kq_fieldid+" != '' or b."+kq_fieldid+" is not null) and a.id=?"; + String id = ""; + String kqbh = ""; + rs.executeQuery(sql,userid); + while (rs.next()) { + id = Util.null2String(rs.getString("id")); + kqbh = Util.null2String(rs.getString("kqbh")); + map.put(kqbh, id); + } + return map; + } + + + /** + * post 请求 json格式 + * @param url + * @param headers + * @param stringJson + * @param encode + * @return + */ + public static String httpPostKqData(String url, Map headers, String stringJson, String encode){ + String result = ""; + if(encode == null){ + encode = "utf-8"; + } + RecordSet rs = new RecordSet(); + String content = null; + CloseableHttpResponse httpResponse = null; + CloseableHttpClient closeableHttpClient = null; + try { + closeableHttpClient = HttpClients.createDefault(); + HttpPost httpost = new HttpPost(url); + //设置header + httpost.setHeader("Content-type", "application/json"); + if (headers != null && headers.size() > 0) { + for (Map.Entry entry : headers.entrySet()) { + httpost.setHeader(entry.getKey(),entry.getValue()); + } + } + //组织请求参数 + StringEntity stringEntity = new StringEntity(stringJson, encode); + httpost.setEntity(stringEntity); + //响应信息 + httpResponse = closeableHttpClient.execute(httpost); + if(httpResponse != null) { + HttpEntity entity = httpResponse.getEntity(); + content = EntityUtils.toString(entity, encode); + if (content != null && !"".equals(content)) { + JSONObject json = JSONObject.parseObject(content); + result = json.toString(); + } + } + } catch (Exception e) { + e.printStackTrace(); + rs.writeLog(e); + }finally{ + try { + httpResponse.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + try { //关闭连接、释放资源 + closeableHttpClient.close(); + } catch (IOException e) { + e.printStackTrace(); + } + return result; + } + + private void getTrafficRecords(List> plist,List recordList,Map userMap,String formmodeid, String modedatacreater, String modedatacreatertype, String modedatacreatedate, String modedatacreatetime, String url, int kq_number, String maxid) { + BaseBean rs = new BaseBean(); + JSONObject requestBody = new JSONObject(); + requestBody.put("id", Integer.parseInt(maxid)); + requestBody.put("number", kq_number); + rs.writeLog("-SyncKqDataFromZKJob-url:" + url); + Map headers = new HashMap<>(); + String result = httpPostKqData(url,headers,requestBody.toString(),"utf-8"); + JSONObject resObj = JSONObject.parseObject(result); + + int ret = (int) resObj.get("ret"); + if (ret == 0) { + JSONObject data = (JSONObject) resObj.get("data"); + JSONArray listArr = (JSONArray) data.get("items"); + if (listArr.size() > 0) { + //插入数据到建模表 + for (int i = 0; i < listArr.size(); i++) { + JSONObject list = (JSONObject) listArr.get(i); + String id = Util.null2String(list.get("id")); + rs.writeLog("id:"+id); + if (recordList.contains(id)) { + continue; + } else { + //插入数据到建模表 + //考勤编号 + String kqbh = Util.null2String(list.get("pin")); + rs.writeLog("kqbh:"+kqbh); + //人员id + String userid = Util.null2String(userMap.get(kqbh)); + rs.writeLog("userid:"+userid); + if ("".equals(kqbh) || "".equals(userid)) { + userid = "-9999"; + } + + String datetime = Util.null2String(list.get("checktime")); + + String checkdate = Util.null2String(datetime.substring(0, 10)); + String checktime = Util.null2String(datetime.substring(11, 19)); + + String ename = Util.null2String(list.get("ename")); + String deptnumber = Util.null2String(list.get("deptnumber")); + String deptname = Util.null2String(list.get("deptname")); + String sn = Util.null2String(list.get("sn")); + String alias = Util.null2String(list.get("alias")); + + + List listobj = new ArrayList<>(); + listobj.add(UUID.randomUUID().toString()); + listobj.add(formmodeid); + listobj.add(modedatacreater); + listobj.add(modedatacreatertype); + listobj.add(modedatacreatedate); + listobj.add(modedatacreatetime); + + //业务字段 + listobj.add(userid); + listobj.add(id); + listobj.add(kqbh); + listobj.add(ename); + listobj.add(deptnumber); + listobj.add(deptname); + listobj.add(checkdate); + listobj.add(checktime); + listobj.add(sn); + listobj.add(alias); + + plist.add(listobj); + } + } + } + } + } + + +%> + + + + + + +

Congratulation Mode 666666 !

+ +

分部的 <%=sum%>

+ + + \ No newline at end of file diff --git a/领悦二开new/interface/lingyue/re_user.jsp b/领悦二开new/interface/lingyue/re_user.jsp new file mode 100644 index 0000000..369c464 --- /dev/null +++ b/领悦二开new/interface/lingyue/re_user.jsp @@ -0,0 +1,332 @@ +<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> +<%@page import="weaver.general.Util"%> +<%@ page import="com.alibaba.fastjson.JSONObject" %> +<%@ page import="com.alibaba.fastjson.JSONArray" %> +<%@ page import="java.util.*" %> +<%@ page import="weaver.conn.RecordSet" %> +<%@ page import="org.apache.http.client.methods.CloseableHttpResponse" %> +<%@ page import="org.apache.http.impl.client.CloseableHttpClient" %> +<%@ page import="org.apache.http.impl.client.HttpClients" %> +<%@ page import="org.apache.http.client.methods.HttpPost" %> +<%@ page import="org.apache.http.entity.StringEntity" %> +<%@ page import="org.apache.http.HttpEntity" %> +<%@ page import="org.apache.http.util.EntityUtils" %> +<%@ page import="java.io.IOException" %> +<%@ page import="weaver.hrm.company.DepartmentComInfo" %> +<%@ page import="weaver.hrm.resource.ResourceComInfo" %> + + + +<% + int add_sum = 0; + String add_message = ""; + int leave_sum = 0; + String leave_message = ""; + + String codes = ""; + + List list = new ArrayList<>(); + + String sql = "select a.*,b.createdate,b.createtime,b.lastoperatedate,b.lastoperatetime from formtable_main_72 a,workflow_requestbase b where a.requestid=b.requestid and b.currentnodetype=3"; + rs.executeQuery(sql); + while(rs.next()){ + //姓名 + String userid = Util.null2String(rs.getString("xm")); + list.add(userid); + + // 离职原因 + String lzyyid = Util.null2String(rs.getString("lzyy")); + String lzyyname = getLzyyname(lzyyid); + + // 离职类型 下拉框 0 - 主动 1 - 被动 + int lzlxid = Util.getIntValue(rs.getString("lzlx")); + int lzlx = -1; + if(lzlxid==0){ + lzlx = 2; + }else{ + lzlx = 1; + } + + // 最后离职日期 + String tyzhgzr = Util.null2String(rs.getString("tyzhgzr")); + + String createdate = Util.null2String(rs.getString("createdate")); + String createtime = Util.null2String(rs.getString("createtime")); + String lastoperatedate = Util.null2String(rs.getString("lastoperatedate")); + String lastoperatetime = Util.null2String(rs.getString("lastoperatetime")); + String lasttime = lastoperatetime.substring(0,5); + + //离职时间 + String leavetime = tyzhgzr+" "+lasttime; + + + String key = rs.getPropValue("hrm_zhongkong","key"); + String url = rs.getPropValue("hrm_zhongkong","add_update_user_url"); + url = url + "?key=" + key; + String leaveurl = rs.getPropValue("hrm_zhongkong","leave_user_url"); + leaveurl = leaveurl + "?key=" + key; + Map headers = new HashMap<>(); + JSONArray jsonArray = new JSONArray(); + JSONObject json_main = new JSONObject(); + JSONObject json_main_leave = new JSONObject(); + + rs1.executeQuery("select * from hrmresource where status=5 and id=?",userid); + rs1.next(); + String workcode = Util.null2String(rs1.getString("workcode")); + String lastname = Util.null2String(rs1.getString("lastname")); + String departmentid = Util.null2String(rs1.getString("departmentid")); + String mobile = Util.null2String(rs1.getString("mobile")); + String sex = Util.null2String(rs1.getString("sex")); + String certificatenum = Util.null2String(rs1.getString("certificatenum")); + String birthday = Util.null2String(rs1.getString("birthday")); + String companystartdate = Util.null2String(rs1.getString("companystartdate")); + + String pincode = ""; + String cuscode = getCusIdByUserid(userid); + if(cuscode != null && !"".equals(cuscode)){ + pincode = cuscode; + }else{ + pincode = workcode; + } + + codes += pincode+ ","; + + String deptcode = ""; + String sup_Deptcode = getDeptCuscode(departmentid); + if(sup_Deptcode != null && !"".equals(sup_Deptcode)){ + deptcode = sup_Deptcode; + }else{ + deptcode = new DepartmentComInfo().getDepartmentCode(departmentid); + } + + // 新增人员的 入参 + json_main.put("pin",pincode); + json_main.put("name",lastname); + json_main.put("deptnumber",deptcode); + json_main.put("mobile",mobile); + json_main.put("gender","0".equals(sex)?"M":"F"); + json_main.put("identitycard",certificatenum); + json_main.put("birthday",birthday); + json_main.put("hiredday",companystartdate); + + jsonArray.add(json_main); + rs.writeLog("========================== 新增或修改人员,同步至中控考勤机 ======================================"); + rs.writeLog(url+" ========= "+jsonArray.toString()); + + + // 人员离职的入参 + json_main_leave.put("pin",pincode); + json_main_leave.put("leavedate",leavetime); + json_main_leave.put("leavetype",lzlx); + json_main_leave.put("reason",lzyyname); + + int result = -1; + String msg = ""; + int result1 = -1; + String msg1 = ""; + +// String content = httpPost(url,headers,jsonArray.toString(),"utf-8"); +// if (content != null && !"".equals(content)) { +// JSONObject json = JSONObject.parseObject(content); +// rs.writeLog("============= httpPost pushInfo json =================== " + json); +// int resultt = Integer.parseInt(json.getString("ret")); +// if(resultt == 0){ +// result = 0; +// }else{ +// result = 1; +// } +// msg = Util.null2String(json.getString("msg")); +// } + +// if(result == 0){ +// add_sum++; +// add_message += lastname +" ====== add user result ========== "+ msg+", "; + + String contentt = httpPost(leaveurl,headers,json_main_leave.toString(),"utf-8"); + if (contentt != null && !"".equals(contentt)) { + JSONObject json = JSONObject.parseObject(contentt); + rs.writeLog("============= httpPost pushInfo json =================== " + json); + int resultt = Integer.parseInt(json.getString("ret")); + if(resultt == 0){ + result1 = 0; + }else{ + result1 = 1; + } + msg1 = Util.null2String(json.getString("msg")); + } + if(result1 == 0) { + leave_sum++; + leave_message += lastname + " ====== leave user result ========== " + msg1 + ", "; + } +// } + } + + int len = list.size(); + String userids = ""; + String usernames = ""; + for(String userid : list){ + String username = new ResourceComInfo().getLastname(userid); + usernames += username +","; + userids += userid +","; + } + + if(userids.endsWith(",")){ + userids = userids.substring(0,userids.length()-1); + } + if(usernames.endsWith(",")){ + usernames = usernames.substring(0,usernames.length()-1); + } + if(codes.endsWith(",")){ + codes = codes.substring(0,codes.length()-1); + } + + + +%> + +<%! + + /** + * post 请求 json格式 + * @param url + * @param headers + * @param stringJson + * @param encode + * @return + */ + public static String httpPost(String url, Map headers, String stringJson, String encode){ + int result = 0; + if(encode == null){ + encode = "utf-8"; + } + RecordSet rs = new RecordSet(); + String content = ""; + CloseableHttpResponse httpResponse = null; + CloseableHttpClient closeableHttpClient = null; + try { + closeableHttpClient = HttpClients.createDefault(); + HttpPost httpost = new HttpPost(url); + //设置header + httpost.setHeader("Content-type", "application/json"); + if (headers != null && headers.size() > 0) { + for (Map.Entry entry : headers.entrySet()) { + httpost.setHeader(entry.getKey(),entry.getValue()); + } + } + //组织请求参数 + StringEntity stringEntity = new StringEntity(stringJson, encode); + httpost.setEntity(stringEntity); + //响应信息 + httpResponse = closeableHttpClient.execute(httpost); + if(httpResponse != null) { + HttpEntity entity = httpResponse.getEntity(); + content = EntityUtils.toString(entity, encode); + } + } catch (Exception e) { + e.printStackTrace(); + rs.writeLog(e); + }finally{ + try { + httpResponse.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + try { //关闭连接、释放资源 + closeableHttpClient.close(); + } catch (IOException e) { + e.printStackTrace(); + } + return content; + } + + /** + * 获取 部门中控系统id + * @param deptid + * @return + */ + public static String getDeptCuscode(String deptid){ + RecordSet rs = new RecordSet(); + String code = ""; + rs.executeQuery("select zkxtid from hrmdepartmentdefined where deptid = ?",deptid); + if(rs.next()){ + code = Util.null2String(rs.getString("zkxtid")); + } + return code; + } + + /** + * 获取 分部 中控系统id + * @param subcomid + * @return + */ + public static String getSubcomCuscode(String subcomid){ + RecordSet rs = new RecordSet(); + String code = ""; + rs.executeQuery("select zkid from hrmsubcompanydefined where subcomid = ?",subcomid); + if(rs.next()){ + code = Util.null2String(rs.getString("zkid")); + } + return code; + } + + /** + * 根据 人员id 获取 自定义 考勤卡号,也就是 中控考勤机那边的 人员编号 pin + * @param userid + * @return + */ + public static String getCusIdByUserid(String userid){ + String result = ""; + RecordSet rs = new RecordSet(); + String kq_fieldid = rs.getPropValue("hrm_zhongkong","kq_fieldid"); + rs.executeQuery("select "+ kq_fieldid +" from cus_fielddata where scope = 'HrmCustomFieldByInfoType' and scopeid = -1 and id = ?",userid); + if(rs.next()){ + result = Util.null2String(rs.getString(kq_fieldid)); + } + return result; + } + + /** + * 获取 离职原因 名称 + * @param lzyyid + * @return + */ + public static String getLzyyname(String lzyyid){ + String result = ""; + RecordSet rs = new RecordSet(); + String lzyy_fieldid = rs.getPropValue("hrm_zhongkong","lzyy_fieldid"); + if (lzyyid != null && !"".equals(lzyyid)) { + rs.executeQuery("select selectname from workflow_selectitem where cancel=0 and fieldid = ? and selectvalue=?", lzyy_fieldid, lzyyid); + if (rs.next()) { + result = Util.null2String(rs.getString("selectname")); + } + } + return result; + } + +%> + + + + + + +

Congratulation Mode 666666 !

+ +

新增的人数 <%=add_sum%>

+ +

新增的人是: <%=add_message%>

+ +

离职的 人数 <%=leave_sum%>

+ +

离职的人是: <%=leave_message%>

+ +

新增的人数 <%=len%>

+ +

离职的人数id <%=userids%>

+ +

离职的人数的工号 <%=codes%>

+ +

新增的人是这些 <%=usernames%>

+ + \ No newline at end of file diff --git a/领悦二开new/interface/lingyue/repairKqAttendInfos.jsp b/领悦二开new/interface/lingyue/repairKqAttendInfos.jsp new file mode 100644 index 0000000..f8cf0ef --- /dev/null +++ b/领悦二开new/interface/lingyue/repairKqAttendInfos.jsp @@ -0,0 +1,92 @@ +<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> +<%@page import="weaver.general.Util"%> +<%@ page import="java.math.BigDecimal" %> + + +<% + int detail_sum = 0; + int total_sum = 0; + + String resourceId = Util.null2String(request.getParameter("userid")); + String fromDate = Util.null2String(request.getParameter("fromdate")); + String toDate = Util.null2String(request.getParameter("todate")); + + rs.executeQuery("select * from kq_format_detail where resourceid = ? and kqdate >= ? and kqdate <= ?",resourceId,fromDate,toDate); + while(rs.next()){ + //数据ID + String mxid = Util.null2o(rs.getString("id")); + //出勤时长 + String attendanceMins = Util.null2o(rs.getString("attendanceMins")); + //迟到时长 + String belatemins = Util.null2o(rs.getString("belatemins")); + //严重迟到时长 + String graveBeLateMins = Util.null2o(rs.getString("graveBeLateMins")); + //早退时长 + String leaveearlymins = Util.null2o(rs.getString("leaveearlymins")); + //严重早退时长 + String graveLeaveEarlyMins = Util.null2o(rs.getString("graveLeaveEarlyMins")); + + String attendancemins = floatAdd(attendanceMins,floatAdd(floatAdd(belatemins,graveBeLateMins),floatAdd(leaveearlymins,graveLeaveEarlyMins))); + + boolean bool = rst.executeUpdate("update kq_format_detail set attendanceMins=? where id = ?",attendancemins,mxid); + if(bool){ + detail_sum ++; + } + } + + rs.executeQuery("select * from kq_format_total where resourceid = ? and kqdate >= ? and kqdate <= ?",resourceId,fromDate,toDate); + while(rs.next()){ + //数据ID + String mxid = Util.null2o(rs.getString("id")); + //出勤时长 + String attendanceMins = Util.null2o(rs.getString("attendanceMins")); + //迟到时长 + String belatemins = Util.null2o(rs.getString("belatemins")); + //严重迟到时长 + String graveBeLateMins = Util.null2o(rs.getString("graveBeLateMins")); + //早退时长 + String leaveearlymins = Util.null2o(rs.getString("leaveearlymins")); + //严重早退时长 + String graveLeaveEarlyMins = Util.null2o(rs.getString("graveLeaveEarlyMins")); + + String attendancemins = floatAdd(attendanceMins,floatAdd(floatAdd(belatemins,graveBeLateMins),floatAdd(leaveearlymins,graveLeaveEarlyMins))); + + boolean bool = rst.executeUpdate("update kq_format_total set attendanceMins=? where id = ?",attendancemins,mxid); + if(bool){ + total_sum ++; + } + } + +%> + +<%! + /** + * 方法描述 : 对两个字符串进行金额的相加 + * @param a + * @param b + * @return + * String + */ + public static String floatAdd(String a, String b) { + a=a.equals("")?"0":a; + b=b.equals("")?"0":b; + BigDecimal bg1 = new BigDecimal(a); + BigDecimal bg2 = new BigDecimal(b); + BigDecimal bd = bg1.add(bg2); + return bd.toString(); + } + +%> + + + + + + +

Congratulation Mode 666666 !

+ +

分部的 <%=sub_sum%>

+ +

部门的 <%=dept_sum%>

+ + \ No newline at end of file diff --git a/领悦二开new/interface/lingyue/syntest.jsp b/领悦二开new/interface/lingyue/syntest.jsp new file mode 100644 index 0000000..14e7698 --- /dev/null +++ b/领悦二开new/interface/lingyue/syntest.jsp @@ -0,0 +1,423 @@ +<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> +<%@page import="weaver.general.Util"%> +<%@ page import="java.math.BigDecimal" %> +<%@ page import="weaver.conn.RecordSet" %> +<%@ page import="com.engine.kq.util.KQDurationCalculatorUtil" %> +<%@ page import="weaver.hrm.User" %> +<%@ page import="java.util.*" %> +<%@ page import="java.text.SimpleDateFormat" %> +<%@ page import="weaver.common.DateUtil" %> +<%@ page import="weaver.hrm.common.Tools" %> +<%@ page import="weaver.conn.BatchRecordSet" %> +<%@ page import="com.engine.kq.bean.ImportSetting" %> +<%@ page import="com.engine.kq.entity.KQScheduleSignEntity" %> +<%@ page import="java.text.DateFormat" %> +<%@ page import="weaver.conn.RecordSetDataSource" %> +<%@ page import="java.sql.Timestamp" %> +<%@ page import="weaver.common.StringUtil" %> +<%@ page import="com.alibaba.fastjson.JSONObject" %> +<%@ page import="com.google.common.collect.Maps" %> +<%@ page import="com.google.common.collect.Lists" %> +<%@ page import="com.engine.kq.biz.KQFormatBiz" %> +<%@ page import="com.engine.kq.timer.KQTaskBean" %> +<%@ page import="com.engine.kq.wfset.util.SplitActionUtil" %> +<%@ page import="com.engine.kq.timer.KQQueue" %> + + +<% + int sum = 0; + String id = Util.null2String(request.getParameter("userid")); + String fromDate = Util.null2String(request.getParameter("fromdate")); + String toDate = Util.null2String(request.getParameter("todate")); + + User user = new User(Integer.parseInt(id)); + + String username = user.getLastname(); + + + + + importData(fromDate,toDate,id,false); + + sum++; + +%> + +<%! + private int userlanguage = 7; //登录语言 + + public void importData(String beginDate, String endDate, String userId, boolean isSyn) throws Exception { + RecordSet rs = new RecordSet(); + rs.writeLog("考勤机同步:importData:开始>>>>>>beginDate>>"+beginDate+">>>>>endDate>>>>"+endDate+">>>>>>"+ DateUtil.getFullDate()); + RecordSet delrs = new RecordSet(); + String sql = ""; + endDate = Tools.getDate(endDate, 1); + BatchRecordSet bRs = new BatchRecordSet(); + List> lsParams = new ArrayList<>(); + List params = null; + + List> lsDelParams = new ArrayList<>(); + List delParams = null; + + List lsFormatData = new ArrayList<>(); + List> lsFormatParams = new ArrayList<>(); + List formatParams = null; + + Map> users = getUsers(userId,this.userlanguage); + Map loginidMap = users.get("loginidMap"); + Map lastnameMap = users.get("lastnameMap"); + Map workcodeMap = users.get("workcodeMap"); + List keymap = new ArrayList<>(); + + + List lsImportSetting = new ArrayList<>(); + ImportSetting importSetting = null; + sql = " select datasourceid, loginid, workcode, lastname, signdate, signtime, tablename, clientaddress,longitude,latitude,addr,memo " + + " from HrmScheduleSignSet "; + rs.execute(sql); + while (rs.next()) { + importSetting = new ImportSetting(); + importSetting.setDatasourceid(Util.null2String(rs.getString("datasourceid")).trim()); + importSetting.setLoginid(Util.null2String(rs.getString("loginid")).trim()); + importSetting.setWorkcode(Util.null2String(rs.getString("workcode")).trim()); + importSetting.setLastname(Util.null2String(rs.getString("lastname")).trim()); + importSetting.setSigndate(Util.null2String(rs.getString("signdate")).trim()); + importSetting.setSigntime(Util.null2String(rs.getString("signtime")).trim()); + importSetting.setTablename(Util.null2String(rs.getString("tablename")).trim()); + importSetting.setClientaddress(Util.null2String(rs.getString("clientaddress")).trim()); + importSetting.setLongitude(Util.null2String(rs.getString("longitude")).trim()); + importSetting.setLatitude(Util.null2String(rs.getString("latitude")).trim()); + importSetting.setAddr(Util.null2String(rs.getString("addr")).trim()); + importSetting.setMemo(Util.null2String(rs.getString("memo")).trim()); + lsImportSetting.add(importSetting); + } + List lsKQScheduleSignData = new ArrayList<>(); + KQScheduleSignEntity kqScheduleSignData = null; + for (int i = 0; lsImportSetting != null && i < lsImportSetting.size(); i++) { + try { + importSetting = lsImportSetting.get(i); + String datasourceid = importSetting.getDatasourceid(); + String loginid = importSetting.getLoginid(); + String workcode = importSetting.getWorkcode(); + String lastname = importSetting.getLastname(); + String signdate = importSetting.getSigndate(); + String signtime = importSetting.getSigntime(); + String tablename = importSetting.getTablename(); + String clientaddress = importSetting.getClientaddress(); + String longitude = importSetting.getLongitude(); + String latitude = importSetting.getLatitude(); + String addr = importSetting.getAddr(); + String memo = importSetting.getMemo(); + + DateFormat df = new SimpleDateFormat("HH:mm:ss"); + + sql = "select * from " + tablename + " where " + signdate + " >= '" + beginDate + "' and " + signdate + " < '" + endDate + "' and oary='"+userId+"' order by " + signdate + (signtime.length() == 0 || signtime.equalsIgnoreCase(signdate) ? "" : (", " + signtime)); + + //有遇到外部同步,上面的【conn = ds.getConnection();】这个阻塞住,导致下面的同步不执行,下面的用法和集成领导确认 + RecordSetDataSource rsds = new RecordSetDataSource(datasourceid); + + rsds.execute(sql); + + List noRepertSynData = new ArrayList<>(); + while (rsds.next()) { + String tmpLoginid = ""; + String tmpWorkcode = ""; + String tmpLastname = ""; + String tmpSigndate = ""; + String tmpSigntime = ""; + String tmpClientaddress = ""; + String tmpLongitude = ""; + String tmpLatitude = ""; + String tmpAddr = ""; + String tmpMemo = ""; + + if (loginid.length() > 0) tmpLoginid = Util.null2String(rsds.getString(loginid)).trim(); + if (workcode.length() > 0) tmpWorkcode = Util.null2String(rsds.getString(workcode)).trim(); + if (lastname.length() > 0) tmpLastname = Util.null2String(rsds.getString(lastname)).trim(); + if (signdate.length() > 0) tmpSigndate = Util.null2String(rsds.getString(signdate)).trim(); + if (clientaddress.length() > 0) + tmpClientaddress = Util.null2String(rsds.getString(clientaddress)); + if (longitude.length() > 0) tmpLongitude = Util.null2String(rsds.getString(longitude)).trim(); + if (latitude.length() > 0) tmpLatitude = Util.null2String(rsds.getString(latitude)).trim(); + if (addr.length() > 0) tmpAddr = Util.null2String(rsds.getString(addr)).trim(); + if (memo.length() > 0) tmpMemo = Util.null2String(rsds.getString(memo)).trim(); + + if (signtime.length() > 0) { + tmpSigntime = Util.null2String(rsds.getString(signtime)).trim(); + //判断tmpSigntime格式 08:21:11 如果为长格式需要格式化 + if (tmpSigntime.length() > 8) { + if(tmpSigntime.length()<16){//有遇到signtime格式为hh:mm:ss.0000的格式导致同步不成功 + tmpSigntime = tmpSigntime.substring(0,8); + }else{//比如上yyyy-mm-dd hh:mm的格式走原逻辑 + tmpSigntime = df.format(Timestamp.valueOf(tmpSigntime)); + } + } else if (tmpSigntime.length() < 8) { + //不带秒的情况 自动补齐 + tmpSigntime += ":00"; + } + } else { + tmpSigntime = ""; + } + + if (tmpSigndate.length() > 10) { + //如果时间为长格式,从signdate字段中格式化时间 + if (tmpSigndate.length() == 16) { + //不带秒的情况 自动补齐 + tmpSigndate += ":00"; + } + if (tmpSigntime.length() == 0) {//以signtime字段为有限 + tmpSigndate = tmpSigndate.length()>19?tmpSigndate.substring(0,19):tmpSigndate; + tmpSigntime = df.format(Timestamp.valueOf(tmpSigndate)); + } + tmpSigndate = Tools.formatDate(tmpSigndate, "yyyy-MM-dd"); + } + + //如果时间格式不带秒补齐 + if (tmpSigntime.length() <= 5) { + tmpSigntime += ":00"; + } + + kqScheduleSignData = new KQScheduleSignEntity(); + kqScheduleSignData.setLoginid(tmpLoginid); + kqScheduleSignData.setWorkcode(tmpWorkcode); + kqScheduleSignData.setLastname(tmpLastname); + kqScheduleSignData.setSigndate(tmpSigndate); + kqScheduleSignData.setSigntime(tmpSigntime); + kqScheduleSignData.setClientaddress(tmpClientaddress); + kqScheduleSignData.setLongitude(tmpLongitude); + kqScheduleSignData.setLatitude(tmpLatitude); + kqScheduleSignData.setAddr(tmpAddr); + kqScheduleSignData.setMemo(tmpMemo); + lsKQScheduleSignData.add(kqScheduleSignData); + } + } catch (Exception e) { + rs.writeLog(e); + } + } + List noRepertSynData = new ArrayList<>(); + for (int i = 0; lsKQScheduleSignData != null && i < lsKQScheduleSignData.size(); i++) { + kqScheduleSignData = lsKQScheduleSignData.get(i); + String tmpLoginid = kqScheduleSignData.getLoginid(); + String tmpWorkcode = kqScheduleSignData.getWorkcode(); + String tmpLastname = kqScheduleSignData.getLastname(); + String tmpSigndate = kqScheduleSignData.getSigndate(); + String tmpSigntime = kqScheduleSignData.getSigntime(); + String tmpClientaddress = kqScheduleSignData.getClientaddress(); + String tmpLongitude = kqScheduleSignData.getLongitude(); + String tmpLatitude = kqScheduleSignData.getLatitude(); + String tmpAddr = kqScheduleSignData.getAddr(); + String tmpMemo = kqScheduleSignData.getMemo(); + int userid = 0; + if (Util.null2String(tmpLoginid).length() > 0) { + userid = StringUtil.parseToInt(loginidMap.get(tmpLoginid), 0); + } + if (userid == 0 && Util.null2String(tmpWorkcode).length() > 0) { + userid = StringUtil.parseToInt(workcodeMap.get(tmpWorkcode), 0); + } + if (userid == 0 && Util.null2String(tmpLastname).length() > 0) { + userid = StringUtil.parseToInt(lastnameMap.get(tmpLastname), 0); + } + + if (userid <= 0) { + rs.writeLog("人员id未找到>>>>>>>>>>" + JSONObject.toJSONString(kqScheduleSignData)); + continue; + } + String dkParamData = userid + "#" + tmpSigndate + "#" + tmpSigntime; + if (noRepertSynData.contains(dkParamData)) { + continue; + } + noRepertSynData.add(dkParamData); + params = new ArrayList<>(); + params.add(userid); + params.add(1); + params.add(tmpSigndate); + params.add(tmpSigntime); + params.add(tmpClientaddress); + params.add(1); + params.add(1); + params.add("OutDataSourceSyn"); + params.add(tmpLongitude); + params.add(tmpLatitude); + params.add(tmpAddr); + params.add(tmpMemo); + lsParams.add(params); + + String belongDate = getBelongDate(new User(userid), tmpSigndate, tmpSigntime); + + String formatData = userid + "|" + tmpSigndate+ "|" + belongDate; + if (!lsFormatData.contains(formatData)) { + lsFormatData.add(formatData); + } + } + + Map> overtimeMap = Maps.newHashMap(); + List overtimeList = Lists.newArrayList(); + //刷新报表数据 + for (int i = 0; lsFormatData != null && i < lsFormatData.size(); i++) { + formatParams = new ArrayList<>(); + String key = lsFormatData.get(i); + String[] formatData = Util.splitString(lsFormatData.get(i), "|"); + String date_1 = DateUtil.addDate(formatData[1], -1); + formatParams.add(formatData[0]); + formatParams.add(date_1); + lsFormatParams.add(formatParams); + + formatParams = new ArrayList<>(); + formatParams.add(formatData[0]); + formatParams.add(formatData[1]); + lsFormatParams.add(formatParams); + + if (!keymap.contains(key)) { + keymap.add(key); + delParams = new ArrayList<>(); + delParams.add(formatData[0]); + delParams.add(formatData[1]); + lsDelParams.add(delParams); + } + + String resourceId = formatData[0]; + String kqdate = formatData[1]; + String belongDate = formatData[2]; + if (overtimeMap.containsKey(resourceId)) { + List tmp_overtimeList = overtimeMap.get(resourceId); + if (!tmp_overtimeList.contains(kqdate)) { + tmp_overtimeList.add(kqdate); + if(!kqdate.equals(belongDate)) { + tmp_overtimeList.add(belongDate); + } + } + } else { + if (!overtimeList.contains(kqdate)) { + overtimeList.add(kqdate); + if(!kqdate.equals(belongDate)) { + overtimeList.add(belongDate); + } + } + overtimeMap.put(resourceId, overtimeList); + } + } + + rs.writeLog("同步之前删除数据:"+ JSONObject.toJSONString(lsDelParams)); + rs.writeLog("同步插入数据:"+ JSONObject.toJSONString(lsParams)); + + //删除本次同步数据 + sql = " delete from hrmschedulesign where signfrom='OutDataSourceSyn' and userid =? and signdate = ? "; + bRs.executeBatchSql(sql, lsDelParams); + + + sql = " insert into HrmScheduleSign (userid, usertype, signdate, signtime, clientaddress, isincom, isimport, signfrom, longitude, latitude, addr,memo) " + + " values(?,?,?,?,?,?,?,?,?,?,?,?)"; + bRs.executeBatchSql(sql, lsParams); + + new KQFormatBiz().format(lsFormatParams, 12); + + //处理加班生成 + List tasks = new ArrayList<>(); + for (Map.Entry> mme : overtimeMap.entrySet()) { + String resid = mme.getKey(); + List overList = mme.getValue(); + for (String date : overList) { + SplitActionUtil.pushOverTimeTasks(date, date, resid, tasks); + } + } + if (!tasks.isEmpty()) { + KQQueue.writeTasks(tasks); + } + } + + public String getCusIdByUserid(String userid){ + String result = ""; + RecordSet rs = new RecordSet(); + String kq_fieldid = rs.getPropValue("hrm_zhongkong","kq_fieldid"); + rs.executeQuery("select "+ kq_fieldid +" from cus_fielddata where scope = 'HrmCustomFieldByInfoType' and scopeid = -1 and id = ?",userid); + if(rs.next()){ + result = Util.null2String(rs.getString(kq_fieldid)); + } + return result; + } + + public String getUseridByPin(String pin){ + String result = ""; + RecordSet rs = new RecordSet(); + String kq_fieldid = rs.getPropValue("hrm_zhongkong","kq_fieldid"); + rs.executeQuery("select a.id from hrmresource a,cus_fielddata b where a.id=b.id and a.status in (0,1,2,3,5) and scope = 'HrmCustomFieldByInfoType' and scopeid = -1 and "+kq_fieldid+" = ?",pin); + if(rs.next()){ + result = Util.null2String(rs.getString("id")); + } + return result; + } + + public Map> getUsers(String userid,int language) { + RecordSet rs = new RecordSet(); + rs.writeLog("------------------ getUsers userid ----------------------- "+ userid); + String sql = "select id,loginid,lastname,workcode from hrmresource where status in(0,1,2,3,5) and id="+ userid; + if (Util.isEnableMultiLang()) { + if (rs.getDBType().equalsIgnoreCase("sqlserver")) { + sql = "select id,loginid,ltrim(rtrim(dbo.convToMultiLang(ltrim(rtrim(lastname)),"+language+"))) as lastname,workcode from hrmresource where status in(0,1,2,3,5) and id = "+ userid; + } else { + sql = "select id,loginid,ltrim(rtrim(convToMultiLang(ltrim(rtrim(lastname)),"+language+"))) as lastname,workcode from hrmresource where status in(0,1,2,3,5) and id = "+ userid; + } + } + + Map> users = new HashMap>(); + rs.execute(sql); + Map loginidMap = new HashMap(); + Map lastnameMap = new HashMap(); + Map workcodeMap = new HashMap(); + String resourceId = "", loginid = "",lastname = "", workcode = ""; + while (rs.next()) { + if (StringUtil.isNull(resourceId = StringUtil.vString(rs.getString("id")))) continue; + loginid = StringUtil.vString(rs.getString("loginid")); + if (StringUtil.isNull(loginid)){ + }else{ + loginidMap.put(loginid, resourceId); + } + if (StringUtil.isNotNull(lastname = StringUtil.vString(rs.getString("lastname")))) lastnameMap.put(lastname, resourceId); + if (StringUtil.isNotNull(workcode = StringUtil.vString(rs.getString("workcode")))) workcodeMap.put(workcode, resourceId); + } + users.put("loginidMap", loginidMap); + users.put("lastnameMap", lastnameMap); + users.put("workcodeMap", workcodeMap); + return users; + } + + public int getUserlanguage() { + return userlanguage; + } + + public void setUserlanguage(int userlanguage) { + this.userlanguage = userlanguage; + } + + private String getBelongDate(User user, String curDate, String signDateTime) { + String belongDate = curDate; + Map todayLineMap = KQDurationCalculatorUtil.getWorkButton(user, curDate,true); + if(todayLineMap != null) { + List> preInfo = (ArrayList>)todayLineMap.get("pre_signTime"); + if(preInfo != null) { + for(Map entry : preInfo) { + String pre_endtime_across = entry.get("endtime_across"); + String pre_endtime = entry.get("endtime"); + String signEndInfo = "1".equals(pre_endtime_across) ? (curDate+" "+pre_endtime+":00") : (DateUtil.addDate(curDate,-1)+" "+pre_endtime+":00"); + String signOutDateTime = signDateTime; + if(signOutDateTime.compareTo(signEndInfo) < 0) { + belongDate = DateUtil.addDate(curDate, -1); + } + } + } + } + return belongDate; + } +%> + + + + + +

以下是 <%=username%> 的 相关数据展示

+ +

sum <%=sum%>

+ + + + \ No newline at end of file diff --git a/领悦二开new/src/com/api/hrm/service/HrmResourceAddService.java b/领悦二开new/src/com/api/hrm/service/HrmResourceAddService.java new file mode 100644 index 0000000..cada6c9 --- /dev/null +++ b/领悦二开new/src/com/api/hrm/service/HrmResourceAddService.java @@ -0,0 +1,1100 @@ +package com.api.hrm.service; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import com.api.hrm.bean.FieldItem; +import com.alibaba.fastjson.JSONObject; +import com.api.browser.bean.SearchConditionItem; +import com.api.browser.bean.SearchConditionOption; +import com.api.browser.util.ConditionType; +import com.api.hrm.bean.HrmFieldBean; +import com.api.hrm.util.HrmFieldSearchConditionComInfo; +import com.engine.common.biz.SimpleBizLogger; +import com.engine.common.constant.BizLogOperateAuditType; +import com.engine.common.constant.BizLogOperateType; +import com.engine.common.constant.BizLogSmallType4Hrm; +import com.engine.common.constant.BizLogType; +import com.engine.common.entity.BizLogContext; +import com.engine.common.util.LogUtil; +import com.engine.common.util.ParamUtil; +import com.engine.hrm.biz.HrmClassifiedProtectionBiz; +import com.engine.hrm.util.HrmWeakPasswordUtil; +import com.engine.hrm.util.face.HrmFaceCheckManager; +import ln.LN; +import weaver.conn.RecordSet; +import weaver.encrypt.EncryptUtil; +import weaver.file.Prop; +import weaver.filter.XssUtil; +import weaver.general.BaseBean; +import weaver.general.GCONST; +import weaver.general.PasswordUtil; +import weaver.general.Util; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; +import weaver.hrm.company.DepartmentComInfo; +import weaver.hrm.definedfield.HrmFieldGroupComInfo; +import weaver.hrm.definedfield.HrmFieldManager; +import weaver.hrm.moduledetach.ManageDetachComInfo; +import weaver.hrm.passwordprotection.manager.HrmResourceManager; +import weaver.hrm.privacy.PrivacyBaseComInfo; +import weaver.hrm.privacy.PrivacyComInfo; +import weaver.hrm.privacy.UserPrivacyComInfo; +import weaver.hrm.resource.HrmListValidate; +import weaver.hrm.resource.ResourceComInfo; +import weaver.hrm.settings.ChgPasswdReminder; +import weaver.hrm.settings.RemindSettings; +//import weaver.interfaces.email.CoreMailAPI; +import weaver.interfaces.hrm.HrmServiceManager; +import org.apache.commons.lang3.StringUtils; +import weaver.license.PluginUserCheck; +import weaver.rsa.security.RSA; +import weaver.rtx.OrganisationCom; +import weaver.rtx.OrganisationComRunnable; +import weaver.systeminfo.SysMaintenanceLog; +import weaver.systeminfo.SystemEnv; +import weaver.systeminfo.systemright.CheckSubCompanyRight; + +/*** + * 新建人员 + * @author lvyi + * + */ +public class HrmResourceAddService extends BaseBean { + + public boolean hasRightSystemInfo(HttpServletRequest request, HttpServletResponse response) { + User user = HrmUserVarify.getUser(request, response); + boolean isRight = false; + try { + HrmListValidate HrmListValidate = new HrmListValidate(); + isRight = HrmListValidate.isValidate(15) && HrmUserVarify.checkUserRight("ResourcesInformationSystem:All", user); + } catch (Exception e) { + writeLog(e); + } + return isRight; + } + + /** + * 新建人员表单Simple + * + * @param request + * @param response + * @return + */ + public String getHrmResourceAddSimpleForm(HttpServletRequest request, HttpServletResponse response) { + User user = HrmUserVarify.getUser(request, response); + + Map retmap = new HashMap(); + if(!HrmUserVarify.checkUserRight("HrmResourceAdd:Add", user)){ + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage())); + return JSONObject.toJSONString(retmap); + } + + //姓名、性别、部门、岗位、直接上级、状态、照片、办公地点、移动电话、办公室电话、电子邮件+必填的自定义字段 + String fromfields = ",workcode,lastname,sex,accounttype,belongto,departmentid,jobtitle,managerid,status,resourceimageid,locationid,mobile," + + "telephone,email,"; + ChgPasswdReminder reminder = new ChgPasswdReminder(); + RemindSettings settings = reminder.getRemindSettings(); + String passwordComplexity = settings.getPasswordComplexity(); + int minpasslen = settings.getMinPasslen(); + boolean flagaccount = GCONST.getMOREACCOUNTLANDING(); + List lsGroup = new ArrayList(); + Map groupitem = null; + List itemlist = null; + try { + PrivacyComInfo pc = new PrivacyComInfo(); + PrivacyBaseComInfo privacyBaseComInfo = new PrivacyBaseComInfo(); + Map mapShowSets = pc.getMapShowSets(); + Map mapShowTypes = pc.getMapShowTypes(); + //总体的大开关的默认设置 + Map mapBaseShowTypeDefaults = privacyBaseComInfo.getMapShowTypeDefaults(); + + //基本信息 + int scopeId = -1; + HrmFieldGroupComInfo HrmFieldGroupComInfo = new HrmFieldGroupComInfo(); + HrmFieldSearchConditionComInfo hrmFieldSearchConditionComInfo = new HrmFieldSearchConditionComInfo(); + HrmFieldManager hfm = new HrmFieldManager("HrmCustomFieldByInfoType", scopeId); + + while (HrmFieldGroupComInfo.next()) { + int grouptype = Util.getIntValue(HrmFieldGroupComInfo.getType()); + if (grouptype != scopeId) continue; + int grouplabel = Util.getIntValue(HrmFieldGroupComInfo.getLabel()); + int groupid = Util.getIntValue(HrmFieldGroupComInfo.getid()); + hfm.getCustomFields(groupid); + if (hfm.getGroupCount() == 0 || groupid == 3) continue; + + groupitem = new HashMap(); + itemlist = new ArrayList(); + groupitem.put("title", SystemEnv.getHtmlLabelName(grouplabel, user.getLanguage())); + groupitem.put("defaultshow", true); + groupitem.put("items", itemlist); + lsGroup.add(groupitem); + while (hfm.next()) { + int tmpviewattr = 2; + String fieldName = hfm.getFieldname(); + String cusFieldname = ""; + if (hfm.isBaseField(fieldName)) { + if (fromfields.indexOf("," + fieldName + ",") == -1) continue; + } else { + cusFieldname = "customfield_0_" + hfm.getFieldid(); + if (!hfm.isMand()) continue; + } + if (!hfm.isUse()) { + continue; + } + + if (fieldName.equals("loginid") || fieldName.equals("jobactivity") || fieldName.equals("departmentvirtualids")) + continue; + if (fieldName.equals("accounttype") && !flagaccount) continue; + org.json.JSONObject hrmFieldConf = hfm.getHrmFieldConf(fieldName); + HrmFieldBean hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldid((String) hrmFieldConf.get("id")); + hrmFieldBean.setFieldname(cusFieldname.length() > 0 ? cusFieldname : fieldName); + hrmFieldBean.setFieldlabel(hfm.getLable()); + hrmFieldBean.setFieldhtmltype((String) hrmFieldConf.get("fieldhtmltype")); + hrmFieldBean.setType((String) hrmFieldConf.get("type")); + hrmFieldBean.setDmlurl((String) hrmFieldConf.get("dmlurl")); + hrmFieldBean.setIssystem("" + (Integer) hrmFieldConf.get("issystem")); + hrmFieldBean.setIsFormField(true); + if (hrmFieldBean.getFieldname().equals("lastname")) { + hrmFieldBean.setMultilang(true); + } else { + hrmFieldBean.setMultilang(false); + } + if (((String) hrmFieldConf.get("ismand")).equals("1")) { + tmpviewattr = 3; + } + + if (fieldName.equals("belongto") && flagaccount) { + tmpviewattr = 3; + } + + if (fieldName.equals("mobile") || fieldName.equals("email")) { + hrmFieldBean.setMultilang(false); + } + + if (fieldName.equals("departmentid")) { + hrmFieldBean.setFieldvalue(Util.null2String(request.getParameter("departmentid"))); + } + + SearchConditionItem searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + if (searchConditionItem == null) continue; + if(fieldName.equals("sex")){ + List options = new ArrayList(); + options.add(new SearchConditionOption("0", SystemEnv.getHtmlLabelName(28473, user.getLanguage()), true)); + options.add(new SearchConditionOption("1", SystemEnv.getHtmlLabelName(28474, user.getLanguage()))); + searchConditionItem.setOptions(options); + } + if(fieldName.equals("accounttype")){ + List options = new ArrayList(); + options.add(new SearchConditionOption("0", SystemEnv.getHtmlLabelName(17746, user.getLanguage()), true)); + options.add(new SearchConditionOption("1", SystemEnv.getHtmlLabelName(17747, user.getLanguage()))); + searchConditionItem.setOptions(options); + } + if (fieldName.equals("belongto") && flagaccount) { + XssUtil xssUtil = new XssUtil(); + String accountSql = "(accounttype=0 or accounttype is null)"; + searchConditionItem.getBrowserConditionParam().getDataParams().put("sqlwhere", xssUtil.put(accountSql)); + searchConditionItem.getBrowserConditionParam().getCompleteParams().put("sqlwhere", xssUtil.put(accountSql)); + searchConditionItem.getBrowserConditionParam().getDestDataParams().put("sqlwhere", xssUtil.put(accountSql)); + } + if (fieldName.equals("status")) { + List statusOptions = new ArrayList(); + statusOptions.add(new SearchConditionOption("0", SystemEnv.getHtmlLabelName(15710, user.getLanguage()), true)); + statusOptions.add(new SearchConditionOption("1", SystemEnv.getHtmlLabelName(15711, user.getLanguage()))); + statusOptions.add(new SearchConditionOption("2", SystemEnv.getHtmlLabelName(480, user.getLanguage()))); + searchConditionItem.setOptions(statusOptions); + } + if (searchConditionItem.getBrowserConditionParam() != null) { + searchConditionItem.getBrowserConditionParam().setViewAttr(tmpviewattr); + if (hrmFieldBean.getFieldname().equals("departmentid")) { + searchConditionItem.getBrowserConditionParam().getDataParams().put("rightStr", "HrmResourceAdd:Add"); + searchConditionItem.getBrowserConditionParam().getCompleteParams().put("rightStr", "HrmResourceAdd:Add"); + } + } + if (!passwordComplexity.equals("0") && !searchConditionItem.getConditionType().equals(ConditionType.DATE)) { + searchConditionItem.setLabelcol(6); + searchConditionItem.setFieldcol(12); + } + searchConditionItem.setViewAttr(tmpviewattr); + itemlist.add(searchConditionItem); + + if (fieldName.equals("jobtitle")) {//岗位后加入上下级关系 + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname("managerid"); + hrmFieldBean.setFieldlabel("15709"); + hrmFieldBean.setFieldhtmltype("3"); + hrmFieldBean.setType("1"); + hrmFieldBean.setIssystem("1"); + hrmFieldBean.setIsFormField(true); + searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + if (searchConditionItem == null) continue; + if (searchConditionItem.getBrowserConditionParam() != null) { + searchConditionItem.getBrowserConditionParam().setViewAttr(2); + } + if (!passwordComplexity.equals("0") && !searchConditionItem.getConditionType().equals(ConditionType.DATE)) { + searchConditionItem.setLabelcol(6); + searchConditionItem.setFieldcol(12); + } + searchConditionItem.setViewAttr(2); + itemlist.add(searchConditionItem); + } +// if(fieldName.equals("mobile")){ +// String mobileShowSet = Util.null2String(settings.getMobileShowSet()); +// String mobileShowType = Util.null2String(settings.getMobileShowType()); +// String mobileShowTypeDefault = Util.null2String(settings.getMobileShowTypeDefault()); +// if(mobileShowSet.equals("1")){ +// hrmFieldBean = new HrmFieldBean(); +// hrmFieldBean.setFieldname("mobileshowtype"); +// hrmFieldBean.setFieldlabel("32684"); +// hrmFieldBean.setFieldhtmltype("5"); +// hrmFieldBean.setType("1"); +// hrmFieldBean.setIssystem("1"); +// hrmFieldBean.setIsFormField(true); +// searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); +// if(searchConditionItem==null)continue; +// if(!passwordComplexity.equals("0")&&!searchConditionItem.getConditionType().equals(ConditionType.DATE)){ +// searchConditionItem.setLabelcol(6); +// searchConditionItem.setFieldcol(12); +// } +// searchConditionItem.setViewAttr(2); +// List statusOptions = new ArrayList(); +// if(mobileShowType.indexOf("1")!=-1){ +// statusOptions.add(new SearchConditionOption("1",SystemEnv.getHtmlLabelName(2161,user.getLanguage()),mobileShowTypeDefault.equals("1"))); +// }if(mobileShowType.indexOf("2")!=-1){ +// statusOptions.add(new SearchConditionOption("2",SystemEnv.getHtmlLabelName(32670,user.getLanguage()),mobileShowTypeDefault.equals("2"))); +// }if(mobileShowType.indexOf("3")!=-1){ +// statusOptions.add(new SearchConditionOption("3",SystemEnv.getHtmlLabelName(32671,user.getLanguage()),mobileShowTypeDefault.equals("3"))); +// } +// searchConditionItem.setOptions(statusOptions); +// itemlist.add(searchConditionItem); +// } +// } + + if (mapShowSets != null && mapShowSets.get(fieldName) != null) { + String mobileShowSet = Util.null2String(mapShowSets.get(fieldName)); + String mobileShowType = Util.null2String(mapShowTypes.get(fieldName)); + String baseMobileShowTypeDefaults = Util.null2String(mapBaseShowTypeDefaults.get(fieldName)); + + if (mobileShowSet.equals("1")) { + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname(fieldName + "showtype"); + hrmFieldBean.setFieldlabelname(SystemEnv.getHtmlLabelNames(hfm.getLable(), user.getLanguage()) + SystemEnv.getHtmlLabelName(385571, user.getLanguage())); + hrmFieldBean.setFieldhtmltype("5"); + hrmFieldBean.setType("1"); + hrmFieldBean.setIssystem("1"); + hrmFieldBean.setIsFormField(true); + searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + if (searchConditionItem == null) continue; + List statusOptions = new ArrayList(); + if (mobileShowType.indexOf("1") != -1) { + if (baseMobileShowTypeDefaults.indexOf("1") != -1) { + statusOptions.add(new SearchConditionOption("1", SystemEnv.getHtmlLabelName(2161, user.getLanguage()), true)); + } else { + statusOptions.add(new SearchConditionOption("1", SystemEnv.getHtmlLabelName(2161, user.getLanguage()))); + } + } + if (mobileShowType.indexOf("2") != -1) { + if (baseMobileShowTypeDefaults.indexOf("2") != -1) { + statusOptions.add(new SearchConditionOption("2", SystemEnv.getHtmlLabelName(32670, user.getLanguage()), true)); + } else { + statusOptions.add(new SearchConditionOption("2", SystemEnv.getHtmlLabelName(32670, user.getLanguage()))); + } + } + if (mobileShowType.indexOf("3") != -1) { + if (baseMobileShowTypeDefaults.indexOf("3") != -1) { + statusOptions.add(new SearchConditionOption("3", SystemEnv.getHtmlLabelName(32671, user.getLanguage()), true)); + } else { + statusOptions.add(new SearchConditionOption("3", SystemEnv.getHtmlLabelName(32671, user.getLanguage()))); + } + } + searchConditionItem.setOptions(statusOptions); + itemlist.add(searchConditionItem); + } + } + } + if (itemlist.size() == 0) lsGroup.remove(groupitem); + } + + RecordSet rs = new RecordSet(); + String sql = "select * from hrm_formfield where fieldname=? "; + + String[] fields = new String[]{"companystartdate,1516,3,2","workstartdate,23519,3,2"}; + SearchConditionItem searchConditionItem = null; + HrmFieldBean hrmFieldBean = null; + itemlist = new ArrayList(); + groupitem = new HashMap(); + groupitem.put("title", SystemEnv.getHtmlLabelName(15688, user.getLanguage())); + groupitem.put("defaultshow", true); + for (int i = 0; i < fields.length; i++) { + String[] fieldinfo = fields[i].split(","); + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname(fieldinfo[0]); + hrmFieldBean.setFieldlabel(fieldinfo[1]); + hrmFieldBean.setFieldhtmltype(fieldinfo[2]); + hrmFieldBean.setType(fieldinfo[3]); + hrmFieldBean.setIsFormField(true); + hrmFieldBean.setMultilang(false); + boolean isUse = false; + boolean isMand = false; + rs.executeQuery(sql,hrmFieldBean.getFieldname()); + if(rs.next()){ + if(rs.getInt("isUse")==1){ + isUse = true; + } + if(rs.getInt("isMand")==1){ + isMand = true; + } + } + if(!isUse)continue; + searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + searchConditionItem.setViewAttr(isMand?3:2); + itemlist.add(searchConditionItem); + } + if(!itemlist.isEmpty()){ + lsGroup.add(groupitem); + groupitem.put("items", itemlist); + } + + + //登录名、密码、密码确认、安全级别 + if (hasRightSystemInfo(request, response)) { + String[] fields2 = new String[]{"loginid,412,1,1", "password,409,1,4", "password1,501,1,4", "seclevel,683,1,2","validatecode,22910,1,1"}; + SearchConditionItem searchConditionItem2 = null; + HrmFieldBean hrmFieldBean2 = null; + itemlist = new ArrayList(); + groupitem = new HashMap(); + groupitem.put("title", SystemEnv.getHtmlLabelName(15804, user.getLanguage())); + groupitem.put("defaultshow", true); + lsGroup.add(groupitem); + for (int i = 0; i < fields2.length; i++) { + String[] fieldinfo = fields2[i].split(","); + hrmFieldBean2 = new HrmFieldBean(); + hrmFieldBean2.setFieldname(fieldinfo[0]); + hrmFieldBean2.setFieldlabel(fieldinfo[1]); + hrmFieldBean2.setFieldhtmltype(fieldinfo[2]); + hrmFieldBean2.setType(fieldinfo[3]); + hrmFieldBean2.setIsFormField(true); + hrmFieldBean2.setMultilang(false); + if(hrmFieldBean2.getFieldname().equals("validatecode")){ + hrmFieldBean2.setViewAttr(3); + hrmFieldBean2.setRules("required|string"); + } + searchConditionItem2 = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean2, user); + if ("seclevel".equalsIgnoreCase(hrmFieldBean2.getFieldname())) { + searchConditionItem2.setMin("-999"); + searchConditionItem2.setMax("999"); + } + if (fieldinfo[3].equals("4")) { + Map otherParams = new HashMap(); + otherParams.put("type", "password"); + if (fieldinfo[0].equals("password")) { + String title = ""; + if (passwordComplexity.equals("1")) { + title = SystemEnv.getHtmlLabelName(24080, user.getLanguage()); + } else if (passwordComplexity.equals("2")) { + title = SystemEnv.getHtmlLabelName(24081, user.getLanguage()); + } else if (passwordComplexity.equals("3")) { + title = SystemEnv.getHtmlLabelName(512563, user.getLanguage()); + } + otherParams.put("tip", title); + otherParams.put("tipLength", "100"); + if (!passwordComplexity.equals("0")) { + otherParams.put("passwordStrength", true); + otherParams.put("passwordStrengthIdx", 1); + } + } + searchConditionItem2.setOtherParams(otherParams); + } + if (!passwordComplexity.equals("0") && !searchConditionItem2.getConditionType().equals(ConditionType.DATE)) { + searchConditionItem2.setLabelcol(6); + searchConditionItem2.setFieldcol(12); + } + itemlist.add(searchConditionItem2); + } + groupitem.put("items", itemlist); + } + + } catch (Exception e) { + writeLog(e); + } + retmap.put("condition", lsGroup); + retmap.put("passwordComplexity", passwordComplexity); + retmap.put("minpasslen", minpasslen); + //是否开启了RSA加密 + String openRSA = Util.null2String(Prop.getPropValue("openRSA","isrsaopen")); + retmap.put("openRSA",openRSA); + retmap.put("hasJobTitlesAdd", HrmUserVarify.checkUserRight("HrmJobTitlesAdd:Add", user)); + return JSONObject.toJSONString(retmap); + } + + /** + * 新建人员表单 + * + * @param request + * @param response + * @return + */ + public String getHrmResourceAddForm(HttpServletRequest request, HttpServletResponse response) { + Map retmap = new HashMap(); + Map result = new HashMap(); + try { + User user = HrmUserVarify.getUser(request, response); + + if(!HrmUserVarify.checkUserRight("HrmResourceAdd:Add", user)){ + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage())); + return JSONObject.toJSONString(retmap); + } + + ChgPasswdReminder reminder = new ChgPasswdReminder(); + RemindSettings settings = reminder.getRemindSettings(); + String passwordComplexity = settings.getPasswordComplexity(); + int minpasslen = settings.getMinPasslen(); + int needdynapass = settings.getNeeddynapass(); + String needusbHt = settings.getNeedusbHt(); + String needusbDt = settings.getNeedusbDt(); + String needCL = settings.getNeedCL(); + HrmResourceBaseService HrmResourceBaseService = new HrmResourceBaseService(); + HrmResourcePersonalService HrmResourcePersonalService = new HrmResourcePersonalService(); + HrmResourceWorkService HrmResourceWorkService = new HrmResourceWorkService(); + + HrmListValidate HrmListValidate = new HrmListValidate(); + retmap.put("basecondition", HrmResourceBaseService.getFormFields(request, response, true)); + result = HrmResourcePersonalService.getFormFields(request, response, true); + if (HrmListValidate.isValidate(11)) { + retmap.put("personalcondition", result != null ? result.get("conditions") : null); + if(result!=null){ + List> tables = (List>) result.get("tables") ; + for(Map tableInfo : tables){ + Map table = (Map)tableInfo.get("tabinfo") ; + if(table!=null) { + List> columns = (List>) table.get("columns"); + if (columns != null) { + for (Map c : columns) { + String key = (String) c.get("key"); + if ("company".equals(key) || "jobtitle".equals(key)) { + c.put("key", "person_" + key); + c.put("dataIndex", "person_" + key); + List coms = (List) c.get("com") ; + if(coms != null){ + for(FieldItem com : coms){ + com.setKey("person_"+key); + } + } + } + } + } + } + } + } + + retmap.put("personaltables", result != null ? result.get("tables") : null); + } + if (HrmListValidate.isValidate(12)) { + result = HrmResourceWorkService.getFormFields(request, response, true); + retmap.put("workcondition", result != null ? result.get("conditions") : null); + retmap.put("worktables", result != null ? result.get("tables") : null); + } + + //系统信息 + if (hasRightSystemInfo(request, response)) { + List lsGroup = new ArrayList(); + Map groupitem = null; + List itemlist = null; + //登录名、密码、密码确认、辅助校验方式、系统语言、电子邮件、安全级别 + String[] fields = new String[]{"loginid,412,1,1", "password,409,1,4", + "password1,501,1,4", "userUsbType,81629,5,1", "usbstate,602,5,1", + "tokenKey,32897,1,1", "serial,21597,1,1", "seclevel,683,1,2","validatecode,22910,1,1"};//,"systemlanguage,16066,3,259","email,477,1,1" + + HrmFieldSearchConditionComInfo hrmFieldSearchConditionComInfo = new HrmFieldSearchConditionComInfo(); + SearchConditionItem searchConditionItem = null; + HrmFieldBean hrmFieldBean = null; + itemlist = new ArrayList(); + groupitem = new HashMap(); + groupitem.put("title", SystemEnv.getHtmlLabelName(15804, user.getLanguage())); + groupitem.put("defaultshow", true); + for (int i = 0; i < fields.length; i++) { + String[] fieldinfo = fields[i].split(","); + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname(fieldinfo[0]); + hrmFieldBean.setFieldlabel(fieldinfo[1]); + hrmFieldBean.setFieldhtmltype(fieldinfo[2]); + hrmFieldBean.setType(fieldinfo[3]); + hrmFieldBean.setIsFormField(true); + hrmFieldBean.setMultilang(false); + if(hrmFieldBean.getFieldname().equals("validatecode")){ + hrmFieldBean.setViewAttr(3); + hrmFieldBean.setRules("required|string"); + } + if (hrmFieldBean.getFieldname().equals("userUsbType")) { + if (needdynapass == 1 || "1".equals(needusbHt) || "1".equals(needusbDt)|| "1".equals(needCL)) { + } else { + continue; + } + } + searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + if ("seclevel".equalsIgnoreCase(hrmFieldBean.getFieldname())) { + searchConditionItem.setMin("-999"); + searchConditionItem.setMax("999"); + } + if (fieldinfo[3].equals("4")) { + Map otherParams = new HashMap(); + otherParams.put("type", "password"); + if (fieldinfo[0].equals("password")) { + String title = ""; + if (passwordComplexity.equals("1")) { + title = SystemEnv.getHtmlLabelName(24080, user.getLanguage()); + } else if (passwordComplexity.equals("2")) { + title = SystemEnv.getHtmlLabelName(24081, user.getLanguage()); + } else if (passwordComplexity.equals("3")) { + title = SystemEnv.getHtmlLabelName(512563, user.getLanguage()); + } + otherParams.put("tip", title); + otherParams.put("tipLength", "100"); + if (!passwordComplexity.equals("0")) { + otherParams.put("passwordStrengthIdx", 2); + otherParams.put("passwordStrength", true); + } + } + searchConditionItem.setOtherParams(otherParams); + } else if (hrmFieldBean.getFieldhtmltype().equals("5")) { + List statusOptions = new ArrayList(); + if (hrmFieldBean.getFieldname().equals("userUsbType")) { + statusOptions.add(new SearchConditionOption("", "", true)); + if (needdynapass == 1) { + statusOptions.add(new SearchConditionOption("4", SystemEnv.getHtmlLabelName(32511, user.getLanguage()))); + } + if ("1".equals(needusbHt)) { + statusOptions.add(new SearchConditionOption("2", SystemEnv.getHtmlLabelName(21589, user.getLanguage()))); + } + if ("1".equals(needusbDt)) { + statusOptions.add(new SearchConditionOption("3", SystemEnv.getHtmlLabelName(32896, user.getLanguage()))); + } + if ("1".equals(needCL)) { + statusOptions.add(new SearchConditionOption("7", SystemEnv.getHtmlLabelName(388414, user.getLanguage()))); + } + searchConditionItem.setOptions(statusOptions); + } else if (hrmFieldBean.getFieldname().equals("usbstate")) { + statusOptions.add(new SearchConditionOption("0", SystemEnv.getHtmlLabelName(18095, user.getLanguage()), true)); + statusOptions.add(new SearchConditionOption("1", SystemEnv.getHtmlLabelName(18096, user.getLanguage()))); + statusOptions.add(new SearchConditionOption("2", SystemEnv.getHtmlLabelName(21384, user.getLanguage()))); + searchConditionItem.setOptions(statusOptions); + } + } + if (!passwordComplexity.equals("0") && !searchConditionItem.getConditionType().equals(ConditionType.DATE)) { + searchConditionItem.setLabelcol(6); + searchConditionItem.setFieldcol(12); + } + itemlist.add(searchConditionItem); + + } + + boolean isOpenClassification = HrmClassifiedProtectionBiz.isOpenClassification();//判断是否开启了分级保护 + if (isOpenClassification) { + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname("classification");//人员密级 + hrmFieldBean.setFieldlabel("130506"); + hrmFieldBean.setFieldhtmltype("5"); + hrmFieldBean.setType("1"); + hrmFieldBean.setIsFormField(true); + hrmFieldBean.setViewAttr(3); + searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + List statusOptions = new ArrayList(); + HrmClassifiedProtectionBiz hrmClassifiedProtectionBiz = new HrmClassifiedProtectionBiz(); + statusOptions = hrmClassifiedProtectionBiz.getOptionListByUserId("0",""+user.getLanguage()); + searchConditionItem.setOptions(statusOptions); + itemlist.add(searchConditionItem); + } + + groupitem.put("items", itemlist); + lsGroup.add(groupitem); + retmap.put("systeminfocondition", lsGroup); + retmap.put("passwordComplexity", passwordComplexity); + retmap.put("minpasslen", minpasslen); + } + retmap.put("hrmId", user.getUID()); + retmap.put("hasJobTitlesAdd", HrmUserVarify.checkUserRight("HrmJobTitlesAdd:Add", user)); + //是否开启了RSA加密 + String openRSA = Util.null2String(Prop.getPropValue("openRSA","isrsaopen")); + retmap.put("openRSA",openRSA); + } catch (Exception e) { + retmap.put("api_status", false); + retmap.put("api_errormsg", e.getMessage()); + e.printStackTrace(); + } + return JSONObject.toJSONString(retmap); + } + + /** + * 保存新建人员simple + * + * @param request + * @param response + * @return + */ + public String saveSimple(HttpServletRequest request, HttpServletResponse response) { + Map retmap = new HashMap(); + RecordSet rs = new RecordSet(); + String sql = ""; + try { + User user = HrmUserVarify.getUser(request, response); + DepartmentComInfo departmentComInfo = new DepartmentComInfo(); + boolean canEdit = HrmUserVarify.checkUserRight("HrmResourceEdit:Edit", user); + if (!canEdit) { + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(22620, user.getLanguage())); + return JSONObject.toJSONString(retmap); + } + + String loginid = Util.null2String(request.getParameter("loginid")); + String accounttype = Util.null2s(Util.fromScreen3(request.getParameter("accounttype"), user.getLanguage()), "0"); + if(accounttype.equals("1"))loginid="";//次账号没有loginid + boolean canSave = false; + LN LN = new LN(); + int ckHrmnum = LN.CkHrmnum(); + if(loginid.length()>0) { + if (ckHrmnum < 0) {//只有License检查人数小于规定人数,才能修改。防止客户直接修改数据库数据 + canSave = true; + } + }else{ + canSave = true; + } + if (!canSave) { + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(84760, user.getLanguage())); + return JSONObject.toJSONString(retmap); + } + + /*验证码是否正确 start*/ + String validatecode = Util.null2String(request.getParameter("validatecode")); + String validateRand = Util.null2String((String) request.getSession(true).getAttribute("validateRand")); + request.getSession(true).removeAttribute("validateRand"); + if (!validateRand.toLowerCase().equals(validatecode.trim().toLowerCase()) || (loginid.length()>0&&"".equals(validatecode.trim().toLowerCase()))) { + retmap.put("message", SystemEnv.getHtmlLabelName(10000304, Util.getIntValue(user.getLanguage()))); + retmap.put("status", "-1"); + return JSONObject.toJSONString(retmap); + } + /*验证码是否正确 end*/ + + if (!loginid.equals("") && "0".equals(accounttype)) { + sql = "select count(1) from hrmresourceallview where loginid='" + loginid + "' "; + rs.executeSql(sql); + if (rs.next()) { + if (rs.getInt(1) > 0) { + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(15094, user.getLanguage())); + return JSONObject.toJSONString(retmap); + } + } + } + + String departmentid = Util.null2String(request.getParameter("departmentid")); + String subcompanyid = departmentComInfo.getSubcompanyid1(departmentid); + if (!loginid.equals("") && !subcompanyid.equals("0") && new HrmResourceManager().noMore(subcompanyid)) { + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(81926, user.getLanguage())); + return JSONObject.toJSONString(retmap); + } + + ResourceComInfo ResourceComInfo = new ResourceComInfo(); + HrmResourceBaseService HrmResourceBaseService = new HrmResourceBaseService(); + Map result = HrmResourceBaseService.addResourceBase(request, response, false); + + String addResourceBaseCode = result.get("status") ; + if("-1".equals(addResourceBaseCode)){ + retmap.put("status", "-1"); + retmap.put("message", result.get("message")); + return JSONObject.toJSONString(retmap) ; + } + + + int id = Util.getIntValue(result.get("id")); + String password = Util.null2String(request.getParameter("password")); + //是否开启了RSA加密 + String openRSA = Util.null2String(Prop.getPropValue("openRSA","isrsaopen")); + List passwordList = new ArrayList(); + if("1".equals(openRSA)){ + passwordList.add(password); + + RSA rsa = new RSA(); + List resultList = rsa.decryptList(request,passwordList); + password = resultList.get(0); + } + ChgPasswdReminder reminder = new ChgPasswdReminder(); + RemindSettings settings = reminder.getRemindSettings(); + + //判断是否开启了【启用初始密码】 + String defaultPasswordEnable = Util.null2String(settings.getDefaultPasswordEnable()); + //【初始密码】 + String defaultPassword = Util.null2String(settings.getDefaultPassword()); + //如果管理员设置的密码为空。并且开启了【启用初始密码】,且初始密码不为空,则默认取初始密码作为密码 + if (password.equals("") && defaultPasswordEnable.equals("1") && !defaultPassword.equals("")) { + password = defaultPassword; + } + + //判断是否开启了【禁止弱密码保存】 + String weakPasswordDisable = Util.null2s(settings.getWeakPasswordDisable(), "0"); + if (weakPasswordDisable.equals("1")) { + if (password.equals("")) {//密码为空的情况 + } else { + //判断是否为弱密码 + HrmWeakPasswordUtil hrmWeakPasswordUtil = new HrmWeakPasswordUtil(); + if (hrmWeakPasswordUtil.isWeakPsd(password)) { + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(515420, user.getLanguage())); + return JSONObject.toJSONString(retmap); + } + } + } + + int seclevel = Util.getIntValue(request.getParameter("seclevel"), 0); + if (id > 0) {//保存系统信息 + SimpleBizLogger logger = new SimpleBizLogger(); + Map params = ParamUtil.request2Map(request); + BizLogContext bizLogContext = new BizLogContext(); + bizLogContext.setLogType(BizLogType.HRM);//模块类型 + bizLogContext.setBelongType(BizLogSmallType4Hrm.HRM_RSOURCE_CARD);//所属大类型 + bizLogContext.setLogSmallType(BizLogSmallType4Hrm.HRM_RSOURCE_CARD_SYSTEM);//当前小类型 + bizLogContext.setOperateType(BizLogOperateType.ADD); + bizLogContext.setOperateAuditType(BizLogOperateAuditType.WARNING); + bizLogContext.setParams(params);//当前request请求参数 + logger.setUser(user);//当前操作人 + String mainSql = "select * from hrmresource where id=" + id; + logger.setMainSql(mainSql, "id");//主表sql + logger.setMainPrimarykey("id");//主日志表唯一key + logger.setMainTargetNameColumn("lastname");//当前targetName对应的列(对应日志中的对象名) + logger.before(bizLogContext);//写入操作前日志 + + String workstartdate = Util.null2String(request.getParameter("workstartdate"));//参加工作日期 + String companystartdate = Util.null2String(request.getParameter("companystartdate"));//入职日期 + String dsporder = Util.fromScreen3(request.getParameter("dsporder"), user.getLanguage()); + if (dsporder.length() == 0) dsporder = "" + id; + if (accounttype.equals("0")) { + + String encrptPassword = "" ; + String salt = "" ; + if(StringUtils.isNotBlank(password)){ + String[] encrypts = PasswordUtil.encrypt(password); + encrptPassword = encrypts[0] ; + salt = encrypts[1] ; + } + + sql = " update hrmresource set loginid='" + loginid + "', password='" + encrptPassword + "'," + + "seclevel=" + seclevel + ",dsporder=" + dsporder + + ",salt='" + salt + "',workstartdate='" + workstartdate + "',companystartdate='" + companystartdate + "' where id = " + id; + } else { + sql = " update hrmresource set seclevel=" + seclevel + ",dsporder=" + dsporder + + " ,workstartdate='" + workstartdate + "',companystartdate='" + companystartdate + "' where id = " + id; + } + HrmResourceWorkService hrmResourceWorkService =new HrmResourceWorkService(); + String workinfoid =String.valueOf(id); + hrmResourceWorkService.updateWorkInfo(request,workinfoid, user); + + rs.executeSql(sql); + try{ + //登录信息签名 + PasswordUtil.saveSign(""+id); + }catch (Exception e){ + writeLog(e); + } + HrmFaceCheckManager.setUserPassowrd(id+"",password); + HrmFaceCheckManager.sync(id+"", HrmFaceCheckManager.getOptInsert(), "HrmResourceAddService_saveSimple_addResource", HrmFaceCheckManager.getOaResource()); + + LogUtil.writeBizLog(logger.getBizLogContexts()); + } + + //同步RTX端的用户信息. + new OrganisationCom().checkUser(id); + new Thread(new OrganisationComRunnable("user", "add", "" + id)).start(); + ResourceComInfo.updateResourceInfoCache("" + id); + new PluginUserCheck().clearPluginUserCache("messager"); + //OA与第三方接口单条数据同步方法开始 + new HrmServiceManager().SynInstantHrmResource("" + id, "1"); + //OA与第三方接口单条数据同步方法结束 + //BBS集成相关 + String bbsLingUrl = new BaseBean().getPropValue(GCONST.getConfigFile(), "ecologybbs.linkUrl"); + if (!password.equals("0")) { + if (!bbsLingUrl.equals("")) { + new Thread(new weaver.bbs.BBSRunnable(loginid, password)).start(); + } + } + + //修改人员实时同步到CoreMail邮件系统 + //CoreMailAPI coremailapi = CoreMailAPI.getInstance(); + //coremailapi.synUser(""+id); + + retmap.put("status", "1"); + } catch (Exception e) { + writeLog("保存新建人员simple错误:" + e); + retmap.put("status", "-1"); + retmap.put("message", ""+ SystemEnv.getHtmlLabelName(22620,weaver.general.ThreadVarLanguage.getLang())+""); + } + return JSONObject.toJSONString(retmap); + } + + + public static ThreadLocal saveStatusThreadLocal = new ThreadLocal<>() ; + + /** + * 保存新建人员 + * + * @param request + * @param response + * @return + */ + public String save(HttpServletRequest request, HttpServletResponse response) { + saveStatusThreadLocal.set(true); + Map retmap = new HashMap(); + RecordSet rs = new RecordSet(); + RecordSet rs1 = new RecordSet(); + RecordSet temprs = new RecordSet(); + String sql = ""; + String sql1 = ""; + try { + User user = HrmUserVarify.getUser(request, response); + boolean canEdit = HrmUserVarify.checkUserRight("HrmResourceEdit:Edit", user); + if (!canEdit) { + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(22620, user.getLanguage())); + return JSONObject.toJSONString(retmap); + } + DepartmentComInfo departmentComInfo = new DepartmentComInfo(); + HrmResourceBaseService HrmResourceBaseService = new HrmResourceBaseService(); + HrmResourcePersonalService HrmResourcePersonalService = new HrmResourcePersonalService(); + HrmResourceWorkService HrmResourceWorkService = new HrmResourceWorkService(); + + String loginid = Util.null2String(request.getParameter("loginid")); + String accounttype = Util.null2s(Util.fromScreen3(request.getParameter("accounttype"), user.getLanguage()), "0"); + if(accounttype.equals("1"))loginid="";//次账号没有loginid + boolean canSave = false; + LN LN = new LN(); + int ckHrmnum = LN.CkHrmnum(); + if(loginid.length()>0) { + if (ckHrmnum < 0) {//只有License检查人数小于规定人数,才能修改。防止客户直接修改数据库数据 + canSave = true; + } + }else{ + canSave = true; + } + + if (!canSave) { + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(84760, user.getLanguage())); + return JSONObject.toJSONString(retmap); + } + + /*验证码是否正确 start*/ + String validatecode = Util.null2String(request.getParameter("validatecode")); + String validateRand = Util.null2String((String) request.getSession(true).getAttribute("validateRand")); + request.getSession(true).removeAttribute("validateRand"); + if(user.getUID()==1){ + //esb 同步需要,超级管理员暂不限制 + }else { + if (!validateRand.toLowerCase().equals(validatecode.trim().toLowerCase()) || (loginid.length() > 0 && "".equals(validatecode.trim().toLowerCase()))) { + retmap.put("message", SystemEnv.getHtmlLabelName(10000304, Util.getIntValue(user.getLanguage()))); + retmap.put("status", "-1"); + return JSONObject.toJSONString(retmap); + } + } + /*验证码是否正确 end*/ + + if (!loginid.equals("") && ("0".equals(accounttype) || StringUtils.isBlank(accounttype))) { + sql = "select count(1) from HrmResource where loginid='" + loginid + "' "; + rs.executeSql(sql); + if (rs.next()) { + if (rs.getInt(1) > 0) { + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(15094, user.getLanguage())); + return JSONObject.toJSONString(retmap); + } + } + //管理员表判断 + sql1 = "select count(1) from HrmResourceManager where loginid='" + loginid + "' "; + rs1.executeSql(sql1); + if (rs1.next()) { + if (rs1.getInt(1) > 0) { + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(15094, user.getLanguage())); + return JSONObject.toJSONString(retmap); + } + } + } + + String certificatenum = Util.null2String(request.getParameter("certificatenum"));/*证件号码*/ + certificatenum=certificatenum.trim(); + if(!certificatenum.equals("")){ + if(!accounttype.equals("1")) { + temprs.executeSql("select id from HrmResource where certificatenum='"+certificatenum+"' and (accounttype != '1' or accounttype is null)"); + if(temprs.next()){ + retmap.put("status", "-1"); + retmap.put("message", ""+ SystemEnv.getHtmlLabelName(83521,weaver.general.ThreadVarLanguage.getLang())+""); + return JSONObject.toJSONString(retmap); + } + } + } + + + + String departmentid = Util.null2String(request.getParameter("departmentid")); + String subcompanyid = departmentComInfo.getSubcompanyid1(departmentid); + if (!loginid.equals("") && !subcompanyid.equals("0") && new HrmResourceManager().noMore(subcompanyid)) { + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(81926, user.getLanguage())); + return JSONObject.toJSONString(retmap); + } + + Map result = HrmResourceBaseService.addResourceBase(request, response, false); + + String addResourceBaseCode = result.get("status") ; + if("-1".equals(addResourceBaseCode)){ + retmap.put("status", "-1"); + retmap.put("message", result.get("message")); + return JSONObject.toJSONString(retmap) ; + } + + int id = Util.getIntValue(result.get("id")); + if (Util.getIntValue(result.get("status")) > 0 && id > 0) { + ResourceComInfo ResourceComInfo = new ResourceComInfo(); + HrmResourcePersonalService.addResourcePersonal("" + id, request, response); + saveStatusThreadLocal.remove(); + HrmResourceWorkService.addResourceWork("" + id, request, response); + + SimpleBizLogger logger = new SimpleBizLogger(); + Map params = ParamUtil.request2Map(request); + BizLogContext bizLogContext = new BizLogContext(); + bizLogContext.setLogType(BizLogType.HRM);//模块类型 + bizLogContext.setBelongType(BizLogSmallType4Hrm.HRM_RSOURCE_CARD);//所属大类型 + bizLogContext.setLogSmallType(BizLogSmallType4Hrm.HRM_RSOURCE_CARD_SYSTEM);//当前小类型 + bizLogContext.setOperateType(BizLogOperateType.ADD); + bizLogContext.setOperateAuditType(BizLogOperateAuditType.WARNING); + bizLogContext.setParams(params);//当前request请求参数 + logger.setUser(user);//当前操作人 + String mainSql = "select * from hrmresource where id=" + id; + logger.setMainSql(mainSql, "id");//主表sql + logger.setMainPrimarykey("id");//主日志表唯一key + logger.setMainTargetNameColumn("lastname");//当前targetName对应的列(对应日志中的对象名) + logger.before(bizLogContext);//写入操作前日志 + + //保存系统信息 + String password = Util.null2String(request.getParameter("password")); + //判断是否开启了RSA加密 + String openRSA = Util.null2String(Prop.getPropValue("openRSA","isrsaopen")); + List passwordList = new ArrayList(); + if("1".equals(openRSA)){ + passwordList.add(password); + + RSA rsa = new RSA(); + List resultList = rsa.decryptList(request,passwordList); + password = resultList.get(0); + } + + ChgPasswdReminder reminder = new ChgPasswdReminder(); + RemindSettings settings = reminder.getRemindSettings(); + + //判断是否开启了【启用初始密码】 + String defaultPasswordEnable = Util.null2String(settings.getDefaultPasswordEnable()); + //【初始密码】 + String defaultPassword = Util.null2String(settings.getDefaultPassword()); + //如果管理员设置的密码为空。并且开启了【启用初始密码】,且初始密码不为空,则默认取初始密码作为密码 + if (password.equals("") && defaultPasswordEnable.equals("1") && !defaultPassword.equals("")) { + password = defaultPassword; + } + + String systemlanguage = Util.null2String(request.getParameter("systemlanguage")); + if (systemlanguage.equals("") || systemlanguage.equals("0")) systemlanguage = "7"; + String email = Util.null2String(request.getParameter("email")); + int seclevel = Util.getIntValue(request.getParameter("seclevel"), 0); + String userUsbType = Util.null2String(request.getParameter("userUsbType"));//辅助校验 + String usbstate = Util.null2String(request.getParameter("usbstate"));//是否启用 + String tokenkey = Util.null2String(request.getParameter("tokenKey"));//动态令牌序列号 + String serial = Util.null2String(request.getParameter("serial"));//海泰key秘钥 + String needdynapass = ""; + String needusb = ""; + StringBuffer upSql = new StringBuffer(); + if (userUsbType.equals("4")) { + needdynapass = "1"; + needusb = "0"; + } else if (userUsbType.equals("2") || userUsbType.equals("3")) { + needdynapass = "0"; + needusb = "1"; + } else { + needdynapass = "0"; + needusb = "0"; + } + if (!"".equals(usbstate) && !"".equals(userUsbType)) { + upSql.append(" ,needusb = ").append(needusb) + .append(" ,usbstate = ").append(usbstate) + .append(" ,needdynapass = ").append(needdynapass) + .append(" ,userUsbType = ").append(userUsbType); + if (userUsbType.equals("2")) { + upSql.append(" ,serial='" + (serial.equals("0") ? "" : serial) + "' "); + } else if (userUsbType.equals("3")) { + upSql.append(" ,tokenkey='" + tokenkey + "' "); + } + } + + String belongto = Util.fromScreen3(request.getParameter("belongto"), user.getLanguage()); + if (accounttype.equals("1") && loginid.equalsIgnoreCase("")) { + rs.executeSql("select loginid from HrmResource where id =" + belongto); + if (rs.next()) { + loginid = rs.getString(1); + } + if (!loginid.equals("")) { + loginid = loginid + (id + 1); + } + } + + if (!accounttype.equals("1") && !loginid.equalsIgnoreCase("")) { + String encrptPassword = "" ; + String salt = "" ; + if(StringUtils.isNotBlank(password)){ + String[] encrypts = PasswordUtil.encrypt(password); + encrptPassword = encrypts[0] ; + salt = encrypts[1] ; + } + upSql.append(" ,loginid='" + loginid + "' "); + upSql.append(" ,password='" + encrptPassword + "',salt='" + salt + "' "); + } + + String dsporder = Util.fromScreen3(request.getParameter("dsporder"), user.getLanguage()); + if (dsporder.length() == 0) dsporder = "" + id; + sql = " update hrmresource set systemlanguage=" + systemlanguage + ",email='" + email + "',seclevel=" + seclevel + + ",dsporder=" + dsporder + + upSql.toString() + + " where id = " + id; + rs.executeSql(sql); + + String classification = Util.null2String(request.getParameter("classification")); + String classificationSql = "update HrmResource set classification=?,encKey=?,crc=? where id=?"; + Map crcInfo = new EncryptUtil().getLevelCRC(""+id, classification); + String encKey = Util.null2String(crcInfo.get("encKey")); + String crc = Util.null2String(crcInfo.get("crc")); + rs.executeUpdate(classificationSql, classification, encKey, crc, id); + + LogUtil.writeBizLog(logger.getBizLogContexts()); + ResourceComInfo.updateResourceInfoCache("" + id); + + try{ + //登录信息签名 + PasswordUtil.saveSign(""+id); + }catch (Exception e){ + writeLog(e); + } + HrmFaceCheckManager.setUserPassowrd(id+"",password); + HrmFaceCheckManager.sync(id+"", HrmFaceCheckManager.getOptInsert(), "HrmResourceAddService_save_addResource", HrmFaceCheckManager.getOaResource()); + } + retmap.put("status", "1"); + } catch (Exception e) { + writeLog("保存新建人员simple错误:" + e); + retmap.put("status", "-1"); + retmap.put("message", ""+ SystemEnv.getHtmlLabelName(22620,weaver.general.ThreadVarLanguage.getLang())+""); + } + return JSONObject.toJSONString(retmap); + } +} diff --git a/领悦二开new/src/com/api/hrm/service/HrmResourceBaseService.java b/领悦二开new/src/com/api/hrm/service/HrmResourceBaseService.java new file mode 100644 index 0000000..ccbdb8c --- /dev/null +++ b/领悦二开new/src/com/api/hrm/service/HrmResourceBaseService.java @@ -0,0 +1,3635 @@ +package com.api.hrm.service; + +import java.io.File; +import java.lang.reflect.Method; +import java.text.SimpleDateFormat; +import java.util.*; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import javax.ws.rs.core.Context; + +import com.alibaba.fastjson.JSONObject; +import com.api.doc.detail.util.DocDownloadCheckUtil; +import com.api.hrm.bean.HrmFieldBean; +import com.api.hrm.bean.RightMenu; +import com.api.hrm.bean.RightMenuType; +import com.api.hrm.util.HrmFieldSearchConditionComInfo; +import com.api.hrm.util.HrmFieldUtil; +import com.api.hrm.util.ServiceUtil; +import com.api.browser.bean.SearchConditionItem; +import com.api.browser.bean.SearchConditionOption; + +import com.cloudstore.dev.api.util.TextUtil; +import com.engine.common.biz.SimpleBizLogger; +import com.engine.common.constant.BizLogOperateType; +import com.engine.common.constant.BizLogSmallType4Hrm; +import com.engine.common.constant.BizLogType; +import com.engine.common.entity.BizLogContext; +import com.engine.common.service.HrmCommonService; +import com.engine.common.service.impl.HrmCommonServiceImpl; +import com.engine.common.util.LogUtil; +import com.engine.common.util.ParamUtil; +import com.engine.hrm.biz.HrmFieldManager; +import com.engine.hrm.entity.RuleCodeType; +import com.engine.hrm.util.CodeRuleManager; +import com.engine.hrm.util.face.HrmFaceCheckManager; +import com.engine.kq.wfset.util.KQ122Util; +import com.engine.portal.biz.constants.ModuleConstants; +import com.engine.portal.biz.nonstandardfunction.SysModuleInfoBiz; +import com.engine.hrm.util.face.ValidateFieldManager; +import com.engine.hrm.util.face.bean.CheckItemBean; +import com.lingyue.util.KqUtil; +import ln.LN; +import org.apache.commons.lang3.StringUtils; +import weaver.hrm.definedfield.HrmFieldComInfo; +import weaver.hrm.job.JobCallComInfo; +import weaver.blog.BlogShareManager; +import weaver.common.DateUtil; +import weaver.common.StringUtil; +import weaver.conn.RecordSet; +import weaver.conn.RecordSetTrans; +import weaver.cowork.CoworkShareManager; +import weaver.cpt.search.CptSearchComInfo; +import weaver.crm.CrmShareBase; +import weaver.docs.docs.CustomFieldManager; +import weaver.docs.search.DocSearchComInfo; +import weaver.file.FileUpload; +import weaver.file.ImageFileManager; +import weaver.file.Prop; +import weaver.filter.XssUtil; +import weaver.formmode.cuspage.cpt.Cpt4modeUtil; +import weaver.general.BaseBean; +import weaver.general.GCONST; +import weaver.general.StaticObj; +import weaver.general.Util; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; +import weaver.hrm.appdetach.AppDetachComInfo; +import weaver.hrm.common.DbFunctionUtil; +import weaver.hrm.company.DepartmentComInfo; +import weaver.hrm.company.SubCompanyComInfo; +import weaver.hrm.companyvirtual.DepartmentVirtualComInfo; +import weaver.hrm.definedfield.HrmFieldGroupComInfo; +import weaver.hrm.finance.SalaryManager; +import weaver.hrm.job.JobActivitiesComInfo; +import weaver.hrm.job.JobTitlesComInfo; +import weaver.hrm.location.LocationComInfo; +import weaver.hrm.moduledetach.ManageDetachComInfo; +import weaver.hrm.privacy.PrivacyBaseComInfo; +import weaver.hrm.privacy.PrivacyComInfo; +import weaver.hrm.privacy.PrivacyUtil; +import weaver.hrm.privacy.UserPrivacyComInfo; +import weaver.hrm.resource.*; +import weaver.hrm.settings.ChgPasswdReminder; +import weaver.hrm.settings.RemindSettings; +import weaver.hrm.tools.HrmResourceFile; +import weaver.hrm.tools.HrmValidate; +//import weaver.interfaces.email.CoreMailAPI; +import weaver.interfaces.hrm.HrmServiceManager; +import weaver.license.PluginUserCheck; +import weaver.login.Account; +import weaver.login.VerifyLogin; +import weaver.proj.search.SearchComInfo; +import weaver.rtx.OrganisationCom; +import weaver.rtx.OrganisationComRunnable; +import weaver.system.SysRemindWorkflow; +import weaver.systeminfo.MouldStatusCominfo; +import weaver.systeminfo.SysMaintenanceLog; +import weaver.systeminfo.SystemEnv; +import weaver.systeminfo.language.LanguageComInfo; +import weaver.systeminfo.setting.HrmUserSettingComInfo; +import weaver.systeminfo.systemright.CheckSubCompanyRight; +import weaver.wechat.util.Utils; +import weaver.workflow.search.WorkflowRequestUtil; +import weaver.encrypt.EncryptUtil; + +/*** + * 人员卡片 + * @author lvyi + * + */ +public class HrmResourceBaseService extends BaseBean { + private static final char separator = Util.getSeparator(); + private String today = DateUtil.getCurrentDate(); + + private boolean isMobx = false; + private String id = ""; + + /** + * 人员卡片头部信息 + * + * @param request + * @param response + * @return + */ + public String getResourceBaseTitle(HttpServletRequest request, HttpServletResponse response) { + Map retmap = new HashMap(); + try { + User user = HrmUserVarify.getUser(request, response); + AppDetachComInfo adci = new AppDetachComInfo(); + HrmListValidate hrmListValidate = new HrmListValidate(); + boolean hasRight = false; + String id = Util.null2String(request.getParameter("id")); + if (id.equals("") || id.equals(Util.null2String(user.getUID() + ""))) { + id = String.valueOf(user.getUID()); + hasRight = true; + } else { + hasRight = adci.checkUserAppDetach(id, "1", user) == 1; + } + retmap.put("hasRight", hasRight); + if(!hasRight){ + return JSONObject.toJSONString(retmap); + } + ResourceComInfo ResourceComInfo = new ResourceComInfo(); + DepartmentComInfo DepartmentComInfo = new DepartmentComInfo(); + Map jsondata = new HashMap(); + + RecordSet rs = new RecordSet(); + String sql = "select * from hrmresource where id=" + id; + rs.executeSql(sql); + if (rs.next()) { + String lastname = Util.toScreen(rs.getString("lastname"), user.getLanguage()); + String workcode = Util.toScreen(rs.getString("workcode"), user.getLanguage()); + String sex = Util.null2String(rs.getString("sex")).trim(); + if(sex.length()==0) sex = "0"; + String departmentid = Util.toScreen(rs.getString("departmentid"), user.getLanguage()); + String subcompanyid = Util.toScreen(rs.getString("subcompanyid1"), user.getLanguage()); + lastname = lastname.endsWith("\\") && !lastname.endsWith("\\\\") == true ? lastname + "\\" : lastname; + lastname = StringUtil.replace(lastname, "'", "\\\\'"); + + String messagerUrls = Util.toScreen(rs.getString("messagerurl"), user.getLanguage()); + String resourceimageid = ResourceComInfo.getResourceimageid(id); + if (messagerUrls.length() == 0 && !resourceimageid.equals("0") && resourceimageid.length() > 0) { + messagerUrls = ServiceUtil.saveMessagerUrl(Util.getIntValue(resourceimageid), id); + } else { + messagerUrls = ResourceComInfo.getMessagerUrls(id); + } +// String filePath = GCONST.getRootPath() + messagerUrls; +// File file = new File(filePath); +// if (!file.exists() || !hrmListValidate.isValidate(36)) { +// if (resourceimageid > 0) { +// String mainControlHost = Util.null2String(Prop.getInstance().getPropValue("Others", "MAINCONTROLHOST")); +// messagerUrls = mainControlHost + "/weaver/weaver.file.FileDownload?fileid=" + resourceimageid; +// } else { +// if (sex.equals("0")) { +// messagerUrls = "/messager/images/icon_m_wev8.jpg"; +// } else if (sex.equals("1")) { +// messagerUrls = "/messager/images/icon_w_wev8.jpg"; +// } +// } +// } +// +// boolean USERICONLASTNAME = Util.null2String(new BaseBean().getPropValue("Others", "USERICONLASTNAME")).equals("1"); +// if (USERICONLASTNAME && (messagerUrls.indexOf("icon_w_wev8.jpg") > -1 || messagerUrls.indexOf("icon_m_wev8.jpg") > -1 || messagerUrls.indexOf("dummyContact.png") > -1)) { +// jsondata.put("shortname", User.getLastname(Util.null2String(Util.formatMultiLang(lastname, "" + user.getLanguage())))); +// } + jsondata.put("lastname", lastname); + jsondata.put("messagerurl", messagerUrls); + jsondata.put("requestParams", ResourceComInfo.getUserIconInfoStr(id,user)); + jsondata.put("workcode", workcode); + HrmFieldComInfo hrmFieldComInfo = new HrmFieldComInfo(); + String isused = Util.null2String(hrmFieldComInfo.getBaseFieldMap("sex").getString("isused")); + if ("1".equals(isused)) { + Map sexdata = new HashMap(); + jsondata.put("sex", sexdata);//0:男性,1:女性 + sexdata.put("value", sex); + if (sex.equals("0")) { + sexdata.put("name", SystemEnv.getHtmlLabelName(28473, user.getLanguage())); + } else if (sex.equals("1")) { + sexdata.put("name", SystemEnv.getHtmlLabelName(28474, user.getLanguage())); + } + } + if (Util.null2String(Prop.getInstance().getPropValue("Others", "showDepartmentFullName")).equals("1")) { + jsondata.put("orginfo", DepartmentComInfo.getAllParentDepartmentNames(departmentid, subcompanyid)); + } else { + jsondata.put("orginfo", DepartmentComInfo.getAllParentDepartmentMarks(departmentid, subcompanyid)); + } + } + retmap.put("result", jsondata); + retmap.put("id", id); + } catch (Exception e) { + writeLog(e); + } + + return JSONObject.toJSONString(retmap); + } + + /** + * 查询人员列表右键菜单 + * + * @param request + * @param response + * @return + * @throws Exception + */ + public String getRightMenu(HttpServletRequest request, HttpServletResponse response) { + Map apidatas = new HashMap(); + try { + ChgPasswdReminder reminder = new ChgPasswdReminder(); + RemindSettings settings = reminder.getRemindSettings(); + User user = HrmUserVarify.getUser(request, response); + String id = Util.null2String(request.getParameter("id")); + if (id.equals("")) id = String.valueOf(user.getUID()); + + HrmListValidate HrmListValidate = new HrmListValidate(); + List rightMenus = new ArrayList(); + int language = user.getLanguage(); + int hrmdetachable = 0; + HttpSession session = request.getSession(true); + String status = ""; + String subcompanyid = ""; + String departmentid = ""; + + String textMessageSql = "select dataValue from ecology_message_valve_config where dataKey = 'emSwitch'"; + RecordSet textRs = new RecordSet(); + textRs.execute(textMessageSql); + textRs.next(); + //dataValue为0代表关闭发消息选项 + String dataValue = textRs.getString("dataValue"); + + RecordSet rs = new RecordSet(); + rs.executeSql("select subcompanyid1,departmentid, status from hrmresource where id = " + id); + if (rs.next()) { + status = Util.toScreen(rs.getString("status"), user.getLanguage()); + subcompanyid = Util.toScreen(rs.getString("subcompanyid1"), user.getLanguage()); + departmentid = Util.toScreen(rs.getString("departmentid"), user.getLanguage()); + if (subcompanyid == null || subcompanyid.equals("") || subcompanyid.equalsIgnoreCase("null")) + subcompanyid = "-1"; + session.setAttribute("hrm_subCompanyId", subcompanyid); + } + + boolean isSelf = false; + if (id.equals("" + user.getUID())) { + isSelf = true; + } + //人力资源模块是否开启了管理分权,如不是,则不显示框架,直接转向到列表页面(新的分权管理) + if (session.getAttribute("hrmdetachable") != null) { + hrmdetachable = Util.getIntValue(String.valueOf(session.getAttribute("hrmdetachable")), 0); + } else { + boolean isUseHrmManageDetach = new ManageDetachComInfo().isUseHrmManageDetach(); + if (isUseHrmManageDetach) { + hrmdetachable = 1; + session.setAttribute("detachable", "1"); + session.setAttribute("hrmdetachable", String.valueOf(hrmdetachable)); + } else { + hrmdetachable = 0; + session.setAttribute("detachable", "0"); + session.setAttribute("hrmdetachable", String.valueOf(hrmdetachable)); + } + } + int operatelevel = -1; + if (hrmdetachable == 1) { + operatelevel = new CheckSubCompanyRight().ChkComRightByUserRightCompanyId(user.getUID(), "HrmResourceEdit:Edit", Integer.parseInt(subcompanyid)); + } else { + if (HrmUserVarify.checkUserRight("HrmResourceEdit:Edit", user, departmentid)) + operatelevel = 2; + } + + + if (((isSelf && isHasModify(-1)) || operatelevel > 0) && !status.equals("10")) {//编辑 + rightMenus.add(new RightMenu(language, RightMenuType.BTN_EDIT, "editCard")); + } + + if (HrmListValidate.isValidate(33) && !isSelf && "1".equals(Utils.null2String(dataValue))) {//发送消息 + rightMenus.add(new RightMenu(language, RightMenuType.BTN_SENDMESAGE, "sendEmessage")); + } + + if (HrmListValidate.isValidate(31) && !isSelf) {//发送短信 + rightMenus.add(new RightMenu(language, RightMenuType.BTN_SENDSMSMESSAGE, "sendSmsMessage")); + } + + if (HrmListValidate.isValidate(19) && !isSelf) {//发送邮件 + rightMenus.add(new RightMenu(language, RightMenuType.BTN_SENDMAIL, "sendMail")); + } + + if (HrmListValidate.isValidate(32) && !isSelf) {//新建日程 + rightMenus.add(new RightMenu(language, RightMenuType.BTN_DOADDWORKPLANBYHRM, "doAddWorkPlanByHrm")); + } + + if (((isSelf && canEditUserIcon()) || operatelevel > 0) && !status.equals("10")) {//设置个人头像 + rightMenus.add(new RightMenu(language, RightMenuType.BTN_SetUserIcon, "showPortraitSetting")); + } + + Map params = new HashMap<>(); + params.put("logSmallType", BizLogSmallType4Hrm.HRM_RSOURCE_CARD_BASE.getCode()); + params.put("targetId", id); + rightMenus.add(new RightMenu(language, RightMenuType.BTN_log, "showLog", params)); + + apidatas.put("rightMenus", rightMenus); + } catch (Exception e) { + writeLog(e); + apidatas.put("api_status", false); + apidatas.put("api_errormsg", "catch exception : " + e.getMessage()); + } + return JSONObject.toJSONString(apidatas); + } + + public String isAdmin(HttpServletRequest request, HttpServletResponse response) { + User user = HrmUserVarify.getUser(request, response); + Map result = new HashMap(); + String id = Util.null2String(request.getParameter("id")); + if (id.length() == 0) { + id = "" + user.getUID(); + } + result.put("isAdmin", ServiceUtil.isAdmin(id)); + return JSONObject.toJSONString(result); + } + + public String getQRCode(HttpServletRequest request, HttpServletResponse response) { + Map jsondata = new HashMap(); + Map options = new HashMap(); + User user = HrmUserVarify.getUser(request, response); + String id = Util.null2String(request.getParameter("id")); + if (id.equals("")) id = String.valueOf(user.getUID()); + + if(!"".equals(id) && !id.equals(""+user.getUID())){ + AppDetachComInfo adci = new AppDetachComInfo(); + if(adci.isUseAppDetach()){ + if(!adci.getScopeIds(user, "resource", id)) { + jsondata.put("status", "-1"); + jsondata.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage())); + return JSONObject.toJSONString(jsondata); + } + } + } + + try { + //var data = { "lastname": "吕益", "mobile": "13899998888","telephone":"021-99998888","email":"lvyi@weaver.com","jobtitle":"开发工程师","department":"人力资源组","locationname":"上海"}; + RecordSet rs = new RecordSet(); + DepartmentComInfo DepartmentComInfo = new DepartmentComInfo(); + JobTitlesComInfo jobTitlesComInfo = new JobTitlesComInfo(); + LocationComInfo locationComInfo = new LocationComInfo(); + JobCallComInfo jobCallComInfo = new JobCallComInfo(); + HrmListValidate HrmListValidate = new HrmListValidate(); + + String sql = "select * from hrmresource where id=" + id; + rs.executeSql(sql); + if (rs.next()) { + String lastname = Util.toScreen(rs.getString("lastname"), user.getLanguage()); + String departmentid = Util.toScreen(rs.getString("departmentid"), user.getLanguage()); + String jobtitle = Util.toScreen(rs.getString("jobtitle"), user.getLanguage()); + String mobile = Util.toScreen(rs.getString("mobile"), user.getLanguage()); + String telephone = Util.toScreen(rs.getString("telephone"), user.getLanguage()); + String email = Util.toScreen(rs.getString("email"), user.getLanguage()); + String locationid = Util.toScreen(rs.getString("locationid"), user.getLanguage()); + String jobcallid = Util.toScreen(rs.getString("jobcall"), user.getLanguage()); + lastname = lastname.endsWith("\\") && !lastname.endsWith("\\\\") == true ? lastname + "\\" : lastname; + lastname = StringUtil.replace(lastname, "'", "\\\\'"); + boolean hasQRCode = HrmListValidate.isValidate(37); + + //隐私设置部分 + PrivacyComInfo pc = new PrivacyComInfo(); + Map mapShowSets = pc.getMapShowSets(); + Map mapShowTypeDefaults = pc.getMapShowTypeDefaults(); + mobile = PrivacyUtil.checkByPrivacy(id, user, "mobile", mobile, mapShowSets, mapShowTypeDefaults, pc); + telephone = PrivacyUtil.checkByPrivacy(id, user, "telephone", telephone, mapShowSets, mapShowTypeDefaults, pc); + email = PrivacyUtil.checkByPrivacy(id, user, "email", email, mapShowSets, mapShowTypeDefaults, pc); + + jsondata.put("hasQRCode", hasQRCode); + jsondata.put("options", options); + if (hasQRCode) { + options.put("lastname", lastname); + options.put("mobile", mobile); + options.put("telephone", telephone); + options.put("email", email); + options.put("jobtitle", jobTitlesComInfo.getJobTitlesname(jobtitle)); //对应的应该是岗位 + options.put("department", DepartmentComInfo.getDepartmentname(departmentid)); //对应的应该是职称 + //options.put("locationname", locationComInfo.getLocationname(departmentid)); + options.put("locationname", locationComInfo.getLocationname(locationid)); //对应的应该是工作地点 + } + } + } catch (Exception e) { + writeLog(e); + } + return JSONObject.toJSONString(jsondata); + } + + public String getHrmResourceItem(HttpServletRequest request, HttpServletResponse response) { + List> tablist = new ArrayList>(); + Map itemdata = new HashMap(); + User user = HrmUserVarify.getUser(request, response); + String resourceid = request.getParameter("id"); + boolean noLoadData = Util.null2String(request.getParameter("noLoadData")).equals("1");//不加载数据 + if (resourceid.equals("")) resourceid = String.valueOf(user.getUID()); + String currentUserId = "" + user.getUID(); + try { + boolean workflowshow = SysModuleInfoBiz.checkModuleStatus(ModuleConstants.Workflow); + boolean docshow = SysModuleInfoBiz.checkModuleStatus(ModuleConstants.Doc); + boolean customshow = SysModuleInfoBiz.checkModuleStatus(ModuleConstants.Crm); + boolean projectshow = SysModuleInfoBiz.checkModuleStatus(ModuleConstants.Project); + boolean cptshow = SysModuleInfoBiz.checkModuleStatus(ModuleConstants.Fa); + boolean coworkshow = SysModuleInfoBiz.checkModuleStatus(ModuleConstants.Cowork); + boolean weiboshow = SysModuleInfoBiz.checkModuleStatus(ModuleConstants.Blog); + + //流程 + if (workflowshow) { + int wf_count = 0; + if (!noLoadData) { + wf_count = new WorkflowRequestUtil().getRequestCount(user, resourceid); + } + itemdata = new HashMap(); + itemdata.put("name", "item_workflow"); + itemdata.put("label", SystemEnv.getHtmlLabelName(18015, user.getLanguage())); + itemdata.put("num", wf_count); + itemdata.put("icon", "/hrm/hrm_e9/image/workflow.png"); + itemdata.put("font-color", "#1ab7f4"); + itemdata.put("url", "/spa/workflow/static/index.html#/main/workflow/listDoing?resourceid=" + resourceid); + tablist.add(itemdata); + } + + //文档 + if (docshow) { + Object[] docInfo = new Object[]{"/spa/document/static/index.html#/main/document/search?viewcondition=2&doccreaterid=" + resourceid, "0"}; + if (!noLoadData) { + docInfo = new DocSearchComInfo().getDocCount4Hrm(resourceid, user); + } + itemdata = new HashMap(); + itemdata.put("name", "item_doc"); + itemdata.put("label", SystemEnv.getHtmlLabelName(58, user.getLanguage())); + itemdata.put("num", docInfo[1]); + itemdata.put("icon", "/hrm/hrm_e9/image/doc.png"); + itemdata.put("font-color", "#68c12c"); + itemdata.put("url", "/spa/document/static/index.html#/main/document/search?viewcondition=2&doccreaterid=" + resourceid); + tablist.add(itemdata); + } + + //客户 + if (customshow) { + String[] crmInfo = new String[]{"", "0"}; + if (!noLoadData) { + crmInfo = new CrmShareBase().getCrmCount4Hrm(resourceid, currentUserId); + } + itemdata = new HashMap(); + itemdata.put("name", "item_custom"); + itemdata.put("label", SystemEnv.getHtmlLabelName(136, user.getLanguage())); + itemdata.put("num", crmInfo[1]); + itemdata.put("icon", "/hrm/hrm_e9/image/custom.png"); + itemdata.put("font-color", "#558de4"); + itemdata.put("url", "/spa/crm/static/index.html#/main/crm/customer/hrmView?searchHrmId=" + resourceid); + tablist.add(itemdata); + } + + //项目 + if (projectshow) { + String[] prjInfo = new String[]{"/spa/prj/index.html#/main/prj/mineProject?search_resourceid=" + resourceid, "0"}; + if (!noLoadData) { + prjInfo = new SearchComInfo().getPrjCount4Hrm(resourceid, user); + } + itemdata = new HashMap(); + itemdata.put("name", "item_project"); + itemdata.put("label", SystemEnv.getHtmlLabelName(101, user.getLanguage())); + itemdata.put("num", prjInfo[1]); + itemdata.put("icon", "/hrm/hrm_e9/image/project.png"); + itemdata.put("font-color", "#29cf87"); + itemdata.put("url", "/spa/prj/index.html#/main/prj/mineProject?search_resourceid=" + resourceid); + tablist.add(itemdata); + } + + //资产 + if (cptshow) { + String url = "/spa/cpt/index.html#/main/cpt/mycapital?hrmid=" + resourceid; + String[] cptInfo = new String[]{url, "0"}; + if (!noLoadData) { + cptInfo = new CptSearchComInfo().getCptCount4Hrm(resourceid, user); + } + itemdata = new HashMap(); + itemdata.put("name", "item_cpt"); + itemdata.put("label", SystemEnv.getHtmlLabelName(535, user.getLanguage())); + itemdata.put("num", cptInfo[1]); + itemdata.put("icon", "/hrm/hrm_e9/image/cpt.png"); + itemdata.put("font-color", "#f6ae40"); + itemdata.put("url", url); + tablist.add(itemdata); + } + + //协作 + if (coworkshow) { + String[] coworkInfo = new String[]{"", "0"}; + if (!noLoadData) { + coworkInfo = new CoworkShareManager().getCoworkCount4Hrm(resourceid, currentUserId); + } + itemdata = new HashMap(); + itemdata.put("name", "item_cowork"); + itemdata.put("label", SystemEnv.getHtmlLabelName(17855, user.getLanguage())); + itemdata.put("num", coworkInfo[1]); + itemdata.put("icon", "/hrm/hrm_e9/image/cowork.png"); + itemdata.put("font-color", "#826efd"); + itemdata.put("url", "/spa/cowork/static/index.html#/main/cowork/hrmview?searchHrmid=" + resourceid); + tablist.add(itemdata); + } + + //微博 + if (weiboshow) { + String[] weiboInfo = new String[]{"", "0"}; + if (!noLoadData) { + weiboInfo = new BlogShareManager().getBlogCount4Hrm(resourceid); + } + itemdata = new HashMap(); + itemdata.put("name", "item_weibo"); + itemdata.put("label", SystemEnv.getHtmlLabelName(26467, user.getLanguage())); + itemdata.put("num", weiboInfo[1]); + itemdata.put("icon", "/hrm/hrm_e9/image/weibo.png"); + itemdata.put("font-color", "#fb6f47"); + itemdata.put("url", "/spa/blog/static/index.html#/user/" + resourceid); + tablist.add(itemdata); + } + } catch (Exception e) { + writeLog(e); + } + + return JSONObject.toJSONString(tablist); + } + + public String getHrmResourceTab(HttpServletRequest request, HttpServletResponse response) { + int isgoveproj = 0; + User user = HrmUserVarify.getUser(request, response); + String id = Util.null2String(request.getParameter("id")); + this.id = id; + this.isMobx = Util.null2String(request.getParameter("isMobx")).equals("1"); + if (id.equals("")) id = String.valueOf(user.getUID()); + List> tablist = new ArrayList>(); + try { + AppDetachComInfo AppDetachComInfo = new AppDetachComInfo(); + ResourceComInfo ResourceComInfo = new ResourceComInfo(); + AllManagers AllManagers = new AllManagers(); + HrmListValidate HrmListValidate = new HrmListValidate(); + CheckSubCompanyRight CheckSubCompanyRight = new CheckSubCompanyRight(); + MouldStatusCominfo MouldStatusCominfo = new MouldStatusCominfo(); + HrmResourceBaseTabComInfo HrmResourceBaseTabComInfo = new HrmResourceBaseTabComInfo(); + RecordSet rs = new RecordSet(); + + //人力资源模块是否开启了管理分权 + int hrmdetachable = 0; + HttpSession session = request.getSession(true); + ManageDetachComInfo ManageDetachComInfo = new ManageDetachComInfo(); + if (session.getAttribute("hrmdetachable") != null) { + hrmdetachable = Util.getIntValue(String.valueOf(session.getAttribute("hrmdetachable")), 0); + } else { + boolean isUseHrmManageDetach = ManageDetachComInfo.isUseHrmManageDetach(); + if (isUseHrmManageDetach) { + hrmdetachable = 1; + session.setAttribute("detachable", "1"); + session.setAttribute("hrmdetachable", String.valueOf(hrmdetachable)); + } else { + hrmdetachable = 0; + session.setAttribute("detachable", "0"); + session.setAttribute("hrmdetachable", String.valueOf(hrmdetachable)); + } + } + if (AppDetachComInfo.isUseAppDetach()) { + boolean isApp = true; + if(!AppDetachComInfo.getScopeIds(user, "resource",id)) { + isApp = false; + } + if (!isApp) { + String errMsg = SystemEnv.getHtmlLabelName(2012, user.getLanguage()); + HashMap jsondata = new HashMap(); + jsondata.put("errMsg", errMsg); + jsondata.put("status", "-1"); + return jsondata.toString(); + } + } + String departmentid = ""; + String subcompanyid = ""; + rs.executeProc("HrmResource_SelectByID", id); + if (rs.next()) { + departmentid = Util.toScreen(rs.getString("departmentid"), user.getLanguage()); /*所属部门*/ + subcompanyid = Util.toScreen(rs.getString("subcompanyid1"), user.getLanguage()); + } + + /*显示权限判断*/ + int userid = user.getUID(); + boolean isSelf = false; + boolean isManager = false; +// boolean isSys = ResourceComInfo.isSysInfoView(userid,id); +// boolean isCap = ResourceComInfo.isCapInfoView(userid,id); +// boolean ishasF =HrmUserVarify.checkUserRight("HrmResourceWelfareEdit:Edit",user); + boolean isSys = ResourceComInfo.isSysInfoView2(userid, id); + boolean isCap = ResourceComInfo.isCapInfoView2(userid, id); + boolean ishasF = HrmUserVarify.checkUserRight("HrmResourceWelfareEdit:Edit", user,departmentid) || ResourceComInfo.isFinInfoView2(userid, id); + ; + + + AllManagers.getAll(id); + if (id.equals("" + user.getUID())) { + isSelf = true; + } + while (AllManagers.next()) { + String tempmanagerid = AllManagers.getManagerID(); + if (tempmanagerid.equals("" + user.getUID())) { + isManager = true; + } + } + int idx = 0; + //tabInfo.put(SystemEnv.getHtmlLabelName(,user.getLanguage()), "/hrm/resource/HrmResourceBase.jsp?isfromtab=true&id="+id); + tablist.add(setTabInfo("HrmResourceBase", 1361, GCONST.getContextPath()+"/hrm/resource/HrmResourceBase.jsp?isfromtab=true&id=" + id, "/main/hrm/resource/HrmResourceBase/" + id, user)); + idx++; + + //原工作历程变为其他 + if (HrmListValidate.isValidate(29)) { + //tabInfo.put(SystemEnv.getHtmlLabelName(30804,user.getLanguage()), "/hrm/resource/HrmResourceTotal.jsp?isfromtab=true&id="+id); + tablist.add(setTabInfo("HrmResourceTotal", 30804, GCONST.getContextPath()+"/wui/index.html#/main/hrm/HrmResourceTotal" + id, "/main/hrm/HrmResourceTotal" + id, user)); + idx++; + } + + //tabInfo.put(SystemEnv.getHtmlLabelName(81554,user.getLanguage()), "/hrm/resource/HrmResourceGroupView.jsp?id="+id); + if (HrmListValidate.isValidate(64)) { + tablist.add(setTabInfo("HrmResourceGroupView", 81554, GCONST.getContextPath()+"/hrm/resource/HrmResourceGroupView.jsp?id=" + id, "/main/hrm/resource/HrmResourceGroupView/" + id, user)); + idx++; + } + + int operatelevel = -1; + if (hrmdetachable == 1) { + operatelevel = CheckSubCompanyRight.ChkComRightByUserRightCompanyId(user.getUID(), "HrmResourceEdit:Edit", Integer.parseInt(subcompanyid)); + } else { + if (HrmUserVarify.checkUserRight("HrmResourceEdit:Edit", user, departmentid)) { + operatelevel = 2; + } + } + int operatelevelnew = -1; + if (hrmdetachable == 1) { + operatelevelnew = CheckSubCompanyRight.ChkComRightByUserRightCompanyId(user.getUID(), "ResourcesInformationSystem:All", Integer.parseInt(subcompanyid)); + } else { + String departmentidtmp = ResourceComInfo.getDepartmentID(id); + if (HrmUserVarify.checkUserRight("ResourcesInformationSystem:All", user, departmentidtmp)) { + operatelevelnew = 2; + } + } + + StaticObj staticobj = StaticObj.getInstance(); + String software = (String) staticobj.getObject("software"); + if (software == null) software = "ALL"; + if (software.equals("ALL") || software.equals("HRM")) { + if ((isSelf || operatelevel >= 0) && HrmListValidate.isValidate(11)) { + //tabInfo.put(SystemEnv.getHtmlLabelName(15687,user.getLanguage()), "/hrm/resource/HrmResourcePersonalView.jsp?isfromtab=true&id="+id); + tablist.add(setTabInfo("HrmResourcePersonalView", 15687, GCONST.getContextPath()+"/hrm/resource/HrmResourcePersonalView.jsp?isfromtab=true&id=" + id, "/main/hrm/resource/HrmResourcePersonalView/" + id, user)); + idx++; + } + if ((isSelf || isManager || operatelevel >= 0) && HrmListValidate.isValidate(12)) { + //tabInfo.put(SystemEnv.getHtmlLabelName(15688,user.getLanguage()), "/hrm/resource/HrmResourceWorkView.jsp?isfromtab=true&id="+id); + tablist.add(setTabInfo("HrmResourceWorkView", 15688, GCONST.getContextPath()+"/hrm/resource/HrmResourceWorkView.jsp?isfromtab=true&id=" + id, "/main/hrm/resource/HrmResourceWorkView/" + id, user)); + idx++; + } + } + + if ((isSelf || operatelevelnew >= 0 || isSys) && HrmListValidate.isValidate(15)) { + //tabInfo.put(SystemEnv.getHtmlLabelName(15804,user.getLanguage()), "/hrm/resource/HrmResourceSystemView.jsp?isfromtab=true&id="+id+"&isView=1"); + tablist.add(setTabInfo("HrmResourceSystemView", 15804, GCONST.getContextPath()+"/hrm/resource/HrmResourceSystemView1.jsp?isfromtab=true&id=" + id + "&isView=1", "/main/hrm/resource/HrmResourceSystemView/" + id, user)); + idx++; + } + + if (software.equals("ALL") || software.equals("HRM")) { + if (isgoveproj == 0) { + if ((isSelf || ishasF) && HrmListValidate.isValidate(13)) { + //tabInfo.put(SystemEnv.getHtmlLabelName(16480,user.getLanguage()), "/hrm/resource/HrmResourceFinanceView.jsp?isfromtab=true&id="+id+"&isView=1"); + tablist.add(setTabInfo("HrmResourceFinanceView", 16480, GCONST.getContextPath()+"/hrm/resource/HrmResourceFinanceView.jsp?isfromtab=true&id=" + id + "&isView=1", "/main/hrm/resource/HrmResourceFinanceView/" + id, user)); + idx++; + } + } + if ((isSelf || operatelevel >= 0 || isCap) && HrmListValidate.isValidate(14) && "1".equals(MouldStatusCominfo.getStatus("cpt"))) { + String cpturl = GCONST.getContextPath()+"/cpt/search/SearchOperation.jsp?resourceid=" + id + "&isdata=2&from=hrmResourceBase"; + if (Cpt4modeUtil.isUse()) { + cpturl = GCONST.getContextPath()+"/formmode/search/CustomSearchBySimpleIframe.jsp?customid=" + Cpt4modeUtil.getSearchid("wdzc") + "&resourceid=" + id + "&from=hrmResourceBase&mymodetype=wdzc&sqlwhere=" + new XssUtil().put("where resourceid=" + id); + } + //tabInfo.put(SystemEnv.getHtmlLabelName(15806,user.getLanguage()), cpturl); + tablist.add(setTabInfo("iframe-" + (idx++) + "-cptsearch", 15806, GCONST.getContextPath()+"/spa/cpt/index.html#/main/cpt/mycapital?from=hrm&hrmid=" + id, "/spa/cpt/index.html#/main/cptcapital/mycapitalResult", user)); + } + } + + if ((isSelf || isManager || HrmUserVarify.checkUserRight("HrmResource:Workflow", user, departmentid)) && HrmListValidate.isValidate(17)) { + //tabInfo.put(SystemEnv.getHtmlLabelName(1207,user.getLanguage()), "/workflow/search/WFSearchTemp.jsp?method=all&viewScope=doing&complete=0&viewcondition=0&resourceid="+id); + tablist.add(setTabInfo("iframe-" + (idx++) + "-workflowsearch", 1207, GCONST.getContextPath()+"/spa/workflow/static/index.html#/main/workflow/listDoing?needTop=false&needTree=false&resourceid=" + id, "/spa/workflow/index.html#/main/workflow/listDoing", user)); + //tablist.add(setTabInfo("iframe-"+(idx++)+"-workflowsearch",1207,"/workflow/search/WFSearchTemp.jsp?method=all&viewScope=doing&complete=0&viewcondition=0&resourceid="+id,"/spa/workflow/index.html#/main/workflow/listDoing",user)); + } + if ((isSelf || isManager || HrmUserVarify.checkUserRight("HrmResource:Plan", user, departmentid)) && HrmListValidate.isValidate(18)) { + //tabInfo.put(SystemEnv.getHtmlLabelName(2192,user.getLanguage()), "/workplan/data/WorkPlan.jsp?resourceid="+id); + tablist.add(setTabInfo("iframe-" + (idx++) + "-workplansearch", 2192, GCONST.getContextPath()+"/spa/workplan/static/index.html#/main/wp/myWorkPlan?fromcard=true&selectedUser=" + id, "/main/workplan/data/WorkPlan", user)); + } + + if (isgoveproj == 0) { + if (software.equals("ALL") || software.equals("HRM")) { + if (isSelf || isManager || HrmUserVarify.checkUserRight("HrmResource:Absense", user, departmentid)) { + if (HrmListValidate.isValidate(20)) { + //tabInfo.put(SystemEnv.getHtmlLabelName(20080,user.getLanguage()), "/hrm/resource/HrmResourceAbsense.jsp?resourceid="+id); + tablist.add(setTabInfo("HrmResourceAbsense", 20080, GCONST.getContextPath()+"/hrm/resource/HrmResourceAbsense.jsp?resourceid=" + id, "/main/hrm/HrmResourceAbsense", user)); + idx++; + } + } + if (isSelf || isManager || HrmUserVarify.checkUserRight("HrmResource:TrainRecord", user)) { + if (HrmListValidate.isValidate(21)) { + //tabInfo.put(SystemEnv.getHtmlLabelName(816,user.getLanguage()), "/hrm/resource/HrmResourceTrainRecord.jsp?resourceid="+id); + tablist.add(setTabInfo("HrmResourceTrainRecord", 816, GCONST.getContextPath()+"/hrm/resource/HrmResourceTrainRecord.jsp?resourceid=" + id, "/main/hrm/resource/HrmResourceTrainRecord/" + id, user)); + idx++; + } + } + if (isSelf || isManager || HrmUserVarify.checkUserRight("HrmResource:RewardsRecord", user)) { + if (HrmListValidate.isValidate(22)) { + //tabInfo.put(SystemEnv.getHtmlLabelName(16065,user.getLanguage()), "/hrm/resource/HrmResourceRewardsRecordView.jsp?id="+id); + tablist.add(setTabInfo("HrmResourceRewardsRecordView", 16065, GCONST.getContextPath()+"/hrm/resource/HrmResourceRewardsRecordView.jsp?id=" + id, "/main/hrm/resource/HrmResourceRewardsRecordView/" + id, user)); + idx++; + } + } + } + } + + //判断该用户对编辑人员机构是否具有的角色维护权限(TD19119) + boolean rolesmanage = false; + int varifylevel = -1; + if (hrmdetachable == 1) { + varifylevel = CheckSubCompanyRight.ChkComRightByUserRightCompanyId(user.getUID(), "HrmRolesEdit:Edit", Integer.parseInt(subcompanyid)); + if (varifylevel > 0) { + if (HrmUserVarify.checkUserRight("HrmRolesEdit:Edit", user)) { + varifylevel = 2; + } else { + varifylevel = -1; + } + } + } else { + if (HrmUserVarify.checkUserRight("HrmRolesEdit:Edit", user)) { + varifylevel = 2; + } + } + if (varifylevel > 0) { + rolesmanage = true; + } + + if (HrmUserVarify.checkUserRight("HrmResourceEdit:Edit", user, departmentid) && rolesmanage) { + //tabInfo.put(SystemEnv.getHtmlLabelName(16527,user.getLanguage()), "/hrm/roles/HrmResourceNewRoles.jsp?resourceid="+id ); + tablist.add(setTabInfo("HrmResourceNewRoles", 16527, GCONST.getContextPath()+"/hrm/roles/HrmResourceNewRoles.jsp?resourceid=" + id, "/main/hrm/resource/HrmResourceNewRoles/" + id, user)); + idx++; + } + + //取自定义标签页 + HrmResourceBaseTabComInfo.setTofirstRow(); + while (HrmResourceBaseTabComInfo.next()) { + if (!HrmResourceBaseTabComInfo.getIsopen().equals("1")) { + continue; + } + String tab_urlTemp = HrmResourceBaseTabComInfo.getLinkurl(); + String tab_urlTemp1 = tab_urlTemp.replaceAll("\\Q{#id}", "" + id); + if (tab_urlTemp1.indexOf("?") >= 0) { + tab_urlTemp1 += "&hrmResourceID=" + id; + } else { + tab_urlTemp1 += "?hrmResourceID=" + id; + } + String groupname = HrmResourceBaseTabComInfo.getGroupName(); + if (HrmResourceBaseTabComInfo.getTabnum().trim().length() != 0) { + try { + Class c = Class.forName(HrmResourceBaseTabComInfo.getTabnum().trim()); + Object cObject = c.newInstance(); + Method m = c.getMethod("execute"); + Method method = c.getMethod("setOwnerid", String.class); + method.invoke(cObject, "" + id); + method = c.getMethod("setUserid", String.class); + method.invoke(cObject, "" + user.getUID()); + int num = (Integer) m.invoke(cObject); + groupname += "(" + num + ")"; + } catch (Exception e) { + e.printStackTrace(); + groupname += "(error)"; + } + } + tablist.add(setTabInfo("iframe-" + (idx++) + "-DefineTab" + id, groupname, tab_urlTemp1, "", user)); + } + + List> tablist1 = new ArrayList>(); + for (Map obj : tablist) { + if (!obj.isEmpty()) { + tablist1.add(obj); + } + } + tablist = tablist1; + } catch (Exception e) { + writeLog(e); + } + return JSONObject.toJSONString(tablist); + } + + /** + * 设置tabInfo 后续可以考虑直接读取数据 + * + * @param key + * @param labelid + * @param url + * @param rotueurl + * @param user + * @return + */ + private Map setTabInfo(String key, int labelid, String url, String rotueurl, User user) { + return setTabInfo(key, "" + labelid, url, rotueurl, user); + } + + /** + * 设置tabInfo 后续可以考虑直接读取数据 + * + * @param key + * @param labelid + * @param url + * @param rotueurl + * @param user + * @return + */ + private Map setTabInfo(String key, String labelid, String url, String rotueurl, User user) { + Map tabObj = new HashMap(); + if (isMobx) { + tabObj = getTabInfo4Mobx(key, labelid, url, rotueurl, user); + } else { + tabObj.put("key", key); + if (key.indexOf("DefineTab") != -1) { + tabObj.put("value", labelid); + } else { + tabObj.put("value", SystemEnv.getHtmlLabelNames(labelid, user.getLanguage())); + } + tabObj.put("url", url); + tabObj.put("rotueurl", rotueurl); + } + return tabObj; + } + + private Map getTabInfo4Mobx(String key, String labelid, String url, String rotueurl, User user) { + Map tabObj = new HashMap(); + + if (key.equals("HrmResourceBase")) { + key = "cardInfo"; + } else if (key.equals("HrmResourcePersonalView")) { + key = "cardPersonal"; + } else if (key.equals("HrmResourceWorkView")) { + key = "cardWork"; + } else if (key.equals("HrmResourceSystemView")) { + key = "cardSystemInfo"; + } else if (key.equals("HrmResourceFinanceView")) { + key = "cardFinance"; + } else if (key.equals("HrmResourceAbsense")) { + key = "cardChecking"; + /*判断是否开启了新考勤,如果开启了,那么人员卡片上面的考勤情况也需要切换成新版考勤的路由*/ + KQ122Util kq122Util = new KQ122Util(); + if (kq122Util.is122Open()) { + key = "cardCheckingN"; + } + } else if (key.equals("HrmResourceTrainRecord")) { + key = "cardTrainRecord"; + } else if (key.equals("HrmResourceRewardsRecordView")) { + key = "cardRewardsRecord"; + } else if (key.equals("HrmResourceNewRoles")) { + key = "cardRoleSet"; + } else if (key.equals("HrmResourceTotal")) { + key = "cardTotal"; + } else if (key.equals("HrmResourceGroupView")) { + key = "addGroup"; + } + + if (key.indexOf("DefineTab") != -1) { + tabObj.put("title", labelid); + } else { + tabObj.put("title", SystemEnv.getHtmlLabelNames(labelid, user.getLanguage())); + } + tabObj.put("key", key); + tabObj.put("pathname", "main/hrm/card/" + key + "/" + this.id); + tabObj.put("isIframe", key.startsWith("iframe-")); + if (key.startsWith("iframe-")) { + tabObj.put("url", url); + } + return tabObj; + } + + + /** + * 普通人员只编辑后台开启允许个人修改的字段 + * + * @param request + * @param response + * @return + */ + public String getResourceContactForm(HttpServletRequest request, HttpServletResponse response) { + Map result = new HashMap(); + List lsGroup = new ArrayList(); + Map groupitem = null; + List itemlist = null; + try { + //基本信息 + User user = HrmUserVarify.getUser(request, response); + String id = Util.null2String(request.getParameter("id")); + int viewattr = Util.getIntValue(request.getParameter("viewattr"), 1); + if (id.length() == 0) { + id = "" + user.getUID(); + } + result.put("id", id); + + Map buttons = new Hashtable(); + if (isHasModify(-1)) { + buttons.put("hasEdit", true); + buttons.put("hasSave", true); + } + result.put("buttons", buttons); + result.put("editcontact", "1"); + + UserPrivacyComInfo upc = new UserPrivacyComInfo(); + PrivacyComInfo pc = new PrivacyComInfo(); + PrivacyBaseComInfo privacyBaseComInfo = new PrivacyBaseComInfo(); + Map mapShowSets = pc.getMapShowSets(); + Map mapShowTypes = pc.getMapShowTypes(); + Map mapShowTypeDefaults = pc.getMapShowTypeDefaults(); + //总体的大开关的默认设置 + Map mapBaseShowTypeDefaults = privacyBaseComInfo.getMapShowTypeDefaults(); + + StaticObj staticobj = StaticObj.getInstance(); + String multilanguage = (String) staticobj.getObject("multilanguage"); + if (multilanguage == null) multilanguage = "n"; + boolean isMultilanguageOK = false; + if (multilanguage.equals("y")) isMultilanguageOK = true; + boolean flagaccount = GCONST.getMOREACCOUNTLANDING(); + int scopeId = -1; + HrmFieldGroupComInfo HrmFieldGroupComInfo = new HrmFieldGroupComInfo(); + HrmFieldSearchConditionComInfo hrmFieldSearchConditionComInfo = new HrmFieldSearchConditionComInfo(); + HrmFieldManager hfm = new HrmFieldManager("HrmCustomFieldByInfoType", scopeId); + hfm.isReturnDecryptData(true); + CustomFieldManager cfm = new CustomFieldManager("HrmCustomFieldByInfoType", scopeId); + hfm.getHrmData(Util.getIntValue(id)); + cfm.getCustomData(Util.getIntValue(id)); + + while (HrmFieldGroupComInfo.next()) { + int grouptype = Util.getIntValue(HrmFieldGroupComInfo.getType()); + if (grouptype != scopeId) continue; + int grouplabel = Util.getIntValue(HrmFieldGroupComInfo.getLabel()); + int groupid = Util.getIntValue(HrmFieldGroupComInfo.getid()); + hfm.getCustomFields(groupid); + + groupitem = new HashMap(); + itemlist = new ArrayList(); + groupitem.put("title", SystemEnv.getHtmlLabelName(grouplabel, user.getLanguage())); + groupitem.put("hide", hfm.getContactEditCount() == 0 || !Util.null2String(HrmFieldGroupComInfo.getIsShow()).equals("1")); + groupitem.put("defaultshow", true); + groupitem.put("items", itemlist); + groupitem.put("col", 1); + lsGroup.add(groupitem); + while (hfm.next()) { + int tmpviewattr = viewattr; + String fieldName = hfm.getFieldname(); + String cusFieldname = ""; + String fieldValue = ""; + if (hfm.isBaseField(fieldName)) { + fieldValue = hfm.getHrmData(fieldName); + } else { + cusFieldname = "customfield" + hfm.getFieldid(); + fieldValue = Util.null2String(new EncryptUtil().decrypt("cus_fielddata","field" + hfm.getFieldid(),"HrmCustomFieldByInfoType",""+scopeId,cfm.getData("field" + hfm.getFieldid()),true,true)); + } + + if (!hfm.isUse()||(!hfm.isModify())) { + HrmFieldBean hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname(cusFieldname.length() > 0 ? cusFieldname : fieldName); + hrmFieldBean.setFieldhtmltype("1"); + hrmFieldBean.setType("1"); + hrmFieldBean.setFieldvalue(fieldValue); + hrmFieldBean.setIsFormField(true); + Map otherParams = new HashMap(); + otherParams.put("hide", true); + hrmFieldBean.setOtherparam(otherParams); + SearchConditionItem searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + + itemlist.add(searchConditionItem); + continue; + } + + if (fieldName.equals("systemlanguage") && !isMultilanguageOK) continue; + if (fieldName.equals("accounttype") && !flagaccount) continue; + if (fieldName.equalsIgnoreCase("jobGroupId")) { + continue; + } + + if (fieldName.equals("departmentvirtualids")||fieldName.equals("messagerurl")) + continue; + + if (fieldName.equals("resourceimageid")) { + groupitem.put("hasResourceImage", true); + if (fieldValue.equals("0")) fieldValue = ""; + if(fieldValue.length()>0){ + fieldValue = DocDownloadCheckUtil.checkPermission(fieldValue,user); + } + } + + org.json.JSONObject hrmFieldConf = hfm.getHrmFieldConf(fieldName); + HrmFieldBean hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldid((String) hrmFieldConf.get("id")); + hrmFieldBean.setFieldname(cusFieldname.length() > 0 ? cusFieldname : fieldName); + hrmFieldBean.setFieldlabel(hfm.getLable()); + hrmFieldBean.setFieldhtmltype((String) hrmFieldConf.get("fieldhtmltype")); + hrmFieldBean.setType((String) hrmFieldConf.get("type")); + hrmFieldBean.setDmlurl((String) hrmFieldConf.get("dmlurl")); + hrmFieldBean.setIssystem("" + (Integer) hrmFieldConf.get("issystem")); + if (hrmFieldBean.getFieldname().equals("departmentid")) { + hrmFieldBean.setFieldvalue(Util.null2String(request.getParameter("departmentid"))); + } + hrmFieldBean.setFieldvalue(fieldValue); + hrmFieldBean.setIsFormField(true); + + if (fieldName.equals("mobile") || fieldName.equals("email") || + fieldName.equals("fax") || fieldName.equals("telephone") || fieldName.equals("mobilecall")|| fieldName.equals("workcode")) { + hrmFieldBean.setMultilang(false); + } + + if (((String) hrmFieldConf.get("ismand")).equals("1")) { + if (hrmFieldBean.getFieldname().equals("managerid")) { + + } else { + tmpviewattr = 3; + } + } + + if (hrmFieldBean.getFieldname().equals("status")) {//状态不能编辑 + tmpviewattr = 1; + } + + if (fieldName.equals("belongto") && flagaccount) { + tmpviewattr = 3; + } + String rules = ""; + if(tmpviewattr==3){ + rules = "required|string"; + } + hrmFieldBean.setRules(rules); + SearchConditionItem searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + if (searchConditionItem == null) continue; +// if (fieldName.equals("sex")) { +// List options = new ArrayList(); +// options.add(new SearchConditionOption("0", SystemEnv.getHtmlLabelName(28473, user.getLanguage()), true)); +// options.add(new SearchConditionOption("1", SystemEnv.getHtmlLabelName(28474, user.getLanguage()))); +// searchConditionItem.setOptions(options); +// } +// if (fieldName.equals("accounttype")) { +// List options = new ArrayList(); +// options.add(new SearchConditionOption("0", SystemEnv.getHtmlLabelName(17746, user.getLanguage()), true)); +// options.add(new SearchConditionOption("1", SystemEnv.getHtmlLabelName(17747, user.getLanguage()))); +// searchConditionItem.setOptions(options); +// } + if (fieldName.equals("belongto") && flagaccount) { + XssUtil xssUtil = new XssUtil(); + String accountSql = "(accounttype=0 or accounttype is null)"; + searchConditionItem.getBrowserConditionParam().getDataParams().put("sqlwhere", xssUtil.put(accountSql)); + searchConditionItem.getBrowserConditionParam().getCompleteParams().put("sqlwhere", xssUtil.put(accountSql)); + searchConditionItem.getBrowserConditionParam().getDestDataParams().put("sqlwhere", xssUtil.put(accountSql)); + } + if (searchConditionItem.getBrowserConditionParam() != null) { + searchConditionItem.getBrowserConditionParam().setViewAttr(tmpviewattr); + if (hrmFieldBean.getFieldname().equals("departmentid")) { + searchConditionItem.getBrowserConditionParam().getDataParams().put("rightStr", "HrmResourceAdd:Add"); + searchConditionItem.getBrowserConditionParam().getCompleteParams().put("rightStr", "HrmResourceAdd:Add"); + } + } + searchConditionItem.setViewAttr(tmpviewattr); + itemlist.add(searchConditionItem); + + if (mapShowSets != null && mapShowSets.get(fieldName) != null) { + String mobileShowSet = Util.null2String(mapShowSets.get(fieldName)); + String mobileShowType = Util.null2String(mapShowTypes.get(fieldName)); + String mapShowTypeDefault = Util.null2String(mapShowTypeDefaults.get(fieldName)); + + String baseMobileShowTypeDefaults = Util.null2String(mapBaseShowTypeDefaults.get(fieldName)); + + if (mobileShowSet.equals("1")) { + String comPk = id + "__" + fieldName; + fieldValue = Util.null2String(upc.getPvalue(comPk)); + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname(fieldName + "showtype"); + hrmFieldBean.setFieldlabelname(SystemEnv.getHtmlLabelNames(hfm.getLable(), user.getLanguage()) + SystemEnv.getHtmlLabelName(385571, user.getLanguage())); + hrmFieldBean.setFieldhtmltype("5"); + hrmFieldBean.setType("1"); + hrmFieldBean.setIssystem("1"); + hrmFieldBean.setIsFormField(true); + searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + if (searchConditionItem == null) continue; + List statusOptions = new ArrayList(); + if (mobileShowType.indexOf("1") != -1) { + if (fieldValue.length() > 0) { + statusOptions.add(new SearchConditionOption("1", SystemEnv.getHtmlLabelName(2161, user.getLanguage()), fieldValue.equals("1"))); + } else if (baseMobileShowTypeDefaults.indexOf("1") != -1) { + statusOptions.add(new SearchConditionOption("1", SystemEnv.getHtmlLabelName(2161, user.getLanguage()), true)); + } else { + statusOptions.add(new SearchConditionOption("1", SystemEnv.getHtmlLabelName(2161, user.getLanguage()))); + } + } + if (mobileShowType.indexOf("2") != -1) { + if (fieldValue.length() > 0) { + statusOptions.add(new SearchConditionOption("2", SystemEnv.getHtmlLabelName(32670, user.getLanguage()), fieldValue.equals("2"))); + } else if (baseMobileShowTypeDefaults.indexOf("2") != -1) { + statusOptions.add(new SearchConditionOption("2", SystemEnv.getHtmlLabelName(32670, user.getLanguage()), true)); + } else { + statusOptions.add(new SearchConditionOption("2", SystemEnv.getHtmlLabelName(32670, user.getLanguage()))); + } + } + if (mobileShowType.indexOf("3") != -1) { + if (fieldValue.length() > 0) { + statusOptions.add(new SearchConditionOption("3", SystemEnv.getHtmlLabelName(32671, user.getLanguage()), fieldValue.equals("3"))); + } else if (baseMobileShowTypeDefaults.indexOf("3") != -1) { + statusOptions.add(new SearchConditionOption("3", SystemEnv.getHtmlLabelName(32671, user.getLanguage()), true)); + } else { + statusOptions.add(new SearchConditionOption("3", SystemEnv.getHtmlLabelName(32671, user.getLanguage()))); + } + } + searchConditionItem.setValue(fieldValue); + searchConditionItem.setOptions(statusOptions); + itemlist.add(searchConditionItem); + } + } + } + if (itemlist.size()== 0) lsGroup.remove(groupitem); + } + + result.put("conditions", lsGroup); + } catch (Exception e) { + writeLog(e); + } + + Map retmap = new HashMap(); + retmap.put("result", result); + return JSONObject.toJSONString(retmap); + } + + /** + * 获取人员基本信息编辑表单 + * + * @param request + * @param response + * @return + */ + public String getResourceBaseForm(HttpServletRequest request, HttpServletResponse response) { + User user = HrmUserVarify.getUser(request, response); + + Map result = new HashMap(); + try { + //基本信息 + HrmListValidate HrmListValidate = new HrmListValidate(); + String id = Util.null2String(request.getParameter("id")).trim(); + if (id.length() == 0) { + id = "" + user.getUID(); + } + + AppDetachComInfo AppDetachComInfo = new AppDetachComInfo(); + if (AppDetachComInfo.isUseAppDetach()) { + boolean isApp = true; + if(!AppDetachComInfo.getScopeIds(user, "resource",id)) { + isApp = false; + } + if (!isApp) { + String errMsg = SystemEnv.getHtmlLabelName(2012, user.getLanguage()); + HashMap jsondata = new HashMap(); + jsondata.put("errMsg", errMsg); + jsondata.put("status", "-1"); + return JSONObject.toJSONString(jsondata); + } + } + + + result.put("id", id); + boolean isSelf = false; + if (id.equals("" + user.getUID())) { + isSelf = true; + } + HttpSession session = request.getSession(true); + String subcompanyid = ""; + String departmentId = ""; + String status = ""; + RecordSet rs = new RecordSet(); + rs.executeSql("select subcompanyid1,departmentid, status from hrmresource where id = " + id); + if (rs.next()) { + subcompanyid = Util.toScreen(rs.getString("subcompanyid1"), user.getLanguage()); + departmentId = Util.toScreen(rs.getString("departmentid"), user.getLanguage()); + status = Util.toScreen(rs.getString("status"), user.getLanguage()); + if (subcompanyid == null || subcompanyid.equals("") || subcompanyid.equalsIgnoreCase("null")) { + subcompanyid = "-1"; + } + session.setAttribute("hrm_subCompanyId", subcompanyid); + } + //人力资源模块是否开启了管理分权,如不是,则不显示框架,直接转向到列表页面(新的分权管理) + int hrmdetachable = 0; + if (session.getAttribute("hrmdetachable") != null) { + hrmdetachable = Util.getIntValue(String.valueOf(session.getAttribute("hrmdetachable")), 0); + } else { + boolean isUseHrmManageDetach = new ManageDetachComInfo().isUseHrmManageDetach(); + if (isUseHrmManageDetach) { + hrmdetachable = 1; + session.setAttribute("detachable", "1"); + session.setAttribute("hrmdetachable", String.valueOf(hrmdetachable)); + } else { + hrmdetachable = 0; + session.setAttribute("detachable", "0"); + session.setAttribute("hrmdetachable", String.valueOf(hrmdetachable)); + } + } + int operatelevel = -1; + if (hrmdetachable == 1) { + operatelevel = new CheckSubCompanyRight().ChkComRightByUserRightCompanyId(user.getUID(), "HrmResourceEdit:Edit", Integer.parseInt(subcompanyid)); + } else { + if (HrmUserVarify.checkUserRight("HrmResourceEdit:Edit", user, departmentId)) { + operatelevel = 2; + } + } + if (operatelevel > 0) { + } else if (isSelf) { + return getResourceContactForm(request, response); + } + + Map buttons = new Hashtable(); + if (((isSelf&&isHasModify(-1))|| operatelevel > 0) && !status.equals("10")) {//编辑 + buttons.put("hasEdit", true); + buttons.put("hasSave", true); + } + result.put("hasJobTitlesAdd", HrmUserVarify.checkUserRight("HrmJobTitlesAdd:Add", user)); + result.put("buttons", buttons); + result.put("conditions", getFormFields(request, response, false)); + result.put("validate", getValidate(user)); + } catch (Exception e) { + writeLog(e); + } + + Map retmap = new HashMap(); + retmap.put("result", result); + return JSONObject.toJSONString(retmap); + } + + /** + * 人员基本信息表单字段 + * + * @param request + * @param response + * @return + */ + public List getFormFields(HttpServletRequest request, HttpServletResponse response, boolean isAdd) { + List lsGroup = new ArrayList(); + try { + User user = HrmUserVarify.getUser(request, response); + Map groupitem = null; + List itemlist = null; + ChgPasswdReminder reminder = new ChgPasswdReminder(); + RemindSettings settings = reminder.getRemindSettings(); + + String id = Util.null2String(request.getParameter("id")); + if (id.length() == 0) { + id = "" + user.getUID(); + } + UserPrivacyComInfo upc = new UserPrivacyComInfo(); + PrivacyComInfo pc = new PrivacyComInfo(); + PrivacyBaseComInfo privacyBaseComInfo = new PrivacyBaseComInfo(); + Map mapShowSets = pc.getMapShowSets(); + Map mapShowTypes = pc.getMapShowTypes(); + Map mapShowTypeDefaults = pc.getMapShowTypeDefaults(); + //总体的大开关的默认设置 + Map mapBaseShowTypeDefaults = privacyBaseComInfo.getMapShowTypeDefaults(); + + StaticObj staticobj = StaticObj.getInstance(); + String multilanguage = (String) staticobj.getObject("multilanguage"); + if (multilanguage == null) multilanguage = "n"; + boolean isMultilanguageOK = false; + if (multilanguage.equals("y")) isMultilanguageOK = true; + boolean flagaccount = GCONST.getMOREACCOUNTLANDING(); + int viewattr = isAdd ? 2 : Util.getIntValue(request.getParameter("viewattr"), 1); + int scopeId = -1; + HrmFieldGroupComInfo HrmFieldGroupComInfo = new HrmFieldGroupComInfo(); + HrmFieldSearchConditionComInfo hrmFieldSearchConditionComInfo = new HrmFieldSearchConditionComInfo(); + hrmFieldSearchConditionComInfo.setIsMobile(Util.null2String(request.getParameter("ismobile"))); + HrmFieldManager hfm = new HrmFieldManager("HrmCustomFieldByInfoType", scopeId); + hfm.isReturnDecryptData(true); + CustomFieldManager cfm = new CustomFieldManager("HrmCustomFieldByInfoType", scopeId); + hfm.getHrmData(Util.getIntValue(id)); + cfm.getCustomData(Util.getIntValue(id)); + + while (HrmFieldGroupComInfo.next()) { + int grouptype = Util.getIntValue(HrmFieldGroupComInfo.getType()); + if (grouptype != scopeId) continue; + int grouplabel = Util.getIntValue(HrmFieldGroupComInfo.getLabel()); + int groupid = Util.getIntValue(HrmFieldGroupComInfo.getid()); + hfm.getCustomFields(groupid); + //if(hfm.getGroupCount()==0)continue; + + groupitem = new HashMap(); + itemlist = new ArrayList(); + groupitem.put("title", SystemEnv.getHtmlLabelName(grouplabel, user.getLanguage())); + groupitem.put("defaultshow", true); + groupitem.put("hide", hfm.getGroupCount() == 0 || !Util.null2String(HrmFieldGroupComInfo.getIsShow()).equals("1")); + groupitem.put("items", itemlist); + lsGroup.add(groupitem); + while (hfm.next()) { + int tmpviewattr = viewattr; + String fieldName = hfm.getFieldname(); + String cusFieldname = ""; + String fieldValue = ""; + if (hfm.isBaseField(fieldName)) { + fieldValue = hfm.getHrmData(fieldName); + } else { + cusFieldname = "customfield" + hfm.getFieldid(); + if (isAdd) cusFieldname = "customfield_0_" + hfm.getFieldid(); + fieldValue = Util.null2String(new EncryptUtil().decrypt("cus_fielddata","field" + hfm.getFieldid(),"HrmCustomFieldByInfoType",""+scopeId,cfm.getData("field" + hfm.getFieldid()),true,true)); + } + + if (!hfm.isUse()) { + HrmFieldBean hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname(cusFieldname.length() > 0 ? cusFieldname : fieldName); + hrmFieldBean.setFieldhtmltype("1"); + hrmFieldBean.setType("1"); + if (!isAdd) { + hrmFieldBean.setFieldvalue(fieldValue); + } + hrmFieldBean.setIsFormField(true); + Map otherParams = new HashMap(); + otherParams.put("hide", true); + hrmFieldBean.setOtherparam(otherParams); + SearchConditionItem searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + itemlist.add(searchConditionItem); + continue; + } + if (fieldName.equals("resourceimageid")) { + groupitem.put("hasResourceImage", true); + if (fieldValue.equals("0")) fieldValue = ""; + if(fieldValue.length()>0){ + fieldValue = DocDownloadCheckUtil.checkPermission(fieldValue,user); + } + } + if (fieldName.equals("loginid") || fieldName.equals("jobactivity") || fieldName.equals("departmentvirtualids")||fieldName.equals("messagerurl")) + continue; + if (fieldName.equalsIgnoreCase("jobGroupId")) { + continue; + } + if (!isAdd && fieldName.equals("status")) { + continue; + } + if (fieldName.equals("systemlanguage") && !isMultilanguageOK) continue; + if (fieldName.equals("accounttype") && !flagaccount) continue; + org.json.JSONObject hrmFieldConf = hfm.getHrmFieldConf(fieldName); + HrmFieldBean hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldid((String) hrmFieldConf.get("id")); + hrmFieldBean.setFieldname(cusFieldname.length() > 0 ? cusFieldname : fieldName); + hrmFieldBean.setFieldlabel(hfm.getLable()); + hrmFieldBean.setFieldhtmltype((String) hrmFieldConf.get("fieldhtmltype")); + hrmFieldBean.setType((String) hrmFieldConf.get("type")); + hrmFieldBean.setDmlurl((String) hrmFieldConf.get("dmlurl")); + hrmFieldBean.setIssystem("" + (Integer) hrmFieldConf.get("issystem")); + if (hrmFieldBean.getFieldname().equals("departmentid")) { + hrmFieldBean.setFieldvalue(Util.null2String(request.getParameter("departmentid"))); + } + if (!isAdd) { + hrmFieldBean.setFieldvalue(fieldValue); + } + hrmFieldBean.setIsFormField(true); + + if (fieldName.equals("mobile") || fieldName.equals("email") || + fieldName.equals("fax") || fieldName.equals("telephone") || fieldName.equals("mobilecall")|| fieldName.equals("workcode")) { + hrmFieldBean.setMultilang(false); + } + + if (((String) hrmFieldConf.get("ismand")).equals("1")) { + if (hrmFieldBean.getFieldname().equals("managerid")) { + + } else { + tmpviewattr = 3; + } + } + + if (fieldName.equals("belongto") && flagaccount) { + tmpviewattr = 3; + } + String rules = ""; + if(tmpviewattr==3){ + rules = "required|string"; + } + hrmFieldBean.setRules(rules); + SearchConditionItem searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + + if("departmentid".equals(hrmFieldBean.getFieldname())){ + DepartmentComInfo comInfo =new DepartmentComInfo(); + List> replaceDatas = new ArrayList>(); + Map datas = new HashMap(); + if(!"".equals(fieldValue)){ + String deptname =""; + try { + deptname =comInfo.getDepartmentname(fieldValue); + } catch (Exception e) { + new BaseBean().writeLog(e); + } + datas.put("id",fieldValue); + datas.put("name",deptname); + replaceDatas.add(datas); + } + searchConditionItem.getBrowserConditionParam().setReplaceDatas(replaceDatas); + } + + if (searchConditionItem == null) continue; +// if (fieldName.equals("sex")) { +// List options = new ArrayList(); +// options.add(new SearchConditionOption("0", SystemEnv.getHtmlLabelName(28473, user.getLanguage()), true)); +// options.add(new SearchConditionOption("1", SystemEnv.getHtmlLabelName(28474, user.getLanguage()))); +// searchConditionItem.setOptions(options); +// } +// if (fieldName.equals("accounttype")) { +// List options = new ArrayList(); +// options.add(new SearchConditionOption("0", SystemEnv.getHtmlLabelName(17746, user.getLanguage()), true)); +// options.add(new SearchConditionOption("1", SystemEnv.getHtmlLabelName(17747, user.getLanguage()))); +// searchConditionItem.setOptions(options); +// } + if (fieldName.equals("belongto") && flagaccount) { + XssUtil xssUtil = new XssUtil(); + String accountSql = "(accounttype=0 or accounttype is null)"; + searchConditionItem.getBrowserConditionParam().getDataParams().put("sqlwhere", xssUtil.put(accountSql)); + searchConditionItem.getBrowserConditionParam().getCompleteParams().put("sqlwhere", xssUtil.put(accountSql)); + searchConditionItem.getBrowserConditionParam().getDestDataParams().put("sqlwhere", xssUtil.put(accountSql)); + } + if (searchConditionItem.getBrowserConditionParam() != null) { + searchConditionItem.getBrowserConditionParam().setViewAttr(tmpviewattr); + if (hrmFieldBean.getFieldname().equals("departmentid")) { + searchConditionItem.getBrowserConditionParam().getDataParams().put("rightStr", "HrmResourceAdd:Add"); + searchConditionItem.getBrowserConditionParam().getCompleteParams().put("rightStr", "HrmResourceAdd:Add"); + } + } + searchConditionItem.setViewAttr(tmpviewattr); + if (isAdd && fieldName.equals("status")) { + List statusOptions = new ArrayList(); + statusOptions.add(new SearchConditionOption("0", SystemEnv.getHtmlLabelName(15710, user.getLanguage()), true)); + statusOptions.add(new SearchConditionOption("1", SystemEnv.getHtmlLabelName(15711, user.getLanguage()))); + statusOptions.add(new SearchConditionOption("2", SystemEnv.getHtmlLabelName(480, user.getLanguage()))); + searchConditionItem.setOptions(statusOptions); + } + itemlist.add(searchConditionItem); + + if (mapShowSets != null && mapShowSets.get(fieldName) != null) { + String mobileShowSet = Util.null2String(mapShowSets.get(fieldName)); + String mobileShowType = Util.null2String(mapShowTypes.get(fieldName)); + String mapShowTypeDefault = Util.null2String(mapShowTypeDefaults.get(fieldName)); + + String baseMobileShowTypeDefaults = Util.null2String(mapBaseShowTypeDefaults.get(fieldName)); + + if (mobileShowSet.equals("1")) { +// userid+"__"+ptype + String comPk = id + "__" + fieldName; + fieldValue = Util.null2String(upc.getPvalue(comPk)); + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname(fieldName + "showtype"); + hrmFieldBean.setFieldlabelname(SystemEnv.getHtmlLabelNames(hfm.getLable(), user.getLanguage()) + SystemEnv.getHtmlLabelName(385571, user.getLanguage())); + hrmFieldBean.setFieldhtmltype("5"); + hrmFieldBean.setType("1"); + hrmFieldBean.setIssystem("1"); + hrmFieldBean.setIsFormField(true); + searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + if (searchConditionItem == null) continue; + List statusOptions = new ArrayList(); + if (mobileShowType.indexOf("1") != -1) { + if (fieldValue.length() > 0) { + statusOptions.add(new SearchConditionOption("1", SystemEnv.getHtmlLabelName(2161, user.getLanguage()), fieldValue.equals("1"))); + } else if (baseMobileShowTypeDefaults.indexOf("1") != -1) { + statusOptions.add(new SearchConditionOption("1", SystemEnv.getHtmlLabelName(2161, user.getLanguage()), true)); + } else { + statusOptions.add(new SearchConditionOption("1", SystemEnv.getHtmlLabelName(2161, user.getLanguage()))); + } + } + if (mobileShowType.indexOf("2") != -1) { + if (fieldValue.length() > 0) { + statusOptions.add(new SearchConditionOption("2", SystemEnv.getHtmlLabelName(32670, user.getLanguage()), fieldValue.equals("2"))); + } else if (baseMobileShowTypeDefaults.indexOf("2") != -1) { + statusOptions.add(new SearchConditionOption("2", SystemEnv.getHtmlLabelName(32670, user.getLanguage()), true)); + } else { + statusOptions.add(new SearchConditionOption("2", SystemEnv.getHtmlLabelName(32670, user.getLanguage()))); + } + } + if (mobileShowType.indexOf("3") != -1) { + if (fieldValue.length() > 0) { + statusOptions.add(new SearchConditionOption("3", SystemEnv.getHtmlLabelName(32671, user.getLanguage()), fieldValue.equals("3"))); + } else if (baseMobileShowTypeDefaults.indexOf("3") != -1) { + statusOptions.add(new SearchConditionOption("3", SystemEnv.getHtmlLabelName(32671, user.getLanguage()), true)); + } else { + statusOptions.add(new SearchConditionOption("3", SystemEnv.getHtmlLabelName(32671, user.getLanguage()))); + } + } + searchConditionItem.setValue(fieldValue); + searchConditionItem.setOptions(statusOptions); + itemlist.add(searchConditionItem); + } + } + +// if(fieldName.equals("mobile")){ +// String mobileShowSet = Util.null2String(settings.getMobileShowSet()); +// String mobileShowType = Util.null2String(settings.getMobileShowType()); +// if(mobileShowSet.equals("1")){ +// String sql = ""; +// RecordSet rs = new RecordSet(); +// sql = "select costcenterid,mobileshowtype from HrmResource where id = "+Util.getIntValue(id,-1); +// rs.executeSql(sql); +// if(rs.next()){ +// fieldValue = Util.null2String(rs.getString("mobileshowtype")); +// } +// if(isAdd){ +// fieldValue = Util.null2String(settings.getMobileShowTypeDefault()); +// } +// hrmFieldBean = new HrmFieldBean(); +// hrmFieldBean.setFieldname("mobileshowtype"); +// hrmFieldBean.setFieldlabel("32684"); +// hrmFieldBean.setFieldhtmltype("5"); +// hrmFieldBean.setType("1"); +// hrmFieldBean.setIssystem("1"); +// hrmFieldBean.setIsFormField(true); +// searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); +// if(searchConditionItem==null)continue; +// List statusOptions = new ArrayList(); +// if(mobileShowType.indexOf("1")!=-1){ +// statusOptions.add(new SearchConditionOption("1",SystemEnv.getHtmlLabelName(2161,user.getLanguage()),fieldValue.equals("1"))); +// }if(mobileShowType.indexOf("2")!=-1){ +// statusOptions.add(new SearchConditionOption("2",SystemEnv.getHtmlLabelName(32670,user.getLanguage()),fieldValue.equals("2"))); +// }if(mobileShowType.indexOf("3")!=-1){ +// statusOptions.add(new SearchConditionOption("3",SystemEnv.getHtmlLabelName(32671,user.getLanguage()),fieldValue.equals("3"))); +// } +// searchConditionItem.setOptions(statusOptions); +// itemlist.add(searchConditionItem); +// } +// } + } + if (itemlist.size() == 0) lsGroup.remove(groupitem); + } + } catch (Exception e) { + writeLog(e); + } + return lsGroup; + } + + /** + * 查看人员基本信息 + * + * @param request + * @param response + * @return + */ + public String getResourceBaseView(HttpServletRequest request, HttpServletResponse response) { + Map retmap = new HashMap(); + try { + HrmListValidate HrmListValidate = new HrmListValidate(); + User user = HrmUserVarify.getUser(request, response); + String id = Util.null2String(request.getParameter("id")); + if (id.length() == 0) { + id = "" + user.getUID(); + } + AppDetachComInfo AppDetachComInfo = new AppDetachComInfo(); + if (AppDetachComInfo.isUseAppDetach()) { + boolean isApp = true; + if(!AppDetachComInfo.getScopeIds(user, "resource",id)) { + isApp = false; + } + if (!isApp) { + String errMsg = SystemEnv.getHtmlLabelName(2012, user.getLanguage()); + HashMap jsondata = new HashMap(); + jsondata.put("errMsg", errMsg); + jsondata.put("status", "-1"); + return JSONObject.toJSONString(jsondata); + } + } + + if (id.equals("")) id = String.valueOf(user.getUID()); + String status = ""; + String subcompanyid = "", departmentId = ""; + int scopeId = -1; + RecordSet rs = new RecordSet(); + HttpSession session = request.getSession(true); + rs.executeSql("select subcompanyid1, status, departmentId from hrmresource where id = " + id); + if (rs.next()) { + status = Util.toScreen(rs.getString("status"), user.getLanguage()); + subcompanyid = Util.toScreen(rs.getString("subcompanyid1"), user.getLanguage()); + departmentId = StringUtil.vString(rs.getString("departmentId")); + if (subcompanyid == null || subcompanyid.equals("") || subcompanyid.equalsIgnoreCase("null")) + subcompanyid = "-1"; + session.setAttribute("hrm_subCompanyId", subcompanyid); + } + + boolean isSelf = false; + if (id.equals("" + user.getUID())) { + isSelf = true; + } + int operatelevel = -1; + //人力资源模块是否开启了管理分权,如不是,则不显示框架,直接转向到列表页面(新的分权管理) + int hrmdetachable = 0; + ManageDetachComInfo ManageDetachComInfo = new ManageDetachComInfo(); + if (session.getAttribute("hrmdetachable") != null) { + hrmdetachable = Util.getIntValue(String.valueOf(session.getAttribute("hrmdetachable")), 0); + } else { + boolean isUseHrmManageDetach = ManageDetachComInfo.isUseHrmManageDetach(); + if (isUseHrmManageDetach) { + hrmdetachable = 1; + session.setAttribute("detachable", "1"); + session.setAttribute("hrmdetachable", String.valueOf(hrmdetachable)); + } else { + hrmdetachable = 0; + session.setAttribute("detachable", "0"); + session.setAttribute("hrmdetachable", String.valueOf(hrmdetachable)); + } + } + if (hrmdetachable == 1) { + CheckSubCompanyRight CheckSubCompanyRight = new CheckSubCompanyRight(); + operatelevel = CheckSubCompanyRight.ChkComRightByUserRightCompanyId(user.getUID(), "HrmResourceEdit:Edit", Integer.parseInt(subcompanyid)); + } else { + if (HrmUserVarify.checkUserRight("HrmResourceEdit:Edit", user, departmentId)) { + operatelevel = 2; + } + } + Map buttons = new Hashtable(); + if (((isSelf && isHasModify(-1)) || operatelevel > 0) && !status.equals("10")) { + buttons.put("hasEdit", true); + buttons.put("hasSave", true); + } + retmap.put("buttons", buttons); + + RecordSet RecordSet = new RecordSet(); + SubCompanyComInfo SubCompanyComInfo = new SubCompanyComInfo(); + DepartmentComInfo DepartmentComInfo = new DepartmentComInfo(); + ResourceComInfo resourceComInfo = new ResourceComInfo(); + JobTitlesComInfo jobTitlesComInfo = new JobTitlesComInfo(); + JobActivitiesComInfo jobActivitiesComInfo = new JobActivitiesComInfo(); + LocationComInfo locationComInfo = new LocationComInfo(); + LanguageComInfo languageComInfo = new LanguageComInfo(); + HrmResourceFile hrmResourceFile = new HrmResourceFile(); + HrmFieldGroupComInfo hrmFieldGroupComInfo = new HrmFieldGroupComInfo(); + ResourceBelongtoComInfo resourceBelongtoComInfo = new ResourceBelongtoComInfo(); + HrmFieldManager hfm = new HrmFieldManager("HrmCustomFieldByInfoType", scopeId); + CustomFieldManager cfm = new CustomFieldManager("HrmCustomFieldByInfoType", scopeId); + + String sql = ""; + + List> grouplist = new ArrayList>(); + Map jsondata = null; + + Map item1 = new HashMap();//姓名等头部信息lastname,workcode,sex,orginfo + Map item2 = new HashMap();//账号信息accounttype,accounts,managerid,subordinatescount,status,lastlogindate + Map item3 = new HashMap();//系统登录维护信息createrid,createdate,lastmoddate,lastmodid + grouplist.add(item1); + grouplist.add(item2); + grouplist.add(item3); + List itemlist1 = new ArrayList(); + List itemlist2 = new ArrayList(); + List itemlist3 = new ArrayList(); + item1.put("title", ""+ SystemEnv.getHtmlLabelName(10004508,weaver.general.ThreadVarLanguage.getLang())+""); + item1.put("id", "item1"); + item1.put("defaultshow", true); + item1.put("items", itemlist1); + + item2.put("title", ""+ SystemEnv.getHtmlLabelName(10004509,weaver.general.ThreadVarLanguage.getLang())+""); + item2.put("id", "item2"); + item2.put("defaultshow", true); + item2.put("items", itemlist2); + + item3.put("title", SystemEnv.getHtmlLabelName(2023, user.getLanguage())); + item3.put("id", "item3"); + item3.put("defaultshow", true); + item3.put("items", itemlist3); + + PrivacyComInfo pc = new PrivacyComInfo(); + Map mapShowSets = pc.getMapShowSets(); + Map mapShowTypes = pc.getMapShowTypes(); + Map mapShowTypeDefaults = pc.getMapShowTypeDefaults(); + + UserPrivacyComInfo upc = new UserPrivacyComInfo(); + //基本信息 + sql = "select * from hrmresource where id=" + id; + rs.executeSql(sql); + if (rs.next()) { + String lastname = Util.toScreen(rs.getString("lastname"), user.getLanguage()); + String workcode = Util.toScreen(rs.getString("workcode"), user.getLanguage()); + String sex = Util.toScreen(rs.getString("sex"), user.getLanguage()); + subcompanyid = Util.toScreen(rs.getString("subcompanyid1"), user.getLanguage()); + String departmentid = Util.toScreen(rs.getString("departmentid"), user.getLanguage()); + int accounttype = Util.getIntValue(rs.getString("accounttype"), 0); + String managerid = Util.toScreen(rs.getString("managerid"), user.getLanguage()); + String assistantid = Util.toScreen(rs.getString("assistantid"), user.getLanguage()); + status = Util.toScreen(rs.getString("status"), user.getLanguage()); + String lastlogindate = Util.toScreen(rs.getString("lastlogindate"), user.getLanguage()); + String createrid = Util.toScreen(rs.getString("createrid"), user.getLanguage()); + String createdate = Util.toScreen(rs.getString("createdate"), user.getLanguage()); + String lastmoddate = Util.toScreen(rs.getString("lastmoddate"), user.getLanguage()); + String lastmodid = Util.toScreen(rs.getString("lastmodid"), user.getLanguage()); + String jobtitle = Util.toScreen(rs.getString("jobtitle"), user.getLanguage()); + String jobcall = Util.toScreen(rs.getString("jobcall"), user.getLanguage()); + String joblevel = Util.toScreen(rs.getString("joblevel"), user.getLanguage()); + String jobactivitydesc = Util.toScreen(rs.getString("jobactivitydesc"), user.getLanguage()); + String locationid = Util.toScreen(rs.getString("loactionid"), user.getLanguage()); + String systemlanguage = Util.toScreen(rs.getString("systemlanguage"), user.getLanguage()); + String mobile = resourceComInfo.getMobileShow(id, user); + String fax = Util.toScreen(rs.getString("fax"), user.getLanguage()); + String telephone = Util.toScreen(rs.getString("telephone"), user.getLanguage()); + String email = Util.toScreen(rs.getString("email"), user.getLanguage()); + String mobilecall = Util.toScreen(rs.getString("mobilecall"), user.getLanguage()); + String workroom = Util.toScreen(rs.getString("workroom"), user.getLanguage()); + String resourceimageid = Util.getFileidOut(rs.getString("resourceimageid")); + String messagerurl = Util.null2String(rs.getString("messagerurl")); + String ismobile = Util.null2String(request.getParameter("ismobile")); + /*最后登录时间已存储至另一张表*/ + String lastLoginDateSql = "select * from userlastlogindate where userId=?"; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(lastLoginDateSql, id); + if (recordSet.next()) { + lastlogindate = recordSet.getString("lastLoginDate"); + } + + lastname = lastname.endsWith("\\") && !lastname.endsWith("\\\\") == true ? lastname + "\\" : lastname; + lastname = StringUtil.replace(lastname, "'", "\\\\'"); + + jsondata = new HashMap(); + jsondata.put("name", "lastname"); + jsondata.put("label", SystemEnv.getHtmlLabelName(413, user.getLanguage())); + jsondata.put("value", lastname); + itemlist1.add(jsondata); + + jsondata = new HashMap(); + jsondata.put("name", "messagerurl"); + jsondata.put("label", SystemEnv.getHtmlLabelName(24513, user.getLanguage())); + jsondata.put("value", resourceComInfo.getMessagerUrls(id)); + itemlist1.add(jsondata); + + + jsondata = new HashMap(); + jsondata.put("name", "workcode"); + jsondata.put("label", SystemEnv.getHtmlLabelName(714, user.getLanguage())); + jsondata.put("value", workcode); + itemlist1.add(jsondata); + + jsondata = new HashMap(); + jsondata.put("name", "sex"); + jsondata.put("label", SystemEnv.getHtmlLabelName(416, user.getLanguage())); + jsondata.put("sex", sex);//0:男性,1:女性 + if (sex.equals("0")) { + jsondata.put("value", SystemEnv.getHtmlLabelName(28473, user.getLanguage())); + } else if (sex.equals("1")) { + jsondata.put("value", SystemEnv.getHtmlLabelName(28474, user.getLanguage())); + } + itemlist1.add(jsondata); + + jsondata = new HashMap(); + jsondata.put("name", "orginfo"); + jsondata.put("label", SystemEnv.getHtmlLabelName(376, user.getLanguage())); + jsondata.put("value", DepartmentComInfo.getAllParentDepartmentNames(departmentid, subcompanyid)); + itemlist1.add(jsondata); + + jsondata = new HashMap(); + jsondata.put("name", "resourceimageid"); + jsondata.put("label", SystemEnv.getHtmlLabelName(15707, user.getLanguage())); + String url = ""; + if (!resourceimageid.equals("0") && resourceimageid.length() > 0 && HrmListValidate.isValidate(36)) { + String mainControlHost = Util.null2String(Prop.getInstance().getPropValue("Others", "MAINCONTROLHOST")); + url = mainControlHost + "/weaver/weaver.file.FileDownload?fileid=" + resourceimageid; + } else { + if (sex.equals("") || sex.equals("0")) { + url = "/images/messageimages/temp/man_wev8.png"; + } else if (sex.equals("1")) { + url = "/images/messageimages/temp/women_wev8.png"; + } + } + jsondata.put("value", url); + itemlist2.add(jsondata); + + jsondata = new HashMap(); + Map options = new HashMap(); + jsondata.put("options", options); + itemlist2.add(jsondata); + + //var data = { "lastname": "吕益", "mobile": "13899998888","telephone":"021-99998888","email":"lvyi@weaver.com","jobtitle":"开发工程师","department":"人力资源组","locationname":"上海"}; + options.put("lastname", lastname); + options.put("mobile", mobile); + options.put("telephone", telephone); + options.put("email", email); + options.put("jobtitle", jobTitlesComInfo.getJobTitlesname(joblevel)); + options.put("department", DepartmentComInfo.getDepartmentname(departmentid)); + options.put("locationname", locationComInfo.getLocationname(departmentid)); + + + List lsOption = new ArrayList(); + jsondata = new HashMap(); + + jsondata.put("options", lsOption); + itemlist2.add(jsondata); + Map option = null; + + option = new HashMap();//发消息 + option.put("id", id); + option.put("validateId", "33"); + option.put("name", "sendEmessage"); + option.put("funname", "sendEmessage"); + option.put("title", SystemEnv.getHtmlLabelName(127379, user.getLanguage())); + lsOption.add(option); + + option = new HashMap();//发送短信 + option.put("id", id); + option.put("validateId", "31"); + option.put("name", "openmessage"); + option.put("funname", "sendSmsMessage"); + option.put("title", SystemEnv.getHtmlLabelName(16635, user.getLanguage())); + lsOption.add(option); + + option = new HashMap();//发送邮件 + option.put("id", id); + option.put("validateId", "19"); + option.put("name", "openemail"); + option.put("funname", "sendMail"); + option.put("title", SystemEnv.getHtmlLabelName(2051, user.getLanguage())); + lsOption.add(option); + + option = new HashMap();//新建日程 + option.put("id", id); + option.put("validateId", "32"); + option.put("name", "doAddWorkPlan"); + option.put("funname", "doAddWorkPlanByHrm"); + option.put("title", SystemEnv.getHtmlLabelName(18481, user.getLanguage())); + lsOption.add(option); + + List> ls = new ArrayList>(); + jsondata = new HashMap(); + jsondata.put("accountinfo", ls); + itemlist2.add(jsondata); + String value = ""; + String showName = ""; + List accounts = new VerifyLogin().getAccountsById(Integer.valueOf(id).intValue()); + Iterator iter = null; + if (accounts != null) iter = accounts.iterator(); + Account current = new Account(); + while (iter != null && iter.hasNext()) { + Account a = (Account) iter.next(); + if (("" + a.getId()).equals(id)) + current = a; + } + if (GCONST.getMOREACCOUNTLANDING()) { + jsondata = new HashMap(); + jsondata.put("name", "accounttype"); + jsondata.put("label", SystemEnv.getHtmlLabelName(17745, user.getLanguage())); + jsondata.put("value", accounttype == 0 ? SystemEnv.getHtmlLabelName(17746, user.getLanguage()) : SystemEnv.getHtmlLabelName(17747, user.getLanguage())); + ls.add(jsondata); + + List lsUser = resourceBelongtoComInfo.getBelongtousers("" + id); + if (lsUser != null && lsUser.size() > 0 && current.getType() == 0) { + jsondata = new HashMap(); + jsondata.put("name", "accounts"); + jsondata.put("label", SystemEnv.getHtmlLabelName(17747, user.getLanguage())); + jsondata.put("value", "" + lsUser.size()+""); + ls.add(jsondata); + } + + if (current.getType() == 1) { + jsondata = new HashMap(); + jsondata.put("name", "belongto"); + jsondata.put("label", SystemEnv.getHtmlLabelName(17746, Util.getIntValue(user.getLanguage()))); + jsondata.put("value", resourceComInfo.getBelongTo(id)); + jsondata.put("showName", resourceComInfo.getLastname(resourceComInfo.getBelongTo(id))); + jsondata.put("isOpenHrm", true); + ls.add(jsondata); + } + +// if(current.getType()==1){ +// jsondata = new HashMap(); +// jsondata.put("name","accounts"); +// jsondata.put("label",SystemEnv.getHtmlLabelNames("17747,141,124",user.getLanguage())); +// iter=accounts.iterator(); +// while(accounts.size()>1&&iter.hasNext()){ +// Account a=(Account)iter.next(); +// if(a.getType()==0){ +// String subcompanyname=SubCompanyComInfo.getSubCompanyname(""+a.getSubcompanyid()); +// String departmentname=DepartmentComInfo.getDepartmentname(""+a.getDepartmentid()); +// String jobtitlename=jobTitlesComInfo.getJobTitlesname(""+a.getJobtitleid()); +// //<%=subcompanyname+"/"+departmentname+"/"+jobtitlename%> +// } +// } +// jsondata.put("value",""+accounts.size()); +// ls.add(jsondata); +// } + } + + if (Util.null2String(managerid).length() > 0) { + value = managerid; + showName = resourceComInfo.getLastname(managerid); + if (showName.length() > 0) { + jsondata = new HashMap(); + jsondata.put("name", "managerid"); + jsondata.put("label", SystemEnv.getHtmlLabelName(15709, user.getLanguage())); + jsondata.put("value", value); + jsondata.put("showName", showName); + ls.add(jsondata); + } + } + + RecordSet.executeProc("HrmResource_SCountBySubordinat", id); + RecordSet.next(); + int subordinatescount = RecordSet.getInt(1); + if (subordinatescount > 0) { + jsondata = new HashMap(); + jsondata.put("name", "subordinatescount"); + jsondata.put("label", SystemEnv.getHtmlLabelName(442, user.getLanguage())); + jsondata.put("value", "" + subordinatescount + ""); + ls.add(jsondata); + } + + if (Util.null2String(assistantid).length() > 0 && hfm.isUse("assistantid")) { + value = assistantid; + showName = resourceComInfo.getLastname(assistantid); + if (showName.length() > 0) { + jsondata = new HashMap(); + jsondata.put("name", "assistantid"); + jsondata.put("label", SystemEnv.getHtmlLabelName(441, user.getLanguage())); + jsondata.put("value", value); + jsondata.put("showName", showName); + ls.add(jsondata); + } + } + + jsondata = new HashMap(); + jsondata.put("name", "status"); + jsondata.put("label", SystemEnv.getHtmlLabelName(602, user.getLanguage())); + jsondata.put("value", HrmFieldUtil.getResourceStatusName(status, user)); + ls.add(jsondata); + + jsondata = new HashMap(); + jsondata.put("name", "lastlogindate"); + jsondata.put("label", SystemEnv.getHtmlLabelName(16067, user.getLanguage())); + jsondata.put("value", lastlogindate); + ls.add(jsondata); + + jsondata = new HashMap(); + jsondata.put("name", "createrid"); + jsondata.put("label", SystemEnv.getHtmlLabelName(882, user.getLanguage())); + value = ""; + showName = ""; + if (Util.null2String(createrid).length() > 0) { + value = createrid; + showName = resourceComInfo.getLastname(createrid); + } + jsondata.put("value", value); + jsondata.put("showName", showName); + ls.add(jsondata); + + jsondata = new HashMap(); + jsondata.put("name", "createdate"); + jsondata.put("label", SystemEnv.getHtmlLabelName(1339, user.getLanguage())); + jsondata.put("value", createdate); + ls.add(jsondata); + + jsondata = new HashMap(); + jsondata.put("name", "lastmodid"); + jsondata.put("label", SystemEnv.getHtmlLabelName(3002, user.getLanguage())); + value = ""; + showName = ""; + if (Util.null2String(lastmodid).length() > 0) { + value = lastmodid; + showName = resourceComInfo.getLastname(lastmodid); + } + jsondata.put("value", value); + jsondata.put("showName", showName); + ls.add(jsondata); + + jsondata = new HashMap(); + jsondata.put("name", "lastmoddate"); + jsondata.put("label", SystemEnv.getHtmlLabelName(19521, user.getLanguage())); + jsondata.put("value", lastmoddate); + ls.add(jsondata); + + + Map item = new HashMap(); + List itemlist = new ArrayList(); + grouplist.add(item); + item.put("title", SystemEnv.getHtmlLabelName(1361, user.getLanguage())); + item.put("defaultshow", true); + item.put("items", itemlist); + + jsondata = new HashMap(); + jsondata.put("label", SystemEnv.getHtmlLabelName(6086, user.getLanguage())); + jsondata.put("type", "position"); + jsondata.put("value", "" + Util.toScreen(jobTitlesComInfo.getJobTitlesmark(jobtitle), user.getLanguage()) + ""); + itemlist.add(jsondata); + + boolean hasbaseGroup = false; + rs.executeSql(" select count(*) from hrm_formfield where fieldid = 0 and isuse =1 "); + if (rs.next()) { + if (rs.getInt(1) > 0) hasbaseGroup = true; + } + if (hasbaseGroup) { + jsondata = new HashMap(); + jsondata.put("label", SystemEnv.getHtmlLabelName(1915, user.getLanguage())); + jsondata.put("value", Util.toScreen(jobActivitiesComInfo.getJobActivitiesmarks(jobTitlesComInfo.getJobactivityid(jobtitle)), user.getLanguage())); + itemlist.add(jsondata); + } + + //其他特殊字段 + hfm.getCustomFields(1);//取得基本信息 + hfm.getHrmData(Util.getIntValue(id)); + cfm.getCustomData(Util.getIntValue(id)); + while (hfm.next()) { + if (!hfm.isUse()) continue; + int fieldlabel = Util.getIntValue(hfm.getLable()); + String fieldName = hfm.getFieldname(); + int fieldId = hfm.getFieldid(); + if (fieldName.equals("loginid") || fieldName.equals("workcode") || fieldName.equals("lastname") || fieldName.equals("sex") || + fieldName.equals("accounttype") || fieldName.equals("belongto") || fieldName.equals("departmentid") || + fieldName.equals("jobtitle") || (!ismobile.equals("1") && fieldName.equals("status")) || fieldName.equals("resourceimageid") || fieldName.equals("messagerurl") || fieldName.equals("jobactivity") || fieldName.equalsIgnoreCase("jobGroupId")) { + continue; + } + int type = hfm.getType(); + String dmlurl = hfm.getDmrUrl(); + int fieldhtmltype = Util.getIntValue(hfm.getHtmlType()); + String fieldValue = ""; + if (hfm.isBaseField(fieldName)) { + fieldValue = hfm.getHrmData(fieldName); + } else { + fieldValue = Util.null2String(new EncryptUtil().decrypt("cus_fielddata","field" + hfm.getFieldid(),"HrmCustomFieldByInfoType",""+scopeId,cfm.getData("field" + hfm.getFieldid()),false,true)); + } + + if (hfm.getHtmlType().equals("3")) { + fieldValue = hfm.getHtmlBrowserFieldvalue(user, dmlurl, fieldId, fieldhtmltype, type, fieldValue, "0"); + } else { + fieldValue = hfm.getFieldvalue(user, dmlurl, fieldId, fieldhtmltype, type, fieldValue, Util.getIntValue(request.getParameter("ismobile"))); + } + + if (mapShowSets != null && mapShowSets.get(fieldName) != null) { + String mobileShowSet = Util.null2String(mapShowSets.get(fieldName)); + String showTypeDefault = Util.null2String(mapShowTypeDefaults.get(fieldName)); + if (mobileShowSet.equals("1")) { + String comPk = id + "__" + fieldName; + String comPkValue = Util.null2String(upc.getPvalue(comPk)); + if (comPkValue.length() > 0) { + fieldValue = upc.getShow(id, user, fieldName, fieldValue, comPkValue); + } else { + fieldValue = pc.getShow(id, user, fieldName, fieldValue, showTypeDefault); + } + } else { + fieldValue = pc.getShow(id, user, fieldName, fieldValue, showTypeDefault); + } + } + + if (fieldName.equals("mobile")) {//手机号码格式化 + fieldValue = ResourceComInfo.formatMobile(fieldValue); + } + + jsondata = new HashMap(); + jsondata.put("label", SystemEnv.getHtmlLabelName(fieldlabel, user.getLanguage())); + jsondata.put("value", fieldValue); + itemlist.add(jsondata); + } + + hrmFieldGroupComInfo.setTofirstRow(); + hfm.beforeFirst(); + cfm.beforeFirst(); + while (hrmFieldGroupComInfo.next()) { + int grouptype = Util.getIntValue(hrmFieldGroupComInfo.getType()); + int groupid = Util.getIntValue(hrmFieldGroupComInfo.getid()); + if (grouptype != scopeId || groupid == 1) continue; + int grouplabel = Util.getIntValue(hrmFieldGroupComInfo.getLabel()); + + hfm.getCustomFields(groupid); + if (hfm.getGroupCount() == 0) continue; + + if (groupid == 3) { + boolean tmp_flag = false; + while (hfm.next()) { + if (!hfm.isUse()) continue; + String fieldName = hfm.getFieldname(); + if (fieldName.equals("managerid") || fieldName.equals("assistantid")) { + continue; + } + tmp_flag = true; + break; + } + if (!tmp_flag) continue; + hfm.beforeFirst(); + } + item = new HashMap(); + itemlist = new ArrayList(); + grouplist.add(item); + item.put("title", SystemEnv.getHtmlLabelName(grouplabel, user.getLanguage())); + item.put("defaultshow", true); + item.put("hide", !Util.null2String(hrmFieldGroupComInfo.getIsShow()).equals("1")); + item.put("items", itemlist); + if (grouplabel == 32946) { + item.put("SupSub", true); + } + while (hfm.next()) { + if (!hfm.isUse()) continue; + int fieldlabel = Util.getIntValue(hfm.getLable()); + String fieldName = hfm.getFieldname(); + int fieldId = hfm.getFieldid(); + int type = hfm.getType(); + String dmlurl = hfm.getDmrUrl(); + int fieldhtmltype = Util.getIntValue(hfm.getHtmlType()); + String fieldValue = ""; + + if (fieldName.equals("managerid") || fieldName.equals("assistantid")) { + continue; + } + + if (hfm.isBaseField(fieldName)) { + fieldValue = hfm.getHrmData(fieldName); + } else { + fieldValue = Util.null2String(new EncryptUtil().decrypt("cus_fielddata","field" + hfm.getFieldid(),"HrmCustomFieldByInfoType",""+scopeId,cfm.getData("field" + hfm.getFieldid()),false,true)); + } + + if (mapShowSets != null && mapShowSets.get(fieldName) != null) { + String mobileShowSet = Util.null2String(mapShowSets.get(fieldName)); + String showTypeDefault = Util.null2String(mapShowTypeDefaults.get(fieldName)); + if (mobileShowSet.equals("1")) { + String comPk = id + "__" + fieldName; + String comPkValue = Util.null2String(upc.getPvalue(comPk)); + if (comPkValue.length() > 0) { + fieldValue = upc.getShow(id, user, fieldName, fieldValue, comPkValue); + } else { + fieldValue = pc.getShow(id, user, fieldName, fieldValue, showTypeDefault); + } + } else { + fieldValue = pc.getShow(id, user, fieldName, fieldValue, showTypeDefault); + } + } + + //一些特殊处理 + if (fieldName.equals("mobile")) {//手机号码格式化 + fieldValue = ResourceComInfo.formatMobile(fieldValue); + } + + if (hfm.getHtmlType().equals("3")) { + fieldValue = hfm.getHtmlBrowserFieldvalue(user, dmlurl, fieldId, fieldhtmltype, type, fieldValue, "0"); + } else { + fieldValue = hfm.getFieldvalue(user, dmlurl, fieldId, fieldhtmltype, type, fieldValue, Util.getIntValue(request.getParameter("ismobile"))); + } + + if (fieldName.equals("email")) { + fieldValue = "" + fieldValue + ""; + } + if (fieldName.equals("locationid")) { + fieldValue = "" + fieldValue + ""; + } + + jsondata = new HashMap(); + jsondata.put("label", SystemEnv.getHtmlLabelName(fieldlabel, user.getLanguage())); + jsondata.put("value", fieldValue); + if (fieldName.equals("email")) { + jsondata.put("type", "email");//邮件(手机端标识) + } + if (fieldName.equals("mobile")) { + jsondata.put("type", "mobile");//手机号码(手机端标识) + } + if (fieldName.equals("telephone")) { + jsondata.put("type", "telephone");//电话号码(手机端标识) + } + if (fieldName.equals("mobilecall")) { + jsondata.put("type", "mobilecall");//其他电话(手机端标识) + } + itemlist.add(jsondata); + } + } + + retmap.put("validate", getValidate(user)); + retmap.put("result", grouplist); + /*手机端需要用到的分部ID和部门ID*/ + retmap.put("subcompanyId", resourceComInfo.getSubCompanyID(id));//分部ID + retmap.put("departmentId", resourceComInfo.getSubCompanyID(id));//部门ID + } + } catch (Exception e) { + writeLog(e); + } + + return JSONObject.toJSONString(retmap); + } + + public Map getValidate(User user) { + Map retmap = new LinkedHashMap(); + try { + HrmListValidate hrmListValidate = new HrmListValidate(); + Map map = null; + + /*手机端显示的顺序必须是:发送消息、发送短信、发送邮件*/ + map = new HashMap(); + map.put("isValidate", hrmListValidate.isValidate(33) && HrmValidate.hasEmessage(user)); + map.put("validateName", SystemEnv.getHtmlLabelName(513224, user.getLanguage())); + map.put("mobileUse", true); + retmap.put("33", map); + + String[] validateIds = new String[]{"31", "19", "32", "36", "37", "38"}; + String[] validateTitles = new String[]{"16635", "2051", "18481", "15707", "30184", "83704"}; + for (int i = 0; i < validateIds.length; i++) { + String validateId = validateIds[i]; + map = new HashMap(); + map.put("isValidate", hrmListValidate.isValidate(Util.getIntValue(validateIds[i]))); + map.put("validateName", SystemEnv.getHtmlLabelNames(validateTitles[i], user.getLanguage())); + if (validateId.equals("19") || validateId.equals("31") || validateId.equals("32")) { + map.put("mobileUse", true); + } + retmap.put(validateIds[i], map); + } + } catch (Exception e) { + writeLog(e); + } + return retmap; + } + + public Map addResourceBase(HttpServletRequest request, HttpServletResponse response) { + return addResourceBase(request, response, true); + } + + /** + * 新建人员基本信息 + * + * @param request + * @param response + * @return + */ + public Map addResourceBase(HttpServletRequest request, HttpServletResponse response, boolean needSync) { + Map retmap = new HashMap(); + try { + retmap.put("id", "0"); + User user = HrmUserVarify.getUser(request, response); + LN LN = new LN(); + RecordSet rs = new RecordSet(); + DepartmentComInfo DepartmentComInfo = new DepartmentComInfo(); + ResourceComInfo ResourceComInfo = new ResourceComInfo(); + SalaryManager SalaryManager = new SalaryManager(); + ChgPasswdReminder reminder = new ChgPasswdReminder(); + RemindSettings settings = reminder.getRemindSettings(); + SysRemindWorkflow SysRemindWorkflow = new SysRemindWorkflow(); + CustomFieldTreeManager CustomFieldTreeManager = new CustomFieldTreeManager(); + DepartmentVirtualComInfo DepartmentVirtualComInfo = new DepartmentVirtualComInfo(); + + String para = ""; + FileUpload fu = new FileUpload(request); + String cmd = Util.null2String(fu.getParameter("cmd")); + String id = Util.null2String(fu.getParameter("id")); + String workcode = Util.fromScreen3(fu.getParameter("workcode"), user.getLanguage()); + String lastname = Util.fromScreen3(fu.getParameter("lastname"), user.getLanguage()).trim(); + String sex = Util.fromScreen3(fu.getParameter("sex"), user.getLanguage()); + //String resourceimageid= Util.null2String(fu.uploadFiles("photoid")); + String resourceimageid = Util.null2String(fu.getParameter("resourceimageid")); + if (resourceimageid.length() > 0) { + resourceimageid = "" + DocDownloadCheckUtil.getDownloadfileidstr(resourceimageid); + if(Util.getIntValue(resourceimageid, 0)>0){ + rs.executeQuery("select imagefilename from imagefile where imagefileid=?", resourceimageid); + if(rs.next()){ + String imagefilename = Util.null2String(rs.getString("imagefilename")).trim(); + if(imagefilename.length()>0){ + String imgUrl = Util.null2String(imagefilename.substring(imagefilename.lastIndexOf(".")+1)).trim().toLowerCase(); + if(!"jpg".equals(imgUrl) && !"gif".equals(imgUrl) && !"png".equals(imgUrl)){ + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(132006, user.getLanguage())); + return retmap; + } + } + } + } + } + String departmentid = Util.fromScreen3(fu.getParameter("departmentid"), user.getLanguage()); + String costcenterid = Util.fromScreen3(fu.getParameter("costcenterid"), user.getLanguage()); + String jobtitle = Util.fromScreen3(fu.getParameter("jobtitle"), user.getLanguage()); + String joblevel = Util.fromScreen3(fu.getParameter("joblevel"), user.getLanguage()); + String jobactivitydesc = Util.fromScreen3(fu.getParameter("jobactivitydesc"), user.getLanguage()); + String managerid = Util.fromScreen3(fu.getParameter("managerid"), user.getLanguage()); + String assistantid = Util.fromScreen3(fu.getParameter("assistantid"), user.getLanguage()); + String status = Util.fromScreen3(fu.getParameter("status"), user.getLanguage()); + String locationid = Util.fromScreen3(fu.getParameter("locationid"), user.getLanguage()); + String workroom = Util.fromScreen3(fu.getParameter("workroom"), user.getLanguage()); + String telephone = Util.fromScreen3(fu.getParameter("telephone"), user.getLanguage()); + String mobile = Util.fromScreen3(fu.getParameter("mobile"), user.getLanguage()); + String mobileshowtype = Util.fromScreen3(fu.getParameter("mobileshowtype"), user.getLanguage()); + String mobilecall = Util.fromScreen3(fu.getParameter("mobilecall"), user.getLanguage()); + String fax = Util.fromScreen3(fu.getParameter("fax"), user.getLanguage()); + String jobcall = Util.fromScreen3(fu.getParameter("jobcall"), user.getLanguage()); + String email = Util.fromScreen3(fu.getParameter("email"), user.getLanguage()); + String dsporder = Util.fromScreen3(fu.getParameter("dsporder"), user.getLanguage()); + String accounttype = Util.fromScreen3(fu.getParameter("accounttype"), user.getLanguage()); + String systemlanguage = Util.null2String(fu.getParameter("systemlanguage")); + if (systemlanguage.equals("") || systemlanguage.equals("0")) systemlanguage = "7"; + String belongto = Util.fromScreen3(fu.getParameter("belongto"), user.getLanguage()); + //应聘人员id + String rcid = Util.null2String(fu.getParameter("rcId")); + + CheckItemBean mobileBean = new CheckItemBean("mobile", mobile, id); + ValidateFieldManager.validate(mobileBean); + if (!mobileBean.isPass()) { + retmap.put("status", "-1"); + retmap.put("message", mobileBean.getCheckMsg()); + return retmap; + } + + CheckItemBean telephoneBean = new CheckItemBean("telephone", telephone, id); + ValidateFieldManager.validate(telephoneBean); + if (!telephoneBean.isPass()) { + retmap.put("status", "-1"); + retmap.put("message", telephoneBean.getCheckMsg()); + return retmap; + } + + + if (dsporder.length() == 0) dsporder = id; + if (accounttype.equals("0")) { + belongto = "-1"; + } + String departmentvirtualids = Util.null2String(fu.getParameter("departmentvirtualids"));//虚拟部门id; + + //Td9325,解决多账号次账号没有登陆Id在浏览框组织结构中无法显示的问题。 + boolean falg = false; + String loginid = ""; + if (accounttype.equals("1")) { + rs.executeSql("select loginid from HrmResource where id =" + belongto); + if (rs.next()) { + loginid = rs.getString("loginid"); + } + if (!loginid.equals("")) { + String maxidsql = "select max(id) as id from HrmResource where loginid like '" + loginid + "%'"; + rs.executeSql(maxidsql); + if (rs.next()) { + loginid = loginid + (rs.getInt("id") + 1); + falg = true; + } + } + } + rs.executeProc("HrmResourceMaxId_Get", ""); + rs.next(); + id = "" + rs.getInt(1); + if (!"".equals(rcid)) { + id = rcid; + } + SimpleBizLogger logger = new SimpleBizLogger(); + Map params = ParamUtil.request2Map(request); + BizLogContext bizLogContext = new BizLogContext(); + bizLogContext.setLogType(BizLogType.HRM);//模块类型 + bizLogContext.setBelongType(BizLogSmallType4Hrm.HRM_RSOURCE_CARD);//所属大类型 + bizLogContext.setBelongTypeTargetName(SystemEnv.getHtmlLabelName(1361, user.getLanguage())); + bizLogContext.setLogSmallType(BizLogSmallType4Hrm.HRM_RSOURCE_CARD_BASE);//当前小类型 + bizLogContext.setOperateType(BizLogOperateType.ADD); + bizLogContext.setParams(params);//当前request请求参数 + logger.setUser(user);//当前操作人 + String cusFieldNames = ServiceUtil.getCusFieldNames("HrmCustomFieldByInfoType", -1, "b"); + String mainSql = "select a.*" + (cusFieldNames.length() > 0 ? "," + cusFieldNames : "") + " from hrmresource a left join cus_fielddata b on a.id=b.id and b.scope='HrmCustomFieldByInfoType' and b.scopeid=-1 where a.id=" + id; + logger.setMainSql(mainSql, "id");//主表sql + logger.setMainPrimarykey("id");//主日志表唯一key + logger.setMainTargetNameColumn("lastname");//当前targetName对应的列(对应日志中的对象名) + logger.before(bizLogContext);//写入操作前日志 + + String sql = "select managerstr, seclevel from HrmResource where id = " + Util.getIntValue(managerid); + rs.executeSql(sql); + String managerstr = ""; + String seclevel = ""; + while (rs.next()) { + String tmp_managerstr = rs.getString("managerstr"); + /*********处理managerstr 不以逗号开始或者结束的情况 形如 managerstr:8 begin***********/ + if (!tmp_managerstr.startsWith(",")) tmp_managerstr = "," + tmp_managerstr; + if (!tmp_managerstr.endsWith(",")) tmp_managerstr = tmp_managerstr + ","; + /*********处理managerstr 不以逗号开始或者结束的情况 形如 managerstr:8 end ***********/ + managerstr += tmp_managerstr; + managerstr = "," + managerid + managerstr; + managerstr = managerstr.endsWith(",") ? managerstr : (managerstr + ","); + seclevel = rs.getString("seclevel"); + } + + String subcmpanyid1 = DepartmentComInfo.getSubcompanyid1(departmentid); + RecordSetTrans rst = new RecordSetTrans(); + rst.setAutoCommit(false); + try { + if(resourceimageid.length()==0)resourceimageid="null"; + if(costcenterid.length()==0)costcenterid="null"; + if(managerid.length()==0)managerid="null"; + if(assistantid.length()==0)assistantid="null"; + if(accounttype.length()==0)accounttype="null"; + if(belongto.length()==0)belongto="null"; + if(jobcall.length()==0)jobcall="null"; + if(mobileshowtype.length()==0)mobileshowtype="null"; + if(rst.getDBType().equalsIgnoreCase("postgresql")) + { + if(joblevel.length()==0)joblevel=null; + if(dsporder.length()==0)dsporder=null; + } + workcode = CodeRuleManager.getCodeRuleManager().generateRuleCode(RuleCodeType.USER, subcmpanyid1, departmentid, jobtitle, workcode); + para = "" + id + separator + workcode + separator + lastname + separator + sex + separator + resourceimageid + separator + + departmentid + separator + costcenterid + separator + jobtitle + separator + joblevel + separator + jobactivitydesc + separator + + managerid + separator + assistantid + separator + status + separator + locationid + separator + workroom + separator + telephone + + separator + mobile + separator + mobilecall + separator + fax + separator + jobcall + separator + subcmpanyid1 + separator + managerstr + + separator + accounttype + separator + belongto + separator + systemlanguage + separator + email + separator + dsporder + separator + mobileshowtype; + + rst.executeProc("HrmResourceBasicInfo_Insert", para); + if(Util.null2String(locationid).length()>0) { + rst.executeSql("update hrmresource set countryid=(select countryid from HrmLocations where id=" + locationid + ")," + + DbFunctionUtil.getInsertUpdateSetSql(rst.getDBType(), user.getUID()) + " where id=" + id); + } + String logidsql = "", quickSearchStr = new HrmCommonServiceImpl().generateQuickSearchStr(lastname); + if (falg) { + logidsql = "update HrmResource set loginid = ?, pinyinlastname = ?, ecology_pinyin_search = ? where id = ?"; + rst.executeUpdate(logidsql, loginid, quickSearchStr, quickSearchStr, id); + } else { + logidsql = "update HrmResource set pinyinlastname = ?, ecology_pinyin_search = ? where id = ?"; + rst.executeUpdate(logidsql, quickSearchStr, quickSearchStr, id); + } + if (seclevel == null || "".equals(seclevel)) { + seclevel = "0"; + } + rst.commit(); + } catch (Exception e) { + rst.rollback(); + e.printStackTrace(); + } + + boolean formdefined = false; + weaver.system.CusFormSettingComInfo CusFormSettingComInfo = new weaver.system.CusFormSettingComInfo(); + weaver.system.CusFormSetting CusFormSetting = CusFormSettingComInfo.getCusFormSetting("hrm", "HrmResourceBase"); + if (CusFormSetting != null) { + if (CusFormSetting.getStatus() == 2) { + //自定义布局页面 + formdefined = true; + } + } + int userid = user.getUID(); + String userpara = "" + userid + separator + today; + para = "" + id; + for (int i = 0; i < 5; i++) { + int idx = i; + if (formdefined) idx++; + String datefield = Util.null2String(fu.getParameter("datefield" + idx)); + String numberfield = "" + Util.getDoubleValue(fu.getParameter("numberfield" + idx), 0); + String textfield = Util.null2String(fu.getParameter("textfield" + idx)); + String tinyintfield = "" + Util.getIntValue(fu.getParameter("tinyintfield" + idx), 0); + para += separator + datefield + separator + numberfield + separator + textfield + separator + tinyintfield; + } + rs.executeProc("HrmResourceDefine_Update", para); + rs.executeProc("HrmResource_CreateInfo", "" + id + separator + userpara + separator + userpara); + + //421944 用户自定义隐私设置 + + UserPrivacyComInfo upc = new UserPrivacyComInfo(); + PrivacyComInfo pc = new PrivacyComInfo(); + Map mapShowSets = pc.getMapShowSets(); + String insertSql = ""; + rs = new RecordSet(); + try { + String deletePriSql = " delete from userprivacysetting where userid= '" + id + "'"; + rs.executeSql(deletePriSql); + for (Map.Entry me : mapShowSets.entrySet()) { + String fieldName = me.getKey(); + String fieldVal = Util.null2String(mapShowSets.get(fieldName)); + if (fieldVal.equals("1")) { + String tmpPK = id + "__" + fieldName; + String tmpPvalue = Util.null2String(fu.getParameter(fieldName + "showtype")); + insertSql = "insert into userprivacysetting (combinedid,userid,ptype,pvalue) values('" + tmpPK + "','" + id + "','" + fieldName + "','" + tmpPvalue + "')"; + rs.executeSql(insertSql); + } + } + upc.removeUserPrivacyCache(); + } catch (Exception e) { + e.printStackTrace(); + } + + + // 改为只进行该人缓存信息的添加 + ResourceComInfo.addResourceInfoCache(id); + SalaryManager.initResourceSalary(id); + + para = "" + id + separator + managerid + separator + departmentid + separator + subcmpanyid1 + separator + "0" + separator + managerstr; + rs.executeProc("HrmResource_Trigger_Insert", para); + + String sql_1 = ("insert into HrmInfoStatus (itemid,hrmid) values(1," + id + ")"); + rs.executeSql(sql_1); + String sql_2 = ("insert into HrmInfoStatus (itemid,hrmid) values(2," + id + ")"); + rs.executeSql(sql_2); + String sql_3 = ("insert into HrmInfoStatus (itemid,hrmid) values(3," + id + ")"); + rs.executeSql(sql_3); + String sql_10 = ("insert into HrmInfoStatus (itemid,hrmid) values(10," + id + ")"); + rs.executeSql(sql_10); + + String name = lastname; + String CurrentUser = "" + user.getUID(); + String CurrentUserName = "" + user.getUsername(); + String SWFAccepter = ""; + String SWFTitle = ""; + String SWFRemark = ""; + String SWFSubmiter = ""; + String Subject = ""; + Subject = SystemEnv.getHtmlLabelName(15670, user.getLanguage()); + Subject += ":" + name; + + //modifier by lvyi 2013-12-31 + if (settings.getEntervalid().equals("1")) {//入职提醒 + String thesql = "select hrmids from HrmInfoMaintenance where id<4 or id = 10"; + rs.executeSql(thesql); + String members = ""; + /*while(rs.next()){ + int hrmid_tmp = Util.getIntValue(rs.getString("hrmids"));//TD9392 + if(hrmid_tmp > 0 && user.getUID() != hrmid_tmp){ + members += ","+rs.getString("hrmids"); + } + }*/ + while (rs.next()) { + String hrmid_tmp = Util.null2String(rs.getString("hrmids"));//TD9392 + if (hrmid_tmp.length() != 0) { + members += "," + rs.getString("hrmids"); + } + } + if (!members.equals("")) { + members = members.substring(1); + members = duplicateRemoval(members, user.getUID() + ""); + SWFAccepter = members; + SWFTitle = SystemEnv.getHtmlLabelName(15670, user.getLanguage()); + SWFTitle += ":" + name; + SWFTitle += "-" + CurrentUserName; + SWFTitle += "-" + today; +// SWFRemark=""+Util.fromScreen2(Subject,user.getLanguage())+"";//支持E9弹窗 + SWFRemark = "" + Util.fromScreen2(Subject, user.getLanguage()) + ""; + SWFSubmiter = CurrentUser; + SysRemindWorkflow.setPrjSysRemind(SWFTitle, 0, Util.getIntValue(SWFSubmiter), SWFAccepter, SWFRemark); + } + } + + CustomFieldTreeManager.editCustomDataE9Add("HrmCustomFieldByInfoType", -1, fu, Util.getIntValue(id, 0)); + //应聘人员的个人信息18条 + if (!"".equals(rcid)) { + sql = "select * from HrmCareerApply where id = ?"; + rs.executeQuery(sql,id); + if (rs.next()) { + String birthday = Util.null2String(rs.getString("birthday")); + String folk = Util.null2String(rs.getString("folk")); + String nativeplace = Util.null2String(rs.getString("nativeplace")); + String regresidentplace = Util.null2String(rs.getString("regresidentplace")); + + String certificatenum = Util.null2String(rs.getString("certificatenum")); + String maritalstatus = Util.null2String(rs.getString("maritalstatus")); + String policy = Util.null2String(rs.getString("policy")); + String bememberdate = Util.null2String(rs.getString("bememberdate")); + + String bepartydate = Util.null2String(rs.getString("bepartydate")); + String islabouunion = Util.null2String(rs.getString("islabouunion")); + String educationlevel = Util.null2String(rs.getString("educationlevel")); + String degree = Util.null2String(rs.getString("degree")); + + String healthinfo = Util.null2String(rs.getString("healthinfo")); + + String height = Util.null2String(rs.getString("height")); + if (height.indexOf(".") != -1) height = height.substring(0, height.indexOf(".")); + String weight = Util.null2String(rs.getString("weight")); + if (weight.indexOf(".") != -1) weight = weight.substring(0, weight.indexOf(".")); + + String residentplace = Util.null2String(rs.getString("residentplace")); + String homeaddress = Util.null2String(rs.getString("homeaddress")); + String tempresidentnumber = Util.null2String(rs.getString("tempresidentnumber")); + + para = "" + id + separator + birthday + separator + folk + separator + nativeplace + separator + regresidentplace + separator + maritalstatus + separator + policy + separator + bememberdate + separator + bepartydate + separator + islabouunion + separator + educationlevel + separator + degree + separator + healthinfo + separator + height + separator + weight + separator + residentplace + separator + homeaddress + separator + tempresidentnumber + separator + certificatenum; + RecordSet rs1 = new RecordSet(); + rs1.executeProc("HrmResourcePersonalInfo_Insert", para); + } + } + //更新虚拟组织部门id + if (departmentvirtualids.length() > 0) { + //保存前先删除需要删除的数据,因为有managerid 所以不能全部删除再保存 + sql = "delete from hrmresourcevirtual where resourceid=" + id + " and departmentid not in (" + departmentvirtualids + ")"; + rs.executeSql(sql); + + String[] departmentvirtualid = departmentvirtualids.split(","); + for (int i = 0; departmentvirtualid != null && i < departmentvirtualid.length; i++) { + rs.executeSql(" select count(*) from HrmResourceVirtual where departmentid ='" + departmentvirtualid[i] + "' and resourceid = " + id); + if (rs.next()) { + //如果已存在 无需处理 + if (rs.getInt(1) > 0) continue; + } + + //写入 + int tmpid = 0; + rs.executeSql("select max(id) from HrmResourceVirtual "); + if (rs.next()) { + tmpid = rs.getInt(1) + 1; + } + String subcompanyid = DepartmentVirtualComInfo.getSubcompanyid1(departmentvirtualid[i]); + sql = " insert into HrmResourceVirtual (id,resourceid,subcompanyid,departmentid ) " + + " values (" + tmpid + "," + id + "," + subcompanyid + "," + departmentvirtualid[i] + ")"; + rs.executeSql(sql); + } + } + + LogUtil.writeBizLog(logger.getBizLogContexts()); + + if(needSync) HrmFaceCheckManager.sync(id, HrmFaceCheckManager.getOptInsert(), "hrm_e9_HrmResourceBaseService_addResourceBase", HrmFaceCheckManager.getOaResource()); + //同步RTX端的用户信息. + new OrganisationCom().checkUser(Util.getIntValue(id)); + new Thread(new OrganisationComRunnable("user", "add", "" + id)).start(); + ResourceComInfo.updateResourceInfoCache("" + id); + new PluginUserCheck().clearPluginUserCache("messager"); + //OA与第三方接口单条数据同步方法开始 + new HrmServiceManager().SynInstantHrmResource("" + id, "1"); + //OA与第三方接口单条数据同步方法结束 + + // 新增人员 同步至 中控考勤机 + KqUtil.synAddOrUpdateUserInfo(""+id); + + //新增人员实时同步到CoreMail邮件系统 + //CoreMailAPI.synUser(id); + if (cmd.equals("SaveAndNew")) { + retmap.put("status", "1"); + } else if (cmd.equals("SaveAndNext")) { + retmap.put("status", "2"); + } else { + retmap.put("status", "3"); + } + retmap.put("id", id); + } catch (Exception e) { + writeLog("新建人员基本信息错误:" + e); + retmap.put("status", "-1"); + } + return retmap; + } + + /** + * 编辑人员基本信息 + * + * @param request + * @param response + * @return + */ + public Map editContactInfo(HttpServletRequest request, HttpServletResponse response) { + Map retmap = new HashMap(); + try { + User user = HrmUserVarify.getUser(request, response); + RecordSet rs = new RecordSet(); + String sql = ""; + ResourceComInfo ResourceComInfo = new ResourceComInfo(); + SysMaintenanceLog SysMaintenanceLog = new SysMaintenanceLog(); + HrmServiceManager HrmServiceManager = new HrmServiceManager(); + String para = ""; + + FileUpload fu = new FileUpload(request); + String id = Util.null2String(fu.getParameter("id")); + if (user.getUID() != Util.getIntValue(id)) {//本人才能修改 + retmap.put("status", "-1"); + retmap.put("message", ""+ SystemEnv.getHtmlLabelName(22620,weaver.general.ThreadVarLanguage.getLang())+""); + return retmap; + } + + + LN LN = new LN(); + DepartmentComInfo DepartmentComInfo = new DepartmentComInfo(); + CustomFieldTreeManager CustomFieldTreeManager = new CustomFieldTreeManager(); + CrmShareBase CrmShareBase = new CrmShareBase(); + + String resourceimageidcheck = Util.null2String(fu.getParameter("resourceimageid")); + if (resourceimageidcheck.length() > 0) { + resourceimageidcheck = "" + DocDownloadCheckUtil.getDownloadfileidstr(resourceimageidcheck); + } + String resourceimageBase64check = Util.null2String(fu.getParameter("resourceimageBase64")); + if (resourceimageBase64check.length() > 0) { + resourceimageidcheck = ServiceUtil.saveResourceImage(resourceimageBase64check); + } + String oldresourceimageidcheck = StringUtil.vString(fu.getParameter("oldresourceimage"),"0"); + if ("".equals(resourceimageidcheck)) resourceimageidcheck = oldresourceimageidcheck; + if(Util.getIntValue(resourceimageidcheck, 0)>0){ + rs.executeQuery("select imagefilename from imagefile where imagefileid=?", resourceimageidcheck); + if(rs.next()){ + String imagefilename = Util.null2String(rs.getString("imagefilename")).trim(); + if(imagefilename.length()>0){ + String imgUrl = Util.null2String(imagefilename.substring(imagefilename.lastIndexOf(".")+1)).trim().toLowerCase(); + if(!"jpg".equals(imgUrl) && !"gif".equals(imgUrl) && !"png".equals(imgUrl)){ + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(132006, user.getLanguage())); + return retmap; + } + } + } + } + + String mobile = Util.fromScreen3(fu.getParameter("mobile"), user.getLanguage()); + String telephone = Util.fromScreen3(fu.getParameter("telephone"), user.getLanguage()); + + CheckItemBean mobileBean = new CheckItemBean("mobile", mobile, id); + ValidateFieldManager.validate(mobileBean); + if (!mobileBean.isPass()) { + retmap.put("status", "-1"); + retmap.put("message", mobileBean.getCheckMsg()); + return retmap; + } + CheckItemBean telephoneBean = new CheckItemBean("telephone", telephone, id); + ValidateFieldManager.validate(telephoneBean); + if (!telephoneBean.isPass()) { + retmap.put("status", "-1"); + retmap.put("message", telephoneBean.getCheckMsg()); + return retmap; + } + + + SimpleBizLogger logger = new SimpleBizLogger(); + Map params = ParamUtil.request2Map(request); + BizLogContext bizLogContext = new BizLogContext(); + bizLogContext.setLogType(BizLogType.HRM);//模块类型 + bizLogContext.setBelongType(BizLogSmallType4Hrm.HRM_RSOURCE_CARD);//所属大类型 + bizLogContext.setBelongTypeTargetName(SystemEnv.getHtmlLabelName(1361, user.getLanguage())); + bizLogContext.setLogSmallType(BizLogSmallType4Hrm.HRM_RSOURCE_CARD_BASE);//当前小类型 + bizLogContext.setParams(params);//当前request请求参数 + logger.setUser(user);//当前操作人 + String cusFieldNames = ServiceUtil.getCusFieldNames("HrmCustomFieldByInfoType", -1, "b"); + String mainSql = "select a.*" + (cusFieldNames.length() > 0 ? "," + cusFieldNames : "") + " from hrmresource a left join cus_fielddata b on a.id=b.id and b.scope='HrmCustomFieldByInfoType' and b.scopeid=-1 where a.id=" + id; + logger.setMainSql(mainSql, "id");//主表sql + logger.setMainPrimarykey("id");//主日志表唯一key + logger.setMainTargetNameColumn("lastname");//当前targetName对应的列(对应日志中的对象名) + logger.before(bizLogContext);//吸入操作前日志 + + String updateSql = ""; + List sqlParams = new ArrayList() ; + RecordSetTrans rst = new RecordSetTrans(); + HrmFieldGroupComInfo HrmFieldGroupComInfo = new HrmFieldGroupComInfo(); + HrmFieldSearchConditionComInfo hrmFieldSearchConditionComInfo = new HrmFieldSearchConditionComInfo(); + HrmFieldManager hfm = new HrmFieldManager("HrmCustomFieldByInfoType", -1); + boolean flagaccount = GCONST.getMOREACCOUNTLANDING(); + String accounttype = ""; + String belongto = Util.fromScreen3(fu.getParameter("belongto"), user.getLanguage()); + String oldbelongto = ""; + String dsporder = Util.fromScreen3(fu.getParameter("dsporder"), user.getLanguage());; //显示顺序为空需要和id保持一致 + if (dsporder.length() == 0) dsporder = id; + String locationid = ""; //设置了办公地点需要更新人员的国家 + String loginid = ""; //次帐号的登录名需要和主账号+id保持一致 + boolean falg = false; + while (HrmFieldGroupComInfo.next()) { + int grouptype = Util.getIntValue(HrmFieldGroupComInfo.getType()); + if (grouptype != -1) continue; + int groupid = Util.getIntValue(HrmFieldGroupComInfo.getid()); + hfm.getCustomFields(groupid); + while (hfm.next()) { + String fieldName = hfm.getFieldname(); + if (fieldName.equals("accounttype") && !flagaccount) continue; + if (fieldName.equals("belongto")) continue; + if (fieldName.equals("loginid") || fieldName.equals("jobactivity") || fieldName.equals("status") || fieldName.equals("departmentvirtualids")) continue; + if (fieldName.equals("messagerurl") || fieldName.equals("jobGroupId") || fieldName.equals("managerid") || fieldName.equals("departmentid")) continue; + //没有开启多语言即使开启了系统语言允许个人编辑也不行 + if (!hfm.isUse() || !hfm.isModify() || !hfm.isBaseField(fieldName)) { + continue; + }else{ + String updateValue = Util.fromScreen3(fu.getParameter(fieldName), user.getLanguage()); + if("accounttype".equals(fieldName)){ + accounttype = updateValue; + if (accounttype.equals("0")) { + belongto = "-1"; + } + //Td9325,解决多账号次账号没有登陆Id在浏览框组织结构中无法显示的问题。 + rs.executeQuery("select * from HrmResource where id = ? " ,id); + if (rs.next()) { + loginid = rs.getString("loginid"); + float idsporder = rs.getFloat("dsporder"); + if (idsporder <= 0) { + dsporder = rs.getString("id"); + } else { + dsporder = "" + idsporder; + } + } + + String thisAccounttype = rs.getString("accounttype"); + if (thisAccounttype.equals("1") && updateValue.equals("0")) { + oldbelongto = rs.getString("belongto"); + } + if (accounttype.equals("1") && loginid.equalsIgnoreCase("")) { + rs.executeSql("select loginid from HrmResource where id =" + belongto); + if (rs.next()) { + loginid = rs.getString(1); + } + if (LN.CkHrmnum() >= 0) { + retmap.put("status", "-1"); + return retmap; + } + if (!loginid.equals("")) { + loginid = loginid + (id + 1); + falg = true; + } + } + continue; + } + if("resourceimageid".equals(fieldName)){ + String resourceimageid = updateValue; + if (resourceimageid.length() > 0) { + resourceimageid = "" + DocDownloadCheckUtil.getDownloadfileidstr(resourceimageid); + } + String resourceimageBase64 = Util.null2String(fu.getParameter("resourceimageBase64")); + if (resourceimageBase64.length() > 0) { + resourceimageid = ServiceUtil.saveResourceImage(resourceimageBase64); + } + String oldresourceimageid = StringUtil.vString(fu.getParameter("oldresourceimage"),"0"); + if (resourceimageid.equals("")) resourceimageid = oldresourceimageid; + updateValue = resourceimageid; + } + if("locationid".equals(fieldName)){ + locationid = updateValue; + } + if("dsporder".equals(fieldName)){ + updateValue = dsporder; + } + if("systemlanguage".equals(fieldName)){ + if (updateValue.equals("") || updateValue.equals("0")) { + updateValue = "7"; + } + } + //mysql报错问题java.sql.SQLException: Incorrect integer value: '' for column 'COSTCENTERID' at row 1 + if((fieldName.equals("resourceimageid") || fieldName.equals("costcenterid") || fieldName.equals("managerid") + || fieldName.equals("assistantid") || fieldName.equals("accounttype") || fieldName.equals("belongto") + || fieldName.equals("jobcall") || fieldName.equals("mobileshowtype") || fieldName.equals("joblevel") + ) && updateValue.length()==0){ + updateValue ="null"; + } + if(updateSql.length()>0)updateSql+=","; + updateSql+=(fieldName+" = ? "); + sqlParams.add(updateValue); + } + } + } + if(accounttype.length()>0){ + if(updateSql.length()>0)updateSql+=","; + updateSql+="accounttype = ?,belongto = ?"; + sqlParams.add(accounttype); + sqlParams.add(belongto); + } + if(updateSql.length()>0){ + rst.setAutoCommit(false); + try { + String sqltemp = "update hrmresource set "+updateSql+" where id = ? "; + sqlParams.add(id); + rst.executeUpdate(sqltemp,sqlParams); + if(Util.null2String(locationid).length()>0) { + rst.executeSql("update hrmresource set countryid=(select countryid from HrmLocations where id=" + locationid + ") where id=" + id); + } + if (falg) { + String logidsql = "update HrmResource set loginid = '" + loginid + "' where id = " + id; + rst.executeSql(logidsql); + } + rst.commit(); + } catch (Exception e) { + rst.rollback(); + e.printStackTrace(); + } + } + + //421944 用户自定义隐私设置 + + UserPrivacyComInfo upc = new UserPrivacyComInfo(); + PrivacyComInfo pc = new PrivacyComInfo(); + Map mapShowSets = pc.getMapShowSets(); + String insertSql = ""; + rs = new RecordSet(); + try { + String deletePriSql = " delete from userprivacysetting where userid= '" + id + "'"; + rs.executeSql(deletePriSql); + for (Map.Entry me : mapShowSets.entrySet()) { + String fieldName = me.getKey(); + String fieldVal = Util.null2String(mapShowSets.get(fieldName)); + if (fieldVal.equals("1")) { + String tmpPK = id + "__" + fieldName; + String tmpPvalue = Util.null2String(fu.getParameter(fieldName + "showtype")); + insertSql = "insert into userprivacysetting (combinedid,userid,ptype,pvalue) values('" + tmpPK + "','" + id + "','" + fieldName + "','" + tmpPvalue + "')"; + rs.executeSql(insertSql); + } + } + upc.removeUserPrivacyCache(); + } catch (Exception e) { + e.printStackTrace(); + } + + int userid = user.getUID(); + String userpara = "" + userid + separator + today; + rs.executeProc("HrmResource_ModInfo", "" + id + separator + userpara); + + boolean formdefined = false; + weaver.system.CusFormSettingComInfo CusFormSettingComInfo = new weaver.system.CusFormSettingComInfo(); + weaver.system.CusFormSetting CusFormSetting = CusFormSettingComInfo.getCusFormSetting("hrm", "HrmResourceBase"); + if (CusFormSetting != null) { + if (CusFormSetting.getStatus() == 2) { + //自定义布局页面 + formdefined = true; + } + } + para = "" + id; + for (int i = 0; i < 5; i++) { + int idx = i; + if (formdefined) idx++; + String datefield = Util.null2String(fu.getParameter("datefield" + idx)); + String numberfield = "" + Util.getDoubleValue(fu.getParameter("numberfield" + idx), 0); + String textfield = Util.null2String(fu.getParameter("textfield" + idx)); + String tinyintfield = "" + Util.getIntValue(fu.getParameter("tinyintfield" + idx), 0); + para += separator + datefield + separator + numberfield + separator + textfield + separator + tinyintfield; + } + rs.executeProc("HrmResourceDefine_Update", para); + + new Thread(new OrganisationComRunnable("user", "editbasicinfo", id + "-" + (ResourceComInfo.getStatus(id)))).start(); + // 改为自进行修正 + ResourceComInfo.updateResourceInfoCache(id); + //OA与第三方接口单条数据同步方法开始 + HrmServiceManager.SynInstantHrmResource(id, "2"); + //OA与第三方接口单条数据同步方法结束 + + // 新增人员 同步至 中控考勤机 + KqUtil.synAddOrUpdateUserInfo(id); + + //处理自定义字段 add by wjy + CustomFieldTreeManager.editCustomData("HrmCustomFieldByInfoType", -1, fu, Util.getIntValue(id, 0)); + + //处理次账号修改为主账号时,检查次账号所属 主账号的 其他设置是否需要修改 add by kzw QC159888 + try { + if (!oldbelongto.equals("")) { + HrmUserSettingComInfo userSetting = new HrmUserSettingComInfo(); + String belongtoshow = userSetting.getBelongtoshowByUserId(oldbelongto); + if (belongtoshow.equals("1")) { + rs.executeSql("select id from hrmresource where belongto = " + oldbelongto); + if (!rs.next()) { + String setId = userSetting.getId(oldbelongto); + rs.executeSql("update HrmUserSetting set belongtoshow=0 where id=" + setId); + userSetting.removeHrmUserSettingComInfoCache(); + } + } + } + } catch (Exception e) { + writeLog(e.getMessage()); + } + + rs.execute("update HrmResource set " + DbFunctionUtil.getUpdateSetSql(rs.getDBType(), user.getUID()) + " where id=" + id); + rs.execute("update HrmResourceManager set " + DbFunctionUtil.getUpdateSetSql(rs.getDBType(), user.getUID()) + " where id=" + id); + + //写入操作后日志 + LogUtil.writeBizLog(logger.getBizLogContexts()); + + //修改人员实时同步到CoreMail邮件系统 + //CoreMailAPI.synUser(id); + + HrmFaceCheckManager.sync(id, HrmFaceCheckManager.getOptUpdate(), "hrm_e9_HrmResourceBaseService_editResourceBase", HrmFaceCheckManager.getOaResource()); + + retmap.put("status", "1"); + } catch (Exception e) { + writeLog("编辑人员信息错误:" + e); + retmap.put("status", "-1"); + } + return retmap; + } + + /** + * 编辑人员基本信息 + * + * @param request + * @param response + * @return + */ + public Map editResourceBase(HttpServletRequest request, HttpServletResponse response) { + Map retmap = new HashMap(); + try { + User user = HrmUserVarify.getUser(request, response); + if (Util.null2String(request.getParameter("editcontact")).equals("1")) { + return editContactInfo(request, response); + } + + boolean canEdit = HrmUserVarify.checkUserRight("HrmResourceEdit:Edit", user); + if (!canEdit) { + retmap.put("status", "-1"); + retmap.put("message", ""+ SystemEnv.getHtmlLabelName(22620,weaver.general.ThreadVarLanguage.getLang())+""); + return retmap; + } + LN LN = new LN(); + RecordSet rs = new RecordSet(); + DepartmentComInfo DepartmentComInfo = new DepartmentComInfo(); + ResourceComInfo ResourceComInfo = new ResourceComInfo(); + CustomFieldTreeManager CustomFieldTreeManager = new CustomFieldTreeManager(); + SysMaintenanceLog SysMaintenanceLog = new SysMaintenanceLog(); + HrmServiceManager HrmServiceManager = new HrmServiceManager(); + CrmShareBase CrmShareBase = new CrmShareBase(); + + String para = ""; + FileUpload fu = new FileUpload(request); + String id = Util.null2String(fu.getParameter("id")); + if (id.length()==0) { + retmap.put("status", "-1"); + retmap.put("message", ""+ SystemEnv.getHtmlLabelName(22620,weaver.general.ThreadVarLanguage.getLang())+""); + return retmap; + } + String workcode = Util.fromScreen3(fu.getParameter("workcode"), user.getLanguage()); + String lastname = Util.fromScreen3(fu.getParameter("lastname"), user.getLanguage()).trim(); + String sex = Util.fromScreen3(fu.getParameter("sex"), user.getLanguage()); + String resourceimageid = Util.null2String(fu.getParameter("resourceimageid")); + if(resourceimageid.length()>0) { + resourceimageid = "" + DocDownloadCheckUtil.getDownloadfileidstr(resourceimageid); + } + String resourceimageBase64 = Util.null2String(fu.getParameter("resourceimageBase64")); + if(resourceimageBase64.length()>0){ + resourceimageid = ServiceUtil.saveResourceImage(resourceimageBase64); + } + String oldresourceimageid = Util.null2String(fu.getParameter("oldresourceimage")); + if (resourceimageid.equals("")) resourceimageid = oldresourceimageid; + if(Util.getIntValue(resourceimageid, 0)>0){ + rs.executeQuery("select imagefilename from imagefile where imagefileid=?", resourceimageid); + if(rs.next()){ + String imagefilename = Util.null2String(rs.getString("imagefilename")).trim(); + if(imagefilename.length()>0){ + String imgUrl = Util.null2String(imagefilename.substring(imagefilename.lastIndexOf(".")+1)).trim().toLowerCase(); + if(!"jpg".equals(imgUrl) && !"gif".equals(imgUrl) && !"png".equals(imgUrl)){ + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(132006, user.getLanguage())); + return retmap; + } + } + } + } + String departmentid = Util.fromScreen3(fu.getParameter("departmentid"), user.getLanguage()); + String costcenterid = Util.fromScreen3(fu.getParameter("costcenterid"), user.getLanguage()); + String jobtitle = Util.fromScreen3(fu.getParameter("jobtitle"), user.getLanguage()); + String joblevel = Util.fromScreen3(fu.getParameter("joblevel"), user.getLanguage()); + String jobactivitydesc = Util.fromScreen3(fu.getParameter("jobactivitydesc"), user.getLanguage()); + String managerid = Util.fromScreen3(fu.getParameter("managerid"), user.getLanguage()); + String assistantid = Util.fromScreen3(fu.getParameter("assistantid"), user.getLanguage()); + String status = ""; + String locationid = Util.fromScreen3(fu.getParameter("locationid"), user.getLanguage()); + String workroom = Util.fromScreen3(fu.getParameter("workroom"), user.getLanguage()); + String telephone = Util.fromScreen3(fu.getParameter("telephone"), user.getLanguage()); + String mobile = Util.fromScreen3(fu.getParameter("mobile"), user.getLanguage()); + String mobileshowtype = Util.fromScreen3(fu.getParameter("mobileshowtype"), user.getLanguage()); + String mobilecall = Util.fromScreen3(fu.getParameter("mobilecall"), user.getLanguage()); + String fax = Util.fromScreen3(fu.getParameter("fax"), user.getLanguage()); + String email = Util.fromScreen3(fu.getParameter("email"), user.getLanguage()); + String dsporder = Util.fromScreen3(fu.getParameter("dsporder"), user.getLanguage()); + String jobcall = Util.fromScreen3(fu.getParameter("jobcall"), user.getLanguage()); + String systemlanguage = Util.fromScreen3(fu.getParameter("systemlanguage"), user.getLanguage()); + if (systemlanguage.equals("") || systemlanguage.equals("0")) { + systemlanguage = "7"; + } + String accounttype = Util.fromScreen3(fu.getParameter("accounttype"), user.getLanguage()); + String belongto = Util.fromScreen3(fu.getParameter("belongto"), user.getLanguage()); + if (dsporder.length() == 0) dsporder = id; + if (accounttype.equals("0")) { + belongto = "-1"; + } + + + CheckItemBean mobileBean = new CheckItemBean("mobile", mobile, id); + ValidateFieldManager.validate(mobileBean); + if (!mobileBean.isPass()) { + retmap.put("status", "-1"); + retmap.put("message", mobileBean.getCheckMsg()); + return retmap; + } + CheckItemBean telephoneBean = new CheckItemBean("telephone", telephone, id); + ValidateFieldManager.validate(telephoneBean); + if (!telephoneBean.isPass()) { + retmap.put("status", "-1"); + retmap.put("message", telephoneBean.getCheckMsg()); + return retmap; + } + + + SimpleBizLogger logger = new SimpleBizLogger(); + Map params = ParamUtil.request2Map(request); + BizLogContext bizLogContext = new BizLogContext(); + bizLogContext.setLogType(BizLogType.HRM);//模块类型 + bizLogContext.setBelongType(BizLogSmallType4Hrm.HRM_RSOURCE_CARD);//所属大类型 + bizLogContext.setBelongTypeTargetName(SystemEnv.getHtmlLabelName(1361, user.getLanguage())); + bizLogContext.setLogSmallType(BizLogSmallType4Hrm.HRM_RSOURCE_CARD_BASE);//当前小类型 + bizLogContext.setParams(params);//当前request请求参数 + logger.setUser(user);//当前操作人 + String cusFieldNames = ServiceUtil.getCusFieldNames("HrmCustomFieldByInfoType", -1, "b"); + String mainSql = "select a.*" + (cusFieldNames.length() > 0 ? "," + cusFieldNames : "") + " from hrmresource a left join cus_fielddata b on a.id=b.id and b.scope='HrmCustomFieldByInfoType' and b.scopeid=-1 where a.id=" + id; + logger.setMainSql(mainSql, "id");//主表sql + logger.setMainPrimarykey("id");//主日志表唯一key + logger.setMainTargetNameColumn("lastname");//当前targetName对应的列(对应日志中的对象名) + logger.before(bizLogContext);//吸入操作前日志 + + //Td9325,解决多账号次账号没有登陆Id在浏览框组织结构中无法显示的问题。 + String oldbelongto = ""; + boolean falg = false; + String loginid = ""; + rs.executeSql("select * from HrmResource where id =" + id); + if (rs.next()) { + status = Util.null2String(rs.getString("status")).trim(); + loginid = rs.getString("loginid"); + float idsporder = rs.getFloat("dsporder"); + if (idsporder <= 0) { + dsporder = rs.getString("id"); + } else { + dsporder = "" + idsporder; + } + + String thisAccounttype = rs.getString("accounttype"); + if (thisAccounttype.equals("1") && accounttype.equals("0")) { + oldbelongto = rs.getString("belongto"); + } + } + + if (accounttype.equals("1") && loginid.equalsIgnoreCase("")) { + rs.executeSql("select loginid from HrmResource where id =" + belongto); + if (rs.next()) { + loginid = rs.getString(1); + } + + if (!loginid.equals("")) { + loginid = loginid + (id + 1); + falg = true; + } + } + String sql = "select * from HrmResource where id = " + Util.getIntValue(id); + rs.executeSql(sql); + String oldmanagerid = ""; + String oldmanagerstr = ""; + while (rs.next()) { + oldmanagerid = rs.getString("managerid"); + oldmanagerstr = rs.getString("managerstr"); + /*********处理managerstr 不以逗号开始或者结束的情况 形如 managerstr:8 begin***********/ + if (!oldmanagerstr.startsWith(",")) oldmanagerstr = "," + oldmanagerstr; + if (!oldmanagerstr.endsWith(",")) oldmanagerstr = oldmanagerstr + ","; + /*********处理managerstr 不以逗号开始或者结束的情况 形如 managerstr:8 end ***********/ + } + //mysql报错问题java.sql.SQLException: Incorrect integer value: '' for column 'COSTCENTERID' at row 1 + if(resourceimageid.length()==0)resourceimageid="null"; + if(costcenterid.length()==0)costcenterid="null"; + if(managerid.length()==0)managerid="null"; + if(assistantid.length()==0)assistantid="null"; + if(accounttype.length()==0)accounttype="null"; + if(belongto.length()==0)belongto="null"; + if(jobcall.length()==0)jobcall="null"; + if(mobileshowtype.length()==0)mobileshowtype="null"; + DepartmentComInfo departmentComInfo = new DepartmentComInfo(); + String subcompanyid1 = departmentComInfo.getSubcompanyid1(departmentid); +// workcode = CodeRuleManager.getCodeRuleManager().generateRuleCode(RuleCodeType.USER, subcompanyid1, departmentid, jobtitle, workcode); + if (StringUtils.isNotEmpty(workcode)) { + CodeRuleManager.getCodeRuleManager().checkReservedIfDel(RuleCodeType.USER.getValue(), workcode); + } + para = "" + id + separator + workcode + separator + lastname + separator + sex + separator + resourceimageid + + separator + departmentid + separator + costcenterid + separator + jobtitle + separator + joblevel + + separator + jobactivitydesc + separator + managerid + separator + assistantid + separator + status + + separator + locationid + separator + workroom + separator + telephone + separator + mobile + + separator + mobilecall + separator + fax + separator + jobcall + separator + systemlanguage + + separator + accounttype + separator + belongto + separator + email + separator + dsporder + separator + mobileshowtype; + RecordSetTrans rst = new RecordSetTrans(); + rst.setAutoCommit(false); + try { + rst.executeProc("HrmResourceBasicInfo_Update", para); + if(Util.null2String(locationid).length()>0) { + rst.executeSql("update hrmresource set countryid=(select countryid from HrmLocations where id=" + locationid + ") where id=" + id); + } + String logidsql = "", quickSearchStr = new HrmCommonServiceImpl().generateQuickSearchStr(lastname); + if (falg) { + logidsql = "update HrmResource set loginid = ?, pinyinlastname = ?, ecology_pinyin_search = ? where id = ?"; + rst.executeUpdate(logidsql, loginid, quickSearchStr, quickSearchStr, id); + } else { + logidsql = "update HrmResource set pinyinlastname = ?, ecology_pinyin_search = ? where id = ?"; + rst.executeUpdate(logidsql, quickSearchStr, quickSearchStr, id); + } + rst.commit(); + } catch (Exception e) { + rst.rollback(); + e.printStackTrace(); + } + + if(!"7".equals(systemlanguage) && StringUtils.isNotBlank(systemlanguage)){ + User.setUserLang(Util.getIntValue(id),Util.getIntValue(systemlanguage, 7)); + } + + //421944 用户自定义隐私设置 + + UserPrivacyComInfo upc = new UserPrivacyComInfo(); + PrivacyComInfo pc = new PrivacyComInfo(); + Map mapShowSets = pc.getMapShowSets(); + String insertSql = ""; + rs = new RecordSet(); + try { + String deletePriSql = " delete from userprivacysetting where userid= '" + id + "'"; + rs.executeSql(deletePriSql); + for (Map.Entry me : mapShowSets.entrySet()) { + String fieldName = me.getKey(); + String fieldVal = Util.null2String(mapShowSets.get(fieldName)); + if (fieldVal.equals("1")) { + String tmpPK = id + "__" + fieldName; + String tmpPvalue = Util.null2String(fu.getParameter(fieldName + "showtype")); + insertSql = "insert into userprivacysetting (combinedid,userid,ptype,pvalue) values('" + tmpPK + "','" + id + "','" + fieldName + "','" + tmpPvalue + "')"; + rs.executeSql(insertSql); + } + } + upc.removeUserPrivacyCache(); + } catch (Exception e) { + e.printStackTrace(); + } + + int userid = user.getUID(); + String userpara = "" + userid + separator + today; + rs.executeProc("HrmResource_ModInfo", "" + id + separator + userpara); + String managerstr = ""; + if (!id.equals(managerid)) { + sql = "select managerstr from HrmResource where id = " + Util.getIntValue(managerid); + rs.executeSql(sql); + while (rs.next()) { + managerstr = rs.getString("managerstr"); + /*********处理managerstr 不以逗号开始或者结束的情况 形如 managerstr:8 begin***********/ + if (!managerstr.startsWith(",")) managerstr = "," + managerstr; + if (!managerstr.endsWith(",")) managerstr = managerstr + ","; + /*********处理managerstr 不以逗号开始或者结束的情况 形如 managerstr:8 end ***********/ + managerstr = "," + managerid + managerstr; + managerstr = managerstr.endsWith(",") ? managerstr : (managerstr + ","); + } + } else { + managerstr = "," + managerid + ","; + } + + rst = new RecordSetTrans(); + rst.setAutoCommit(false); + try { + para = "" + id + separator + managerstr; + rst.executeProc("HrmResource_UpdateManagerStr", para); + rst.commit(); + } catch (Exception e) { + rst.rollback(); + e.printStackTrace(); + } + + managerid = Util.null2String(managerid).trim(); + oldmanagerid = Util.null2String(oldmanagerid).trim(); + if(!managerid.equals(oldmanagerid) && !(("".equals(managerid) || "0".equals(managerid)) && ("".equals(oldmanagerid) || "0".equals(oldmanagerid)))){ + String temOldmanagerstr = "," + id + oldmanagerstr; + temOldmanagerstr = temOldmanagerstr.endsWith(",") ? temOldmanagerstr : (temOldmanagerstr + ","); + sql = "select id,departmentid,subcompanyid1,managerid,seclevel,managerstr from HrmResource where managerstr like '%" + temOldmanagerstr + "'"; + rs.executeSql(sql); + while (rs.next()) { + String nowmanagerstr = Util.null2String(rs.getString("managerstr")); + /*********处理managerstr 不以逗号开始或者结束的情况 形如 managerstr:8 begin***********/ + if (!nowmanagerstr.startsWith(",")) nowmanagerstr = "," + nowmanagerstr; + if (!nowmanagerstr.endsWith(",")) nowmanagerstr = nowmanagerstr + ","; + /*********处理managerstr 不以逗号开始或者结束的情况 形如 managerstr:8 end ***********/ + String resourceid = rs.getString("id"); + //指定上级为自身的情况,不更新自身上级 + if (id.equals(resourceid)) + continue; + String nowmanagerstr2 = ""; + int index = nowmanagerstr.lastIndexOf(oldmanagerstr); + if (index != -1) { + if (!"".equals(managerstr)) { + nowmanagerstr2 = nowmanagerstr.substring(0, index) + ("".equals(oldmanagerstr) ? managerstr.substring(1) : managerstr); + } else { + nowmanagerstr2 = nowmanagerstr.substring(0, index) + ("".equals(oldmanagerstr) ? "" : ","); + } + } + rst = new RecordSetTrans(); + rst.setAutoCommit(false); + try { + para = resourceid + separator + nowmanagerstr2; + rst.executeProc("HrmResource_UpdateManagerStr", para); + rst.commit(); + ResourceComInfo.updateResourceInfoCache(resourceid); //更新缓存 + } catch (Exception e) { + rst.rollback(); + e.printStackTrace(); + } + } + } + + String subcmpanyid1 = DepartmentComInfo.getSubcompanyid1(departmentid); + para = "" + id + separator + subcmpanyid1; + rst = new RecordSetTrans(); + rst.setAutoCommit(false); + try { + rst.executeProc("HrmResource_UpdateSubCom", para); + rst.commit(); + } catch (Exception e) { + rst.rollback(); + e.printStackTrace(); + } + + if(!managerid.equals(oldmanagerid) && !(("".equals(managerid) || "0".equals(managerid)) && ("".equals(oldmanagerid) || "0".equals(oldmanagerid)))){//修改人力资源经理,对客户和日程共享重新计算 + CrmShareBase.setShareForNewManager(id); + } + boolean formdefined = false; + weaver.system.CusFormSettingComInfo CusFormSettingComInfo = new weaver.system.CusFormSettingComInfo(); + weaver.system.CusFormSetting CusFormSetting = CusFormSettingComInfo.getCusFormSetting("hrm", "HrmResourceBase"); + if (CusFormSetting != null) { + if (CusFormSetting.getStatus() == 2) { + //自定义布局页面 + formdefined = true; + } + } + para = "" + id; + for (int i = 0; i < 5; i++) { + int idx = i; + if (formdefined) idx++; + String datefield = Util.null2String(fu.getParameter("datefield" + idx)); + String numberfield = "" + Util.getDoubleValue(fu.getParameter("numberfield" + idx), 0); + String textfield = Util.null2String(fu.getParameter("textfield" + idx)); + String tinyintfield = "" + Util.getIntValue(fu.getParameter("tinyintfield" + idx), 0); + para += separator + datefield + separator + numberfield + separator + textfield + separator + tinyintfield; + } + rs.executeProc("HrmResourceDefine_Update", para); + + new Thread(new OrganisationComRunnable("user", "editbasicinfo", id + "-" + status)).start(); + // 改为自进行修正 + ResourceComInfo.updateResourceInfoCache(id); + + try { + //OA与第三方接口单条数据同步方法开始 + HrmServiceManager.SynInstantHrmResource(id, "2"); + //OA与第三方接口单条数据同步方法结束 + } catch (Exception e) { + this.writeLog("OA与第三方接口单条数据同步失败" + e); + } + + //处理自定义字段 add by wjy + CustomFieldTreeManager.editCustomData("HrmCustomFieldByInfoType", -1, fu, Util.getIntValue(id, 0)); + + //处理次账号修改为主账号时,检查次账号所属 主账号的 其他设置是否需要修改 add by kzw QC159888 + try { + if (!oldbelongto.equals("")) { + HrmUserSettingComInfo userSetting = new HrmUserSettingComInfo(); + String belongtoshow = userSetting.getBelongtoshowByUserId(oldbelongto); + if (belongtoshow.equals("1")) { + rs.executeSql("select id from hrmresource where belongto = " + oldbelongto); + if (!rs.next()) { + String setId = userSetting.getId(oldbelongto); + rs.executeSql("update HrmUserSetting set belongtoshow=0 where id=" + setId); + userSetting.removeHrmUserSettingComInfoCache(); + } + } + } + } catch (Exception e) { + writeLog(e.getMessage()); + } + + rs.execute("update HrmResource set " + DbFunctionUtil.getUpdateSetSql(rs.getDBType(), user.getUID()) + " where id=" + id); + rs.execute("update HrmResourceManager set " + DbFunctionUtil.getUpdateSetSql(rs.getDBType(), user.getUID()) + " where id=" + id); + + //写入操作后日志 + LogUtil.writeBizLog(logger.getBizLogContexts()); + + //修改人员实时同步到CoreMail邮件系统 + //CoreMailAPI.synUser(id); + + HrmFaceCheckManager.sync(id, HrmFaceCheckManager.getOptUpdate(), "hrm_e9_HrmResourceBaseService_editResourceBase", HrmFaceCheckManager.getOaResource()); + + retmap.put("status", "1"); + } catch (Exception e) { + writeLog(e); + retmap.put("status", "-1"); + retmap.put("message", ""+ SystemEnv.getHtmlLabelName(22620,weaver.general.ThreadVarLanguage.getLang())+""); + } + return retmap; + } + + /** + * 校验数据合法性 + */ + public Map hrmResourceCheck(HttpServletRequest request, HttpServletResponse response) { + Map retmap = new HashMap(); + try { + User user = HrmUserVarify.getUser(request, response); + RecordSet rs = new RecordSet(); + String id = Util.null2String(request.getParameter("id")); + String temName = Util.null2String(request.getParameter("lastname")); + String temCode = Util.null2String(request.getParameter("workcode")); + String temTelephone = Util.null2String(request.getParameter("telephone")); + String temMobile = Util.null2String(request.getParameter("mobile")); + + String checkMessage = ""; + boolean isCheckHas = false; + boolean isCheckHasName = false; + boolean isCheck = false; + + String tempSql = ""; + + if (temTelephone.equals("sysadmin") || temMobile.equals("sysadmin")) { + checkMessage = SystemEnv.getHtmlLabelName(22305, user.getLanguage()); + isCheck = true; + } + + if (!temCode.equals("")) { + tempSql = "select workcode from HrmResource where workcode='" + temCode + "' "; + if (temCode.equals("sysadmin")) { + checkMessage = SystemEnv.getHtmlLabelName(510739, user.getLanguage()); //判断workcode编号是不是sysadmin + isCheck = true; + } + if (id.length() > 0) { + tempSql += " and id !=" + id; + } + rs.executeSql(tempSql); + if (rs.next()) { + String workcode = rs.getString("workcode"); + if (workcode.equals(temCode)) { + checkMessage = SystemEnv.getHtmlLabelName(21447, user.getLanguage()); + isCheckHas = true; + // 删除和编号重复的预留编号 + String sql = "delete from hrm_coderulereserved where id in(select hcr.id from hrm_coderulereserved hcr left join hrm_coderule hc ON hcr.coderuleid = hc.id where hc.serialtype = ? and reservedcode = ?)"; + rs.executeUpdate(sql, RuleCodeType.USER.getValue(), temCode); + } + } + } + if (!temName.equals("")) { + tempSql = "select lastname from HrmResource where lastname='" + temName + "' "; + if (id.length() > 0) { + tempSql += " and id !=" + id; + } + rs.executeSql(tempSql); + if (rs.next()) { + if (!isCheckHas) { + checkMessage = SystemEnv.getHtmlLabelName(21445, user.getLanguage()); + } else { + checkMessage = SystemEnv.getHtmlLabelName(21446, user.getLanguage()); + } + isCheckHasName = true; + } + } + + if ((isCheckHas && isCheckHasName) || (isCheckHas && !isCheckHasName) || (isCheck)) { + retmap.put("status", "-1"); + retmap.put("message", checkMessage); + } else if (!isCheckHas && isCheckHasName) { + retmap.put("status", "-1"); + retmap.put("messagetype", "confirm"); + retmap.put("message", checkMessage); + } else { + retmap.put("status", "1"); + } + } catch (Exception e) { + writeLog(e); + } + return retmap; + } + + + @SuppressWarnings({"unchecked", "rawtypes"}) + public String duplicateRemoval(String str, String userid) { + String[] ss = str.split(","); + List list = new ArrayList(); + for (String s : ss) { + list.add(s.trim()); + } + HashSet hs = new HashSet(list); + list.clear(); + list.addAll(hs); + if (list.contains(userid)) list.remove(userid); + str = list.toString().replace("[", "").replace("]", "").replace(" ", ""); + return str; + } + + /** + * 获取允许个人编辑的字段数量 + * @param scopeid + * @return + */ + public boolean isHasModify(int scopeid) { + int fieldNum = 0; + HrmFieldGroupComInfo HrmFieldGroupComInfo = new HrmFieldGroupComInfo(); + HrmFieldSearchConditionComInfo hrmFieldSearchConditionComInfo = new HrmFieldSearchConditionComInfo(); + HrmFieldManager hfm = new HrmFieldManager("HrmCustomFieldByInfoType", scopeid); + + StaticObj staticobj = StaticObj.getInstance(); + String multilanguage = (String) staticobj.getObject("multilanguage"); + if (multilanguage == null) multilanguage = "n"; + boolean isMultilanguageOK = false; + if (multilanguage.equals("y")) isMultilanguageOK = true; + boolean flagaccount = GCONST.getMOREACCOUNTLANDING(); + + while (HrmFieldGroupComInfo.next()) { + int grouptype = Util.getIntValue(HrmFieldGroupComInfo.getType()); + if (grouptype != scopeid) continue; + int grouplabel = Util.getIntValue(HrmFieldGroupComInfo.getLabel()); + int groupid = Util.getIntValue(HrmFieldGroupComInfo.getid()); + hfm.getCustomFields(groupid); + while (hfm.next()) { + String fieldName = hfm.getFieldname(); + //没有开启多语言即使开启了系统语言允许个人编辑也不行 + if (fieldName.equals("systemlanguage") && !isMultilanguageOK) continue; + //没有开启主从账号,账号类型也要过滤 + if (fieldName.equals("accounttype") && !flagaccount) continue; + if (fieldName.equals("belongto") && flagaccount) continue; + if (fieldName.equals("loginid") || fieldName.equals("jobactivity") || fieldName.equals("status") || fieldName.equals("departmentvirtualids")) continue; + if (fieldName.equals("messagerurl") || fieldName.equals("jobGroupId")) continue; + if (!hfm.isUse() || !hfm.isModify()) { + continue; + } + fieldNum++; + } + + //个人信息还需要检查自定义子信息是否有允许个人修改的字段 + if (scopeid == 1) { + //自定义信息 + RecordSet RecordSet = new RecordSet(); + CustomFieldTreeManager CustomFieldTreeManager = new CustomFieldTreeManager(); + LinkedHashMap ht = new LinkedHashMap(); + RecordSet.executeSql("select id, formlabel,viewtype from cus_treeform where parentid=" + scopeid + " order by scopeorder"); + while (RecordSet.next()) { + if (RecordSet.getInt("viewtype") != 1) continue; + int subId = RecordSet.getInt("id"); + CustomFieldManager cfm2 = new CustomFieldManager("HrmCustomFieldByInfoType", subId); + cfm2.getCustomFields(); + int colcount1 = cfm2.getSize(); + if (colcount1 != 0) { + while (cfm2.next()) { + if (!cfm2.isUse() || (!cfm2.isModify())) continue; + fieldNum++; + } + } + } + } + } + if (fieldNum > 0) return true; + return false; + } + + public boolean canEditUserIcon() { + RecordSet recordSet = new RecordSet(); + int isModify = 0; + recordSet.executeQuery("select isModify from hrm_formfield where fieldname = ?", "messagerurl"); + if (recordSet.next()) { + isModify = recordSet.getInt("isModify"); + } + if (isModify == 1) { + return true; + } else { + return false; + } + } + + public Map refreshPinyin(HttpServletRequest request, HttpServletResponse response) { + Map retmap = new HashMap(); + try { + User user = HrmUserVarify.getUser(request, response); + if (user.isAdmin()) { + upgradeSearchPinyin(); + retmap.put("status", "1"); + } else { + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage())); + } + } catch (Exception ex) { + ex.printStackTrace(); + writeLog(ex); + retmap.put("status", "-1"); + retmap.put("message", "failed"); + } + return retmap; + } + + public void upgradeSearchPinyin() { + try { + RecordSet rs = new RecordSet(); + rs.executeQuery("select id, lastname from hrmresource"); + while (rs.next()) { + RecordSet rs1 = new RecordSet(); + String id = Util.null2String(rs.getString("id")); + String lastname = Util.null2String(rs.getString("lastname")); + String quickSearchStr = new HrmCommonServiceImpl().generateQuickSearchStr(lastname); + + try { + rs1.executeUpdate("update hrmresource set PINYINLASTNAME = ?, ECOLOGY_PINYIN_SEARCH = ? where id = ?", quickSearchStr, quickSearchStr, id); + } catch (Exception e) { + writeLog(e); + e.printStackTrace(); + } + } + } catch (Exception ex) { + writeLog(ex); + ex.printStackTrace(); + } + } + + public void upgradeAreaSearchPinyin(){ + try{ + String id = ""; + String name = ""; + + RecordSet rs = new RecordSet(); + RecordSet rs1 = new RecordSet(); + + rs.executeQuery("select id, countryname as name from hrmcountry"); + while (rs.next()) { + id = Util.null2String(rs.getString("id")); + name = Util.null2String(rs.getString("name")); + String quickSearchStr = new HrmCommonServiceImpl().generateQuickSearchStr(name); + + try { + rs1.executeUpdate("update hrmcountry set quicksearch = ? where id = ?", quickSearchStr, id); + } catch (Exception e) { + writeLog(e); + e.printStackTrace(); + } + } + + rs.executeQuery("select id, provincename as name from hrmprovince"); + while (rs.next()) { + id = Util.null2String(rs.getString("id")); + name = Util.null2String(rs.getString("name")); + String quickSearchStr = new HrmCommonServiceImpl().generateQuickSearchStr(name); + + try { + rs1.executeUpdate("update hrmprovince set quicksearch = ? where id = ?", quickSearchStr, id); + } catch (Exception e) { + writeLog(e); + e.printStackTrace(); + } + } + + rs.executeQuery("select id, cityname as name from HRMCITY"); + while (rs.next()) { + id = Util.null2String(rs.getString("id")); + name = Util.null2String(rs.getString("name")); + String quickSearchStr = new HrmCommonServiceImpl().generateQuickSearchStr(name); + + try { + rs1.executeUpdate("update HRMCITY set quicksearch = ? where id = ?", quickSearchStr, id); + } catch (Exception e) { + writeLog(e); + e.printStackTrace(); + } + } + + rs.executeQuery("select id, cityname as name from HrmCityTwo"); + while (rs.next()) { + id = Util.null2String(rs.getString("id")); + name = Util.null2String(rs.getString("name")); + String quickSearchStr = new HrmCommonServiceImpl().generateQuickSearchStr(name); + + try { + rs1.executeUpdate("update HrmCityTwo set quicksearch = ? where id = ?", quickSearchStr, id); + } catch (Exception e) { + writeLog(e); + e.printStackTrace(); + } + } + }catch (Exception ex){ + ex.printStackTrace(); + writeLog(ex); + } + } +} diff --git a/领悦二开new/src/com/api/lingyue/SynOtherKqInfoApi.java b/领悦二开new/src/com/api/lingyue/SynOtherKqInfoApi.java new file mode 100644 index 0000000..f7434c7 --- /dev/null +++ b/领悦二开new/src/com/api/lingyue/SynOtherKqInfoApi.java @@ -0,0 +1,16 @@ +package com.api.lingyue; + +import com.engine.lingyue.web.SynOtherKqInfoAction; + +import javax.ws.rs.Path; + +/** + * @Title + * @Author wangchaofa + * @CreateDate 2024/7/17 + * @Version 1.0 + * @Description + */ +@Path("/lingyue/syn") +public class SynOtherKqInfoApi extends SynOtherKqInfoAction { +} diff --git a/领悦二开new/src/com/engine/hrm/cmd/organization/AddDepartmentCmd.java b/领悦二开new/src/com/engine/hrm/cmd/organization/AddDepartmentCmd.java new file mode 100644 index 0000000..17f1955 --- /dev/null +++ b/领悦二开new/src/com/engine/hrm/cmd/organization/AddDepartmentCmd.java @@ -0,0 +1,231 @@ +package com.engine.hrm.cmd.organization; + +import com.api.hrm.util.ServiceUtil; +import com.engine.common.biz.AbstractCommonCommand; +import com.engine.common.biz.SimpleBizLogger; +import com.engine.common.constant.BizLogOperateAuditType; +import com.engine.common.constant.BizLogSmallType4Hrm; +import com.engine.common.constant.BizLogType; +import com.engine.common.entity.BizLogContext; +import com.engine.core.interceptor.CommandContext; +import com.engine.hrm.cmd.matrix.biz.MatrixMaintComInfo; +import com.engine.hrm.entity.RuleCodeType; +import com.engine.hrm.util.CodeRuleManager; +import com.engine.hrm.util.HrmOrganizationUtil; +import com.engine.hrm.util.face.HrmFaceCheckManager; +import com.lingyue.util.KqUtil; +import org.apache.commons.lang3.StringUtils; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; +import weaver.hrm.common.DbFunctionUtil; +import weaver.hrm.company.DepartmentComInfo; +import weaver.hrm.definedfield.HrmDeptFieldManagerE9; +import weaver.interfaces.email.CoreMailAPI; +import weaver.interfaces.hrm.HrmServiceManager; +import weaver.matrix.MatrixUtil; +import weaver.rtx.OrganisationCom; +import weaver.rtx.OrganisationComRunnable; +import weaver.systeminfo.SystemEnv; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class AddDepartmentCmd extends AbstractCommonCommand>{ + + private SimpleBizLogger logger; + + public AddDepartmentCmd(Map params, User user) { + this.user = user; + this.params = params; + + String departmentname = Util.fromScreen((String)params.get("departmentname"),user.getLanguage()); + + this.logger = new SimpleBizLogger(); + BizLogContext bizLogContext = new BizLogContext(); + bizLogContext.setLogType(BizLogType.HRM_ENGINE);//模块类型 + bizLogContext.setBelongType(BizLogSmallType4Hrm.HRM_ENGINE_ORGANIZATION); + bizLogContext.setLogSmallType(BizLogSmallType4Hrm.HRM_ENGINE_ORGANIZATION_DPEARTMENT);//当前小类型 + bizLogContext.setOperateAuditType(BizLogOperateAuditType.WARNING);//警告 + bizLogContext.setParams(params);//当前request请求参数 + logger.setUser(user);//当前操作人 + String mainSql = "select * from HrmDepartment where 1=2 "; + logger.setMainSql(mainSql,"id");//主表sql + logger.setMainPrimarykey("id");//主日志表唯一key + logger.setMainTargetNameColumn("departmentname");//当前targetName对应的列(对应日志中的对象名) + logger.before(bizLogContext); + } + + @Override + public Map execute(CommandContext commandContext) { + Map retmap = new HashMap(); + RecordSet rs = new RecordSet(); + try { + + if (!HrmUserVarify.checkUserRight("HrmDepartmentAdd:Add", user)) { + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage())); + return retmap; + } + + DepartmentComInfo DepartmentComInfo = new DepartmentComInfo(); + //OrganisationCom OrganisationCom = new OrganisationCom(); + HrmServiceManager HrmServiceManager = new HrmServiceManager(); + + String departmentmark = Util.fromScreen((String)params.get("departmentmark"),user.getLanguage()); + String departmentname = Util.fromScreen((String)params.get("departmentname"),user.getLanguage()); + String subcompanyid1 = Util.fromScreen((String)params.get("subcompanyid1"),user.getLanguage()); + int supdepid = Util.getIntValue((String)params.get("supdepid"),0); + String showorder = Util.fromScreen(Util.null2s((String)params.get("showorder"),"0"),user.getLanguage()); + + if(Util.getIntValue(subcompanyid1,0)<=0){ + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(382647, user.getLanguage())); + return retmap; + } + + String allsupdepid = "0"; + String departmentcode = Util.fromScreen((String)params.get("departmentcode"),user.getLanguage()); + int coadjutant=Util.getIntValue((String)params.get("coadjutant"),0); + + /* + * Added by Charoes Huang + * 判断是否10级部门 + */ + int supdepartmentid = supdepid; + if(supdepartmentid > 0){ + Map supMap = new HashMap(); + supMap.put(""+supdepid, "1"); + int supdepidtemp = Util.getIntValue(DepartmentComInfo.getDepartmentsupdepid(""+supdepid), 0); + while(supdepidtemp>0){ + if(supMap.get(""+supdepidtemp)==null){ + supMap.put(""+supdepidtemp, "1"); + supdepidtemp = Util.getIntValue(DepartmentComInfo.getDepartmentsupdepid(""+supdepidtemp), 0); + }else{ + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(382650,user.getLanguage())); + return retmap; + } + } + if(HrmOrganizationUtil.ifDeptLevelEquals10(supdepartmentid)){ + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(382650, user.getLanguage())); + return retmap; + } + } + + // 如果编码为空 自动生成编码 + departmentcode = CodeRuleManager.getCodeRuleManager().generateRuleCode(RuleCodeType.DEPARTMENT, subcompanyid1, departmentcode); + + if(!"".equals(departmentcode)){ + String sql2="select id from hrmdepartment where departmentcode = '" + departmentcode + "' "; + rs.executeSql(sql2); + if(rs.next()){ + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(382653, user.getLanguage())); + return retmap; + } + } + + + char separator = Util.getSeparator() ; + if(supdepid > 0){//当选择了上级部门的时候,需要更改当前部门的上级分部 + subcompanyid1 = DepartmentComInfo.getSubcompanyid1(supdepid+""); + } + + String para = departmentmark + separator + departmentname + separator + + supdepid+separator+allsupdepid+separator+subcompanyid1 + separator+ showorder+separator+coadjutant; + rs.executeProc("HrmDepartment_Insert",para); + int flag=rs.getFlag(); + if(flag==2){ + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(382655, user.getLanguage())); + return retmap; + }else if(flag==3){ + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(382657, user.getLanguage())); + return retmap; + } + + int id=0; + if(rs.next()){ + id = rs.getInt(1); + } + + weaver.hrm.company.OrgOperationUtil OrgOperationUtil = new weaver.hrm.company.OrgOperationUtil(); + OrgOperationUtil.updateDepartmentLevel(""+id,"0"); + String sql3="update hrmdepartment set departmentcode = '" + departmentcode + "' "; + sql3 += ","+ DbFunctionUtil.getInsertUpdateSetSql(rs.getDBType(),user.getUID()) ; + sql3+=" where id = "+id; + rs.executeSql(sql3); + HrmDeptFieldManagerE9 hrmDeptFieldManager = new HrmDeptFieldManagerE9(5); + hrmDeptFieldManager.editCustomData(params,id); + + + DepartmentComInfo.removeCompanyCache(); + rs.executeSql("update orgchartstate set needupdate=1"); + + //add by wjy + //同步RTX端部门信息 + //OrganisationCom.addDepartment(id);//执行速度过慢,改为另起线程执行 + new Thread(new OrganisationComRunnable("department", "add", String.valueOf(id))).start(); + + //同步到CoreMail邮件系统开始 + if(supdepid == 0) { + CoreMailAPI.synOrg(""+id, departmentname, "parent_org_unit_id=com_"+subcompanyid1+"&org_unit_name="+departmentname, "0"); + //testapi.synOrg(""+id, departmentname, "com_"+subcompanyid1, "0"); + } else { + CoreMailAPI.synOrg(""+id, departmentname, "parent_org_unit_id="+supdepid+"&org_unit_name="+departmentname, "0"); + //testapi.synOrg(""+id, departmentname, ""+supdepid, "0"); + } + //同步到CoreMail邮件系统结束 + + //OA与第三方接口单条数据同步方法开始 + HrmServiceManager.SynInstantDepartment(""+id,"1"); + //OA与第三方接口单条数据同步方法结束 + + HrmFaceCheckManager.sync(id+"",HrmFaceCheckManager.getOptInsert(),this.getClass().getName(),HrmFaceCheckManager.getOaDepartment()); + + + //同步部门数据到矩阵 + MatrixUtil.updateDepartmentData(""+id); + //同步矩阵维护范围 + MatrixMaintComInfo maintComInfo = new MatrixMaintComInfo(); + maintComInfo.removeCache(); + //初始化应用分权 + new weaver.hrm.appdetach.AppDetachComInfo().initSubDepAppData(); + + // 同步部门数据到中控考勤机 + KqUtil.synAddOrUpdateDeptInfo(""+id); + + + String mainSql = "select a.* from HrmDepartment a left join HrmDepartmentdefined b on a.id=b.deptid where a.id in(" + id + ")"; + String tableColumns = new ServiceUtil().getTableColumns("select * from HrmDepartmentdefined", "b", "id"); + if (!tableColumns.equals("")) { + mainSql = "select a.*," + tableColumns + " from HrmDepartment a left join HrmDepartmentdefined b on a.id=b.deptid where a.id in(" + id + ")"; + } + logger.setMainSql(mainSql, "id");//主表sql + + retmap.put("id", id); + retmap.put("status", "1"); + retmap.put("message", SystemEnv.getHtmlLabelName(18758, user.getLanguage())); + } catch (Exception e) { + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(382661,user.getLanguage())); + writeLog(e); + } + return retmap; + } + + @Override + public BizLogContext getLogContext() { + return null; + } + + @Override + public List getLogContexts() { + return logger.getBizLogContexts(); + } +} diff --git a/领悦二开new/src/com/engine/hrm/cmd/organization/AddSubCompanyCmd.java b/领悦二开new/src/com/engine/hrm/cmd/organization/AddSubCompanyCmd.java new file mode 100644 index 0000000..0a6b2b8 --- /dev/null +++ b/领悦二开new/src/com/engine/hrm/cmd/organization/AddSubCompanyCmd.java @@ -0,0 +1,245 @@ +package com.engine.hrm.cmd.organization; + +import com.api.hrm.util.ServiceUtil; +import com.engine.common.biz.AbstractCommonCommand; +import com.engine.common.biz.SimpleBizLogger; +import com.engine.common.constant.BizLogOperateAuditType; +import com.engine.common.constant.BizLogSmallType4Hrm; +import com.engine.common.constant.BizLogType; +import com.engine.common.constant.ParamConstant; +import com.engine.common.entity.BizLogContext; +import com.engine.common.service.ThemeService; +import com.engine.common.service.impl.ThemeServiceImpl; +import com.engine.core.interceptor.CommandContext; +import com.engine.hrm.cmd.matrix.biz.MatrixMaintComInfo; +import com.engine.hrm.entity.RuleCodeType; +import com.engine.hrm.util.CodeRuleManager; +import com.engine.hrm.util.HrmOrganizationUtil; +import com.engine.hrm.util.face.HrmFaceCheckManager; +import com.lingyue.util.KqUtil; +import org.apache.commons.lang3.StringUtils; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; +import weaver.hrm.common.DbFunctionUtil; +import weaver.hrm.company.SubCompanyComInfo; +import weaver.hrm.definedfield.HrmDeptFieldManagerE9; +import weaver.interfaces.email.CoreMailAPI; +import weaver.interfaces.hrm.HrmServiceManager; +import weaver.matrix.MatrixUtil; +import weaver.rtx.OrganisationCom; +import weaver.rtx.OrganisationComRunnable; +import weaver.systeminfo.SystemEnv; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class AddSubCompanyCmd extends AbstractCommonCommand> { + private SimpleBizLogger logger; + + public AddSubCompanyCmd(Map params, User user) { + this.user = user; + this.params = params; + + String subcompanyname = Util.fromScreen((String) params.get("subcompanyname"), user.getLanguage()); + + this.logger = new SimpleBizLogger(); + BizLogContext bizLogContext = new BizLogContext(); + bizLogContext.setLogType(BizLogType.HRM_ENGINE);//模块类型 + bizLogContext.setBelongType(BizLogSmallType4Hrm.HRM_ENGINE_ORGANIZATION); + bizLogContext.setLogSmallType(BizLogSmallType4Hrm.HRM_ENGINE_ORGANIZATION_SUBCOMPANY);//当前小类型 + bizLogContext.setOperateAuditType(BizLogOperateAuditType.WARNING);//警告 + bizLogContext.setParams(params);//当前request请求参数 + logger.setUser(user);//当前操作人 + String mainSql = "select * from HrmSubCompany where 1=2 "; + logger.setMainSql(mainSql, "id");//主表sql + logger.setMainPrimarykey("id");//主日志表唯一key + logger.setMainTargetNameColumn("subcompanyname");//当前targetName对应的列(对应日志中的对象名) + logger.before(bizLogContext); + } + + @Override + public Map execute(CommandContext commandContext) { + Map retmap = new HashMap(); + try { + String sql = ""; + RecordSet rs = null; + + if (!HrmUserVarify.checkUserRight("HrmSubCompanyEdit:Edit", user)) { + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage())); + return retmap; + } + + SubCompanyComInfo SubCompanyComInfo = new SubCompanyComInfo(); + //OrganisationCom OrganisationCom = new OrganisationCom(); + HrmServiceManager HrmServiceManager = new HrmServiceManager(); + + int companyid = 1; + int supsubcomid = Util.getIntValue((String) params.get("supsubcomid"), 0); + String subcompanycode = Util.fromScreen((String) params.get("subcompanycode"), user.getLanguage()); + String subcompanyname = Util.fromScreen((String) params.get("subcompanyname"), user.getLanguage()); + String subcompanydesc = Util.fromScreen((String) params.get("subcompanydesc"), user.getLanguage()); + String url = Util.null2String((String) params.get("url")); + float showorder = Util.getFloatValue((String) params.get("showorder"), 0.00f); + int limitUsers = Util.getIntValue(Util.fromScreen((String) params.get("limitUsers"), user.getLanguage()), 0); + limitUsers = limitUsers < 0 ? 0 : limitUsers; + + if (supsubcomid > 0) { + Map supMap = new HashMap(); + supMap.put(""+supsubcomid, "1"); + int supsubcomidtemp = Util.getIntValue(SubCompanyComInfo.getSupsubcomid(""+supsubcomid), 0); + while(supsubcomidtemp>0){ + if(supMap.get(""+supsubcomidtemp)==null){ + supMap.put(""+supsubcomidtemp, "1"); + supsubcomidtemp = Util.getIntValue(SubCompanyComInfo.getSupsubcomid(""+supsubcomidtemp), 0); + }else{ + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(382649,user.getLanguage())); + return retmap; + } + } + if (HrmOrganizationUtil.ifSubComLevelEquals10(supsubcomid)) { + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(382649, user.getLanguage())); + return retmap; + } + } + + // 如果编码为空 自动生成编码 + subcompanycode = CodeRuleManager.getCodeRuleManager().generateRuleCode(RuleCodeType.SUBCOMPANY, subcompanycode); + + if (!"".equals(subcompanycode)) { + sql = "select id from HrmSubCompany where subcompanycode = '" + subcompanycode + "'"; + rs = new RecordSet(); + rs.executeSql(sql); + if (rs.next()) { + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(382651, user.getLanguage())); + return retmap; + } + } + + char separator = Util.getSeparator(); + String para = subcompanyname + separator + subcompanydesc + separator + companyid + separator + supsubcomid + separator + url + separator + showorder; + rs = new RecordSet(); + rs.executeProc("HrmSubCompany_Insert", para); + int flag = rs.getFlag(); + int id = 0; + if (rs.next()) { + id = rs.getInt(1); + } + + if (flag == 2) { + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(382654, user.getLanguage())); + return retmap; + } + if (flag == 3) { + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(382656, user.getLanguage())); + return retmap; + } + + sql = "update HrmSubCompany set subcompanycode = '" + subcompanycode + "'"; + if (user.getUID() == 1){ + sql += ", limitUsers = " + limitUsers; + } + sql += ","+ DbFunctionUtil.getInsertUpdateSetSql(rs.getDBType(),user.getUID()) ; + sql += " where id = " + id; + rs.executeSql(sql); + + HrmDeptFieldManagerE9 hrmDeptFieldManager = new HrmDeptFieldManagerE9(4); + hrmDeptFieldManager.editCustomData(params,id); + + + + // 更新机构权限数据:新增加的分部默认继承上级分部的所有机构权限。 + para = String.valueOf(id) + separator + String.valueOf(supsubcomid); + rs = new RecordSet(); + rs.executeProc("HrmRoleSRT_AddByNewSc", para); + + //新增分部,統一调用门户接口创建门户菜单 + ThemeService themService = new ThemeServiceImpl(); + themService.createSubCompanyMenu(id,supsubcomid); +// // 更新左侧菜单,新增的分部继承上级分部的左侧菜单 +// String strWhere = " where resourcetype=2 and resourceid=" + supsubcomid; +// if (supsubcomid == 0) +// strWhere = " where resourcetype=1 and resourceid=1 "; +// String strSql = "insert into leftmenuconfig (userid,infoid,visible,viewindex,resourceid,resourcetype,locked,lockedbyid,usecustomname,customname,customname_e) select distinct userid,infoid,visible,viewindex," + id + ",2,locked,lockedbyid,usecustomname,customname,customname_e from leftmenuconfig " + strWhere; +// rs = new RecordSet(); +// rs.executeSql(strSql); +// +// // 更新顶部菜单,新增的分部继承上级分部的顶部菜单 +// strWhere = " where resourcetype=2 and resourceid=" + supsubcomid; +// if (supsubcomid == 0) +// strWhere = " where resourcetype=1 and resourceid=1 "; +// strSql = "insert into mainmenuconfig (userid,infoid,visible,viewindex,resourceid,resourcetype,locked,lockedbyid,usecustomname,customname,customname_e) select distinct userid,infoid,visible,viewindex," + id + ",2,locked,lockedbyid,usecustomname,customname,customname_e from mainmenuconfig " + strWhere; +// rs = new RecordSet(); +// rs.executeSql(strSql); + + SubCompanyComInfo.removeCompanyCache(); + + rs = new RecordSet(); + rs.executeSql("update orgchartstate set needupdate=1"); + weaver.hrm.company.OrgOperationUtil OrgOperationUtil = new weaver.hrm.company.OrgOperationUtil(); + OrgOperationUtil.updateSubcompanyLevel("" + id, "0"); + //OrganisationCom.addSubCompany(id);//执行速度过慢,改成另起现成执行 + new Thread(new OrganisationComRunnable("subcompany", "add", String.valueOf(id))).start(); + + // 同步到CoreMail邮件系统开始 + if (supsubcomid > 0) { + CoreMailAPI.synOrg("com_" + id, subcompanyname, "parent_org_unit_id=com_" + supsubcomid + "&org_unit_name=" + subcompanyname, "0"); + // testapi.synOrg("com_"+id, subcompanyname, "com_"+supsubcomid, "0"); + } else { + CoreMailAPI.synOrg("com_" + id, subcompanyname, "org_unit_name=" + subcompanyname, "0"); + // testapi.synOrg("com_"+id, subcompanyname, "", "0"); + } + // 同步到CoreMail邮件系统结束 + + // OA与第三方接口单条数据同步方法开始 + HrmServiceManager.SynInstantSubCompany("" + id, "1"); + // OA与第三方接口单条数据同步方法结束 + + HrmFaceCheckManager.sync(id+"",HrmFaceCheckManager.getOptInsert(),"HRM_AddSubCompanyCmd",HrmFaceCheckManager.getOaSubcompany()); + + // 同步分部数据到矩阵 + MatrixUtil.updateSubcompayData("" + id); + //同步矩阵维护范围 + MatrixMaintComInfo maintComInfo = new MatrixMaintComInfo(); + maintComInfo.removeCache(); + // 初始化应用分权 + new weaver.hrm.appdetach.AppDetachComInfo().initSubDepAppData(); + + // 同步分部数据到中控考勤机 + KqUtil.synAddOrUpdateSubComInfo(""+id); + + String mainSql = "select a.* from HrmSubCompany a left join hrmsubcompanydefined b on a.id=b.subcomid where a.id in(" + id + ") "; + String tableColumns = new ServiceUtil().getTableColumns("select * from hrmsubcompanydefined", "b", "id"); + if (!tableColumns.equals("")) { + mainSql = "select a.*," + tableColumns + " from HrmSubCompany a left join hrmsubcompanydefined b on a.id=b.subcomid where a.id in(" + id + ") "; + } + logger.setMainSql(mainSql, "id");//主表sql + retmap.put("id", id); + retmap.put("status", "1"); + retmap.put("message", SystemEnv.getHtmlLabelName(18758, user.getLanguage())); + } catch (Exception e) { + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(382661,user.getLanguage())); + writeLog(e); + } + return retmap; + } + + @Override + public BizLogContext getLogContext() { + return null; + } + + @Override + public List getLogContexts() { + return logger.getBizLogContexts(); + } +} diff --git a/领悦二开new/src/com/engine/hrm/cmd/organization/CancelDepartmentCmd.java b/领悦二开new/src/com/engine/hrm/cmd/organization/CancelDepartmentCmd.java new file mode 100644 index 0000000..72acde8 --- /dev/null +++ b/领悦二开new/src/com/engine/hrm/cmd/organization/CancelDepartmentCmd.java @@ -0,0 +1,175 @@ +package com.engine.hrm.cmd.organization; + +import com.engine.common.biz.AbstractCommonCommand; +import com.engine.common.biz.SimpleBizLogger; +import com.engine.common.constant.BizLogOperateAuditType; +import com.engine.common.constant.BizLogSmallType4Hrm; +import com.engine.common.constant.BizLogType; +import com.engine.common.entity.BizLogContext; +import com.engine.core.interceptor.CommandContext; +import com.engine.hrm.util.face.HrmFaceCheckManager; +import com.lingyue.util.KqUtil; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; +import weaver.hrm.common.DbFunctionUtil; +import weaver.hrm.company.DepartmentComInfo; +import weaver.interfaces.email.CoreMailAPI; +import weaver.interfaces.hrm.HrmServiceManager; +import weaver.matrix.MatrixUtil; +import weaver.rtx.OrganisationCom; +import weaver.systeminfo.SystemEnv; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class CancelDepartmentCmd extends AbstractCommonCommand>{ + + private SimpleBizLogger logger; + + public CancelDepartmentCmd(Map params, User user) { + this.user = user; + this.params = params; + + this.logger = new SimpleBizLogger(); + String id = Util.null2String(params.get("id")); + BizLogContext bizLogContext = new BizLogContext(); + bizLogContext.setLogType(BizLogType.HRM_ENGINE);//模块类型 + bizLogContext.setBelongType(BizLogSmallType4Hrm.HRM_ENGINE_ORGANIZATION); + bizLogContext.setLogSmallType(BizLogSmallType4Hrm.HRM_ENGINE_ORGANIZATION_DPEARTMENT);//当前小类型 + bizLogContext.setOperateAuditType(BizLogOperateAuditType.WARNING);//警告 + bizLogContext.setParams(params);//当前request请求参数 + logger.setUser(user);//当前操作人 + String mainSql = "select * from Hrmdepartment where id in("+id+")"; + logger.setMainSql(mainSql,"id");//主表sql + logger.setMainPrimarykey("id");//主日志表唯一key + logger.setMainTargetNameColumn("departmentname");//当前targetName对应的列(对应日志中的对象名) + logger.before(bizLogContext); + } + + @Override + public Map execute(CommandContext commandContext) { + Map retmap = new HashMap(); + try { + if(!HrmUserVarify.checkUserRight("HrmDepartmentAdd:Add", user)){ + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage())); + return retmap; + } + + String ids = Util.null2String((String)params.get("id")); + + String[] arrIds = Util.splitString(ids, ","); + if(arrIds.length>1){ + for(int i=0; i cancel(int id) throws Exception { + Map retmap = new HashMap(); + try { + if(!HrmUserVarify.checkUserRight("HrmDepartmentEdit:Edit", user)){ + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage())); + return retmap; + } + + RecordSet rs = new RecordSet(); + DepartmentComInfo DepartmentComInfo = new DepartmentComInfo(); + OrganisationCom OrganisationCom = new OrganisationCom(); + HrmServiceManager HrmServiceManager = new HrmServiceManager(); + + String deptorsubname = ""; + String sqlname = ""; + + String supdepid = ""; + String subcompanyid1 = ""; + sqlname = "select departmentname, supdepid, subcompanyid1 from hrmdepartment where id = "+id; + rs.executeSql(sqlname); + if(rs.next()) { + deptorsubname = rs.getString("departmentname"); + supdepid = Util.null2String(rs.getString("supdepid")); + subcompanyid1 = Util.null2String(rs.getString("subcompanyid1")); + } + + String sqlstr = "select id from hrmresource where status in (0,1,2,3)" + + " and EXISTS (select 1 from hrmdepartment b where hrmresource.departmentid=b.id and b.id = " + + id +")"; + rs.executeSql(sqlstr); + if (rs.next()) { + //部门下有在职的人员 + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(82293, user.getLanguage())); + return retmap; + } + + sqlstr = " select id from hrmdepartment where (canceled = '0' or canceled is null) and id in (select id from hrmdepartment where supdepid = " + + id + ")"; + rs.executeSql(sqlstr); + if (rs.next()) { + //部门存在下级部门 + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(82294, user.getLanguage())); + return retmap; + } + // 同步 删除 中控考勤机 部门数据 + KqUtil.synDeleteDeptInfo(""+id); + + rs.executeSql("update hrmdepartment set canceled = '1', "+ DbFunctionUtil.getUpdateSetSql(rs.getDBType(),user.getUID())+" where id ="+ id); + DepartmentComInfo.removeCompanyCache(); + + OrganisationCom.deleteDepartment(id);//部门封存时同步到RTX + + //部门封存时同步到邮件系统 + if("0".equals(supdepid)) { + CoreMailAPI.synOrg(""+id, deptorsubname, "parent_org_unit_id=com_"+subcompanyid1+"&org_unit_name="+deptorsubname, "1"); + //testapi.synOrg(""+deptorsupid, deptorsubname, "com_"+subcompanyid1, "1"); + } else { + CoreMailAPI.synOrg(""+id, deptorsubname, "parent_org_unit_id="+supdepid+"&org_unit_name="+deptorsubname, "1"); + //testapi.synOrg(""+deptorsupid, deptorsubname, ""+supdepid, "1"); + } + + //OA与第三方接口单条数据同步方法开始 + HrmServiceManager.SynInstantDepartment(""+id,"3"); + //OA与第三方接口单条数据同步方法结束 + + HrmFaceCheckManager.sync(id+"",HrmFaceCheckManager.getOptUpdate(),this.getClass().getName(),HrmFaceCheckManager.getOaDepartment()); + //同步部门数据到矩阵 + MatrixUtil.updateDepartmentData(""+id); + + } catch (Exception e) { + writeLog(e); + throw e; + } + return retmap; + } + + @Override + public BizLogContext getLogContext() { + return null; + } + + @Override + public List getLogContexts() { + return logger.getBizLogContexts(); + } +} diff --git a/领悦二开new/src/com/engine/hrm/cmd/organization/CancelSubCompanyCmd.java b/领悦二开new/src/com/engine/hrm/cmd/organization/CancelSubCompanyCmd.java new file mode 100644 index 0000000..9ada142 --- /dev/null +++ b/领悦二开new/src/com/engine/hrm/cmd/organization/CancelSubCompanyCmd.java @@ -0,0 +1,165 @@ +package com.engine.hrm.cmd.organization; + +import com.engine.common.biz.AbstractCommonCommand; +import com.engine.common.biz.SimpleBizLogger; +import com.engine.common.constant.BizLogOperateAuditType; +import com.engine.common.constant.BizLogSmallType4Hrm; +import com.engine.common.constant.BizLogType; +import com.engine.common.entity.BizLogContext; +import com.engine.core.interceptor.CommandContext; +import com.engine.hrm.util.face.HrmFaceCheckManager; +import com.lingyue.util.KqUtil; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; +import weaver.hrm.common.DbFunctionUtil; +import weaver.hrm.company.SubCompanyComInfo; +import weaver.interfaces.email.CoreMailAPI; +import weaver.interfaces.hrm.HrmServiceManager; +import weaver.matrix.MatrixUtil; +import weaver.rtx.OrganisationCom; +import weaver.systeminfo.SystemEnv; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class CancelSubCompanyCmd extends AbstractCommonCommand>{ + + private SimpleBizLogger logger; + + public CancelSubCompanyCmd(Map params, User user) { + this.user = user; + this.params = params; + + this.logger = new SimpleBizLogger(); + String id = Util.null2String(params.get("id")); + BizLogContext bizLogContext = new BizLogContext(); + bizLogContext.setLogType(BizLogType.HRM_ENGINE);//模块类型 + bizLogContext.setBelongType(BizLogSmallType4Hrm.HRM_ENGINE_ORGANIZATION); + bizLogContext.setLogSmallType(BizLogSmallType4Hrm.HRM_ENGINE_ORGANIZATION_SUBCOMPANY);//当前小类型 + bizLogContext.setOperateAuditType(BizLogOperateAuditType.WARNING);//警告 + bizLogContext.setParams(params);//当前request请求参数 + logger.setUser(user);//当前操作人 + String mainSql = "select * from HrmSubCompany where id in("+id+")"; + logger.setMainSql(mainSql,"id");//主表sql + logger.setMainPrimarykey("id");//主日志表唯一key + logger.setMainTargetNameColumn("subcompanyname");//当前targetName对应的列(对应日志中的对象名) + logger.before(bizLogContext); + } + + @Override + public Map execute(CommandContext commandContext) { + Map retmap = new HashMap(); + try { + if(!HrmUserVarify.checkUserRight("HrmSubCompanyEdit:Edit", user)){ + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage())); + return retmap; + } + + String ids = Util.null2String((String)params.get("id")); + + String[] arrIds = Util.splitString(ids, ","); + if(arrIds.length>1){ + for(int i=0; i cancel(int id) throws Exception { + Map retmap = new HashMap(); + try { + + RecordSet rs = new RecordSet(); + SubCompanyComInfo SubCompanyComInfo = new SubCompanyComInfo(); + OrganisationCom OrganisationCom = new OrganisationCom(); + HrmServiceManager HrmServiceManager = new HrmServiceManager(); + + int supsubcomid = 0; + String deptorsubname = ""; + String sqlname = ""; + sqlname = "select subcompanyname, supsubcomid from HrmSubCompany where id = "+id; + rs.executeSql(sqlname); + if(rs.next()) { + deptorsubname = rs.getString("subcompanyname"); + supsubcomid = Util.getIntValue(rs.getString("supsubcomid"), 0); + } + + String sqlstr = "select id from hrmdepartment where (canceled = '0' or canceled is null) " + + " and exists (select 1 from hrmsubcompany b where hrmdepartment.subcompanyid1 = b.id and b.id ="+ id+ ")"; + rs.executeSql(sqlstr); + if (rs.next()) { + //分部下存在部门 + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(82296, user.getLanguage())); + return retmap; + } + + sqlstr = " select id from hrmsubcompany where (canceled = '0' or canceled is null) and id in (select id from hrmsubcompany where supsubcomid ="+ id + ")"; + rs.executeSql(sqlstr); + if (rs.next()) { + //分部下存在下级分部 + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(82295, user.getLanguage())); + return retmap; + } + // 同步 删除 中控考勤机 部门数据 + KqUtil.synDeleteSubComInfo(""+id); + + rs.executeSql("update HrmSubCompany set canceled = '1' , "+ DbFunctionUtil.getUpdateSetSql(rs.getDBType(),user.getUID())+" where id ="+ id); + SubCompanyComInfo.removeCompanyCache(); + + OrganisationCom.deleteSubCompany(id);//分部封存时同步到RTX + + //分部封存时同步到CoreMail邮件系统 + if(supsubcomid == 0) { + CoreMailAPI.synOrg("com_"+id, deptorsubname, "org_unit_name="+deptorsubname, "1"); + //testapi.synOrg("com_"+deptorsupid, deptorsubname, "", "1"); + } else { + CoreMailAPI.synOrg("com_"+id, deptorsubname, "parent_org_unit_id=com_"+supsubcomid+"&org_unit_name="+deptorsubname, "1"); + //testapi.synOrg("com_"+deptorsupid, deptorsubname, "com_"+supsubcomid, "1"); + } + + //OA与第三方接口单条数据同步方法开始 + HrmServiceManager.SynInstantSubCompany(""+id,"3"); + //OA与第三方接口单条数据同步方法结束 + HrmFaceCheckManager.sync(id+"",HrmFaceCheckManager.getOptUpdate(),"HRM_CancelSubCompanyCmd",HrmFaceCheckManager.getOaSubcompany()); + + //同步分部数据到矩阵 + MatrixUtil.updateSubcompayData(""+id); + + } catch (Exception e) { + writeLog(e); + throw e; + } + return retmap; + } + + @Override + public BizLogContext getLogContext() { + return null; + } + + @Override + public List getLogContexts() { + return logger.getBizLogContexts(); + } +} diff --git a/领悦二开new/src/com/engine/hrm/cmd/organization/DelDepartmentCmd.java b/领悦二开new/src/com/engine/hrm/cmd/organization/DelDepartmentCmd.java new file mode 100644 index 0000000..a47227e --- /dev/null +++ b/领悦二开new/src/com/engine/hrm/cmd/organization/DelDepartmentCmd.java @@ -0,0 +1,182 @@ +package com.engine.hrm.cmd.organization; + +import com.engine.common.biz.AbstractCommonCommand; +import com.engine.common.biz.SimpleBizLogger; +import com.engine.common.constant.BizLogOperateAuditType; +import com.engine.common.constant.BizLogSmallType4Hrm; +import com.engine.common.constant.BizLogType; +import com.engine.common.entity.BizLogContext; +import com.engine.core.interceptor.CommandContext; +import com.engine.hrm.util.face.HrmFaceCheckManager; +import com.lingyue.util.KqUtil; +import weaver.conn.RecordSet; +import org.apache.commons.lang3.StringUtils; +import weaver.general.Util; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; +import weaver.hrm.company.DepartmentComInfo; +import weaver.integration.framework.data.record.SimpleRecordData; +import weaver.interfaces.email.CoreMailAPI; +import weaver.interfaces.hrm.HrmServiceManager; +import weaver.matrix.MatrixUtil; +import weaver.rtx.OrganisationCom; +import weaver.systeminfo.SystemEnv; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class DelDepartmentCmd extends AbstractCommonCommand>{ + + private SimpleBizLogger logger; + + public DelDepartmentCmd(Map params, User user) { + this.user = user; + this.params = params; + + this.logger = new SimpleBizLogger(); + String id = Util.null2String(params.get("id")); + BizLogContext bizLogContext = new BizLogContext(); + bizLogContext.setLogType(BizLogType.HRM_ENGINE);//模块类型 + bizLogContext.setBelongType(BizLogSmallType4Hrm.HRM_ENGINE_ORGANIZATION); + bizLogContext.setLogSmallType(BizLogSmallType4Hrm.HRM_ENGINE_ORGANIZATION_DPEARTMENT);//当前小类型 + bizLogContext.setOperateAuditType(BizLogOperateAuditType.WARNING);//警告 + bizLogContext.setParams(params);//当前request请求参数 + logger.setUser(user);//当前操作人 + String mainSql = "select * from Hrmdepartment where id in("+id+")"; + logger.setMainSql(mainSql,"id");//主表sql + logger.setMainPrimarykey("id");//主日志表唯一key + logger.setMainTargetNameColumn("departmentname");//当前targetName对应的列(对应日志中的对象名) + logger.before(bizLogContext); + } + + @Override + public Map execute(CommandContext commandContext) { + Map retmap = new HashMap(); + try { + if(!HrmUserVarify.checkUserRight("HrmDepartmentEdit:Delete", user)){ + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage())); + return retmap; + } + + String ids = Util.null2String((String)params.get("id")); + + retmap = checkCanDelelte(ids) ; + if(!retmap.isEmpty()){ + return retmap; + } + + String[] arrIds = Util.splitString(ids, ","); + if(arrIds.length>1){ + for(int i=0; i checkCanDelelte(String id)throws Exception{ + if(StringUtils.isBlank(id)) throw new Exception("删除部门错误:id为空!") ; + Map retmap = new HashMap(); + RecordSet rs = new RecordSet(); + String sql = "select count(id) from HrmResource where departmentid in ("+id+")"; + rs.execute(sql) ; + rs.next(); + if(rs.getInt(1)>0){ + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(33594,user.getLanguage())); + return retmap; + } + return retmap; + + } + + private Map del(int id) throws Exception { + Map retmap = new HashMap(); + try { + String sql = ""; + RecordSet rs = new RecordSet();; + + DepartmentComInfo DepartmentComInfo = new DepartmentComInfo(); + OrganisationCom OrganisationCom = new OrganisationCom(); + HrmServiceManager HrmServiceManager = new HrmServiceManager(); + + String departmentname = ""; + int supdepid = 0; + String subcompanyid1 = ""; + + rs.executeSql("select departmentname, supdepid, subcompanyid1 from HrmDepartment where id = " + id); + if(rs.next()) { + departmentname = Util.null2String(rs.getString("departmentname")); + supdepid = Util.getIntValue(rs.getString("supdepid"), 0); + subcompanyid1 = Util.null2String(rs.getString("subcompanyid1")); + } + + String para = ""+id; + + // 同步 删除 中控考勤机 部门数据 + KqUtil.synDeleteDeptInfo(""+id); + + SimpleRecordData recordData = HrmFaceCheckManager.syncQuery(id+"",HrmFaceCheckManager.getOptDelete(),HrmFaceCheckManager.getOaDepartment()); + rs.executeProc("HrmDepartment_Delete",para); + rs.executeUpdate("delete from HrmDepartmentDefined WHERE deptid= " +id); + //add by wjy + //同步RTX端部门信息 + OrganisationCom.deleteDepartment(id); + + //同步到CoreMail邮件系统开始 + if(supdepid == 0) { + CoreMailAPI.synOrg(""+id, departmentname, "parent_org_unit_id=com_"+subcompanyid1+"&org_unit_name="+departmentname, "1"); + //testapi.synOrg(""+id, departmentname, "com_"+subcompanyid1, "1"); + } else { + CoreMailAPI.synOrg(""+id, departmentname, "parent_org_unit_id="+supdepid+"&org_unit_name="+departmentname, "1"); + //testapi.synOrg(""+id, departmentname, ""+supdepid, "1"); + } + //同步到CoreMail邮件系统结束 + + //OA与第三方接口单条数据同步方法开始 + HrmServiceManager.SynInstantDepartment(""+id,"3"); + //OA与第三方接口单条数据同步方法结束 + + HrmFaceCheckManager.sync(id+"",HrmFaceCheckManager.getOptDelete(),this.getClass().getName(),HrmFaceCheckManager.getOaDepartment(),recordData); + + DepartmentComInfo.removeCompanyCache(); + + rs.executeSql("update orgchartstate set needupdate=1"); + + //同步部门数据到矩阵 + MatrixUtil.updateDepartmentData(""+id); + + } catch (Exception e) { + writeLog(e); + throw e; + } + return retmap; + } + + @Override + public BizLogContext getLogContext() { + return null; + } + + @Override + public List getLogContexts() { + return logger.getBizLogContexts(); + } + +} diff --git a/领悦二开new/src/com/engine/hrm/cmd/organization/DelSubCompanyCmd.java b/领悦二开new/src/com/engine/hrm/cmd/organization/DelSubCompanyCmd.java new file mode 100644 index 0000000..53c456f --- /dev/null +++ b/领悦二开new/src/com/engine/hrm/cmd/organization/DelSubCompanyCmd.java @@ -0,0 +1,205 @@ +package com.engine.hrm.cmd.organization; + +import com.engine.common.biz.AbstractCommonCommand; +import com.engine.common.biz.SimpleBizLogger; +import com.engine.common.constant.BizLogOperateAuditType; +import com.engine.common.constant.BizLogSmallType4Hrm; +import com.engine.common.constant.BizLogType; +import com.engine.common.entity.BizLogContext; +import com.engine.core.interceptor.CommandContext; +import com.engine.hrm.util.face.HrmFaceCheckManager; +import com.lingyue.util.KqUtil; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; +import weaver.hrm.company.SubCompanyComInfo; +import weaver.integration.framework.data.record.SimpleRecordData; +import weaver.interfaces.email.CoreMailAPI; +import weaver.interfaces.hrm.HrmServiceManager; +import weaver.matrix.MatrixUtil; +import weaver.rtx.OrganisationCom; +import weaver.systeminfo.SystemEnv; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class DelSubCompanyCmd extends AbstractCommonCommand>{ + private SimpleBizLogger logger; + + public DelSubCompanyCmd(Map params, User user) { + this.user = user; + this.params = params; + this.logger = new SimpleBizLogger(); + + String id = Util.null2String(params.get("id")); + BizLogContext bizLogContext = new BizLogContext(); + bizLogContext.setLogType(BizLogType.HRM_ENGINE);//模块类型 + bizLogContext.setBelongType(BizLogSmallType4Hrm.HRM_ENGINE_ORGANIZATION); + bizLogContext.setLogSmallType(BizLogSmallType4Hrm.HRM_ENGINE_ORGANIZATION_SUBCOMPANY);//当前小类型 + bizLogContext.setOperateAuditType(BizLogOperateAuditType.WARNING);//警告 + bizLogContext.setParams(params);//当前request请求参数 + logger.setUser(user);//当前操作人 + String mainSql = "select * from HrmSubCompany where id in("+id+")"; + logger.setMainSql(mainSql,"id");//主表sql + logger.setMainPrimarykey("id");//主日志表唯一key + logger.setMainTargetNameColumn("subcompanyname");//当前targetName对应的列(对应日志中的对象名) + logger.before(bizLogContext); + } + + @Override + public Map execute(CommandContext commandContext) { + Map retmap = new HashMap(); + try { + if(!HrmUserVarify.checkUserRight("HrmSubCompanyEdit:Delete", user)){ + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage())); + return retmap; + } + + String ids = Util.null2String((String)params.get("id")); + + String[] arrIds = Util.splitString(ids, ","); + if(arrIds.length>1){ + for(int i=0; i del(int id) throws Exception { + Map retmap = new HashMap(); + try { + String sql = ""; + RecordSet rs = new RecordSet();; + + SubCompanyComInfo SubCompanyComInfo = new SubCompanyComInfo(); + OrganisationCom OrganisationCom = new OrganisationCom(); + HrmServiceManager HrmServiceManager = new HrmServiceManager(); + + String subcompanyname = ""; + int supsubcomid = 0; + + rs.executeSql("select subcompanyname, supsubcomid from HrmSubCompany where id = " + id); + if(rs.next()) { + subcompanyname = Util.null2String(rs.getString("subcompanyname")); + supsubcomid = Util.getIntValue(rs.getString("supsubcomid"), 0); + } + String para = ""+id; + + SimpleRecordData recordData = HrmFaceCheckManager.syncQuery(id+"",HrmFaceCheckManager.getOptDelete(),HrmFaceCheckManager.getOaSubcompany()) ; + + // 同步 删除 中控考勤机 部门数据 + KqUtil.synDeleteSubComInfo(""+id); + + rs.executeProc("HrmSubCompany_Delete",para); + + rs.executeUpdate("delete from HrmSubCompanyDefined WHERE SUBCOMID= " +id); + + rs.executeUpdate("delete from mainmenuconfig where resourcetype=2 and resourceid="+id); + rs.executeUpdate("delete from leftmenuconfig where resourcetype=2 and resourceid="+id); + + //更新分级管理数据至默认分部 + rs.executeSql("select detachable,dftsubcomid from SystemSet"); + String detachable = ""; + String dftsubcomid = ""; + if(rs.next()){ + detachable = Util.null2String(rs.getString("detachable")); + dftsubcomid = Util.null2String(rs.getString("dftsubcomid")); + } + if(detachable.equals("1")&&!dftsubcomid.equals("")&&!dftsubcomid.equals("0")){ + //RecordSet.executeProc("SystemSet_DftSCUpdate",""+dftsubcomid); + RecordSet rsupdate = new RecordSet(); + String updatesql = " update HrmRoles set subcompanyid="+dftsubcomid+" "+ + " where subcompanyid is null or subcompanyid=0 or subcompanyid=-1 " + + " or subcompanyid not in (select id from hrmsubcompany) "; + rsupdate.executeSql(updatesql); + + updatesql =" update HrmContractTemplet set subcompanyid="+dftsubcomid+" "+ + " where subcompanyid is null or subcompanyid=0 or subcompanyid=-1 " + + " or subcompanyid not in (select id from hrmsubcompany) "; + rsupdate.executeSql(updatesql); + + updatesql =" update HrmContractType set subcompanyid="+dftsubcomid+" "+ + " where subcompanyid is null or subcompanyid=0 or subcompanyid=-1 " + + " or subcompanyid not in (select id from hrmsubcompany) "; + rsupdate.executeSql(updatesql); + + updatesql =" update HrmCareerApply set subCompanyId="+dftsubcomid+" "+ + " where subCompanyId is null or subCompanyId=0 or subCompanyId=-1 " + + " or subCompanyId not in (select id from hrmsubcompany) "; + rsupdate.executeSql(updatesql); + } + + //add by wjy + //同步RTX端的分部信息. + rs.executeSql("select count(id) from HrmDepartment where (canceled = '0' or canceled is null) and subcompanyid1 ="+id); + if(rs.next()){ + if(rs.getInt(1)>0){ + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(81683,user.getLanguage())); + return retmap; + }else{ + OrganisationCom.deleteSubCompany(id); + + //同步到CoreMail邮件系统开始 + if(supsubcomid > 0) { + CoreMailAPI.synOrg("com_"+id, subcompanyname, "parent_org_unit_id=com_"+supsubcomid+"&org_unit_name="+subcompanyname, "1"); + //testapi.synOrg("com_"+id, subcompanyname, "com_"+supsubcomid, "1"); + } else { + CoreMailAPI.synOrg("com_"+id, subcompanyname, "org_unit_name="+subcompanyname, "1"); + //testapi.synOrg("com_"+id, subcompanyname, "", "1"); + } + //同步到CoreMail邮件系统结束 + + //OA与第三方接口单条数据同步方法开始 + HrmServiceManager.SynInstantSubCompany(""+id,"3"); + //OA与第三方接口单条数据同步方法结束 + HrmFaceCheckManager.sync(id+"",HrmFaceCheckManager.getOptDelete(),"HRM_DelSubCompanyCmd",HrmFaceCheckManager.getOaSubcompany(),recordData); + } + } + + SubCompanyComInfo.removeCompanyCache(); + + sql="update hrmsubcompany set supsubcomid=0 where supsubcomid="+id; + rs.executeSql(sql); + SubCompanyComInfo.removeCompanyCache(); + + rs.executeSql("update orgchartstate set needupdate=1"); + + //同步分部数据到矩阵 + MatrixUtil.updateSubcompayData(""+id); + + } catch (Exception e) { + writeLog(e); + throw e; + } + return retmap; + } + + @Override + public BizLogContext getLogContext() { + return null; + } + + @Override + public List getLogContexts() { + return logger.getBizLogContexts(); + } +} diff --git a/领悦二开new/src/com/engine/hrm/cmd/organization/EditDepartmentCmd.java b/领悦二开new/src/com/engine/hrm/cmd/organization/EditDepartmentCmd.java new file mode 100644 index 0000000..e3e17b1 --- /dev/null +++ b/领悦二开new/src/com/engine/hrm/cmd/organization/EditDepartmentCmd.java @@ -0,0 +1,282 @@ +package com.engine.hrm.cmd.organization; + +import com.api.hrm.util.ServiceUtil; +import com.engine.common.biz.AbstractCommonCommand; +import com.engine.common.biz.SimpleBizLogger; +import com.engine.common.constant.BizLogOperateAuditType; +import com.engine.common.constant.BizLogSmallType4Hrm; +import com.engine.common.constant.BizLogType; +import com.engine.common.entity.BizLogContext; +import com.engine.core.interceptor.CommandContext; +import com.engine.hrm.entity.RuleCodeType; +import com.engine.hrm.util.CodeRuleManager; +import com.engine.hrm.util.HrmOrganizationUtil; +import com.lingyue.util.KqUtil; +import org.apache.commons.lang3.StringUtils; +import weaver.conn.RecordSet; +import weaver.general.Util; +import com.engine.hrm.util.face.HrmFaceCheckManager; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; +import weaver.hrm.common.DbFunctionUtil; +import weaver.hrm.company.DepartmentComInfo; +import weaver.hrm.definedfield.HrmDeptFieldManagerE9; +import weaver.hrm.definedfield.HrmFieldComInfo; +import weaver.hrm.resource.ResourceComInfo; +import weaver.interfaces.email.CoreMailAPI; +import weaver.interfaces.hrm.HrmServiceManager; +import weaver.matrix.MatrixUtil; +import weaver.rtx.OrganisationCom; +import weaver.rtx.OrganisationComRunnable; +import weaver.systeminfo.SystemEnv; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class EditDepartmentCmd extends AbstractCommonCommand> { + + private SimpleBizLogger logger; + + public EditDepartmentCmd(Map params, User user) { + this.user = user; + this.params = params; + + this.logger = new SimpleBizLogger(); + String id = Util.null2String(params.get("id")); + BizLogContext bizLogContext = new BizLogContext(); + bizLogContext.setLogType(BizLogType.HRM_ENGINE);//模块类型 + bizLogContext.setBelongType(BizLogSmallType4Hrm.HRM_ENGINE_ORGANIZATION); + bizLogContext.setLogSmallType(BizLogSmallType4Hrm.HRM_ENGINE_ORGANIZATION_DPEARTMENT);//当前小类型 + bizLogContext.setOperateAuditType(BizLogOperateAuditType.WARNING);//警告 + bizLogContext.setParams(params);//当前request请求参数 + logger.setUser(user);//当前操作人 + String mainSql = "select a.* from HrmDepartment a left join HrmDepartmentdefined b on a.id=b.deptid where a.id in(" + id + ") "; + String tableColumns = new ServiceUtil().getTableColumns("select * from HrmDepartmentdefined", "b", "id"); + if (!tableColumns.equals("")) { + mainSql = "select a.*," + tableColumns + " from HrmDepartment a left join HrmDepartmentdefined b on a.id=b.deptid where a.id in(" + id + ")"; + } + logger.setMainSql(mainSql,"id");//主表sql + logger.setMainPrimarykey("id");//主日志表唯一key + logger.setMainTargetNameColumn("departmentname");//当前targetName对应的列(对应日志中的对象名) + logger.before(bizLogContext); + } + + @Override + public Map execute(CommandContext commandContext) { + Map retmap = new HashMap(); + try { + String sql = ""; + RecordSet rs = null; + RecordSet rs1 = null; + + if (!HrmUserVarify.checkUserRight("HrmDepartmentEdit:Edit", user)) { + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage())); + return retmap; + } + + DepartmentComInfo DepartmentComInfo = new DepartmentComInfo(); + ResourceComInfo ResourceComInfo = new ResourceComInfo(); + //OrganisationCom OrganisationCom = new OrganisationCom(); + HrmServiceManager HrmServiceManager = new HrmServiceManager(); + + int id = Util.getIntValue((String) params.get("id"), 0); + String departmentmark = Util.fromScreen((String) params.get("departmentmark"), user.getLanguage()); + String departmentname = Util.fromScreen((String) params.get("departmentname"), user.getLanguage()); + String subcompanyid1 = Util.fromScreen((String) params.get("subcompanyid1"), user.getLanguage()); + int supdepid = Util.getIntValue((String) params.get("supdepid"), 0); + String showorder = Util.fromScreen(Util.null2s((String) params.get("showorder"), "0"), user.getLanguage()); + + if (Util.getIntValue(subcompanyid1, 0) <= 0) { + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(382658,user.getLanguage())); + return retmap; + } + + int supdepartmentid = supdepid; + if (supdepid > 0) { + if(supdepid==id){ + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(382650,user.getLanguage())); + return retmap; + }else{ + Map supMap = new HashMap(); + supMap.put(""+id, "1"); + supMap.put(""+supdepid, "1"); + int supdepidtemp = Util.getIntValue(DepartmentComInfo.getDepartmentsupdepid(""+supdepid), 0); + while(supdepidtemp>0){ + if(supMap.get(""+supdepidtemp)==null){ + supMap.put(""+supdepidtemp, "1"); + supdepidtemp = Util.getIntValue(DepartmentComInfo.getDepartmentsupdepid(""+supdepidtemp), 0); + }else{ + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(382650,user.getLanguage())); + return retmap; + } + } + } + if (HrmOrganizationUtil.ifDeptLevelEquals10(supdepid)) { + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(382650,user.getLanguage())); + return retmap; + } + } + + String allsupdepid = "0"; + String departmentcode = Util.fromScreen((String) params.get("departmentcode"), user.getLanguage()); + + // 如果编码为空 自动生成编码 +// departmentcode = CodeRuleManager.getCodeRuleManager().generateRuleCode(RuleCodeType.DEPARTMENT, subcompanyid1, departmentcode); + if (StringUtils.isNotEmpty(departmentcode)) { + CodeRuleManager.getCodeRuleManager().checkReservedIfDel(RuleCodeType.DEPARTMENT.getValue(), departmentcode); + } + + int coadjutant = Util.getIntValue((String) params.get("coadjutant"), 0); + + HrmFieldComInfo hrmFieldComInfo = new HrmFieldComInfo(); + sql = "select * from HrmDepartment where id=" + id; + rs = new RecordSet(); + rs.executeSql(sql); + while (rs.next()) { + if (!hrmFieldComInfo.getIsused("73").equals("1")) + departmentmark = rs.getString("departmentmark"); + if (!hrmFieldComInfo.getIsused("74").equals("1")) + departmentname = rs.getString("departmentname"); + if (!hrmFieldComInfo.getIsused("75").equals("1")) + subcompanyid1 = rs.getString("subcompanyid1"); + if (!hrmFieldComInfo.getIsused("76").equals("1")) + supdepid = rs.getInt("supdepid"); + if (!hrmFieldComInfo.getIsused("77").equals("1")) + coadjutant = rs.getInt("coadjutant"); + if (!hrmFieldComInfo.getIsused("78").equals("1")) + showorder = rs.getString("showorder"); + if (!hrmFieldComInfo.getIsused("80").equals("1")) + departmentcode = rs.getString("departmentcode"); + } + if(supdepid > 0){ + supdepartmentid = supdepid; + } + + if (!"".equals(departmentcode)) { + sql = "select id from hrmdepartment where departmentcode = '" + departmentcode + "' and id !=" + id; + rs = new RecordSet(); + rs.executeSql(sql); + if (rs.next()) { + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(382653,user.getLanguage())); + return retmap; + } + } + + char separator = Util.getSeparator(); + if (supdepartmentid > 0) {//当选择了上级部门的时候,需要更改当前部门的上级分部 + subcompanyid1 = DepartmentComInfo.getSubcompanyid1(supdepartmentid + ""); + } + String para = "" + id + separator + departmentmark + separator + departmentname + separator + supdepartmentid + separator + allsupdepid + separator + subcompanyid1 + separator + showorder + separator + coadjutant; + rs = new RecordSet(); + rs.executeProc("HrmDepartment_Update", para); + + int flag = rs.getFlag(); + if (flag == 2) { + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(382655,user.getLanguage())); + return retmap; + } + if (flag == 3) { + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(382657,user.getLanguage())); + return retmap; + } + + weaver.hrm.company.OrgOperationUtil OrgOperationUtil = new weaver.hrm.company.OrgOperationUtil(); + OrgOperationUtil.updateDepartmentLevel("" + id, "0"); + + HrmDeptFieldManagerE9 hrmDeptFieldManager = new HrmDeptFieldManagerE9(5); + hrmDeptFieldManager.editCustomData(params,id); + + sql = "update hrmdepartment set departmentcode = '" + departmentcode + "' "; + sql += ","+ DbFunctionUtil.getUpdateSetSql(rs.getDBType(),user.getUID()) ; + sql += " where id = " + id; + rs = new RecordSet(); + rs.executeSql(sql); + + + ArrayList departmentlist = new ArrayList(); + departmentlist = DepartmentComInfo.getAllChildDeptByDepId(departmentlist, id + ""); + departmentlist.add(id + ""); + + for (int i = 0; i < departmentlist.size(); i++) { + String listdepartmenttemp = (String) departmentlist.get(i); + rs = new RecordSet(); + rs.execute("update HrmDepartment set subcompanyid1=" + subcompanyid1 + " where id=" + listdepartmenttemp); + + //TD16048改为逐条修改 + rs = new RecordSet(); + rs.execute("select id, subcompanyid1,managerid,seclevel,managerstr from hrmresource where departmentid=" + listdepartmenttemp); + while (rs.next()) { + int resourceid_tmp = Util.getIntValue(rs.getString(1), 0); + int oldsubcompanyid1 = Util.getIntValue(rs.getString(2), 0); + int oldmanagerid = Util.getIntValue(rs.getString(3), 0); + int seclevel = Util.getIntValue(rs.getString(4), 0); + String oldmanagerstr = Util.null2String(rs.getString(5)); + rs1 = new RecordSet(); + rs1.execute("update hrmresource set subcompanyid1=" + subcompanyid1 + " where id=" + resourceid_tmp); + para = "" + resourceid_tmp + separator + listdepartmenttemp + separator + subcompanyid1 + separator + oldmanagerid + separator + seclevel + separator + oldmanagerstr + separator + listdepartmenttemp + separator + oldsubcompanyid1 + separator + oldmanagerid + separator + seclevel + separator + oldmanagerstr + separator + "1"; + rs1 = new RecordSet(); + rs1.executeProc("HrmResourceShare", para); + } + //add by wjy + //同步RTX端部门信息 + //OrganisationCom.editDepartment(Util.getIntValue(listdepartmenttemp));//执行速度过慢,改成另起现成执行 + new Thread(new OrganisationComRunnable("department", "edit", String.valueOf(listdepartmenttemp))).start(); + } + + DepartmentComInfo.removeCompanyCache(); + ResourceComInfo.removeResourceCache(); + + rs = new RecordSet(); + rs.executeSql("update orgchartstate set needupdate=1"); + + //同步到CoreMail邮件系统开始 + if (supdepid == 0) { + CoreMailAPI.synOrg("" + id, departmentname, "parent_org_unit_id=com_" + subcompanyid1 + "&org_unit_name=" + departmentname, "0"); + //testapi.synOrg(""+id, departmentname, "com_"+subcompanyid1, "0"); + } else { + CoreMailAPI.synOrg("" + id, departmentname, "parent_org_unit_id=" + supdepid + "&org_unit_name=" + departmentname, "0"); + //testapi.synOrg(""+id, departmentname, ""+supdepid, "0"); + } + //同步到CoreMail邮件系统结束 + + //OA与第三方接口单条数据同步方法开始 + HrmServiceManager.SynInstantDepartment("" + id, "2"); + //OA与第三方接口单条数据同步方法结束 + HrmFaceCheckManager.sync(id+"",HrmFaceCheckManager.getOptUpdate(),this.getClass().getName(),HrmFaceCheckManager.getOaDepartment()); + + //同步部门数据到矩阵 + MatrixUtil.updateDepartmentData("" + id); + + // 同步部门数据到中控考勤机 + KqUtil.synAddOrUpdateDeptInfo(""+id); + + retmap.put("status", "1"); + retmap.put("message", SystemEnv.getHtmlLabelName(18758, user.getLanguage())); + } catch (Exception e) { + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(382661,user.getLanguage())); + writeLog(e); + } + return retmap; + } + + @Override + public BizLogContext getLogContext() { + return null; + } + + @Override + public List getLogContexts() { + return logger.getBizLogContexts(); + } +} diff --git a/领悦二开new/src/com/engine/hrm/cmd/organization/EditSubCompanyCmd.java b/领悦二开new/src/com/engine/hrm/cmd/organization/EditSubCompanyCmd.java new file mode 100644 index 0000000..c40fa09 --- /dev/null +++ b/领悦二开new/src/com/engine/hrm/cmd/organization/EditSubCompanyCmd.java @@ -0,0 +1,223 @@ +package com.engine.hrm.cmd.organization; + +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.api.hrm.util.ServiceUtil; +import com.engine.common.biz.SimpleBizLogger; +import com.engine.common.constant.*; +import com.engine.hrm.entity.RuleCodeType; +import com.engine.hrm.util.CodeRuleManager; +import com.engine.hrm.util.face.HrmFaceCheckManager; +import com.lingyue.util.KqUtil; +import org.apache.commons.lang3.StringUtils; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; +import weaver.hrm.common.DbFunctionUtil; +import weaver.hrm.company.OrgOperationUtil; +import weaver.hrm.company.SubCompanyComInfo; +import weaver.hrm.definedfield.HrmDeptFieldManagerE9; +import weaver.hrm.definedfield.HrmFieldComInfo; +import weaver.interfaces.email.CoreMailAPI; +import weaver.interfaces.hrm.HrmServiceManager; +import weaver.matrix.MatrixUtil; +import weaver.rtx.OrganisationCom; +import weaver.systeminfo.SystemEnv; +import com.engine.common.biz.AbstractCommonCommand; +import com.engine.common.entity.BizLogContext; +import com.engine.core.interceptor.CommandContext; +import com.engine.hrm.util.HrmOrganizationUtil; + +public class EditSubCompanyCmd extends AbstractCommonCommand>{ + + private SimpleBizLogger logger; + + public EditSubCompanyCmd(Map params, User user) { + this.user = user; + this.params = params; + this.logger = new SimpleBizLogger(); + + String id = Util.null2String(params.get("id")); + BizLogContext bizLogContext = new BizLogContext(); + bizLogContext.setLogType(BizLogType.HRM_ENGINE);//模块类型 + bizLogContext.setBelongType(BizLogSmallType4Hrm.HRM_ENGINE_ORGANIZATION); + bizLogContext.setLogSmallType(BizLogSmallType4Hrm.HRM_ENGINE_ORGANIZATION_SUBCOMPANY);//当前小类型 + bizLogContext.setOperateAuditType(BizLogOperateAuditType.WARNING);//警告 + bizLogContext.setParams(params);//当前request请求参数 + logger.setUser(user);//当前操作人 + String mainSql = "select a.* from HrmSubCompany a left join hrmsubcompanydefined b on a.id=b.subcomid where a.id in(" + id + ")"; + String tableColumns = new ServiceUtil().getTableColumns("select * from hrmsubcompanydefined", "b", "id"); + if (!tableColumns.equals("")) { + mainSql = "select a.*," + tableColumns + " from HrmSubCompany a left join hrmsubcompanydefined b on a.id=b.subcomid where a.id in(" + id + ")"; + } + logger.setMainSql(mainSql, "id");//主表sql + logger.setMainPrimarykey("id");//主日志表唯一key + logger.setMainTargetNameColumn("subcompanyname");//当前targetName对应的列(对应日志中的对象名) + logger.before(bizLogContext); + } + + @Override + public Map execute(CommandContext commandContext) { + Map retmap = new HashMap(); + try { + String sql = ""; + RecordSet rs = null; + + if(!HrmUserVarify.checkUserRight("HrmSubCompanyEdit:Edit", user)){ + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage())); + return retmap; + } + + SubCompanyComInfo SubCompanyComInfo = new SubCompanyComInfo(); + OrgOperationUtil OrgOperationUtil = new OrgOperationUtil(); + OrganisationCom OrganisationCom = new OrganisationCom(); + HrmServiceManager HrmServiceManager = new HrmServiceManager(); + + int companyid = 1; + int id = Util.getIntValue((String)params.get("id")); + int supsubcomid=Util.getIntValue((String)params.get("supsubcomid"),0); + String subcompanycode = Util.fromScreen((String)params.get("subcompanycode"),user.getLanguage()); + String subcompanyname = Util.fromScreen((String)params.get("subcompanyname"),user.getLanguage()); + String subcompanydesc = Util.fromScreen((String)params.get("subcompanydesc"),user.getLanguage()); + String url=Util.null2String((String)params.get("url")); + String showorder = Util.fromScreen(Util.null2s((String) params.get("showorder"), "0"), user.getLanguage()); + int limitUsers = Util.getIntValue(Util.fromScreen((String)params.get("limitUsers"),user.getLanguage()), 0); + limitUsers = limitUsers < 0 ? 0 : limitUsers; + + if(supsubcomid > 0){ + if(supsubcomid==id){ + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(382649,user.getLanguage())); + return retmap; + }else{ + Map supMap = new HashMap(); + supMap.put(""+id, "1"); + supMap.put(""+supsubcomid, "1"); + int supsubcomidtemp = Util.getIntValue(SubCompanyComInfo.getSupsubcomid(""+supsubcomid), 0); + while(supsubcomidtemp>0){ + if(supMap.get(""+supsubcomidtemp)==null){ + supMap.put(""+supsubcomidtemp, "1"); + supsubcomidtemp = Util.getIntValue(SubCompanyComInfo.getSupsubcomid(""+supsubcomidtemp), 0); + }else{ + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(382649,user.getLanguage())); + return retmap; + } + } + } + if(HrmOrganizationUtil.ifSubComLevelEquals10(supsubcomid)){ + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(382649,user.getLanguage())); + return retmap; + } + } + + // 如果编码为空 自动生成编码 +// subcompanycode = CodeRuleManager.getCodeRuleManager().generateRuleCode(RuleCodeType.SUBCOMPANY, subcompanycode); + if (StringUtils.isNotEmpty(subcompanycode)) { + CodeRuleManager.getCodeRuleManager().checkReservedIfDel(RuleCodeType.SUBCOMPANY.getValue(), subcompanycode); + } + + if(!"".equals(subcompanycode)){ + sql = "select id from HrmSubCompany where subcompanycode = '" + subcompanycode + "' and id !="+id; + rs = new RecordSet(); + rs.executeSql(sql); + if(rs.next()){ + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(382651,user.getLanguage())); + return retmap; + } + } + + char separator = Util.getSeparator() ; + HrmFieldComInfo hrmFieldComInfo = new HrmFieldComInfo(); + sql = "select * from HrmSubCompany where id="+id; + rs = new RecordSet(); + rs.executeSql(sql); + while(rs.next()){ + if(!hrmFieldComInfo.getIsused("67").equals("1"))subcompanyname = rs.getString("subcompanyname"); + if(!hrmFieldComInfo.getIsused("68").equals("1"))subcompanydesc = rs.getString("subcompanydesc"); + if(!hrmFieldComInfo.getIsused("69").equals("1"))supsubcomid = rs.getInt("supsubcomid"); + if(!hrmFieldComInfo.getIsused("70").equals("1"))url = rs.getString("url"); + if(!hrmFieldComInfo.getIsused("71").equals("1"))showorder = rs.getString("showorder"); + if(!hrmFieldComInfo.getIsused("72").equals("1"))subcompanycode = rs.getString("subcompanycode"); + if(!hrmFieldComInfo.getIsused("84").equals("1"))limitUsers = rs.getInt("limitUsers"); + } + + String para = ""+id + separator + subcompanyname + separator + subcompanydesc + separator + companyid+ separator + supsubcomid+ separator + url+ separator + showorder; + rs = new RecordSet(); + rs.executeProc("HrmSubCompany_Update",para); + int flag=rs.getFlag(); + + sql="update HrmSubCompany set subcompanycode = '" + subcompanycode + "'"; + if(user.getUID() == 1) sql += ", limitUsers = "+limitUsers; + sql += ","+ DbFunctionUtil.getUpdateSetSql(rs.getDBType(),user.getUID()) ; + sql+=" where id = "+id; + rs = new RecordSet(); + rs.executeSql(sql); + + HrmDeptFieldManagerE9 hrmDeptFieldManager = new HrmDeptFieldManagerE9(4); + hrmDeptFieldManager.editCustomData(params,id); + + if(flag==2){ + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(382654,user.getLanguage())); + return retmap; + } + if(flag==3){ + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(382656,user.getLanguage())); + return retmap; + } + + SubCompanyComInfo.removeCompanyCache(); + rs = new RecordSet(); + rs.executeSql("update orgchartstate set needupdate=1"); + OrgOperationUtil.updateSubcompanyLevel(""+id,"0"); + OrganisationCom.editSubCompany(id); + + //同步到CoreMail邮件系统开始 + if(supsubcomid > 0) { + CoreMailAPI.synOrg("com_"+id, subcompanyname, "parent_org_unit_id=com_"+supsubcomid+"&org_unit_name="+subcompanyname, "0"); + } else { + CoreMailAPI.synOrg("com_"+id, subcompanyname, "org_unit_name="+subcompanyname, "0"); + } + //同步到CoreMail邮件系统结束 + + //OA与第三方接口单条数据同步方法开始 + HrmServiceManager.SynInstantSubCompany(""+id,"2"); + //OA与第三方接口单条数据同步方法结束 + + HrmFaceCheckManager.sync(id+"",HrmFaceCheckManager.getOptUpdate(),"HRM_EditSubCompanyCmd",HrmFaceCheckManager.getOaSubcompany()); + + //同步分部数据到矩阵 + MatrixUtil.updateSubcompayData(""+id); + + // 同步分部数据到中控考勤机 + KqUtil.synAddOrUpdateSubComInfo(""+id); + + retmap.put("status", "1"); + retmap.put("message", SystemEnv.getHtmlLabelName(18758, user.getLanguage())); + } catch (Exception e) { + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(382661,user.getLanguage())); + writeLog(e); + } + return retmap; + } + + @Override + public BizLogContext getLogContext() { + return null; + } + + @Override + public List getLogContexts() { + return logger.getBizLogContexts(); + } +} diff --git a/领悦二开new/src/com/engine/kq/bean/KQBalanceOfLeave.java b/领悦二开new/src/com/engine/kq/bean/KQBalanceOfLeave.java new file mode 100644 index 0000000..42f0037 --- /dev/null +++ b/领悦二开new/src/com/engine/kq/bean/KQBalanceOfLeave.java @@ -0,0 +1,497 @@ +package com.engine.kq.bean; + +import com.engine.kq.biz.KQLeaveRulesComInfo; +import com.engine.kq.biz.KQLeaveRulesDetailComInfo; +import com.engine.kq.biz.KQSettingsComInfo; +import com.engine.kq.biz.KQUsageHistoryBiz; +import com.engine.kq.entity.KQUsageHistoryEntity; +import com.engine.kq.jucailin.util.KQDateUtil; +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.BaseBean; +import weaver.general.Util; +import weaver.hrm.resource.ResourceComInfo; +import weaver.systeminfo.SystemEnv; + +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.List; + +/** + * 假期余额--用于Excel导入 + */ +public class KQBalanceOfLeave extends BaseBean { + + /** + * 人员ID + */ + private String resourceId; + /** + * 编号 + */ + private String workcode ; + + /** + * 人员姓名 + */ + private String lastName; + /** + * 假期类型ID + */ + private String leaveRulesId; + /** + * 所属年份 + */ + private String belongYear; + /** + * (混合模式下为法定年假)假期余额基数 + */ + private double baseAmount = 0.00; + /** + * (混合模式下为法定年假)已使用的假期余额 + */ + private double usedAmount = 0.00; + /** + * (混合模式下为法定年假)额外的假期余额 + */ + private double extraAmount = 0.00; + /** + * (仅混合模式下使用,为福利年假)假期余额基数 + */ + private double baseAmount2 = 0.00; + /** + * (仅混合模式下使用,为福利年假)已使用的假期余额 + */ + private double usedAmount2 = 0.00; + /** + * (仅混合模式下使用,为福利年假)额外的假期余额 + */ + private double extraAmount2 = 0.00; + /** + * 用户语言 + */ + private int userlanguage = 7; + /** + * 导入Excel的操作者 + */ + private String operator; + + /** + * 失效日期 + */ + private String expirationDate; + + /** + * 验证模板数据有效性--用于Excel导入 + * + * @return + */ + public String valExcelData() { + + KQSettingsComInfo kqSettingsComInfo = new KQSettingsComInfo(); + String allow_negative = Util.null2String(kqSettingsComInfo.getMain_val("allow_negative"),"0"); + String errorInfo = ""; + if (!isExist(resourceId, lastName)) { + errorInfo = SystemEnv.getHtmlLabelName(389985, userlanguage);//ID和姓名不匹配 + return errorInfo; + } + + if (!"1".equals(allow_negative) && this.baseAmount < 0) { + errorInfo = "基数不能为负数"; + return errorInfo; + } + if (!"1".equals(allow_negative) && this.extraAmount < 0) { + errorInfo = "额外不能为负数"; + return errorInfo; + } + if (this.usedAmount < 0) { + errorInfo = ""+ SystemEnv.getHtmlLabelName(10005288,weaver.general.ThreadVarLanguage.getLang())+""; + return errorInfo; + } + double _totalAmount = this.baseAmount+this.extraAmount; + if (!"1".equals(allow_negative) && _totalAmount < this.usedAmount) { + errorInfo = ""+ SystemEnv.getHtmlLabelName(508124,weaver.general.ThreadVarLanguage.getLang())+""; + return errorInfo; + } + + if (!"1".equals(allow_negative) && this.baseAmount2 < 0) { + errorInfo = "福利基数不能为负数"; + return errorInfo; + } + if (!"1".equals(allow_negative) && this.extraAmount2 < 0) { + errorInfo = "福利额外不能为负数"; + return errorInfo; + } + if (this.usedAmount2 < 0) { + errorInfo = "福利已休不能大于总数"; + return errorInfo; + } + double _totalAmount2 = this.baseAmount2+this.extraAmount2; + if (!"1".equals(allow_negative) && _totalAmount2 < this.usedAmount2) { + errorInfo = ""+ SystemEnv.getHtmlLabelName(508124,weaver.general.ThreadVarLanguage.getLang())+""; + return errorInfo; + } + + return errorInfo; + } + + /** + * 保存数据 + * + * @return + */ + public String save() { + String resultStr = "false"; + try { + /*获取当前日期,当前时间*/ + Calendar today = Calendar.getInstance(); + String currentDate = Util.add0(today.get(Calendar.YEAR), 4) + "-" + + Util.add0(today.get(Calendar.MONTH) + 1, 2) + "-" + + Util.add0(today.get(Calendar.DAY_OF_MONTH), 2); + String currentTime = Util.add0(today.get(Calendar.HOUR_OF_DAY), 2) + ":" + + Util.add0(today.get(Calendar.MINUTE), 2) + ":" + + Util.add0(today.get(Calendar.SECOND), 2); + + /********************************************************************************************************/ + + /*获取人员的相关信息*/ + ResourceComInfo resourceComInfo = new ResourceComInfo(); + + /*分部ID*/ + String subcompanyId = resourceComInfo.getSubCompanyID(this.resourceId); + //部门ID + String departmentId = resourceComInfo.getDepartmentID(this.resourceId); + /*入职日期*/ + String companyStartDate = resourceComInfo.getCompanyStartDate(this.resourceId); + + /********************************************************************************************************/ + + /*获取假期类型的相关设置*/ + KQLeaveRulesComInfo rulesComInfo = new KQLeaveRulesComInfo(); + + /*请假最小单位*/ + String minimumUnit = rulesComInfo.getMinimumUnit(this.leaveRulesId); + + /********************************************************************************************************/ + + /*获取假期规则(一个假期类型下可能存在多个假期规则)的相关设置*/ + KQLeaveRulesDetailComInfo detailComInfo = new KQLeaveRulesDetailComInfo(); + + /*请假时长计算方式:1-按工作日计算请假时长、2-按自然日计算请假时长*/ + int distributionMode = Util.getIntValue(detailComInfo.getDistributionMode(this.leaveRulesId, subcompanyId, departmentId, this.resourceId), 1); + + /*有效期规则:0-永久有效、1-按自然年(1月1日-12月31日)、2-按入职日期起12个月、3-自定义次年失效日期*/ + int validityRule = validityRule = Util.getIntValue(detailComInfo.getValidityRule(this.leaveRulesId, subcompanyId, departmentId, this.resourceId), 0); + + /*失效日期--月(当有效期规则选择4-自定义次年失效日期时有效)*/ + String expirationMonth = detailComInfo.getExpirationMonth(this.leaveRulesId, subcompanyId ,departmentId, this.resourceId); + + /*失效日期--日(当有效期规则选择4-自定义次年失效日期时有效)*/ + String expirationDay = detailComInfo.getExpirationDay(this.leaveRulesId, subcompanyId, departmentId, this.resourceId); + + /*允许延长有效期:0-不允许、1-允许*/ + int extensionEnable = Util.getIntValue(detailComInfo.getExtensionEnable(this.leaveRulesId, subcompanyId, departmentId, this.resourceId), 0); + + /*允许超过有效期天数*/ + int extendedDays = Util.getIntValue(detailComInfo.getExtendedDays(this.leaveRulesId, subcompanyId, departmentId, this.resourceId), 0); + + /********************************************************************************************************/ + + /*员工假期余额变更记录*/ + String insertOrUpdate = ""; + KQUsageHistoryEntity usageHistoryEntity = new KQUsageHistoryEntity();//员工假期余额变更记录实体类 + List usageHistoryEntityList = new ArrayList();//员工假期余额变更记录集合 + + /********************************************************************************************************/ + + double oldBaseAmount = 0.00; + double oldUsedAmount = 0.00; + double oldExtraAmount = 0.00; + double oldBaseAmount2 = 0.00; + double oldUsedAmount2 = 0.00; + double oldExtraAmount2 = 0.00; + + double newBaseAmount = 0.00; + double newUsedAmount = 0.00; + double newExtraAmount = 0.00; + double newBaseAmount2 = 0.00; + double newUsedAmount2 = 0.00; + double newExtraAmount2 = 0.00; + int status = 0; + String expirationDate = ""; + + /*计算有效期 start*/ + if (validityRule == 0) { + /*不限制有效期,默认永久有效*/ + status = 0; + } else if (validityRule == 1) { + /*按自然年(1月1日-12月31日)*/ + if (extensionEnable == 1) { + /*允许延长有效期*/ + expirationDate = DateUtil.addDate(this.belongYear + "-12-31", extendedDays); + if (Util.dayDiff(expirationDate, currentDate) > 1) { + status = 1; + } + } else { + expirationDate = this.belongYear + "-12-31"; + if (Util.dayDiff(expirationDate, currentDate) > 1) { + status = 1; + } + } + } else if (validityRule == 2) { + /*按入职日期起12个月*/ + if (companyStartDate.equals("")) { + status = 1; + } else if (extensionEnable == 1) { + /*允许延长有效期*/ + expirationDate = DateUtil.addDate((Util.getIntValue(this.belongYear) + 1) + companyStartDate.substring(4), extendedDays); + if (Util.dayDiff(expirationDate, currentDate) > 1) { + status = 1; + } + } else { + expirationDate = (Util.getIntValue(this.belongYear) + 1) + companyStartDate.substring(4); + if (Util.dayDiff(expirationDate, currentDate) > 1) { + status = 1; + } + } + } else if (validityRule == 3) { + /*自定义次年失效日期*/ + if (extensionEnable == 1) { + /*允许延长有效期*/ + expirationDate = DateUtil.addDate((Util.getIntValue(this.belongYear) + 1) + "-" + expirationMonth + "-" + expirationDay, extendedDays); + if (Util.dayDiff(expirationDate, currentDate) > 1) { + status = 1; + } + } else { + expirationDate = (Util.getIntValue(this.belongYear) + 1) + "-" + expirationMonth + "-" + expirationDay; + if (Util.dayDiff(expirationDate, currentDate) > 1) { + status = 1; + } + } + } + String nianjiaId = Prop.getInstance().getPropValue("lingyue_nianjia","nianjiaid"); + if (nianjiaId.equals(leaveRulesId)){ + expirationDate = this.expirationDate; + } + /*计算有效期 end*/ + + newBaseAmount = this.baseAmount; + newExtraAmount = this.extraAmount; + newUsedAmount = this.usedAmount; + if (distributionMode == 6) { + newBaseAmount2 = this.baseAmount2; + newExtraAmount2 = this.extraAmount2; + newUsedAmount2 = this.usedAmount2; + } + + Timestamp date = KQDateUtil.getUpdateTimeStamp(); + boolean flag = true;//记录SQL操作是否成功 + String searchSql = "select * from kq_BalanceOfLeave where leaveRulesId=? and resourceId=? and belongYear=?"; + String updateSql = "update kq_BalanceOfLeave set baseAmount=?,extraAmount=?,usedAmount=?,baseAmount2=?,extraAmount2=?,usedAmount2=?,status=?,expirationDate=?,update_time=? where leaveRulesId=? and resourceId=? and belongYear=? "; + String insertSql = "insert into kq_BalanceOfLeave(baseAmount,extraAmount,usedAmount,baseAmount2,extraAmount2,usedAmount2,status,expirationDate,leaveRulesId,resourceId,belongYear,create_time,update_time,creator) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?) "; + RecordSet recordSet = new RecordSet(); + if (recordSet.getDBType().equals("postgresql")) { + updateSql = "update kq_BalanceOfLeave set baseAmount=?,extraAmount=?,usedAmount=?,baseAmount2=?,extraAmount2=?,usedAmount2=?,status=?,expirationDate=?,update_time=?::timestamp where leaveRulesId=? and resourceId=? and belongYear=? "; + insertSql = "insert into kq_BalanceOfLeave(baseAmount,extraAmount,usedAmount,baseAmount2,extraAmount2,usedAmount2,status,expirationDate,leaveRulesId,resourceId,belongYear,create_time,update_time,creator) values(?,?,?,?,?,?,?,?,?,?,?,?::timestamp,?::timestamp,?) "; + } + recordSet.executeQuery(searchSql, this.leaveRulesId, this.resourceId, this.belongYear); + if (recordSet.next()) { + oldBaseAmount = Util.getDoubleValue(recordSet.getString("baseAmount"), 0.00); + oldExtraAmount = Util.getDoubleValue(recordSet.getString("extraAmount"), 0.00); + oldUsedAmount = Util.getDoubleValue(recordSet.getString("usedAmount"), 0.00); + if (distributionMode == 6) { + oldBaseAmount2 = Util.getDoubleValue(recordSet.getString("baseAmount2"), 0.00); + oldExtraAmount2 = Util.getDoubleValue(recordSet.getString("extraAmount2"), 0.00); + oldUsedAmount2 = Util.getDoubleValue(recordSet.getString("usedAmount2"), 0.00); + } + + /*更新员工假期余额 start*/ + flag = recordSet.executeUpdate(updateSql, String.format("%.2f", newBaseAmount), String.format("%.2f", newExtraAmount), String.format("%.2f", newUsedAmount), String.format("%.2f", newBaseAmount2), String.format("%.2f", newExtraAmount2), String.format("%.2f", newUsedAmount2), status, expirationDate,date, this.leaveRulesId, this.resourceId, this.belongYear); + resultStr = String.valueOf(flag); + if (!flag) { + resultStr = "false"; + return resultStr; + } + /*更新员工假期余额 end*/ + + insertOrUpdate = "update"; + } else { + /*新增员工假期余额 start*/ + flag = recordSet.executeUpdate(insertSql, String.format("%.2f", newBaseAmount), String.format("%.2f", newExtraAmount), String.format("%.2f", newUsedAmount), String.format("%.2f", newBaseAmount2), String.format("%.2f", newExtraAmount2), String.format("%.2f", newUsedAmount2), status, expirationDate, this.leaveRulesId, this.resourceId, this.belongYear,date,date,Util.getIntValue(resourceId)); + resultStr = String.valueOf(flag); + if (!flag) { + return resultStr; + } + /*新增员工假期余额 end*/ + + insertOrUpdate = "insert"; + } + + /*员工假期余额变更记录 start*/ + usageHistoryEntity = new KQUsageHistoryEntity(); + usageHistoryEntity.setLeaveRulesId(this.leaveRulesId); + usageHistoryEntity.setRelatedId(this.resourceId); + usageHistoryEntity.setWfRequestId(""); + usageHistoryEntity.setOperator(this.operator); + usageHistoryEntity.setOperateDate(currentDate); + usageHistoryEntity.setOperateTime(currentTime); + usageHistoryEntity.setOperateType("7"); + usageHistoryEntity.setBelongYear(this.belongYear); + usageHistoryEntity.setOldBaseAmount(String.format("%.2f", oldBaseAmount)); + usageHistoryEntity.setNewBaseAmount(String.format("%.2f", newBaseAmount)); + usageHistoryEntity.setOldExtraAmount(String.format("%.2f", oldExtraAmount)); + usageHistoryEntity.setNewExtraAmount(String.format("%.2f", newExtraAmount)); + usageHistoryEntity.setOldUsedAmount(String.format("%.2f", oldUsedAmount)); + usageHistoryEntity.setNewUsedAmount(String.format("%.2f", newUsedAmount)); + usageHistoryEntity.setOldBaseAmount2(String.format("%.2f", oldBaseAmount2)); + usageHistoryEntity.setNewBaseAmount2(String.format("%.2f", newBaseAmount2)); + usageHistoryEntity.setOldExtraAmount2(String.format("%.2f", oldExtraAmount2)); + usageHistoryEntity.setNewExtraAmount2(String.format("%.2f", newExtraAmount2)); + usageHistoryEntity.setOldUsedAmount2(String.format("%.2f", oldUsedAmount2)); + usageHistoryEntity.setNewUsedAmount2(String.format("%.2f", newUsedAmount2)); + usageHistoryEntity.setOldMinimumUnit(minimumUnit); + usageHistoryEntity.setNewMinimumUnit(minimumUnit); + usageHistoryEntity.setInsertOrUpdate(insertOrUpdate); + + usageHistoryEntityList.add(usageHistoryEntity); + KQUsageHistoryBiz usageHistoryBiz = new KQUsageHistoryBiz(); + flag = usageHistoryBiz.save(usageHistoryEntityList); + resultStr = String.valueOf(flag); + if (!flag) { + return resultStr; + } + /*员工假期余额变更记录 end*/ + } catch (Exception e) { + writeLog(e); + } + return resultStr; + } + + /** + * 判断ID和姓名是否匹配,系统中是否存在此人员 + * + * @param resourceId + * @param lastName + * @return + */ + private boolean isExist(String resourceId, String lastName) { + String sql = "select 1 from HrmResource where id=? "; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql, resourceId); + if (recordSet.next()) { + return true; + } else { + return false; + } + } + + public String getResourceId() { + return resourceId; + } + + public void setResourceId(String resourceId) { + this.resourceId = resourceId; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getLeaveRulesId() { + return leaveRulesId; + } + + public void setLeaveRulesId(String leaveRulesId) { + this.leaveRulesId = leaveRulesId; + } + + public String getBelongYear() { + return belongYear; + } + + public void setBelongYear(String belongYear) { + this.belongYear = belongYear; + } + + public double getBaseAmount() { + return baseAmount; + } + + public void setBaseAmount(double baseAmount) { + this.baseAmount = baseAmount; + } + + public double getUsedAmount() { + return usedAmount; + } + + public void setUsedAmount(double usedAmount) { + this.usedAmount = usedAmount; + } + + public double getExtraAmount() { + return extraAmount; + } + + public void setExtraAmount(double extraAmount) { + this.extraAmount = extraAmount; + } + + public double getBaseAmount2() { + return baseAmount2; + } + + public void setBaseAmount2(double baseAmount2) { + this.baseAmount2 = baseAmount2; + } + + public double getUsedAmount2() { + return usedAmount2; + } + + public void setUsedAmount2(double usedAmount2) { + this.usedAmount2 = usedAmount2; + } + + public double getExtraAmount2() { + return extraAmount2; + } + + public void setExtraAmount2(double extraAmount2) { + this.extraAmount2 = extraAmount2; + } + + public void setUserLanguage(String languageId) { + this.userlanguage = Util.getIntValue(languageId, 7); + } + + public String getOperator() { + return operator; + } + + public void setOperator(String operator) { + this.operator = operator; + } + + public String getWorkcode() { + return workcode; + } + + public void setWorkcode(String workcode) { + this.workcode = workcode; + } + + public String getExpirationDate() { + return expirationDate; + } + + public void setExpirationDate(String expirationDate) { + this.expirationDate = expirationDate; + } +} diff --git a/领悦二开new/src/com/engine/kq/bean/KQChildrenBean.java b/领悦二开new/src/com/engine/kq/bean/KQChildrenBean.java new file mode 100644 index 0000000..472b343 --- /dev/null +++ b/领悦二开new/src/com/engine/kq/bean/KQChildrenBean.java @@ -0,0 +1,46 @@ +package com.engine.kq.bean; + +/** + * 排班制考勤组----排班设置权限(数据存储在建模表中) + */ +public class KQChildrenBean { + private String id; + + private String birthday; + + private String title; + + private String resourceid; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getBirthday() { + return birthday; + } + + public void setBirthday(String birthday) { + this.birthday = birthday; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getResourceid() { + return resourceid; + } + + public void setResourceid(String resourceid) { + this.resourceid = resourceid; + } +} diff --git a/领悦二开new/src/com/engine/kq/bean/KqLockAttenda.java b/领悦二开new/src/com/engine/kq/bean/KqLockAttenda.java new file mode 100644 index 0000000..2eb52c6 --- /dev/null +++ b/领悦二开new/src/com/engine/kq/bean/KqLockAttenda.java @@ -0,0 +1,74 @@ +package com.engine.kq.bean; + +/** + * 排班制考勤组----排班设置权限(数据存储在建模表中) + */ +public class KqLockAttenda { + private String LOCK_COM; + + private String LOCK_SUBCOM; + + private String LOCK_DEPT; + + private String LOCK_RESOURCE; + + private String LOCK_FROMDATE; + private String LOCK_TODATE; + private String LOCK_LOCK; + + public String getLOCK_COM() { + return LOCK_COM; + } + + public void setLOCK_COM(String LOCK_COM) { + this.LOCK_COM = LOCK_COM; + } + + public String getLOCK_SUBCOM() { + return LOCK_SUBCOM; + } + + public void setLOCK_SUBCOM(String LOCK_SUBCOM) { + this.LOCK_SUBCOM = LOCK_SUBCOM; + } + + public String getLOCK_DEPT() { + return LOCK_DEPT; + } + + public void setLOCK_DEPT(String LOCK_DEPT) { + this.LOCK_DEPT = LOCK_DEPT; + } + + public String getLOCK_RESOURCE() { + return LOCK_RESOURCE; + } + + public void setLOCK_RESOURCE(String LOCK_RESOURCE) { + this.LOCK_RESOURCE = LOCK_RESOURCE; + } + + public String getLOCK_FROMDATE() { + return LOCK_FROMDATE; + } + + public void setLOCK_FROMDATE(String LOCK_FROMDATE) { + this.LOCK_FROMDATE = LOCK_FROMDATE; + } + + public String getLOCK_TODATE() { + return LOCK_TODATE; + } + + public void setLOCK_TODATE(String LOCK_TODATE) { + this.LOCK_TODATE = LOCK_TODATE; + } + + public String getLOCK_LOCK() { + return LOCK_LOCK; + } + + public void setLOCK_LOCK(String LOCK_LOCK) { + this.LOCK_LOCK = LOCK_LOCK; + } +} diff --git a/领悦二开new/src/com/engine/kq/biz/KQBalanceOfLeaveBiz.java b/领悦二开new/src/com/engine/kq/biz/KQBalanceOfLeaveBiz.java new file mode 100644 index 0000000..feae597 --- /dev/null +++ b/领悦二开new/src/com/engine/kq/biz/KQBalanceOfLeaveBiz.java @@ -0,0 +1,4908 @@ +package com.engine.kq.biz; + +import com.alibaba.fastjson.JSONObject; +import com.engine.kq.bean.KQChildrenBean; +import com.engine.kq.entity.KQBalanceOfLeaveEntity; +import com.engine.kq.entity.KQOvertimeRulesDetailEntity; +import com.engine.kq.entity.KQUsageHistoryEntity; +import com.engine.kq.jucailin.util.KQDateUtil; +import com.engine.kq.log.KQLog; +import com.engine.kq.util.lingyuewuye.NianJiaUtil; +import com.engine.kq.wfset.bean.OvertimeBalanceTimeBean; +import com.google.common.collect.Maps; +import org.apache.commons.lang3.StringUtils; +import weaver.common.DateUtil; +import weaver.common.StringUtil; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.BaseBean; +import weaver.general.TimeUtil; +import weaver.general.Util; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; +import weaver.hrm.company.SubCompanyComInfo; +import weaver.hrm.moduledetach.ManageDetachComInfo; +import weaver.hrm.resource.ResourceComInfo; +import weaver.systeminfo.SystemEnv; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.text.SimpleDateFormat; +import java.time.*; +import java.time.format.DateTimeFormatter; +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * 假期余额相关接口 + */ +public class KQBalanceOfLeaveBiz { + + private static KQLog logger = new KQLog();//用于记录日志信息 + + public static String getBalanceOfLeave(String resourceId, String ruleId, String date) { + return getBalanceOfLeave(resourceId, ruleId, date, true); + } + + public static String getBalanceOfLeave(String resourceId, String ruleId, String date, boolean isAll) { + return getBalanceOfLeave(resourceId, ruleId, date, false, isAll); + } + + public static String getBalanceOfLeave(String resourceId, String ruleId, String searchDate, boolean calcByCurrentDate, boolean isAll) { + return getRestAmount(resourceId, ruleId, searchDate, calcByCurrentDate, isAll); + } + + /** + * 获取指定人员的指定假期的有效的假期余额 + * + * @param resourceId 指定的人员ID + * @param ruleId 指定的假期类型的ID(表kq_leaveRules的主键ID) + * @param date 请假日期(根据此日期计算释放规则以及判断员工假期余额是否失效) + * @return 如果传入的指定假期类型没有开启假期余额,则返回0.00 + */ + public static String getRestAmount(String resourceId, String ruleId, String date) { + return getRestAmount(resourceId, ruleId, date, true); + } + + /** + * 获取指定人员的指定假期的有效的假期余额 + * + * @param resourceId 指定的人员ID + * @param ruleId 指定的假期类型的ID(表kq_leaveRules的主键ID) + * @param date 请假日期(根据此日期计算释放规则以及判断员工假期余额是否失效) + * @param isAll true--查询所有年份加起来的总有效余额、false--仅仅查询指定请假日期那一年的有效余额 + * @return 如果传入的指定假期没有开启假期余额,则返回0.00 + */ + public static String getRestAmount(String resourceId, String ruleId, String date, boolean isAll) { + return getRestAmount(resourceId, ruleId, date, false, isAll); + } + + /** + * 获取指定人员的指定假期的有效的假期余额 + * + * @param resourceId 指定的人员ID + * @param ruleId 指定的假期类型的ID(表kq_leaveRules的主键ID) + * @param searchDate 请假日期(不可为空) + * @param calcByCurrentDate true--根据当前日期计算释放规则以及判断员工假期余额是否失效、false--根据请假日期来计算释放规则以及判断员工假期余额是否失效 + * @param isAll true--查询所有年份加起来的总有效余额、false--仅仅查询指定请假日期那一年的有效余额 + * @return 如果传入的指定假期没有开启假期余额,则返回0.00 + */ + public static String getRestAmount(String resourceId, String ruleId, String searchDate, boolean calcByCurrentDate, boolean isAll) { + //员工的假期余额 + String balanceOfLeave = "0"; + Map params = new HashMap<>(); + params.put("resourceId",resourceId); + params.put("ruleId",ruleId); + params.put("searchDate",searchDate); + params.put("calcByCurrentDate",calcByCurrentDate); + params.put("isAll",isAll); + try { + BigDecimal restAmount = new BigDecimal("0"); + //获取当前日期 + Calendar today = Calendar.getInstance(); + //当前日期 + String currentDate = Util.add0(today.get(Calendar.YEAR), 4) + "-" + + Util.add0(today.get(Calendar.MONTH) + 1, 2) + "-" + + Util.add0(today.get(Calendar.DAY_OF_MONTH), 2); + //所属年份 + String searchYear = searchDate.substring(0, 4); + + /**********************************************************************************************************/ + + //假期类型缓存类 + KQLeaveRulesComInfo rulesComInfo = new KQLeaveRulesComInfo(); + //是否启用假期余额:0-未开启、1-开启 + int balanceEnable = Util.getIntValue(rulesComInfo.getBalanceEnable(ruleId), 0); + + /**********************************************************************************************************/ + + //人员缓存类 + ResourceComInfo resourceComInfo = new ResourceComInfo(); + //分部ID + String subCompanyId = resourceComInfo.getSubCompanyID(resourceId); + //部门ID + String departmentId = resourceComInfo.getDepartmentID(resourceId); + /**********************************************************************************************************/ + + //假期规则缓存类 + KQLeaveRulesDetailComInfo detailComInfo = new KQLeaveRulesDetailComInfo(); + //余额发放方式:1-手动发放、2-按司龄自动发放、3-按工龄自动发放、4-每年自动发放固定天数、5-加班时长自动计入余额、6-按司龄+工龄自动发放 + int distributionMode = Util.getIntValue(detailComInfo.getDistributionMode(ruleId, subCompanyId, departmentId, resourceId), 1); + // + int decimalDigit = Util.getIntValue(detailComInfo.getDecimalDigit(ruleId, subCompanyId, departmentId, resourceId), 2); + + /**********************************************************************************************************/ + + //该假期没有启用假期余额,记录错误日志,返回假期余额0 + if (balanceEnable != 1) { + logger.info("获取员工假期余额失败,此假期类型没有开启假期余额。params=" + JSONObject.toJSONString(params)); + return "0"; + } + //传入的请假日期为空,记录错误日期,返回假期余额0 + if (searchDate.equals("")) { + logger.info("获取员工假期余额失败,传入的请假日期为空。params=" + JSONObject.toJSONString(params)); + return "0"; + } + //传入的指定日期格式不对,记录错误日期,返回假期余额0 + Pattern pattern = Pattern.compile("^\\d{4}\\-\\d{2}\\-\\d{2}$"); + Matcher matcher = pattern.matcher(searchDate); + if (!matcher.matches()) { + logger.info("获取员工假期余额失败,传入的请假日期格式不对。params=" + JSONObject.toJSONString(params)); + return "0"; + } + //根据指定日期(或者根据当前日期)判断假期是否已经过了有效期 + String date = calcByCurrentDate ? currentDate : searchDate; + + //如果是调休,获取假期余额的逻辑会不太一样 + if (distributionMode == 5) { + restAmount = getRestAmountByDis5(ruleId, resourceId, searchDate, calcByCurrentDate, isAll); + return restAmount.setScale(decimalDigit, RoundingMode.HALF_UP).toPlainString(); + } + if (distributionMode == 8) { + restAmount = getRestAmountByDis8(ruleId, resourceId, searchDate, calcByCurrentDate, isAll); + return restAmount.setScale(decimalDigit, RoundingMode.HALF_UP).toPlainString(); + } + + //计算员工假期余额总和 + RecordSet recordSet = new RecordSet(); + String sql = "select * from kq_BalanceOfLeave where resourceId=? and leaveRulesId=? and (isDelete is null or isDelete<>1) "; + //是查询所有有效的假期余额还是仅仅查询指定日期当年的 + if(KQSettingsBiz.is_balanceofleave()){//开启开关 + if (!isAll) { + sql += " and belongYear='" + searchYear + "'"; + }else{ + sql += " and belongYear<='" + searchYear + "'"; + } + }else{ + if (!isAll) { + sql += " and belongYear='" + searchYear + "'"; + } + } + recordSet.executeQuery(sql, resourceId, ruleId); + while (recordSet.next()) { + //所属年份 + String belongYear = recordSet.getString("belongYear"); + //生效日期 + String effectiveDate = recordSet.getString("effectiveDate"); + //失效日期 + String expirationDate = recordSet.getString("expirationDate"); + //是否失效 + boolean status = getBalanceStatus(ruleId, resourceId, belongYear, date, effectiveDate, expirationDate); + if (!status) { + continue; + } + + if (distributionMode == 6) { + BigDecimal baseAmount = new BigDecimal(Util.null2s(recordSet.getString("baseAmount"), "0"));//混合模式下的法定年假基数 + BigDecimal usedAmount = new BigDecimal(Util.null2s(recordSet.getString("usedAmount"), "0"));//混合模式下的已休法定年假数 + BigDecimal extraAmount = new BigDecimal(Util.null2s(recordSet.getString("extraAmount"), "0"));//混合模式下的额外法定年假数 + //根据释放规则获取已释放的天数/小时数 + baseAmount = getCanUseAmount(resourceId, ruleId, belongYear, baseAmount, "legal", date); + + BigDecimal baseAmount2 = new BigDecimal(Util.null2s(recordSet.getString("baseAmount2"), "0"));//混合模式下的福利年假基数 + BigDecimal usedAmount2 = new BigDecimal(Util.null2s(recordSet.getString("usedAmount2"), "0"));//混合模式下的已休福利年假数 + BigDecimal extraAmount2 = new BigDecimal(Util.null2s(recordSet.getString("extraAmount2"), "0"));//混合模式下的额外福利年假数 + //根据释放规则获取已释放的天数/小时数 + baseAmount2 = getCanUseAmount(resourceId, ruleId, belongYear, baseAmount2, "welfare", date); + //剩余=已释放+额外-已休 + restAmount = restAmount.add(baseAmount.add(extraAmount).subtract(usedAmount).add(baseAmount2).add(extraAmount2).subtract(usedAmount2)); + } else { + BigDecimal baseAmount = new BigDecimal(Util.null2s(recordSet.getString("baseAmount"), "0"));//假期余额基数 + BigDecimal usedAmount = new BigDecimal(Util.null2s(recordSet.getString("usedAmount"), "0"));//已休的假期时长 + BigDecimal extraAmount = new BigDecimal(Util.null2s(recordSet.getString("extraAmount"), "0"));//额外的假期时长 + //根据释放规则获取已释放的天数/小时数 + baseAmount = getCanUseAmount(resourceId, ruleId, belongYear, baseAmount, "", date); + //剩余=已释放+额外-已休 + restAmount = restAmount.add(baseAmount.add(extraAmount).subtract(usedAmount)); + } + } + balanceOfLeave = restAmount.setScale(decimalDigit, RoundingMode.HALF_UP).toPlainString(); + } catch (Exception e) { + logger.info(e.getMessage()); + logger.info("获取员工假期余额失败。params=" + JSONObject.toJSONString(params)); + } + return balanceOfLeave; + } + + /** + * 获取指定人员的指定假期类型的指定年份在指定日期的可用余额(假期基数*释放比例) + * + * @param resourceId 指定的人员ID + * @param ruleId 指定的假期类型ID(对应于数据库表kq_leaveRules的主键ID) + * @param belongYear 指定的所属年份(格式yyyy) + * @param baseAmount 假期基数 + * @param legalOrWelfare 是计算[法定年假]还是计算[福利年假]:legal-法定年假、welfare-福利年假 + * @param date 指定日期(获取的就是此日期的假期可用余额) + * @return + */ + public static BigDecimal getCanUseAmount(String resourceId, String ruleId, String belongYear, BigDecimal baseAmount, String legalOrWelfare, String date) { + BigDecimal canUseAmount = new BigDecimal("0"); + try { + //人员缓存类 + ResourceComInfo resourceComInfo = new ResourceComInfo(); + //分部ID + String subCompanyId = resourceComInfo.getSubCompanyID(resourceId); + String departmentId = resourceComInfo.getDepartmentID(resourceId); + //创建日期 + String createDate = resourceComInfo.getCreatedate(resourceId); + //入职日期 + String companyStartDate = resourceComInfo.getCompanyStartDate(resourceId); + //没有维护入职日期时取创建日期 + companyStartDate = companyStartDate.equals("") ? createDate : companyStartDate; + //参加工作日期 + String workStartDate = resourceComInfo.getWorkStartDate(resourceId); + //没有维护参加工作日期时取创建日期 + workStartDate = workStartDate.equals("") ? createDate : workStartDate; + + /*********************************************************************************/ + + //指定日期--用于计算已释放天数的日期 + Calendar searchDate = DateUtil.getCalendar(date); + //指定日期的年份 + String searchYear = Util.add0(searchDate.get(Calendar.YEAR), 4); + //指定日期那年一共多少天 + BigDecimal actualMaximum = new BigDecimal("" + searchDate.getActualMaximum(Calendar.DAY_OF_YEAR)); + //指定日期是那年的第几天 + BigDecimal dayOfYear = new BigDecimal("" + searchDate.get(Calendar.DAY_OF_YEAR)); + //指定日期是那年的第几月 + BigDecimal monthOfYear = new BigDecimal("" + (searchDate.get(Calendar.MONTH) + 1)); + + /*********************************************************************************/ + + //如果人员已离职--根据合同结束日期计算年假天数 + String resourcestatus = Util.null2String(resourceComInfo.getStatus(resourceId)); + if(resourcestatus.equals("5")){ + try{ + String enddate = Util.null2String(resourceComInfo.getEndDate(resourceId));//合同结束日期 + Calendar calenddate = DateUtil.getCalendar(enddate); + //指定日期是那年的第几天 + dayOfYear = new BigDecimal("" + calenddate.get(Calendar.DAY_OF_YEAR)); + //指定日期是那年的第几月 + monthOfYear = new BigDecimal("" + (calenddate.get(Calendar.MONTH) + 1)); + }catch (Exception e){ + e.printStackTrace(); + } + } + /*********************************************************************************/ + //获取此假期类型下,该人员所在分部对应的假期规则 + KQLeaveRulesDetailComInfo detailComInfo = new KQLeaveRulesDetailComInfo(); + //余额发放方式 + int distributionMode = Util.getIntValue(detailComInfo.getDistributionMode(ruleId, subCompanyId, departmentId, resourceId), 1); + //释放规则:0-不限制、1-按天释放、2-按月释放 + int releaseRule = Util.getIntValue(detailComInfo.getReleaseRule(ruleId, subCompanyId, departmentId, resourceId), 0); + //小数位数 + int decimalDigit = Util.getIntValue(detailComInfo.getDecimalDigit(ruleId, subCompanyId, departmentId, resourceId), 2); + + /*********************************************************************************/ + + //这几种发放方式不支持释放规则 + if (distributionMode == 5 || distributionMode == 7|| distributionMode == 8) { + return baseAmount; + } + + //指定日期小于入职日期时,释放出来的假期余额应为0(无人提出此要求,暂时不加此限制) + + /*********************************************************************************/ + + //这一年什么时候开始想有假期的 + Calendar calendar = null; + + //如果指定日期的年份大于假期余额的所属年份,则代表假期基数已经全部释放 + if (searchYear.compareTo(belongYear) > 0) { + return baseAmount; + } else if (searchYear.compareTo(belongYear) < 0) { + //如果指定日期的年份小于假期余额的所属年份,则代表假期基数还没有开始释放 + if (releaseRule != 0) { + return new BigDecimal("0"); + } + } else if (searchYear.compareTo(belongYear) == 0) { + } + if (distributionMode == 6) { + calendar = getReleaseDateByDis6(resourceId, ruleId, belongYear, legalOrWelfare); + } else { + calendar = getReleaseDate(resourceId, ruleId, belongYear); + } + + /****************************************************************************************/ + + /* 释放规则 start */ + if (releaseRule == 0) { + canUseAmount = baseAmount; + } else if (releaseRule == 1) { + BigDecimal dateIndex = new BigDecimal("" + (calendar.get(Calendar.DAY_OF_YEAR) - 1)); + canUseAmount = baseAmount.multiply(dayOfYear.subtract(dateIndex)).divide(actualMaximum.subtract(dateIndex), decimalDigit, RoundingMode.HALF_UP); + } else if (releaseRule == 2) { + BigDecimal monthIndex = new BigDecimal("" + calendar.get(Calendar.MONTH)); + canUseAmount = baseAmount.multiply(monthOfYear.subtract(monthIndex)).divide(new BigDecimal("12").subtract(monthIndex), decimalDigit, RoundingMode.HALF_UP); + } + /* 释放规则 end */ + //如果释放为负数,就修改为0 + int i=canUseAmount.compareTo(BigDecimal.ZERO); + if(i < 0){ + canUseAmount = new BigDecimal("0"); + } + } catch (Exception e) { + e.printStackTrace(); + } + return canUseAmount; + } + + /** + * 获取失效日期 + * + * @param ruleId 指定的假期类型ID(对应于数据库表kq_leaveRules的主键ID) + * @param resourceId 指定的人员ID + * @param belongYear 指定的所属年份(格式yyyy) + * @param effectiveDate 生效日期 + * @param expirationDate 失效日期(待计算返回的) + * @return + */ + public static String getExpirationDate(String ruleId, String resourceId, String belongYear, String effectiveDate, String expirationDate) { + try { + //人力资源缓存类 + ResourceComInfo resourceComInfo = new ResourceComInfo(); + //入职日期 + String companyStartDate = resourceComInfo.getCompanyStartDate(resourceId); + //创建日期 + String createDate = resourceComInfo.getCreatedate(resourceId); + //如果入职日期为空,默认取创建日期 + companyStartDate = companyStartDate.equals("") ? createDate : companyStartDate; + //分部ID + String subcompanyId = resourceComInfo.getSubCompanyID(resourceId); + String departmentId = resourceComInfo.getDepartmentID(resourceId); + + + //假期规则缓存类 + KQLeaveRulesDetailComInfo detailComInfo = new KQLeaveRulesDetailComInfo(); + //有效期规则:0-不限制、1-按自然年失效、2-按入职日期起12个月、3-自定义次年失效日期、4-按天数失效、5-按季度失效、6-按月数失效 + int validityRule = Util.getIntValue(detailComInfo.getValidityRule(ruleId, subcompanyId, departmentId, resourceId), 0); + //自定义有效天数([validityRule=4]时有效) + int effectiveDays = Util.getIntValue(detailComInfo.getEffectiveDays(ruleId, subcompanyId, departmentId, resourceId), 0); + //自定义有效月数([validityRule=6]时有效) + int effectiveMonths = Util.getIntValue(detailComInfo.getEffectiveMonths(ruleId, subcompanyId, departmentId, resourceId), 0); + //自定义次年失效的月份([validityRule=3]时有效) + String expirationMonth = detailComInfo.getExpirationMonth(ruleId, subcompanyId, departmentId, resourceId); + //自定义次年失效的日期([validityRule=3]时有效) + String expirationDay = detailComInfo.getExpirationDay(ruleId, subcompanyId, departmentId, resourceId); + //允许延长有效期:0--不允许、1--允许 + int extensionEnable = Util.getIntValue(detailComInfo.getExtensionEnable(ruleId, subcompanyId, departmentId, resourceId), 0); + //允许延长的有效天数 + int extendedDays = Util.getIntValue(detailComInfo.getExtendedDays(ruleId, subcompanyId, departmentId, resourceId)); + //获取当前日期 + String currentDate = DateUtil.getCurrentDate(); + //如果生效日期为空,默认取当前日期 + effectiveDate = effectiveDate.equals("") ? currentDate : effectiveDate; + + if (validityRule == 0) { + //不限制有效期,默认永久有效(永久有效时有效日期默认为2222-12-31) + expirationDate = "2222-12-31"; + } else if (validityRule == 1) { + //按自然年(1月1日-12月31日) + if (extensionEnable == 1) { + //允许延长有效期 + expirationDate = DateUtil.addDate(belongYear + "-12-31", extendedDays); + } else { + expirationDate = belongYear + "-12-31"; + } + } else if (validityRule == 2) { + //按入职日期起12个月 + if (companyStartDate.equals("")) { + expirationDate = effectiveDate; + } else if (extensionEnable == 1) { + /*允许延长有效期*/ + expirationDate = DateUtil.addDate((Util.getIntValue(belongYear) + 1) + companyStartDate.substring(4), extendedDays); + } else { + expirationDate = (Util.getIntValue(belongYear) + 1) + companyStartDate.substring(4); + } + } else if (validityRule == 3) { + /*自定义次年失效日期*/ + if (extensionEnable == 1) { + /*允许延长有效期*/ + expirationDate = DateUtil.addDate((Util.getIntValue(belongYear) + 1) + "-" + expirationMonth + "-" + expirationDay, extendedDays); + } else { + expirationDate = (Util.getIntValue(belongYear) + 1) + "-" + expirationMonth + "-" + expirationDay; + } + } else if (validityRule == 4) { + //按天数失效 + if(expirationDate.length() > 0){ + + }else{ + expirationDate = DateUtil.addDate(effectiveDate, effectiveDays); + } + } else if (validityRule == 5) { + //按季度失效 + expirationDate = DateUtil.getLastDayOfQuarter(effectiveDate); + if (extensionEnable == 1) { + /*允许延长有效期*/ + expirationDate = DateUtil.addDate(expirationDate, extendedDays); + } + } else if (validityRule == 6){ + Calendar calendar = DateUtil.addMonth(DateUtil.getCalendar(effectiveDate), effectiveMonths - 1); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + String dateStr = sdf.format(calendar.getTime()); + //按月数失效 + expirationDate = DateUtil.getLastDayOfMonth(dateStr); + if (extensionEnable == 1) { + /*允许延长有效期*/ + expirationDate = DateUtil.addDate(expirationDate, extendedDays); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + return expirationDate; + } + /** + * 获取育儿家失效日期 + * + * @param ruleId 指定的假期类型ID(对应于数据库表kq_leaveRules的主键ID) + * @param resourceId 指定的人员ID + * @param belongYear 指定的所属年份(格式yyyy) + * @param effectiveDate 生效日期 + * @param searchDate 查询搜索日期 + * @return + */ + public static boolean getParentalExpirationDate(String ruleId, String resourceId, String belongYear, String effectiveDate, String searchDate) { + boolean status = false; + try { + //人力资源缓存类 + ResourceComInfo resourceComInfo = new ResourceComInfo(); + //分部ID + String subcompanyId = resourceComInfo.getSubCompanyID(resourceId); + String departmentId = resourceComInfo.getDepartmentID(resourceId); + //假期规则缓存类 + KQLeaveRulesDetailComInfo detailComInfo = new KQLeaveRulesDetailComInfo(); + //有效期规则:0-不限制、1-按自然年失效、2-按入职日期起12个月、3-自定义次年失效日期、4-按天数失效、5-按季度失效、6-按月数失效 + String rulesDetailId = detailComInfo.getId(ruleId, subcompanyId, departmentId, resourceId); + int validityRule = Util.getIntValue(detailComInfo.getValidityRule(ruleId, subcompanyId, departmentId, resourceId), 0); + int yearsOld = StringUtil.parseToInt(detailComInfo.getYearsOld(ruleId, subcompanyId, departmentId, resourceId), 0); + String isprovince = Util.null2s(detailComInfo.getIsProvince(ruleId, subcompanyId, departmentId, resourceId), "1"); + if(isprovince.equals("2")){ + Map params = new HashMap<>(); + getChildrenProvinceId(rulesDetailId,resourceComInfo.getLocationid(resourceId),params); + yearsOld = Util.getIntValue(Util.null2String(params.get("yearsOld"))); + } + //自定义有效天数([validityRule=4]时有效) + if (validityRule == 0) { + //不限制有效期,默认永久有效(永久有效时有效日期默认为2222-12-31) + return true; + } else { + ArrayList listDates = getParentalLeaveDate(resourceId); + for (int i = 0; i < listDates.size(); i++) { + String dateOfBirth = listDates.get(i); + String baseAmountReleaseDate = belongYear + dateOfBirth.substring(4); + int ageLimit = getAgeLimit(dateOfBirth, baseAmountReleaseDate); + if (ageLimit >= 0 && ageLimit <= yearsOld-1) { + String expirationDate = (Util.getIntValue(belongYear) + 1) + dateOfBirth.substring(4); + if (expirationDate.compareTo(searchDate) > 0) { + status = true; + break; + } else { + status = false; + } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + return status; + } + + /** + * 判断假期余额是否有效 + * + * @param ruleId 指定的假期类型ID(对应于数据库表kq_leaveRules的主键ID) + * @param resourceId 指定的人员ID + * @param belongYear 指定的所属年份(格式yyyy) + * @param searchDate 指定日期(根据此日期判断假期余额是否有效) + * @param effectiveDate 数据库中存放的生效日期 + * @param expirationDate 数据库中存放的失效日期 + * @return + */ + public static boolean getBalanceStatus(String ruleId, String resourceId, String belongYear, String searchDate, String effectiveDate, String expirationDate) { + boolean status = true; + try { + //育儿假 + if (KQLeaveRulesBiz.isLeaveOfParental(ruleId)) { + return getParentalExpirationDate(ruleId, resourceId, belongYear, effectiveDate, searchDate); + } + ResourceComInfo resourceComInfo = new ResourceComInfo(); + String subCompanyId = resourceComInfo.getSubCompanyID(resourceId); + String departmentId = resourceComInfo.getDepartmentID(resourceId); + if (!KQLeaveRulesBiz.isTiaoXiu(ruleId,subCompanyId,departmentId,resourceId)) { + String nianjiaId = Prop.getInstance().getPropValue("lingyue_nianjia","nianjiaid"); + + if (ruleId.equals(nianjiaId)){//如果假期是年假 + new BaseBean().writeLog("qc3286856 走的是年假的失效日期判断"); + + expirationDate = NianJiaUtil.getNianJiaExpriationDate(ruleId, resourceId, belongYear); + new BaseBean().writeLog("qc3286856 searchDate="+searchDate+";expirationDate="+expirationDate); + }else { + expirationDate = getExpirationDate(ruleId, resourceId, belongYear, effectiveDate, expirationDate); + } + + } + if (!expirationDate.equals("") && expirationDate.compareTo(searchDate)<0) { + status = false; + } + } catch (Exception e) { + e.printStackTrace(); + } + return status; + } + + /** + * 保存加班时长转换成的调休时长,当加班时长的单位与调休单位不一致时根据【加班单位】中的日折算时长转换 + * + * @param resourceId 指定人员ID(根据人员ID判断属于哪个考勤组,根据考勤组获取加班规则ID) + * @param date 指定日期(根据指定日期判断是节假日还是工作日还是休息日、日期格式yyyy-MM-dd) + * @param durationOfOvertime 加班时长 + * @param type 加班时长单位:0-分钟、1-小时、2-天 + * 单位可为空(为空则默认取【加班单位】中设置的最小加班单位) + * @param hoursOfworkday 指定日期的工作时长(只有当指定日期为工作日的时候才有工作时长) + * 当最小加班单位与调休单位不一致时,且指定日期为工作日时使用此工作时长进行折算 + * @param requestId 加班流程的requestId(用于使用记录中可追溯至加班流程) + * @param fromCardOrFlow 是打卡数据还是审批数据:1--打卡、2--流程 + * @param fromDateDb 加班流程表单中的加班开始日期 + * @return + */ + public static boolean saveTimeOfLeave(String resourceId, String date, String durationOfOvertime, String type, String hoursOfworkday, String requestId, String fromCardOrFlow, String fromDateDb) { + //加班转调休是否成功 + boolean flag = true; + try { + String tiaoxiuId = addExtraAmountByDis5(resourceId,date,durationOfOvertime,type,hoursOfworkday,requestId,fromCardOrFlow,fromDateDb,null); + flag = Util.getIntValue(tiaoxiuId, -1) > 0; + } catch (Exception e) { + new BaseBean().writeLog(e); + } + return flag; + } + + /** + * 保存加班时长转换成的调休时长,当加班时长的单位与调休单位不一致时根据【加班单位】中的日折算时长转换 + * + * @param resourceId 指定人员ID(根据人员ID判断属于哪个考勤组,根据考勤组获取加班规则ID) + * @param date 指定日期(根据指定日期判断是节假日还是工作日还是休息日、日期格式yyyy-MM-dd) + * @param durationOfOvertime 加班时长 + * @param type 加班时长单位:0-分钟、1-小时、2-天 + * 单位可为空(为空则默认取【加班单位】中设置的最小加班单位) + * @param hoursOfworkday 指定日期的工作时长(只有当指定日期为工作日的时候才有工作时长) + * 当最小加班单位与调休单位不一致时,且指定日期为工作日时使用此工作时长进行折算 + * @param requestId 加班流程的requestId(用于使用记录中可追溯至加班流程) + * @param fromCardOrFlow 是打卡数据还是审批数据:1--打卡、2--流程 + * @param fromDateDb 加班流程表单中的加班开始日期 + * @return + */ + public static String addExtraAmountByDis5(String resourceId, String date, String durationOfOvertime, String type, String hoursOfworkday, String requestId, String fromCardOrFlow, String fromDateDb,Map otherParam) { + Map params = new HashMap(); + params.put("resourceId", resourceId); + params.put("date", date); + params.put("durationOfOvertime", durationOfOvertime); + params.put("type", type); + params.put("hoursOfworkday", hoursOfworkday); + params.put("requestId", requestId); + params.put("fromCardOrFlow", fromCardOrFlow); + params.put("fromDateDb", fromDateDb); + //加班转的调休明细ID(KQ_BalanceOfLeave的ID) + String tiaoxiuId = "-1"; + try { + String workflowid = "-1"; + RecordSet rs = new RecordSet(); + if(requestId.length() > 0 && Util.getIntValue(requestId) > 0){ + String workflow_sql = "select workflowid from workflow_requestbase where requestid = ? "; + rs.executeQuery(workflow_sql, requestId); + if(rs.next()){ + workflowid = Util.null2s(rs.getString("workflowid"),"-1"); + } + } + //加班转调休是否成功 + boolean flag = false; + //人员信息缓存类 + ResourceComInfo resourceComInfo = new ResourceComInfo(); + //创建日期 + String createDate = Util.null2String(resourceComInfo.getCompanyStartDate(resourceId)); + //入职日期 + String companyStartDate = Util.null2String(resourceComInfo.getCompanyStartDate(resourceId)); + //如果入职日期为空,则取创建日期 + companyStartDate = "".equals(companyStartDate) ? createDate : companyStartDate; + //分部ID + String subCompanyId = resourceComInfo.getSubCompanyID(resourceId); + String departmentId = resourceComInfo.getDepartmentID(resourceId); + //日期类型:1-节假日、2-工作日、3-休息日(节假日设置的优先级高于考勤组中的设置) + int changeType = KQOvertimeRulesBiz.getChangeType(resourceId, date); + //获取当前日期,当前时间 + Calendar today = Calendar.getInstance(); + //当前日期 + String currentDate = Util.add0(today.get(Calendar.YEAR), 4) + "-" + + Util.add0(today.get(Calendar.MONTH) + 1, 2) + "-" + + Util.add0(today.get(Calendar.DAY_OF_MONTH), 2); + //当前时间 + String currentTime = Util.add0(today.get(Calendar.HOUR_OF_DAY), 2) + ":" + + Util.add0(today.get(Calendar.MINUTE), 2) + ":" + + Util.add0(today.get(Calendar.SECOND), 2); + + /****************************************************************************************************************/ + + //假期类型的缓存类 + KQLeaveRulesComInfo rulesComInfo = new KQLeaveRulesComInfo(); + KQLeaveRulesDetailComInfo detailComInfo = new KQLeaveRulesDetailComInfo(); + //[调休]的假期类型的ID + //找到[调休]的假期类型ID + rs.writeLog("lxr2018>addExtraAmountByDis5开始"); + String leaveRulesId = KQLeaveRulesBiz.getTiaoXiu(subCompanyId, departmentId, resourceId)+""; + rulesComInfo.setTofirstRow(); + rs.writeLog("lxr2018>addExtraAmountByDis5="+leaveRulesId); + //[调休]的假期类型的最小请假单位:1-按天、2-按半天、3-按小时、4-按整天 + int minimumUnit = Util.getIntValue(rulesComInfo.getMinimumUnit(leaveRulesId), -1); + //假期规则的缓存类 +// KQLeaveRulesDetailComInfo detailComInfo = new KQLeaveRulesDetailComInfo(); + //有效期规则:0-永久有效、1-按自然年(1月1日-12月31日)、2-按入职日期起12个月、3-自定义次年失效日期、4-按天数失效 + int validityRule = Util.getIntValue(detailComInfo.getValidityRule(leaveRulesId, subCompanyId,departmentId,resourceId)); + //保留几位小数 + int decimalDigit = Util.getIntValue(detailComInfo.getDecimalDigit(leaveRulesId, subCompanyId,departmentId,resourceId), 2); + + String order = getDeductOrder(""+changeType,detailComInfo.getId(leaveRulesId, subCompanyId,departmentId,resourceId)); + rs.writeLog("lxr2018>order="+order+",changeType="+changeType+",getId="+detailComInfo.getId(leaveRulesId, subCompanyId,departmentId,resourceId)); + + /*如果没有设置调休的假期类型,则直接退出方法*/ + if ("".equals(leaveRulesId)) { + logger.info("未设置调休的假期类型或未调休的假期类型下未设置改人员所在分部可用的假期规则。params=" + JSONObject.toJSONString(params)); + return "-1"; + } + /*【调休】的假期规则的最小请假单位有误时,记录错误日志,直接返回*/ + if (minimumUnit < 1 || minimumUnit > 6) { + logger.info("调休的请假规则的最小请假单位有误。params=" + JSONObject.toJSONString(params)); + return "-1"; + } + /*【调休】的假期规则的有效期规则有误时,记录错误日志,直接返回*/ + if (validityRule < 0 || validityRule > 6) { + logger.info("调休的请假规则的有效期规则有误。params=" + JSONObject.toJSONString(params)); + return "-1"; + } + + /****************************************************************************************************************/ + + //所属年份 + String belongYear = date.substring(0, 4); + //失效日期 + String expirationDate = ""; + //根据有效期规则获取有效日期 + expirationDate = getExpirationDate(leaveRulesId, resourceId, belongYear, date, expirationDate); + + /****************************************************************************************************************/ + + //最小加班单位:1-按天、2-按半天、3-按小时、4-按整天、5-按半小时加班、6-整小时 + int minimumUnitOfOvertime = -1; + //日折算时长 + double hoursToDay = -1.00; + + String sql = "select * from kq_OvertimeUnit where (isDelete is null or isDelete !=1) and id=1"; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql); + if (recordSet.next()) { + minimumUnitOfOvertime = Util.getIntValue(recordSet.getString("minimumUnit"), -1); + hoursToDay = Util.getDoubleValue(recordSet.getString("hoursToDay"), 8.00); + } + /*【加班单位】的相关设置获取有误时,记录错误日志,直接返回*/ + if (minimumUnitOfOvertime == -1 || hoursToDay < 0) { + logger.info("获取到的加班单位的相关设置有误。params=" + JSONObject.toJSONString(params)); + return "-1"; + } + + /** + * 加班单位与调休单位不一致,实现转换 + */ + if (changeType == 2) { + if (hoursOfworkday.equals("")) { + logger.info("指定日期为工作日,但未传入工作日的工作时长。params=" + JSONObject.toJSONString(params)); + } + //当最小加班单位与调休单位不一致时,且指定日期为工作日时使用此工作时长进行折算 + hoursToDay = Util.getDoubleValue(hoursOfworkday, hoursToDay); + } + BigDecimal _hoursToDay = new BigDecimal("" + hoursToDay); + //把加班时长只按照分钟先处理一下 + BigDecimal min_durationOfOvertime = new BigDecimal(Util.null2s(durationOfOvertime, "0")); + if (type.equals("0")) { + } else if (type.equals("1")) { + //加班时长类型为小时---将加班分钟时长*60 + min_durationOfOvertime = min_durationOfOvertime.multiply(new BigDecimal("60")); + } else if (type.equals("2")) { + //加班时长类型为天----将加班分钟时长*一天加班小时数*60 + min_durationOfOvertime = min_durationOfOvertime.multiply(_hoursToDay).multiply(new BigDecimal("60")); + } else if (type.equals("")) { + } + BigDecimal _durationOfOvertime = new BigDecimal(Util.null2s(durationOfOvertime, "0")); + if (minimumUnit == 1 || minimumUnit == 2 || minimumUnit == 4) {//调休单位为天 + if (type.equals("0")) { + //加班时长类型为分钟、调休单位为天----将加班时长转换为天 + _durationOfOvertime = _durationOfOvertime.divide(new BigDecimal("60").multiply(_hoursToDay), 5, RoundingMode.HALF_UP); + } else if (type.equals("1")) { + //加班时长类型为小时、调休单位为天----将加班时长转换为天 + _durationOfOvertime = _durationOfOvertime.divide(_hoursToDay, 5, RoundingMode.HALF_UP); + } else if (type.equals("2")) { + //加班时长类型为天、调休单位为天----不作转换 + } else if (type.equals("")) { + //加班时长类型为空,取【加班单位】中设置的最小加班单位 + if (minimumUnitOfOvertime == 3 || minimumUnitOfOvertime== 5 || minimumUnitOfOvertime== 6) { + //最小加班单位为小时、调休单位为天----将加班时长转换为天 + _durationOfOvertime = _durationOfOvertime.divide(_hoursToDay, 5, RoundingMode.HALF_UP); + } else { + //最小加班单位为天、调休单位为天----不作转换 + } + } + } else if (KQUnitBiz.isLeaveHour(minimumUnit+"")) {//调休单位为小时 + if (type.equals("0")) { + //加班时长类型为分钟、调休单位为小时----将加班时长转换为小时 + _durationOfOvertime = _durationOfOvertime.divide(new BigDecimal("60"), 5, RoundingMode.HALF_UP); + } else if (type.equals("1")) { + //加班时长类型为小时、调休单位为小时----不作转换 + } else if (type.equals("2")) { + //加班时长类型为天、调休单位为小时----将加班时长转换为小时 + _durationOfOvertime = _durationOfOvertime.multiply(_hoursToDay).setScale(5, RoundingMode.HALF_UP); + } else if (type.equals("")) { + //加班时长类型为空,取【加班单位】中设置的最小加班单位 + if (minimumUnitOfOvertime == 3 || minimumUnitOfOvertime== 5 || minimumUnitOfOvertime== 6) { + //最小加班单位为小时、调休单位为小时----不作转换 + } else { + //最小加班单位为天、调休单位为小时----将加班时长转换为小时 + _durationOfOvertime = _durationOfOvertime.multiply(_hoursToDay).setScale(5, RoundingMode.HALF_UP); + } + } + } + logger.info("记录一下【最小加班单位】和调休的【最小请假单位】。params=" + JSONObject.toJSONString(params)); + + /*员工假期余额变更记录*/ + KQUsageHistoryBiz usageHistoryBiz = new KQUsageHistoryBiz(); + KQUsageHistoryEntity usageHistoryEntity = new KQUsageHistoryEntity(); + List usageHistoryEntityList = new ArrayList(); + + Map changeTypeMap = Maps.newHashMap(); + DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + Map overRulesDetailMap = Maps.newHashMap(); + Map> restTimeMap = Maps.newHashMap(); + Map computingModeMap = Maps.newHashMap(); + KQOverTimeRuleCalBiz kqOverTimeRuleCalBiz = new KQOverTimeRuleCalBiz(); + kqOverTimeRuleCalBiz.getOverTimeDataMap(resourceId, date, date, dateFormatter,changeTypeMap,overRulesDetailMap,restTimeMap,computingModeMap); + + Map overtimeLogMap = null; + if (otherParam != null && !otherParam.isEmpty()) { + if (otherParam.containsKey("overtimeLogMap")) { + overtimeLogMap = (Map) otherParam.get("overtimeLogMap"); + } + } + String changeType_key = date+"_"+changeType; + KQOvertimeRulesDetailEntity kqOvertimeRulesDetailEntity = overRulesDetailMap.get(changeType_key); + if(kqOvertimeRulesDetailEntity == null){ + logOvertimeMap(overtimeLogMap,changeType_key,"|加班规则为null|KQOvertimeRulesDetailEntity"); + logger.info("加班转调休记录日志保存失败。获取不到加班规则信息=" + JSONObject.toJSONString(changeType_key)); + return "-1"; + }else{ + logger.info("加班转调休记录。kqOvertimeRulesDetailEntity=" + JSONObject.toJSONString(kqOvertimeRulesDetailEntity)); + } + String timepoint_key = Util.null2String(otherParam.get("timepoint_key")); + /** + * 判断是否允许加班补偿,若未允许,则不累加调休时长,只记录记录使用记录 + * paidLeaveEnable:是否允许加班补偿:0-不允许、1-允许 + */ + String overtime_type = ""; + int paidLeaveEnable = kqOvertimeRulesDetailEntity.getPaidLeaveEnable(); + int paidLeaveEnableType = kqOvertimeRulesDetailEntity.getPaidLeaveEnableType(); + if(2 == paidLeaveEnableType){ + if(otherParam != null && !otherParam.isEmpty()){ + if(otherParam.containsKey("overtime_type")){ + overtime_type = Util.null2String(otherParam.get("overtime_type")); + if("0".equalsIgnoreCase(overtime_type)){ + paidLeaveEnable = 1; + }else if("1".equalsIgnoreCase(overtime_type)){ + paidLeaveEnable = 0; + }else{ + paidLeaveEnable = -1; + } + } + } + } + logOvertimeMap(overtimeLogMap,params,timepoint_key+"|生成调休参数|params"); + logOvertimeMap(overtimeLogMap,paidLeaveEnable,timepoint_key+"|是否生成调休|paidLeaveEnable"); + + usageHistoryEntity = new KQUsageHistoryEntity(leaveRulesId,resourceId,requestId,resourceId,currentDate,currentTime,fromCardOrFlow.equals("1") ? "3" : "4",belongYear,"0","0","0","0","0" + ,"0","0","0","0","0","0","0",""+minimumUnit,""+minimumUnit,"","-1",workflowid); + + if (paidLeaveEnable != 1) { + logger.info("未开启加班转调休,记录使用日志。params=" + JSONObject.toJSONString(params)); + /*记录使用记录*/ + usageHistoryEntity.setInsertOrUpdate("PaidLeaveEnable"); + usageHistoryEntityList.add(usageHistoryEntity); + flag = usageHistoryBiz.save(usageHistoryEntityList); + if (!flag){ + logger.info("加班转调休记录日志保存失败。params=" + JSONObject.toJSONString(params)); + } + return "-1"; + }else { + String paidLeaveEnableInfo = "paidLeaveEnable:"+paidLeaveEnable+":paidLeaveEnableType:"+paidLeaveEnableType+":overtime_type:"+overtime_type; + logOvertimeMap(overtimeLogMap,paidLeaveEnableInfo,"|未开启调休|paidLeaveEnable"); + } + + Map paidMap = Maps.newHashMap(); + paidMap.put("changeType", String.valueOf(changeType)); + paidMap.put("order", order); + if(1 == paidLeaveEnableType){ +// 默认加班补偿规则 +// 1-按加班时长比例转调休时长、2-按加班时长范围设置转调休时长、3-按加班的时间段设置转调休时长 + int paidLeaveEnableDefaultType = kqOvertimeRulesDetailEntity.getPaidLeaveEnableDefaultType(); + if(1 == paidLeaveEnableDefaultType){ + Map resultMap = save_paidLeaveEnableDefaultType1(kqOvertimeRulesDetailEntity,_durationOfOvertime,date,leaveRulesId, resourceId,belongYear,expirationDate,fromCardOrFlow,paidMap); + if(!resultMap.isEmpty()){ + return handleUsageHistory(resultMap,params,usageHistoryEntity); + } + }else if(2 == paidLeaveEnableDefaultType){ + int ruleDetailid = kqOvertimeRulesDetailEntity.getId(); + if(ruleDetailid > 0){ + Map resultMap = save_paidLeaveEnableDefaultType2(date,leaveRulesId, resourceId,belongYear,expirationDate,fromCardOrFlow,ruleDetailid,min_durationOfOvertime,minimumUnit,_hoursToDay,paidMap); + if(!resultMap.isEmpty()){ + return handleUsageHistory(resultMap,params,usageHistoryEntity); + } + } + }else if(3 == paidLeaveEnableDefaultType){ + int ruleDetailid = kqOvertimeRulesDetailEntity.getId(); + if(ruleDetailid > 0) { + if (otherParam != null && !otherParam.isEmpty()) { + if (otherParam.containsKey("OvertimeBalanceTimeBean")) { + OvertimeBalanceTimeBean overtimeBalanceTimeBean = (OvertimeBalanceTimeBean) otherParam.get("OvertimeBalanceTimeBean"); + if(overtimeBalanceTimeBean != null){ + int list_index = overtimeBalanceTimeBean.getList_index(); + if(list_index > -1) { + int timepoint_min = overtimeBalanceTimeBean.getTimepoint_mins(); + if(timepoint_min <= 0){ + logger.info("时间区间内加班生成为0。overtimeBalanceTimeBean=" + JSONObject.toJSONString(overtimeBalanceTimeBean)); + } + Map resultMap = save_paidLeaveEnableDefaultType3(date, + leaveRulesId, resourceId, belongYear, expirationDate, fromCardOrFlow, + ruleDetailid, overtimeBalanceTimeBean,list_index,minimumUnit,_hoursToDay,overtimeLogMap,timepoint_key,paidMap); + if(!resultMap.isEmpty()){ + return handleUsageHistory(resultMap,params,usageHistoryEntity); + } + }else{ + logger.info("时间区间内加班下标为-1,overtimeBalanceTimeBean=" + JSONObject.toJSONString(overtimeBalanceTimeBean)); + } + } + } + } + } + } + }else if(2 == paidLeaveEnableType){ + //根据员工在加班流程上选择的加班补偿类型进行补偿两种 +// 1-按加班时长比例转调休时长、2-按加班时长范围设置转调休时长、3-按加班的时间段设置转调休时长 + int paidLeaveEnableFlowType = kqOvertimeRulesDetailEntity.getPaidLeaveEnableFlowType(); + if(1 == paidLeaveEnableFlowType){ + Map resultMap = save_paidLeaveEnableDefaultType1(kqOvertimeRulesDetailEntity,_durationOfOvertime,date,leaveRulesId, resourceId,belongYear,expirationDate,fromCardOrFlow,paidMap); + if(!resultMap.isEmpty()){ + return handleUsageHistory(resultMap,params,usageHistoryEntity); + } + }else if(2 == paidLeaveEnableFlowType){ + int ruleDetailid = kqOvertimeRulesDetailEntity.getId(); + if(ruleDetailid > 0){ + Map resultMap = save_paidLeaveEnableDefaultType2(date,leaveRulesId, resourceId,belongYear,expirationDate,fromCardOrFlow,ruleDetailid,min_durationOfOvertime, + minimumUnit, _hoursToDay,paidMap); + if(!resultMap.isEmpty()){ + return handleUsageHistory(resultMap,params,usageHistoryEntity); + } + } + }else if(3 == paidLeaveEnableFlowType){ + int ruleDetailid = kqOvertimeRulesDetailEntity.getId(); + if(ruleDetailid > 0) { + if (otherParam != null && !otherParam.isEmpty()) { + if (otherParam.containsKey("OvertimeBalanceTimeBean")) { + OvertimeBalanceTimeBean overtimeBalanceTimeBean = (OvertimeBalanceTimeBean) otherParam.get("OvertimeBalanceTimeBean"); + if(overtimeBalanceTimeBean != null){ + int list_index = overtimeBalanceTimeBean.getList_index(); + if(list_index > -1) { + int timepoint_min = overtimeBalanceTimeBean.getTimepoint_mins(); + if(timepoint_min <= 0){ + logger.info("时间区间内加班生成为0。overtimeBalanceTimeBean=" + JSONObject.toJSONString(overtimeBalanceTimeBean)); + } + Map resultMap = save_paidLeaveEnableDefaultType3(date, + leaveRulesId, resourceId, belongYear, expirationDate, fromCardOrFlow, + ruleDetailid, overtimeBalanceTimeBean,list_index, minimumUnit, + _hoursToDay, overtimeLogMap, timepoint_key,paidMap); + if(!resultMap.isEmpty()){ + return handleUsageHistory(resultMap,params,usageHistoryEntity); + } + }else{ + logger.info("时间区间内加班下标为-1,overtimeBalanceTimeBean=" + JSONObject.toJSONString(overtimeBalanceTimeBean)); + } + } + } + } + } + } + } + } catch (Exception e) { + logger.info("加班转调休出错。params=" + JSONObject.toJSONString(params)); + new BaseBean().writeLog(e); + } + return tiaoxiuId; + } + + + /** + * 输出日志并记录假期使用记录 + * @param resultMap + * @param params + * @param usageHistoryEntity + * @return + */ + private static String handleUsageHistory(Map resultMap, Map params, KQUsageHistoryEntity usageHistoryEntity) { + + boolean flag = false; + KQUsageHistoryBiz usageHistoryBiz = new KQUsageHistoryBiz(); + List usageHistoryEntityList = new ArrayList(); + + String result_status = Util.null2String(resultMap.get("status")); + String extraAmount = Util.null2s(Util.null2String(resultMap.get("extraAmount")),"0"); + String tiaoxiuId = Util.null2String(resultMap.get("tiaoxiuId")); + if("-1".equalsIgnoreCase(result_status)){ + logger.info("加班转调休余额为0,不产生调休明细,记录使用日志。params=" + JSONObject.toJSONString(params)); + usageHistoryEntity.setInsertOrUpdate("OnlyRecordLog"); + usageHistoryEntity.setNewExtraAmount("0"); + /*记录使用记录*/ + usageHistoryEntityList.add(usageHistoryEntity); + flag = usageHistoryBiz.save(usageHistoryEntityList); + if (!flag) { + logger.info("加班转调休记录日志保存失败。params=" + JSONObject.toJSONString(params)); + } + return "-1"; + } + if("-2".equalsIgnoreCase(result_status)){ + logger.info("加班转调休保存失败。params=" + JSONObject.toJSONString(params)); + return "-1"; + } + if("1".equalsIgnoreCase(result_status)){ + usageHistoryEntity.setInsertOrUpdate("insert"); + usageHistoryEntity.setNewExtraAmount(extraAmount); + usageHistoryEntity.setBalanceOfLeaveId(tiaoxiuId); + usageHistoryEntityList.add(usageHistoryEntity); + flag = usageHistoryBiz.save(usageHistoryEntityList); + if (!flag) { + logger.info("加班转调休记录日志保存失败。params=" + JSONObject.toJSONString(params)); + } + } + return tiaoxiuId; + } + + /** + * 按加班的时间段设置转调休时长 + */ + private static Map save_paidLeaveEnableDefaultType3(String date, + String leaveRulesId, String resourceId, String belongYear, String expirationDate, + String fromCardOrFlow, int ruleDetailid, OvertimeBalanceTimeBean overtimeBalanceTimeBean, + int list_index, int minimumUnit, BigDecimal _hoursToDay, + Map overtimeLogMap, String timepoint_key, + Map paidMap) { + int changeType = Util.getIntValue(Util.null2String(paidMap.get("changeType"))); + String order = Util.null2String(paidMap.get("order")); + if(Util.getIntValue(order) <= 0){ + order = ""; + } + Map resultMap = Maps.newHashMap(); + + String tiaoxiuId = "-1"; + boolean flag = false; + RecordSet recordSet = new RecordSet(); + String extraAmount = ""; + + KQOvertimeRulesBiz kqOvertimeRulesBiz = new KQOvertimeRulesBiz(); + Map> balanceLengthDetailMap = kqOvertimeRulesBiz.getBalanceTimeDetailMap(ruleDetailid); + + int timepoint_min = overtimeBalanceTimeBean.getTimepoint_mins(); + List lenOfOvertimeList = balanceLengthDetailMap.get("lenOfOvertimeList"); + List lenOfLeaveList = balanceLengthDetailMap.get("lenOfLeaveList"); + String lenOfOvertime = lenOfOvertimeList.get(list_index); + String lenOfLeave = lenOfLeaveList.get(list_index); + + BigDecimal _timepoint_min = new BigDecimal(Util.null2s(""+timepoint_min, "0")); + BigDecimal _lenOfLeave = new BigDecimal(lenOfLeave); + BigDecimal _lenOfOvertime = new BigDecimal(lenOfOvertime); + BigDecimal durationOfLeave = _timepoint_min.multiply(_lenOfLeave).divide(_lenOfOvertime, 5, RoundingMode.HALF_UP); + + if (minimumUnit == 1 || minimumUnit == 2 || minimumUnit == 4) {//调休单位为天 + durationOfLeave = durationOfLeave.divide(new BigDecimal("60").multiply(_hoursToDay), 5, RoundingMode.HALF_UP); + + } else if (KQUnitBiz.isLeaveHour(minimumUnit+"")) {//调休单位为小时 + durationOfLeave = durationOfLeave.divide(new BigDecimal("60"), 5, RoundingMode.HALF_UP); + } + + extraAmount = durationOfLeave.setScale(5, RoundingMode.HALF_UP).toPlainString(); + String paidLeaveEnableDefaultType3 = "minimumUnit:"+minimumUnit+":durationOfLeave:"+durationOfLeave + +":_lenOfLeave:"+_lenOfLeave+":_lenOfOvertime:"+_lenOfOvertime+":_timepoint_min:"+_timepoint_min+":_hoursToDay:"+_hoursToDay; + logOvertimeMap(overtimeLogMap,paidLeaveEnableDefaultType3,timepoint_key+"|生成调休|save_paidLeaveEnableDefaultType3"); + + if (Util.getDoubleValue(extraAmount) <= 0) { + resultMap.put("status", "-1"); + return resultMap; + } + java.sql.Timestamp date1 = KQDateUtil.getUpdateTimeStamp(); + /*插入调休时长*/ + String _belongYear = date.substring(0, 4); + String _belongMonth = date.substring(5, 7); + String sql = "insert into kq_balanceOfLeave(leaveRulesId,resourceId,belongYear,belongMonth,baseAmount,tiaoxiuamount,usedAmount,baseAmount2,extraAmount2,usedAmount2,status,expirationDate,effectiveDate,overtimeType,isDelete,create_time,update_time,creator,changetype,deductorder) " + + "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + if (recordSet.getDBType().equals("postgresql")) { + sql = "insert into kq_balanceOfLeave(leaveRulesId,resourceId,belongYear,belongMonth,baseAmount,tiaoxiuamount,usedAmount,baseAmount2,extraAmount2,usedAmount2,status,expirationDate,effectiveDate,overtimeType,isDelete,create_time,update_time,creator,changetype,deductorder) " + + "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?::timestamp,?::timestamp,?,?,?)"; + } + flag = recordSet.executeUpdate(sql, leaveRulesId, resourceId, _belongYear, _belongMonth, 0, extraAmount, 0, 0, 0, 0, 0, expirationDate, date, fromCardOrFlow.equals("0") ? "3" : "4", 0,date1,date1,Util.getIntValue(resourceId),changeType,order); + if (!flag) { + resultMap.put("status", "-2"); + return resultMap; + } + //获取刚才插入的调休明细的ID + sql = "select max(id) from kq_balanceOfLeave where leaveRulesId=? and resourceId=? and belongYear=?"; + recordSet.executeQuery(sql, leaveRulesId, resourceId, belongYear); + if (recordSet.next()) { + tiaoxiuId = recordSet.getString(1); + } + resultMap.put("status", "1"); + resultMap.put("tiaoxiuId", tiaoxiuId); + resultMap.put("extraAmount", extraAmount); + return resultMap; + } + + /** + * 按加班时长范围设置转调休时长 + */ + private static Map save_paidLeaveEnableDefaultType2( + String date, String leaveRulesId, String resourceId, + String belongYear, String expirationDate, String fromCardOrFlow, int ruleDetailid, + BigDecimal min_durationOfOvertime, int minimumUnit, BigDecimal _hoursToDay, + Map paidMap) { + int changeType = Util.getIntValue(Util.null2String(paidMap.get("changeType"))); + String order = Util.null2String(paidMap.get("order")); + if(Util.getIntValue(order) <= 0){ + order = ""; + } + Map resultMap = Maps.newHashMap(); + + String tiaoxiuId = "-1"; + boolean flag = false; + RecordSet recordSet = new RecordSet(); + String extraAmount = ""; + + int overtimelength_i = -1; + KQOvertimeRulesBiz kqOvertimeRulesBiz = new KQOvertimeRulesBiz(); + Map> balanceLengthDetailMap = kqOvertimeRulesBiz.getBalanceLengthDetailMap(ruleDetailid); + if(balanceLengthDetailMap != null && !balanceLengthDetailMap.isEmpty()){ + List overtimelengthList = balanceLengthDetailMap.get("overtimelengthList"); + for(int i = 0 ; i < overtimelengthList.size() ; i++){ + String overtimelength = Util.null2s(overtimelengthList.get(i),""); + if(overtimelength.length() == 0){ + continue; + } + BigDecimal b_60Mins = new BigDecimal(60); + BigDecimal b_overtimelength = new BigDecimal(overtimelength).multiply(b_60Mins); + if(min_durationOfOvertime.compareTo(b_overtimelength) >= 0){ + overtimelength_i = i; + break; + } + } + if(overtimelength_i > -1){ + List balancelengthList = balanceLengthDetailMap.get("balancelengthList"); + if(balancelengthList.size() > overtimelength_i){ + String balancelength = balancelengthList.get(overtimelength_i); + BigDecimal b_balancelength = new BigDecimal(balancelength); + if (minimumUnit == 1 || minimumUnit == 2 || minimumUnit == 4) {//调休单位为天 + b_balancelength = b_balancelength.divide(_hoursToDay, 5, RoundingMode.HALF_UP); + + } else if (KQUnitBiz.isLeaveHour(minimumUnit+"")) {//调休单位为小时 + } + extraAmount = Util.null2s(b_balancelength.toPlainString(), "0"); + } + } + } + new KQLog().info("save_paidLeaveEnableDefaultType2 balanceLengthDetailMap:"+balanceLengthDetailMap + +":min_durationOfOvertime:"+min_durationOfOvertime+":extraAmount:"+extraAmount); + + if (Util.getDoubleValue(extraAmount) <= 0) { + extraAmount = "0.0"; + } + if(overtimelength_i < 0){ + extraAmount = "0.0"; + } + java.sql.Timestamp date1 = KQDateUtil.getUpdateTimeStamp(); + /*插入调休时长*/ + String _belongYear = date.substring(0, 4); + String _belongMonth = date.substring(5, 7); + String sql = "insert into kq_balanceOfLeave(leaveRulesId,resourceId,belongYear,belongMonth,baseAmount,tiaoxiuamount,usedAmount,baseAmount2,extraAmount2,usedAmount2,status,expirationDate,effectiveDate,overtimeType,isDelete,create_time,update_time,creator,changetype,deductorder) " + + "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + if (recordSet.getDBType().equals("postgresql")) { + sql = "insert into kq_balanceOfLeave(leaveRulesId,resourceId,belongYear,belongMonth,baseAmount,tiaoxiuamount,usedAmount,baseAmount2,extraAmount2,usedAmount2,status,expirationDate,effectiveDate,overtimeType,isDelete,create_time,update_time,creator,changetype,deductorder) " + + "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?::timestamp,?::timestamp,?,?,?)"; + } + flag = recordSet.executeUpdate(sql, leaveRulesId, resourceId, _belongYear, _belongMonth, 0, extraAmount, 0, 0, 0, 0, 0, expirationDate, date, fromCardOrFlow.equals("0") ? "3" : "4", 0,date1,date1,Util.getIntValue(resourceId),changeType,order); + if (!flag) { + resultMap.put("status", "-2"); + return resultMap; + } + //获取刚才插入的调休明细的ID + sql = "select max(id) from kq_balanceOfLeave where leaveRulesId=? and resourceId=? and belongYear=?"; + recordSet.executeQuery(sql, leaveRulesId, resourceId, belongYear); + if (recordSet.next()) { + tiaoxiuId = recordSet.getString(1); + } + resultMap.put("status", "1"); + resultMap.put("tiaoxiuId", tiaoxiuId); + resultMap.put("extraAmount", extraAmount); + return resultMap; + } + + /** + * 按加班时长比例转调休时长 + */ + private static Map save_paidLeaveEnableDefaultType1( + KQOvertimeRulesDetailEntity kqOvertimeRulesDetailEntity, + BigDecimal _durationOfOvertime, String date, String leaveRulesId, String resourceId, + String belongYear, String expirationDate, String fromCardOrFlow, + Map paidMap) { + int changeType = Util.getIntValue(Util.null2String(paidMap.get("changeType"))); + String order = Util.null2String(paidMap.get("order")); + if(Util.getIntValue(order) <= 0){ + order = ""; + } + Map resultMap = Maps.newHashMap(); + + String tiaoxiuId = "-1"; + boolean flag = false; + RecordSet recordSet = new RecordSet(); + String extraAmount = ""; + /** + * 计算调休时长并存入调休余额中 + */ + BigDecimal _lenOfLeave = new BigDecimal("" + kqOvertimeRulesDetailEntity.getLenOfLeave()); + BigDecimal _lenOfOvertime = new BigDecimal("" + kqOvertimeRulesDetailEntity.getLenOfOvertime()); + BigDecimal durationOfLeave = _durationOfOvertime.multiply(_lenOfLeave).divide(_lenOfOvertime, 5, RoundingMode.HALF_UP); + extraAmount = durationOfLeave.setScale(5, RoundingMode.HALF_UP).toPlainString(); + + if (durationOfLeave.doubleValue() <= 0) { + extraAmount = "0.0"; + } + java.sql.Timestamp date1 = KQDateUtil.getUpdateTimeStamp(); + /*插入调休时长*/ + String _belongYear = date.substring(0, 4); + String _belongMonth = date.substring(5, 7); + String sql = "insert into kq_balanceOfLeave(leaveRulesId,resourceId,belongYear,belongMonth,baseAmount,tiaoxiuamount,usedAmount,baseAmount2,extraAmount2,usedAmount2,status,expirationDate,effectiveDate,overtimeType,isDelete,create_time,update_time,creator,changetype,deductorder) " + + "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + if (recordSet.getDBType().equals("postgresql")) { + sql = "insert into kq_balanceOfLeave(leaveRulesId,resourceId,belongYear,belongMonth,baseAmount,tiaoxiuamount,usedAmount,baseAmount2,extraAmount2,usedAmount2,status,expirationDate,effectiveDate,overtimeType,isDelete,create_time,update_time,creator,changetype,deductorder) " + + "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?::timestamp,?::timestamp,?,?,?)"; + } + flag = recordSet.executeUpdate(sql, leaveRulesId, resourceId, _belongYear, _belongMonth, 0, extraAmount, 0, 0, 0, 0, 0, expirationDate, date, fromCardOrFlow.equals("0") ? "3" : "4", 0,date1,date1,Util.getIntValue(resourceId),changeType,order); + if (!flag) { + resultMap.put("status", "-2"); + return resultMap; + } + //获取刚才插入的调休明细的ID + sql = "select max(id) from kq_balanceOfLeave where leaveRulesId=? and resourceId=? and belongYear=?"; + recordSet.executeQuery(sql, leaveRulesId, resourceId, belongYear); + if (recordSet.next()) { + tiaoxiuId = recordSet.getString(1); + } + resultMap.put("status", "1"); + resultMap.put("tiaoxiuId", tiaoxiuId); + resultMap.put("extraAmount", extraAmount); + return resultMap; + } + + /** + * 根据员工假期余额的ID + * + * @param balanceOfLeaveId 调休余额的ID + * @param durationOfOvertime 加班时长,默认为分钟 + * @return + */ + public static boolean updateExtraAmountByDis5(String balanceOfLeaveId, double durationOfOvertime, String requestId) { + boolean result = false; + try { + if (balanceOfLeaveId == null && !balanceOfLeaveId.equals("")) { + logger.info("传入的员工假期余额ID为空。"); + logger.info("balanceOfLeaveId=" + balanceOfLeaveId + ",newExtraAmount=" + durationOfOvertime + ",requestId=" + requestId); + return false; + } + String workflowid = "-1"; + RecordSet rs = new RecordSet(); + if(requestId.length() > 0 && Util.getIntValue(requestId) > 0){ + String workflow_sql = "select workflowid from workflow_requestbase where requestid = ? "; + rs.executeQuery(workflow_sql, requestId); + if(rs.next()){ + workflowid = Util.null2s(rs.getString("workflowid"),"-1"); + } + } + + //获取当前日期,当前时间 + Calendar today = Calendar.getInstance(); + //当前日期 + String currentDate = Util.add0(today.get(Calendar.YEAR), 4) + "-" + + Util.add0(today.get(Calendar.MONTH) + 1, 2) + "-" + + Util.add0(today.get(Calendar.DAY_OF_MONTH), 2); + //当前时间 + String currentTime = Util.add0(today.get(Calendar.HOUR_OF_DAY), 2) + ":" + + Util.add0(today.get(Calendar.MINUTE), 2) + ":" + + Util.add0(today.get(Calendar.SECOND), 2); + + //假期类型的缓存类 + KQLeaveRulesComInfo rulesComInfo = new KQLeaveRulesComInfo(); + + //add + ResourceComInfo resourceComInfo1 = null; + String resourceId1 = ""; + try { + resourceComInfo1 = new ResourceComInfo(); + } catch (Exception e) { + e.printStackTrace(); + } + RecordSet rs1 = new RecordSet(); + String sql1 = "select * from KQ_BalanceOfLeave where id=?"; + rs1.executeQuery(sql1, balanceOfLeaveId); + if (rs1.next()) { + String id = rs1.getString("id"); + resourceId1 = rs1.getString("resourceId"); + } + //分部ID + String subCompanyId = resourceComInfo1.getSubCompanyID(resourceId1); + String departmentId = resourceComInfo1.getDepartmentID(resourceId1); + //[调休]的假期类型的ID + String leaveRulesId = ""; + //找到[调休]的假期类型ID + rulesComInfo.setTofirstRow(); + while (rulesComInfo.next()) { + if (KQLeaveRulesBiz.isTiaoXiu(rulesComInfo.getId(),subCompanyId,departmentId,resourceId1)) { + leaveRulesId = rulesComInfo.getId(); + break; + } + } + //[调休]的假期类型的最小请假单位:1-按天、2-按半天、3-按小时、4-按整天 + int minimumUnit = Util.getIntValue(rulesComInfo.getMinimumUnit(leaveRulesId), 3); + + /****************************************************************************************************************/ + + //加班单位中的日折算时长 + double hoursToDay = 8.00; + String overtimeSql = "select * from kq_OvertimeUnit where (isDelete is null or isDelete !=1) and id=1"; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(overtimeSql); + if (recordSet.next()) { + hoursToDay = Util.getDoubleValue(recordSet.getString("hoursToDay"), 8.00); + } + + /****************************************************************************************************************/ + + BigDecimal _hoursToDay = new BigDecimal("" + hoursToDay); + BigDecimal _durationOfOvertime = new BigDecimal("" + durationOfOvertime); + if (minimumUnit == 1 || minimumUnit == 2 || minimumUnit == 4) {//调休单位为天 + //加班时长类型为分钟、调休单位为天----将加班时长转换为天 + _durationOfOvertime = _durationOfOvertime.divide(new BigDecimal("60").multiply(_hoursToDay), 5, RoundingMode.HALF_UP); + } else if (KQUnitBiz.isLeaveHour(minimumUnit+"")) {//调休单位为小时 + //加班时长类型为分钟、调休单位为小时----将加班时长转换为小时 + _durationOfOvertime = _durationOfOvertime.divide(new BigDecimal("60"), 5, RoundingMode.HALF_UP); + } + logger.info("记录一下需要重新生成调休时长的调休时长。"); + logger.info("balanceOfLeaveId=" + balanceOfLeaveId + ",newExtraAmount=" + durationOfOvertime + ",requestId=" + requestId + ",_durationOfOvertime=" + _durationOfOvertime.doubleValue()); + + boolean flag = true; + KQUsageHistoryBiz kqUsageHistoryBiz = new KQUsageHistoryBiz(); + KQUsageHistoryEntity kqUsageHistoryEntity = new KQUsageHistoryEntity(); + List kqUsageHistoryEntities = new ArrayList<>(); + + String sql = "select * from KQ_BalanceOfLeave where id=?"; + recordSet.executeQuery(sql, balanceOfLeaveId); + if (recordSet.next()) { + String id = recordSet.getString("id"); + String resourceId = recordSet.getString("resourceId"); + String belongYear = recordSet.getString("belongYear"); + String belongMonth = recordSet.getString("belongMonth"); + String baseAmount = recordSet.getString("baseAmount"); + String extraAmount = recordSet.getString("extraAmount"); + String usedAmount = recordSet.getString("usedAmount"); + String effectiveDate = recordSet.getString("effectiveDate"); + String expirationDate = recordSet.getString("expirationDate"); + + //根据加班时长以及转换比例得出调休时长 + BigDecimal _lenOfLeave = new BigDecimal("" + KQOvertimeRulesBiz.getLenOfLeave(resourceId, effectiveDate)); + BigDecimal _lenOfOvertime = new BigDecimal("" + KQOvertimeRulesBiz.getLenOfOvertime(resourceId, effectiveDate)); + BigDecimal durationOfLeave = _durationOfOvertime.multiply(_lenOfLeave).divide(_lenOfOvertime, 5, RoundingMode.HALF_UP); + + sql = "update KQ_BalanceOfLeave set extraAmount=?,update_time=? where id=?"; + if (recordSet.getDBType().equals("postgresql")) { + sql = "update KQ_BalanceOfLeave set extraAmount=?,update_time=?::timestamp where id=?"; + } + result = recordSet.executeUpdate(sql, durationOfLeave.setScale(5, RoundingMode.HALF_UP).doubleValue(), KQDateUtil.getUpdateTimeStamp(), id); + if (result) { + kqUsageHistoryEntities = new ArrayList<>(); + kqUsageHistoryEntity = new KQUsageHistoryEntity(leaveRulesId, resourceId, requestId, resourceId, currentDate, currentTime, "8", belongYear, baseAmount, baseAmount, extraAmount, durationOfLeave.setScale(5, RoundingMode.HALF_UP).toPlainString(), usedAmount + , usedAmount, "0", "0", "0", "0", "0", "0", "" + minimumUnit, "" + minimumUnit, "update", id,workflowid); + kqUsageHistoryEntities.add(kqUsageHistoryEntity); + kqUsageHistoryBiz.save(kqUsageHistoryEntities); + } else { + logger.info("加班重新生成调休,员工假期余额更新失败。"); + logger.info("balanceOfLeaveId=" + balanceOfLeaveId + ",newExtraAmount=" + durationOfOvertime + ",requestId=" + requestId + ",_durationOfOvertime=" + durationOfLeave.doubleValue()); + return false; + } + } else { + logger.info("未找到对应的员工假期余额。"); + logger.info("balanceOfLeaveId=" + balanceOfLeaveId + ",newExtraAmount=" + durationOfOvertime + ",requestId=" + requestId); + return false; + } + } catch (Exception e) { + new BaseBean().writeLog(e); + } + return result; + } + + public static String getDeductOrder(String changetype,String ruledetailid){ + RecordSet recordSet = new RecordSet(); + String deductorder = "-1"; + if(Util.null2String(ruledetailid).length() == 0 || Util.null2String(changetype).length() == 0){ + recordSet.writeLog("getDeductOrder.changetype="+changetype+",ruledetailid="+ruledetailid); + return deductorder; + } + String sql = "select ruleId,ruleName,scopeType,scopeValue,distributionMode,deductorder from kq_LeaveRulesDetail where id = '"+ruledetailid+"'"; + recordSet.executeQuery(sql); + if(recordSet.next()){ + String tmp_order = Util.null2String(recordSet.getString("deductorder")); + if(tmp_order.length()>0){ + String[] orders = tmp_order.split(","); + if(null != orders && orders.length>0){ + for (int i = 0; i < orders.length; i++) { + if(orders[i].equals(changetype) && i==0){ + deductorder = "1"; + }else if(orders[i].equals(changetype) && i==1){ + deductorder = "2"; + }else if(orders[i].equals(changetype) && i==2){ + deductorder = "3"; + } + } + } + } + } + recordSet.writeLog("getDeductOrder.changetype="+changetype+",ruledetailid="+ruledetailid+",deductorder="+deductorder+",sql="+sql); + + return deductorder; + } + + /** + * 累加已用的假期时长 + * + * @param resourceId 指定人员ID + * @param date 请假日期(目前请假扣减逻辑:如果请假跨了多天,会拆分成一天一天扣减) + * @param ruleId 指定假期规则 + * @param duration 请假时长 + * @param type 时长类型:0-分钟、1-小时、2-天 + * 传入空值则默认取假期规则设置中的单位 + * @param fromDateDb 请假流程表单中的请假开始日期(根据请假开始日期判断假期余额是否有效) + * @param requestId 请假流程的requestId + */ + public static void addUsedAmount(String resourceId, String date, String ruleId, String duration, String type, String requestId, String fromDateDb) { + try { + if(Util.getDoubleValue(duration) <= 0) { + logger.info("请假时长为0不做扣减。resourceId=" + resourceId + ",date=" + date + ",ruleId=" + ruleId + ",type=" + type + ",duration=" + duration + ",requestId=" + requestId); + return; + } + java.sql.Timestamp updateDate = KQDateUtil.getUpdateTimeStamp(); + /*获取当前日期,当前时间*/ + Calendar today = Calendar.getInstance(); + String currentDate = Util.add0(today.get(Calendar.YEAR), 4) + "-" + + Util.add0(today.get(Calendar.MONTH) + 1, 2) + "-" + + Util.add0(today.get(Calendar.DAY_OF_MONTH), 2); + String currentTime = Util.add0(today.get(Calendar.HOUR_OF_DAY), 2) + ":" + + Util.add0(today.get(Calendar.MINUTE), 2) + ":" + + Util.add0(today.get(Calendar.SECOND), 2); + + /****************************************************************************************************************/ + + //人力资源缓存类 + ResourceComInfo resourceComInfo = new ResourceComInfo(); + //分部ID + String subcompanyId = resourceComInfo.getSubCompanyID(resourceId); + String departmentId = resourceComInfo.getDepartmentID(resourceId); + /****************************************************************************************************************/ + + //假期类型缓存类 + KQLeaveRulesComInfo rulesComInfo = new KQLeaveRulesComInfo(); + //最小请假单位:1-按天请假、2-按半天请假、3-按小时请假、4-按整天请假 + int minimumUnit = Util.getIntValue(rulesComInfo.getMinimumUnit(ruleId)); + //最小请假单位获取有误,记录错误日志,直接退出方法 + if (minimumUnit < 1 || minimumUnit > 6) { + logger.info("最小请假单位获取有误。resourceId=" + resourceId + ",date=" + date + ",ruleId=" + ruleId + ",type=" + type + ",duration=" + duration + ",requestId=" + requestId); + return; + } + //是否启用假期余额:0-不启用、1-启用 + int balanceEnable = Util.getIntValue(rulesComInfo.getBalanceEnable(ruleId), 0); + //该假期未开启假期余额,记录错误日志,退出方法 + if (balanceEnable != 1) { + logger.info("该假期未开启假期余额。resourceId=" + resourceId + ",date=" + date + ",ruleId=" + ruleId + ",type=" + type + ",duration=" + duration + ",requestId=" + requestId); + return; + } + //前台传回的请假时长类型与后台设置的假期限制的最小请假单位不相符,暂不支持转换,记录错误日志,直接退出方法 + boolean flag = type.equals("") || ("1".equals(type) && KQUnitBiz.isLeaveHour(minimumUnit+"")) || ("2".equals(type) && (minimumUnit == 1 || minimumUnit == 2 || minimumUnit == 4)); + if (!flag) { + logger.info("前台传回的请假时长类型与后台设置的请假类型限制的最小请假单位不相符。" + + "resourceId=" + resourceId + ",date=" + date + ",ruleId=" + ruleId + ",type=" + type + ",duration=" + duration + ",requestId=" + requestId); + return; + } + + /****************************************************************************************************************/ + + //假期规则缓存类(每个假期类型下可能存在多个假期规则) + KQLeaveRulesDetailComInfo detailComInfo = new KQLeaveRulesDetailComInfo(); + //余额发放方式:1-手动发放、2-按司龄自动发放、3-按工龄自动发放、4-每年自动发放固定天数、5-加班时长自动计入余额、6-按入职时长+工龄自动发放 + int distributionMode = Util.getIntValue(detailComInfo.getDistributionMode(ruleId, subcompanyId, departmentId, resourceId)); + //扣减优先级:1-法定年假、2-福利年假 + int priority = Util.getIntValue(detailComInfo.getPriority(ruleId, subcompanyId, departmentId, resourceId), 1); + + /****************************************************************************************************************/ + + //如果请假开始日期为空,默认取请假日期 + fromDateDb = date; + + boolean istiaoxiu = false; + + + //员工假期余额变更记录 + KQUsageHistoryEntity usageHistoryEntity = new KQUsageHistoryEntity(); + List usageHistoryEntityList = new ArrayList(); + + List updateList = new ArrayList(); + BigDecimal _duration = new BigDecimal(Util.null2s(duration, "0")); + RecordSet recordSet = new RecordSet(); + String sql = "select * from kq_balanceOfLeave where (isDelete is null or isDelete<>1) and leaveRulesId=" + ruleId + " and resourceId=" + resourceId + " order by belongYear"; + if (distributionMode == 5) { + istiaoxiu = true; + if (recordSet.getDBType().equalsIgnoreCase("sqlserver") + || recordSet.getDBType().equalsIgnoreCase("mysql")) { + sql = " select * from kq_balanceOfLeave " + + " where (isDelete is null or isDelete<>1) and resourceId=" + resourceId + " and leaveRulesId=" + ruleId + " and (expirationDate is null or expirationDate='' or expirationDate>='" + fromDateDb + "') " + + " order by deductorder asc,belongYear asc,expirationDate asc,id asc "; + } else { + sql = " select * from kq_balanceOfLeave " + + " where (isDelete is null or isDelete<>1) and resourceId=" + resourceId + " and leaveRulesId=" + ruleId + " and (expirationDate is null or expirationDate>='" + fromDateDb + "') " + + " order by deductorder asc,belongYear asc,expirationDate asc,id asc "; + } + } + // 如果是育儿假 + boolean leaveOfParental = KQLeaveRulesBiz.isLeaveOfParentalNum(ruleId); + if(leaveOfParental){ + sql = " select * from kq_balanceOfLeave " + + " where (isDelete is null or isDelete<>1) and resourceId=" + resourceId + " and leaveRulesId=" + ruleId + " and (expirationDate is null or expirationDate='' or expirationDate>='" + fromDateDb + "') " + + " order by belongYear asc,expirationDate asc,id asc "; + } + new BaseBean().writeLog("==查询的sql==selectsql:"+sql); + recordSet.executeQuery(sql); + int total = recordSet.getCounts(); + int index = 0; + KQSettingsComInfo kqSettingsComInfo = new KQSettingsComInfo(); + String allow_negative = Util.null2String(kqSettingsComInfo.getMain_val("allow_negative"),"0"); + boolean allow_negative_flag = "1".equals(allow_negative); + int indexStatus = 0; + while (recordSet.next()) { + index++; + // + String id = recordSet.getString("id"); + //所属年份 + String belongYear = recordSet.getString("belongYear"); + //失效日期 + String expirationDate = recordSet.getString("expirationDate"); + //生效日期 + String effectiveDate = recordSet.getString("effectiveDate"); + //判断假期余额是否失效 + boolean status = getBalanceStatus(ruleId, resourceId, belongYear, fromDateDb, effectiveDate, expirationDate); + if (!status) { + //如果是调休+开启了负数+最后一行 + if(allow_negative_flag && index == total){ + indexStatus = 1; + } + continue; + } + + + String changetype = Util.null2String(recordSet.getString("changetype")); + //基数 + BigDecimal baseAmount = new BigDecimal(Util.null2s(recordSet.getString("baseAmount"), "0")); + //额外 + BigDecimal extraAmount = new BigDecimal(Util.null2s(recordSet.getString("extraAmount"), "0")); + + //加班生成调休 + BigDecimal tiaoxiuAmount = new BigDecimal(Util.null2s(recordSet.getString("tiaoxiuamount"), "0")); + //已休 + BigDecimal usedAmount = new BigDecimal(Util.null2s(recordSet.getString("usedAmount"), "0")); + //福利年假的基数 + BigDecimal baseAmount2 = new BigDecimal(Util.null2s(recordSet.getString("baseAmount2"), "0")); + //福利年假的额外 + BigDecimal usedAmount2 = new BigDecimal(Util.null2s(recordSet.getString("usedAmount2"), "0")); + //福利年假的已休 + BigDecimal extraAmount2 = new BigDecimal(Util.null2s(recordSet.getString("extraAmount2"), "0")); + if (distributionMode == 6) { + if (baseAmount.add(extraAmount).add(tiaoxiuAmount).subtract(usedAmount).add(baseAmount2).add(extraAmount2).subtract(usedAmount2).doubleValue() <= 0) { + if(!(allow_negative_flag && index == total)){ + continue; + } + } + + baseAmount = getCanUseAmount(resourceId, ruleId, belongYear, baseAmount, "legal", fromDateDb); + baseAmount2 = getCanUseAmount(resourceId, ruleId, belongYear, baseAmount2, "welfare", fromDateDb); + } else if(distributionMode == 5||leaveOfParental){ + //不过滤前端会有扣减为0的记录 + if (baseAmount.add(extraAmount).add(tiaoxiuAmount).subtract(usedAmount).doubleValue() <= 0) { + if(!(allow_negative_flag && index == total)) { + continue; + } + } + } else{ + if (baseAmount.add(extraAmount).add(tiaoxiuAmount).subtract(usedAmount).doubleValue() <= 0) { + if(!(allow_negative_flag && index == total)) { + continue; + } + } + baseAmount = getCanUseAmount(resourceId, ruleId, belongYear, baseAmount, "", fromDateDb); + } + + logger.info("addusedamount.id="+id+",indexStatus="+indexStatus+",baseAmount="+baseAmount+",baseAmount2="+baseAmount2+",distributionMode="+distributionMode+",extraAmount="+extraAmount+",usedAmount="+usedAmount); + + //员工假期余额使用记录 + usageHistoryEntity = new KQUsageHistoryEntity(); + usageHistoryEntity.setLeaveRulesId(ruleId); + usageHistoryEntity.setRelatedId(resourceId); + usageHistoryEntity.setWfRequestId(requestId); + usageHistoryEntity.setOperator(resourceId); + usageHistoryEntity.setOperateDate(currentDate); + usageHistoryEntity.setOperateTime(currentTime); + usageHistoryEntity.setOperateType("1"); + usageHistoryEntity.setInsertOrUpdate("update"); + usageHistoryEntity.setBelongYear(belongYear); + usageHistoryEntity.setOldUsedAmount(usedAmount.setScale(5, RoundingMode.HALF_UP).toPlainString()); + usageHistoryEntity.setOldUsedAmount2(usedAmount2.setScale(5, RoundingMode.HALF_UP).toPlainString()); + usageHistoryEntity.setOldMinimumUnit("" + minimumUnit); + usageHistoryEntity.setNewMinimumUnit("" + minimumUnit); + usageHistoryEntityList.add(usageHistoryEntity); + + if (distributionMode == 6) {//如果年假为混合模式(法定年假+福利年假) + if (priority == 1) {//扣减优先级:先扣减法定年假、再扣减福利年假 + BigDecimal temp = baseAmount.add(extraAmount).subtract(usedAmount).subtract(_duration); + if (temp.doubleValue() >= 0) { + String newUsedAmount = usedAmount.add(_duration).setScale(5, RoundingMode.HALF_UP).toPlainString(); + String updateSql = "update kq_balanceOfLeave set usedAmount=" + (newUsedAmount) + ", update_time=? where id=" + id; + updateList.add(updateSql); + + usageHistoryEntity.setNewUsedAmount(newUsedAmount); + usageHistoryEntity.setBalanceOfLeaveId(id); + + //请假时长扣减完了重置下,以免影响下面的新增逻辑 + _duration = new BigDecimal("0"); + break; + } else { + temp = baseAmount.add(extraAmount).subtract(usedAmount).add(baseAmount2).add(extraAmount2).subtract(usedAmount2).subtract(_duration); + //该假期剩余假期余额不足以扣减,记录错误日志,退出方法 + if (index == total && temp.doubleValue() < 0) { + logger.info("该人员的该假期所有的剩余假期余额都不足以扣减。" + + "resourceId=" + resourceId + ",date=" + date + ",ruleId=" + ruleId + ",type=" + type + ",duration=" + duration + ",requestId=" + requestId + + ",baseAmount=" + baseAmount.doubleValue() + ",extraAmount=" + extraAmount.doubleValue() + ",usedAmount=" + usedAmount.doubleValue() + + ",baseAmount2=" + baseAmount2.doubleValue() + ",extraAmount2=" + extraAmount2.doubleValue() + ",usedAmount2=" + usedAmount2.doubleValue()); + String newUsedAmount = baseAmount.add(extraAmount).setScale(5,RoundingMode.HALF_UP).toPlainString(); + String newUsedAmount2 = _duration.subtract(baseAmount.add(extraAmount).subtract(usedAmount)).add(usedAmount2).setScale(5, RoundingMode.HALF_UP).toString(); + String updateSql = "update kq_balanceOfLeave set usedAmount=" + (newUsedAmount) + ",usedAmount2=" + (newUsedAmount2) + ", update_time=? where id=" + id; + updateList.add(updateSql); + + usageHistoryEntity.setNewUsedAmount(newUsedAmount); + usageHistoryEntity.setNewUsedAmount2(newUsedAmount2); + usageHistoryEntity.setBalanceOfLeaveId(id); + + //请假时长扣减完了重置下,以免影响下面的新增逻辑 + _duration = new BigDecimal("0"); + break; + } + if (temp.doubleValue() >= 0) { + String newUsedAmount = baseAmount.add(extraAmount).setScale(5, RoundingMode.HALF_UP).toPlainString(); + String newUsedAmount2 = _duration.subtract(baseAmount.add(extraAmount).subtract(usedAmount)).add(usedAmount2).setScale(5, RoundingMode.HALF_UP).toString(); + String updateSql = "update kq_balanceOfLeave set usedAmount=" + (newUsedAmount) + ",usedAmount2=" + (newUsedAmount2) + ", update_time=? where id=" + id; + updateList.add(updateSql); + + usageHistoryEntity.setNewUsedAmount(newUsedAmount); + usageHistoryEntity.setNewUsedAmount2(newUsedAmount2); + usageHistoryEntity.setBalanceOfLeaveId(id); + + //请假时长扣减完了重置下,以免影响下面的新增逻辑 + _duration = new BigDecimal("0"); + break; + } else { + _duration = new BigDecimal("0").subtract(temp); + String newUsedAmount = baseAmount.add(extraAmount).setScale(5, RoundingMode.HALF_UP).toPlainString(); + String newUsedAmount2 = baseAmount2.add(extraAmount2).setScale(5, RoundingMode.HALF_UP).toPlainString(); + String updateSql = "update kq_balanceOfLeave set usedAmount=" + (newUsedAmount) + ",usedAmount2=" + (newUsedAmount2) + ", update_time=? where id=" + id; + updateList.add(updateSql); + + usageHistoryEntity.setNewUsedAmount(newUsedAmount); + usageHistoryEntity.setNewUsedAmount2(newUsedAmount2); + usageHistoryEntity.setBalanceOfLeaveId(id); + continue; + } + } + } else {//扣减优先级:先扣减福利年假、再扣减法定年假 + BigDecimal temp = baseAmount2.add(extraAmount2).subtract(usedAmount2).subtract(_duration); + if (temp.doubleValue() >= 0) { + String newUsedAmount2 = usedAmount2.add(_duration).setScale(5, RoundingMode.HALF_UP).toPlainString(); + String updateSql = "update kq_balanceOfLeave set usedAmount2=" + (newUsedAmount2) + ", update_time=? where id=" + id; + updateList.add(updateSql); + + usageHistoryEntity.setNewUsedAmount2(newUsedAmount2); + usageHistoryEntity.setBalanceOfLeaveId(id); + break; + } else { + temp = baseAmount2.add(extraAmount2).subtract(usedAmount2).add(baseAmount).add(extraAmount).subtract(usedAmount).subtract(_duration); + /*该假期剩余假期余额不足以扣减,记录错误日志,退出方法*/ + if (index == total && temp.doubleValue() < 0) { + logger.info("该人员的该假期所有的剩余假期余额都不足以扣减。" + + "resourceId=" + resourceId + ",date=" + date + ",ruleId=" + ruleId + ",type=" + type + ",duration=" + duration + ",requestId=" + requestId + + ",baseAmount=" + baseAmount.doubleValue() + ",extraAmount=" + extraAmount.doubleValue() + ",usedAmount=" + usedAmount.doubleValue() + + ",baseAmount2=" + baseAmount2.doubleValue() + ",extraAmount2=" + extraAmount2.doubleValue() + ",usedAmount2=" + usedAmount2.doubleValue()); + String newUsedAmount2 = baseAmount2.add(extraAmount2).setScale(5, RoundingMode.HALF_UP).toPlainString(); + String newUsedAmount = _duration.subtract(baseAmount2.add(extraAmount2).subtract(usedAmount2)).add(usedAmount).setScale(5, RoundingMode.HALF_UP).toPlainString(); + String updateSql = "update kq_balanceOfLeave set usedAmount2=" + (newUsedAmount2) + ",usedAmount=" + (newUsedAmount) + ", update_time=? where id=" + id; + updateList.add(updateSql); + + usageHistoryEntity.setNewUsedAmount2(newUsedAmount2); + usageHistoryEntity.setNewUsedAmount(newUsedAmount); + usageHistoryEntity.setBalanceOfLeaveId(id); + + //请假时长扣减完了重置下,以免影响下面的新增逻辑 + _duration = new BigDecimal("0"); + break; + } + if (temp.doubleValue() >= 0) { + String newUsedAmount2 = baseAmount2.add(extraAmount2).setScale(5, RoundingMode.HALF_UP).toPlainString(); + String newUsedAmount = _duration.subtract(baseAmount2.add(extraAmount2).subtract(usedAmount2)).add(usedAmount).setScale(5, RoundingMode.HALF_UP).toPlainString(); + String updateSql = "update kq_balanceOfLeave set usedAmount2=" + (newUsedAmount2) + ",usedAmount=" + (newUsedAmount) + ", update_time=? where id=" + id; + updateList.add(updateSql); + + usageHistoryEntity.setNewUsedAmount2(newUsedAmount2); + usageHistoryEntity.setNewUsedAmount(newUsedAmount); + usageHistoryEntity.setBalanceOfLeaveId(id); + + //请假时长扣减完了重置下,以免影响下面的新增逻辑 + _duration = new BigDecimal("0"); + break; + } else { + _duration = new BigDecimal("0").subtract(temp); + String newUsedAmount2 = baseAmount2.add(extraAmount2).setScale(5, RoundingMode.HALF_UP).toPlainString(); + String newUsedAmount = baseAmount.add(extraAmount).setScale(5, RoundingMode.HALF_UP).toPlainString(); + String updateSql = "update kq_balanceOfLeave set usedAmount2=" + (newUsedAmount2) + ",usedAmount=" + (newUsedAmount) + ", update_time=? where id=" + id; + updateList.add(updateSql); + + usageHistoryEntity.setNewUsedAmount2(newUsedAmount2); + usageHistoryEntity.setNewUsedAmount(newUsedAmount); + usageHistoryEntity.setBalanceOfLeaveId(id); + continue; + } + } + } + } else {//非混合模式 + BigDecimal temp = baseAmount.add(extraAmount).add(tiaoxiuAmount).subtract(usedAmount).subtract(_duration); + logger.info("addusedamount.temp="+temp+",index="+index+",total="+total); + /*该假期剩余假期余额不足以扣减,记录错误日志,退出方法*/ + if (index == total && temp.doubleValue() < 0) { + logger.info("该人员的该假期所有的剩余假期余额都不足以扣减。" + + "resourceId=" + resourceId + ",date=" + date + ",ruleId=" + ruleId + ",type=" + type + ",duration=" + duration + ",requestId=" + requestId + + ",baseAmount=" + baseAmount.doubleValue() + ",extraAmount=" + extraAmount.doubleValue() + ",usedAmount=" + usedAmount.doubleValue()); + String newUsedAmount = usedAmount.add(_duration).setScale(5, RoundingMode.HALF_UP).toPlainString(); + String updateSql = "update kq_balanceOfLeave set usedAmount=" + (newUsedAmount) + ", update_time=? where id=" + id; + updateList.add(updateSql); + + logger.info("addusedamount.updateSql1="+updateSql); + usageHistoryEntity.setNewUsedAmount(newUsedAmount); + usageHistoryEntity.setBalanceOfLeaveId(id); + + //请假时长扣减完了重置下,以免影响下面的新增逻辑 + _duration = new BigDecimal("0"); + break; + } + if (temp.doubleValue() >= 0) { + String newUsedAmount = usedAmount.add(_duration).setScale(5, RoundingMode.HALF_UP).toPlainString(); + String updateSql = "update kq_balanceOfLeave set usedAmount=" + (newUsedAmount) + ", update_time=? where id=" + id; + updateList.add(updateSql); + + logger.info("addusedamount.updateSql2="+updateSql); + usageHistoryEntity.setNewUsedAmount(newUsedAmount); + usageHistoryEntity.setBalanceOfLeaveId(id); + + //请假时长扣减完了重置下,以免影响下面的新增逻辑 + _duration = new BigDecimal("0"); + break; + } else { + _duration = new BigDecimal("0").subtract(temp); + String newUsedAmount = baseAmount.add(extraAmount).add(tiaoxiuAmount).setScale(5, RoundingMode.HALF_UP).toPlainString(); + String updateSql = "update kq_balanceOfLeave set usedAmount=" + (newUsedAmount) + ", update_time=? where id=" + id; + updateList.add(updateSql); + + logger.info("addusedamount.updateSql3="+updateSql); + usageHistoryEntity.setNewUsedAmount(newUsedAmount); + usageHistoryEntity.setBalanceOfLeaveId(id); + continue; + } + } + } + + //index=0表示没有假期数据 + if (allow_negative_flag && (index == 0 || indexStatus==1)) { + //所属年份 + String belongYear = fromDateDb.substring(0, 4); + //基数 + BigDecimal baseAmount = new BigDecimal("0"); + //额外 + BigDecimal extraAmount = new BigDecimal("0"); + //加班生成调休 + BigDecimal tiaoxiuAmount = new BigDecimal("0"); + //已休 + BigDecimal usedAmount = new BigDecimal("0"); + + if(_duration.doubleValue()>0){ + //员工假期余额使用记录 + usageHistoryEntity = new KQUsageHistoryEntity(); + usageHistoryEntity.setLeaveRulesId(ruleId); + usageHistoryEntity.setRelatedId(resourceId); + usageHistoryEntity.setWfRequestId(requestId); + usageHistoryEntity.setOperator(resourceId); + usageHistoryEntity.setOperateDate(currentDate); + usageHistoryEntity.setOperateTime(currentTime); + usageHistoryEntity.setOperateType("1"); + usageHistoryEntity.setInsertOrUpdate("insert"); + usageHistoryEntity.setBelongYear(belongYear); + usageHistoryEntity.setOldUsedAmount("0"); + usageHistoryEntity.setOldMinimumUnit("" + minimumUnit); + usageHistoryEntity.setNewMinimumUnit("" + minimumUnit); + usageHistoryEntityList.add(usageHistoryEntity); + + + //非混合模式 + BigDecimal temp = baseAmount.add(extraAmount).add(tiaoxiuAmount).subtract(usedAmount).subtract(_duration); + /*该假期剩余假期余额不足以扣减,记录错误日志,退出方法*/ + if (temp.doubleValue() < 0) { + logger.info("该人员的该假期所有的剩余假期余额都不足以扣减。" + + "resourceId=" + resourceId + ",date=" + date + ",ruleId=" + ruleId + ",type=" + type + ",duration=" + duration + ",requestId=" + requestId + + ",baseAmount=" + baseAmount.doubleValue() + ",extraAmount=" + extraAmount.doubleValue() + ",usedAmount=" + usedAmount.doubleValue()); + String newUsedAmount = usedAmount.add(_duration).setScale(5, RoundingMode.HALF_UP).toPlainString(); + String updateSql = "INSERT INTO KQ_BalanceOfLeave(resourceId,leaveRulesId,belongYear,baseAmount,extraAmount,usedAmount,effectiveDate, update_time) " + + "VALUES(" + resourceId + "," + ruleId + ",'" + belongYear + "',0,0," + newUsedAmount + ",'" + fromDateDb + "',?)"; + if (recordSet.getDBType().equals("postgresql")) { + updateSql = "INSERT INTO KQ_BalanceOfLeave(resourceId,leaveRulesId,belongYear,baseAmount,extraAmount,usedAmount,effectiveDate, update_time) " + + "VALUES(" + resourceId + "," + ruleId + ",'" + belongYear + "',0,0," + newUsedAmount + ",'" + fromDateDb + "',?::timestamp)"; + } + updateList.add(updateSql); + usageHistoryEntity.setNewUsedAmount(newUsedAmount); + + logger.info("addusedamount.updateSql4="+updateSql); + } + } + } + + logger.info("requestId:"+requestId+"::updateList:"+updateList); + /*SQL操作批处理*/ + for (int i = 0; i < updateList.size(); i++) { + flag = recordSet.executeUpdate(updateList.get(i),updateDate); + if (!flag) { + logger.info("员工提交请假流程累计已休假期的SQL执行失败。" + + "resourceId=" + resourceId + ",date=" + date + ",ruleId=" + ruleId + ",type=" + type + ",duration=" + duration + ",requestId=" + requestId); + return; + } + } + /*记录假期使用记录*/ + if (flag && usageHistoryEntityList.size() > 0) { + KQUsageHistoryBiz usageHistoryBiz = new KQUsageHistoryBiz(); + flag = usageHistoryBiz.save(usageHistoryEntityList); + if (!flag) { + logger.info("请假流程,员工假期余额变更记录SQL执行失败。" + + "resourceId=" + resourceId + ",date=" + date + ",ruleId=" + ruleId + ",type=" + type + ",duration=" + duration + ",requestId=" + requestId); + return; + } + } + } catch (Exception e) { + logger.info(e.getMessage()); + logger.info("请假流程扣减出错。" + + "resourceId=" + resourceId + ",date=" + date + ",ruleId=" + ruleId + ",type=" + type + ",duration=" + duration + ",requestId=" + requestId); + return; + } + } + + /** + * 销假流程归档时,需要将曾经扣减的假期余额返还给相应人员 + * + * @param resourceId 指定人员ID + * @param date 指定日期 + * 根据日期取指定指定日期年份之前的所有有效的余额,传入空值则取所有年份的有效余额 + * @param ruleId 指定假期规则 + * @param duration 请假时长 + * @param type 时长类型:1-小时、2-天 + * 传入空值则默认取假期规则设置中的单位 + * @param requestId 请假流程的requestId + * @return + */ + public static void reduceUsedAmount(String resourceId, String date, String ruleId, String duration, String type, String requestId) { + KQBalanceOfLeaveBiz.reduceUsedAmount(resourceId, date, ruleId, duration, type,requestId,null); + } + public static void reduceUsedAmount(String resourceId, String date, String ruleId, String duration, String type, String requestId, String back_requestid) { + try { + if(Util.getDoubleValue(duration) <= 0) { + logger.info("时长为0不做返还。resourceId=" + resourceId + ",date=" + date + ",ruleId=" + ruleId + ",type=" + type + ",duration=" + duration + ",requestId=" + requestId); + return; + } + java.sql.Timestamp updateDate = KQDateUtil.getUpdateTimeStamp(); + /*获取当前日期,当前时间*/ + Calendar today = Calendar.getInstance(); + String currentDate = Util.add0(today.get(Calendar.YEAR), 4) + "-" + + Util.add0(today.get(Calendar.MONTH) + 1, 2) + "-" + + Util.add0(today.get(Calendar.DAY_OF_MONTH), 2); + String currentTime = Util.add0(today.get(Calendar.HOUR_OF_DAY), 2) + ":" + + Util.add0(today.get(Calendar.MINUTE), 2) + ":" + + Util.add0(today.get(Calendar.SECOND), 2); + + /****************************************************************************************************************/ + + //人力资源缓存类 + ResourceComInfo resourceComInfo = new ResourceComInfo(); + //分部 + String subcompanyId = resourceComInfo.getSubCompanyID(resourceId); + String departmentId = resourceComInfo.getDepartmentID(resourceId); + /****************************************************************************************************************/ + logger.info("reduceUsedAmount:resourceId:"+resourceId+":fromdatedb:"+date+":newLeaveType:"+ruleId+":duration:"+duration+":requestid:"+requestId+":back_requestid:"+back_requestid); + + //假期规则缓存类 + KQLeaveRulesComInfo rulesComInfo = new KQLeaveRulesComInfo(); + //最小请假单位:1-按天请假、2-按半天请假、3-按小时请假、4-按整天请假 + int minimumUnit = Util.getIntValue(rulesComInfo.getMinimumUnit(ruleId)); + //最小请假单位获取有误,记录错误日志,直接退出方法 + if (minimumUnit < 1 || minimumUnit > 6) { + logger.info("最小请假单位获取有误。resourceId=" + resourceId + ",date=" + date + ",ruleId=" + ruleId + ",type=" + type + ",duration=" + duration + ",requestId=" + requestId); + return; + } + //是否启用假期余额:0-不启用、1-启用 + int balanceEnable = Util.getIntValue(rulesComInfo.getBalanceEnable(ruleId), 0); + //该假期未开启假期余额,记录错误日志,退出方法 + if (balanceEnable != 1) { + logger.info("该假期未开启假期余额。resourceId=" + resourceId + ",date=" + date + ",ruleId=" + ruleId + ",type=" + type + ",duration=" + duration + ",requestId=" + requestId); + return; + } + //前台传回的请假时长类型与后台设置的假期限制的最小请假单位不相符,暂不支持转换,记录错误日志,直接退出方法 + boolean flag = type.equals("") || ("1".equals(type) && KQUnitBiz.isLeaveHour(minimumUnit+"")) || ("2".equals(type) && (minimumUnit == 1 || minimumUnit == 2 || minimumUnit == 4)); + if (!flag) { + logger.info("前台传回的请假时长类型与后台设置的请假类型限制的最小请假单位不相符。" + + "resourceId=" + resourceId + ",date=" + date + ",ruleId=" + ruleId + ",type=" + type + ",duration=" + duration + ",requestId=" + requestId); + return; + } + + /****************************************************************************************************************/ + + //假期规则缓存类(每个假期类型下可能存在多个假期规则) + KQLeaveRulesDetailComInfo detailComInfo = new KQLeaveRulesDetailComInfo(); + //余额发放方式:1-手动发放、2-按司龄自动发放、3-按工龄自动发放、4-每年自动发放固定天数、5-加班时长自动计入余额、6-按入职时长+工龄自动发放 + int distributionMode = Util.getIntValue(detailComInfo.getDistributionMode(ruleId, subcompanyId, departmentId, resourceId)); + //扣减优先级:1-法定年假、2-福利年假 + int priority = Util.getIntValue(detailComInfo.getDistributionMode(ruleId, subcompanyId, departmentId, resourceId)); + + /****************************************************************************************************************/ + + logger.info("reduceUsedAmount:distributionMode:"+distributionMode+":priority:"+priority); + + //员工假期余额变更记录 + KQUsageHistoryEntity usageHistoryEntity = new KQUsageHistoryEntity(); + + List usageHistoryEntityList = new ArrayList(); + + + String deductYear = ""; + KQSettingsComInfo kqSettingsComInfo = new KQSettingsComInfo(); + String leaveback_handle = Util.null2String(kqSettingsComInfo.getMain_val("leaveback_handle"),"0"); + if("1".equals(leaveback_handle) && null != back_requestid && back_requestid.length()>0){ + RecordSet rs1 = new RecordSet(); + String historySql = "select * from kq_usagehistory where relatedId='"+resourceId+"' and leaveRulesId='"+ruleId+"' and wfRequestId='"+back_requestid+"' order by belongYear"; + rs1.executeQuery(historySql); + logger.info("reduceUsedAmount:historySql:"+historySql); + while (rs1.next()){ + String belongyear = Util.null2String(rs1.getString("belongyear")); + deductYear += ",'"+belongyear+"'"; + } + } + logger.info("reduceUsedAmount:deductYear:"+deductYear+",leaveback_handle="+leaveback_handle); + + BigDecimal _duration = new BigDecimal(Util.null2s(duration, "0")); + List updateList = new ArrayList(); + RecordSet recordSet = new RecordSet(); + String sql = "select * from kq_balanceOfLeave where (isDelete is null or isDelete<>1) and leaveRulesId=" + ruleId + " and resourceId=" + resourceId + " order by belongYear desc"; + if(null != deductYear && deductYear.length()>0){ + deductYear = deductYear.substring(1); + sql = "select * from kq_balanceOfLeave where (isDelete is null or isDelete<>1) and leaveRulesId=" + ruleId + " and resourceId=" + resourceId + + " and belongYear in ("+deductYear+") " + + " order by belongYear "; + } + boolean leaveOfParental = KQLeaveRulesBiz.isLeaveOfParentalNum(ruleId); + if(distributionMode == 5||leaveOfParental){ + if (recordSet.getDBType().equalsIgnoreCase("sqlserver") + || recordSet.getDBType().equalsIgnoreCase("mysql")) { + sql = "select * from kq_balanceOfLeave where (isDelete is null or isDelete<>1) and leaveRulesId=" + ruleId + " and resourceId=" + resourceId + " and (expirationDate is null or expirationDate='' or expirationDate>='" + date + "') order by belongYear asc, expirationDate asc, id asc "; + } else { + sql = "select * from kq_balanceOfLeave where (isDelete is null or isDelete<>1) and leaveRulesId=" + ruleId + " and resourceId=" + resourceId + " and (expirationDate is null or expirationDate>='" + date + "') order by belongYear asc, expirationDate asc, id asc "; + } + } + recordSet.executeQuery(sql); + int total = recordSet.getCounts(); + int index = 0; + logger.info("reduceUsedAmount:sql:"+sql); + while (recordSet.next()) { + index++; + // + String id = recordSet.getString("id"); + //所属年份 + String belongYear = recordSet.getString("belongYear"); + //已休 + BigDecimal usedAmount = new BigDecimal(Util.null2s(recordSet.getString("usedAmount"), "0")); + //福利年假的已休 + BigDecimal usedAmount2 = new BigDecimal(Util.null2s(recordSet.getString("usedAmount2"), "0")); + + //记录使用记录 + usageHistoryEntity = new KQUsageHistoryEntity(); + usageHistoryEntity.setLeaveRulesId(ruleId); + usageHistoryEntity.setRelatedId(resourceId); + usageHistoryEntity.setWfRequestId(requestId); + usageHistoryEntity.setOperator(resourceId); + usageHistoryEntity.setOperateDate(currentDate); + usageHistoryEntity.setOperateTime(currentTime); + usageHistoryEntity.setOperateType("2"); + usageHistoryEntity.setInsertOrUpdate("update"); + usageHistoryEntity.setBelongYear(belongYear); + usageHistoryEntity.setOldUsedAmount(usedAmount.setScale(5, RoundingMode.HALF_UP).toPlainString()); + usageHistoryEntity.setOldUsedAmount2(usedAmount2.setScale(5, RoundingMode.HALF_UP).toPlainString()); + usageHistoryEntity.setOldMinimumUnit("" + minimumUnit); + usageHistoryEntity.setNewMinimumUnit("" + minimumUnit); + + if (distributionMode == 6) {//如果年假为混合模式(法定年假+福利年假) + if (priority == 1) { + BigDecimal temp = usedAmount.subtract(_duration); + logger.info("reduceUsedAmount:id1:"+id+":belongYear:"+belongYear+":usedAmount:"+usedAmount+":usedAmount2:"+usedAmount2+":temp1:"+temp); + if (temp.doubleValue() >= 0) { + String newUsedAmount = temp.setScale(5, RoundingMode.HALF_UP).toPlainString(); + String updateSql = "update kq_balanceOfLeave set usedAmount=" + newUsedAmount + ", update_time=? where id=" + id; + updateList.add(updateSql); + + usageHistoryEntity.setNewUsedAmount(newUsedAmount); + usageHistoryEntity.setNewUsedAmount2(usedAmount2.setScale(5, RoundingMode.HALF_UP).toPlainString()); + usageHistoryEntity.setBalanceOfLeaveId(id); + usageHistoryEntityList.add(usageHistoryEntity); + break; + } else { + temp = usedAmount.add(usedAmount2).subtract(_duration); + logger.info("reduceUsedAmount:id2:"+id+":belongYear:"+belongYear+":usedAmount:"+usedAmount+":usedAmount2:"+usedAmount2+":temp2:"+temp); + /*此次销假流程的销假天数大于了他的已休假期,流程参数有误*/ + if (index == total && temp.doubleValue() < 0) { + String newUsedAmount = "0"; + String newUsedAmount2 = temp.setScale(5, RoundingMode.HALF_UP).toPlainString(); + String updateSql = "update kq_balanceOfLeave set usedAmount=0,usedAmount2=" + newUsedAmount2 + ", update_time=? where id=" + id; + updateList.add(updateSql); + + usageHistoryEntity.setNewUsedAmount(newUsedAmount); + usageHistoryEntity.setNewUsedAmount2(newUsedAmount2); + usageHistoryEntity.setBalanceOfLeaveId(id); + usageHistoryEntityList.add(usageHistoryEntity); + + logger.info("此次销假流程的销假天数大于了他的已休假期,流程参数有误。" + + "resourceId=" + resourceId + ",date=" + date + ",ruleId=" + ruleId + ",type=" + type + ",duration=" + duration + ",requestId=" + requestId); + break; + } + if (temp.doubleValue() >= 0) { + String newUsedAmount = "0"; + String newUsedAmount2 = temp.setScale(5, RoundingMode.HALF_UP).toPlainString(); + String updateSql = "update kq_balanceOfLeave set usedAmount=0,usedAmount2=" + newUsedAmount2 + ", update_time=? where id=" + id; + updateList.add(updateSql); + + usageHistoryEntity.setNewUsedAmount(newUsedAmount); + usageHistoryEntity.setNewUsedAmount2(newUsedAmount2); + usageHistoryEntity.setBalanceOfLeaveId(id); + usageHistoryEntityList.add(usageHistoryEntity); + break; + } else { + _duration = new BigDecimal("0").subtract(temp); + String updateSql = "update kq_balanceOfLeave set usedAmount=0,usedAmount2=0,update_time=? where id=" + id; + if (recordSet.getDBType().equals("postgresql")) { + updateSql = "update kq_balanceOfLeave set usedAmount=0,usedAmount2=0,update_time=?::timestamp where id=" + id; + } + updateList.add(updateSql); + + if (usedAmount.doubleValue() != 0 || usedAmount2.doubleValue() != 0) { + usageHistoryEntity.setNewUsedAmount("0"); + usageHistoryEntity.setNewUsedAmount2("0"); + usageHistoryEntity.setBalanceOfLeaveId(id); + usageHistoryEntityList.add(usageHistoryEntity); + } + continue; + } + } + } else { + BigDecimal temp = usedAmount2.subtract(_duration); + if (temp.doubleValue() >= 0) { + String newUsedAmount2 = temp.setScale(5, RoundingMode.HALF_UP).toPlainString(); + String updateSql = "update kq_balanceOfLeave set usedAmount2=" + newUsedAmount2 + ", update_time=? where id=" + id; + updateList.add(updateSql); + + usageHistoryEntity.setNewUsedAmount2(newUsedAmount2); + usageHistoryEntity.setNewUsedAmount(usedAmount.setScale(5, RoundingMode.HALF_UP).toPlainString()); + usageHistoryEntity.setBalanceOfLeaveId(id); + usageHistoryEntityList.add(usageHistoryEntity); + break; + } else { + temp = usedAmount2.add(usedAmount).subtract(_duration); + /*此次销假流程的销假天数大于了他的已休假期,流程参数有误*/ + if (index == total && temp.doubleValue() < 0) { + String newUsedAmount = temp.setScale(5, RoundingMode.HALF_UP).toPlainString(); + String updateSql = "update kq_balanceOfLeave set usedAmount2=0,usedAmount=" + newUsedAmount + ", update_time=? where id=" + id; + updateList.add(updateSql); + + usageHistoryEntity.setNewUsedAmount2("0.00"); + usageHistoryEntity.setNewUsedAmount(newUsedAmount); + usageHistoryEntity.setBalanceOfLeaveId(id); + usageHistoryEntityList.add(usageHistoryEntity); + + logger.info("此次销假流程的销假天数大于了他的已休假期,流程参数有误。" + + "resourceId=" + resourceId + ",date=" + date + ",ruleId=" + ruleId + ",type=" + type + ",duration=" + duration + ",requestId=" + requestId); + break; + } + if (temp.doubleValue() >= 0) { + String newUsedAmount = temp.setScale(5, RoundingMode.HALF_UP).toPlainString(); + String updateSql = "update kq_balanceOfLeave set usedAmount2=0,usedAmount=" + newUsedAmount + ", update_time=? where id=" + id; + updateList.add(updateSql); + + usageHistoryEntity.setNewUsedAmount2("0.00"); + usageHistoryEntity.setNewUsedAmount(newUsedAmount); + usageHistoryEntity.setBalanceOfLeaveId(id); + usageHistoryEntityList.add(usageHistoryEntity); + break; + } else { + _duration = new BigDecimal("0").subtract(temp); + String updateSql = "update kq_balanceOfLeave set usedAmount=0,usedAmount2=0,update_time=? where id=" + id; + if (recordSet.getDBType().equals("postgresql")) { + updateSql = "update kq_balanceOfLeave set usedAmount=0,usedAmount2=0,update_time=?::timestamp where id=" + id; + } + updateList.add(updateSql); + + if (usedAmount.doubleValue() != 0 || usedAmount2.doubleValue() != 0) { + usageHistoryEntity.setNewUsedAmount2("0"); + usageHistoryEntity.setNewUsedAmount("0"); + usageHistoryEntity.setBalanceOfLeaveId(id); + usageHistoryEntityList.add(usageHistoryEntity); + } + continue; + } + } + } + } else {//非混合模式 + BigDecimal temp = usedAmount.subtract(_duration); + /*此次销假流程的销假天数大于了他的已休假期,流程参数有误*/ + if (index == total && temp.doubleValue() < 0) { + String newUsedAmount = temp.setScale(5, RoundingMode.HALF_UP).toPlainString(); + String updateSql = "update kq_balanceOfLeave set usedAmount=" + newUsedAmount + ", update_time=? where id=" + id; + updateList.add(updateSql); + + usageHistoryEntity.setNewUsedAmount(newUsedAmount); + usageHistoryEntity.setBalanceOfLeaveId(id); + usageHistoryEntityList.add(usageHistoryEntity); + + logger.info("此次销假流程的销假天数大于了他的已休假期,流程参数有误。" + + "resourceId=" + resourceId + ",date=" + date + ",ruleId=" + ruleId + ",type=" + type + ",duration=" + duration + ",requestId=" + requestId); + break; + } + if (temp.doubleValue() >= 0) { + String newUsedAmount = temp.setScale(5, RoundingMode.HALF_UP).toPlainString(); + String updateSql = "update kq_balanceOfLeave set usedAmount=" + newUsedAmount + ", update_time=? where id=" + id; + updateList.add(updateSql); + + usageHistoryEntity.setNewUsedAmount(newUsedAmount); + usageHistoryEntity.setBalanceOfLeaveId(id); + usageHistoryEntityList.add(usageHistoryEntity); + break; + } else { + _duration = new BigDecimal("0").subtract(temp); + String updateSql = "update kq_balanceOfLeave set usedAmount=0, update_time=? where id=" + id; + updateList.add(updateSql); + + if (usedAmount.doubleValue() != 0) { + usageHistoryEntity.setNewUsedAmount("0"); + usageHistoryEntity.setBalanceOfLeaveId(id); + usageHistoryEntityList.add(usageHistoryEntity); + } + continue; + } + } + } + + logger.info("requestId:"+requestId+"::updateList:"+updateList); + /*SQL操作批处理*/ + for (int i = 0; i < updateList.size(); i++) { + flag = recordSet.executeUpdate(updateList.get(i),updateDate); + if (!flag) { + logger.info("提交销假流程,回退员工假期余额SQL执行失败。" + + "resourceId=" + resourceId + ",date=" + date + ",ruleId=" + ruleId + ",type=" + type + ",duration=" + duration + ",requestId=" + requestId); + return; + } + } + /*记录假期使用记录*/ + if (flag && usageHistoryEntityList.size() > 0) { + KQUsageHistoryBiz usageHistoryBiz = new KQUsageHistoryBiz(); + flag = usageHistoryBiz.save(usageHistoryEntityList); + if (!flag) { + logger.info("提交销假流程,员工假期余额变更记录SQL执行失败。" + + "resourceId=" + resourceId + ",date=" + date + ",ruleId=" + ruleId + ",type=" + type + ",duration=" + duration + ",requestId=" + requestId); + return; + } + } + } catch (Exception e) { + logger.info(e.getMessage()); + logger.info("销假流程恢复假期余额报错。" + + "resourceId=" + resourceId + ",date=" + date + ",ruleId=" + ruleId + ",type=" + type + ",duration=" + duration + ",requestId=" + requestId); + return; + } + } + + /** + * 初始化系统内所有假期的假期余额 + */ + public static void createBalanceOfLeave() { + try { + Calendar today = Calendar.getInstance(); + String currentYear = Util.add0(today.get(Calendar.YEAR), 4); + today.add(Calendar.YEAR,-1); + String lastYear = Util.add0(today.get(Calendar.YEAR), 4); + KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo(); + kqLeaveRulesComInfo.setTofirstRow(); + while (kqLeaveRulesComInfo.next()) { + if (!kqLeaveRulesComInfo.getIsEnable().equals("1") || !kqLeaveRulesComInfo.getBalanceEnable().equals("1")) { + continue; + } + createData(kqLeaveRulesComInfo.getId(), currentYear, 0, "", "1"); + + // createData(kqLeaveRulesComInfo.getId(), lastYear, 0, "", "1"); + + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * 批处理指定机构的指定假期的指定年份的假期余额 + * + * @param leaveRulesId 指定假期类型的ID(对应的是数据库表kq_LeaveRules的主键ID) + * @param belongYear 指定的所属年份(格式yyyy) + * @param organizationType 机构类型:0-总部、1-分部、2-部门 + * @param organizationIds 指定机构的ID(例如当机构类型为分部时,此为分部ID) + * @param operator 批处理的操作人员的人员ID(-1表示是系统定时任务自动批处理) + * @return false--批处理失败、true--批处理成功 + */ + public static boolean createData(String leaveRulesId, String belongYear, int organizationType, String organizationIds, String operator) { + return createData(leaveRulesId, belongYear, organizationType, organizationIds, operator, false); + } + + /** + * 批处理指定机构的指定假期的指定年份的假期余额 + * + * @param ruleId 指定假期类型的ID(对应的是数据库表kq_LeaveRules的主键ID) + * @param belongYear 指定的所属年份(格式yyyy) + * @param organizationType 机构类型:0-总部、1-分部、2-部门 + * @param organizationIds 指定机构的ID(例如当机构类型为分部时,此为分部ID) + * @param operator 批处理的操作人员的人员ID(-1表示是系统定时任务自动批处理) + * @param canUpdate 是否按照规则更新员工的假期余额基数 + * 因为员工的假期基数可以编辑,会出现和规则计算得出的值不一致的情况,只有当假期规则发生变动的情况时,才会按照最新的规则更新员工的假期基数 + * @return false--批处理失败、true--批处理成功 + */ + public static boolean createData(String ruleId, String belongYear, int organizationType, String organizationIds, String operator, boolean canUpdate) { + boolean isSuccess = true; + try { + //假期类型缓存类 + KQLeaveRulesComInfo rulesComInfo = new KQLeaveRulesComInfo(); + //最小请假单位:1-按天请假、2-按半天请假、3-按小时请假、4-按整天请假 + String minimumUnit = rulesComInfo.getMinimumUnit(ruleId); + //假期类型的标识 + String leaveCode = rulesComInfo.getLeaveCode(ruleId); + + //假期规则缓存类 + KQLeaveRulesDetailComInfo detailComInfo = new KQLeaveRulesDetailComInfo(); + //假期规则的ID + String rulesDetailId = ""; + //余额发放方式:1-手动发放、2-按司龄自动发放、3-按工龄自动发放、4-每年自动发放固定天数、5-加班时长自动计入余额、6-按入职时长+工龄自动发放、7-按司龄自动发放(入职日期当天发放余额) + int distributionMode = 1; + //每人发放小时(天)数(当余额发放方式为每年自动发放固定天数时有效) + double annualAmount = 0; + //法定年假规则(当distributionMode=6时有效):0-工龄、1-司龄、2-工龄+司龄 + int legalKey = 0; + //福利年假规则(当distributionMode=6时有效):0-工龄、1-司龄、2-工龄+司龄 + int welfareKey = 1; + //年假基数计算方式: + // 0-假期基数发放日期和假期基数变动日期均为每年的01月01号(但是假期基数是结合 司龄/工龄 变化前后的值按天数比例折算出来的)、 + // 1-假期基数发放日期和假期基数变动日期均为每年的01月01号、 + // 2-假期基数发放日期发放日期为每年的01月01号,假期基数的变动日期为每年的 入职日期/参加工作日期 + int calcMethod = 0; + //假期基数的折算方式 + int convertMode = 0; + + //多孩叠加开关。 + int severalChildren = 0; + + //孩子多少周岁前发放。默认3岁 + int yearsOld = 3; + + int validityRule = 1; + + //是否按照省份发放育儿假。1否,2是 + String isprovince = "1"; + + //假期基数的小数位数 + int decimalDigit = 2; + //次账号是否能享受此假期:0-排除,即次账号不能享受此假期、1-不排除,即次账号正常享受此假期 + int excludeSubAccount = 1; + //转正之前是否能享受此假期:0-不允许、1-允许 + int beforeFormal = 1; + + //假期基数 + double baseAmount = 0.00; + //福利年假(当distributionMode=6时才有作用) + double baseAmount2 = 0.00; + //系统内原来的假期基数的合集 + Map oldBalanceEntities = getBalanceEntities(organizationType, organizationIds, ruleId, belongYear); + //员工假期余额实体类 + KQBalanceOfLeaveEntity oldBalanceEntity = null; + //此次批处理新计算的假期基数的合集 + List newBalanceEntities = new ArrayList(); + //员工假期余额实体类 + KQBalanceOfLeaveEntity newBalanceEntity = null; + // + Map params = null; + //今天的日期 + String currentDate = DateUtil.getCurrentDate(); + + ManageDetachComInfo manageDetachComInfo = new ManageDetachComInfo(); + //是否开启了人力资源模块的管理分权 + boolean isUseHrmManageDetach = manageDetachComInfo.isUseHrmManageDetach(); + + boolean addOrUpdate = false; + String expirationDate =DateUtil.getCurrentDate(); + String effectiveDate =""; + String belongYearTemp = belongYear; + String belongYearNew =""; + + String sql = " select * from HrmResource where status in (0,1,2,3) "; + if (organizationType == 1) { + sql += " and subCompanyId1 in (" + organizationIds + ") "; + } else if (organizationType == 2) { + sql += " and departmentId in (" + organizationIds + ") "; + } else if (organizationType == 3) { + sql += " and id in (" + organizationIds + ") "; + } + //如果开启了分权 + if (isUseHrmManageDetach) { + SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo(); + String allRightSubComIds = subCompanyComInfo.getRightSubCompany(Util.getIntValue(operator,1),"KQLeaveRulesEdit:Edit",0); + //机构权限只读的情况下,下面的allRightSubComIds是为空的,导致where会拼上一个 and (),导致sql报错 + if(Util.null2String(allRightSubComIds).length()>0){ + sql += " and " + Util.getSubINClause(allRightSubComIds, "subCompanyId1", "in"); + }else{//机构权限只读的情况下。就不让批处理 + sql += " and 1=2 "; + } + + } else { + if (!operator.equals("1")) { + User user = new User(Util.getIntValue(operator)); + String rightLevel = HrmUserVarify.getRightLevel("KQLeaveRulesEdit:Edit", user); + int departmentID = user.getUserDepartment(); + int subcompanyID = user.getUserSubCompany1(); + + if (rightLevel.equals("2")) { + // 总部级别的,什么也不返回 + } else if (rightLevel.equals("1")) { // 分部级别的 + sql += " and subCompanyId1=" + subcompanyID; + } else if (rightLevel.equals("0")) { // 部门级别 + sql += " and departmentId=" + departmentID; + } + } + } + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql); + while (recordSet.next()) { + /*获取人员的相关信息 start*/ + String resourceId = recordSet.getString("id"); + String accountType = Util.null2String(recordSet.getString("accountType")); + String status = Util.null2String(recordSet.getString("status")); + String createDate = Util.null2String(recordSet.getString("createDate")); + String workStartDate = Util.null2String(recordSet.getString("workStartDate")); + String companyStartDate = Util.null2String(recordSet.getString("companyStartDate")); + //如果参加工作日期为空,则默认采用创建日期 + workStartDate = (workStartDate.equals("")||workStartDate.length()<10||workStartDate.indexOf("-")<=0) ? createDate : workStartDate; + //如果入职日期为空,则默认采用创建日期 + companyStartDate = (companyStartDate.equals("")||companyStartDate.length()<10||companyStartDate.indexOf("-")<=0) ? createDate : companyStartDate; + String subCompanyId = Util.null2String(recordSet.getString("subCompanyId1")); + String departmentId = Util.null2String(recordSet.getString("departmentId")); + String locationid = Util.null2String(recordSet.getString("locationid")); + /*获取人员的相关信息 end*/ + + /*获取人员所属分部对应的假期规则 start*/ + rulesDetailId = detailComInfo.getId(ruleId, subCompanyId, departmentId, resourceId); + distributionMode = Util.getIntValue(detailComInfo.getDistributionMode(ruleId, subCompanyId, departmentId, resourceId), 1); + legalKey = Util.getIntValue(detailComInfo.getLegalKey(ruleId, subCompanyId, departmentId, resourceId), 0); + welfareKey = Util.getIntValue(detailComInfo.getWelfareKey(ruleId, subCompanyId, departmentId, resourceId), 1); + annualAmount = Util.getDoubleValue(detailComInfo.getAnnualAmount(ruleId, subCompanyId, departmentId, resourceId), 0.00); + calcMethod = Util.getIntValue(detailComInfo.getCalcMethod(ruleId, subCompanyId, departmentId, resourceId), 0); + convertMode = Util.getIntValue(detailComInfo.getConvertMode(ruleId, subCompanyId, departmentId, resourceId), 0); + decimalDigit = Util.getIntValue(detailComInfo.getDecimalDigit(ruleId, subCompanyId, departmentId, resourceId), 2); + excludeSubAccount = Util.getIntValue(detailComInfo.getExcludeSubAccount(ruleId, subCompanyId, departmentId, resourceId), 1); + beforeFormal = Util.getIntValue(detailComInfo.getBeforeFormal(ruleId, subCompanyId, departmentId, resourceId), 1); + severalChildren = StringUtil.parseToInt(detailComInfo.getSeveralChildren(ruleId, subCompanyId, departmentId, resourceId), 0); + yearsOld = StringUtil.parseToInt(detailComInfo.getYearsOld(ruleId, subCompanyId, departmentId, resourceId), 0); + isprovince = Util.null2s(detailComInfo.getIsProvince(ruleId, subCompanyId, departmentId, resourceId), "1"); + validityRule = Util.getIntValue(detailComInfo.getValidityRule(ruleId, subCompanyId,departmentId,resourceId)); + + /*获取人员所属分部对应的假期规则 end*/ + + //封装参数 start + params = new HashMap(); + params.put("resourceId", resourceId); + params.put("status", status); + params.put("createDate", createDate); + params.put("workStartDate", workStartDate); + params.put("companyStartDate", companyStartDate); + params.put("subCompanyId", subCompanyId); + + params.put("belongYear", belongYear); + params.put("rulesDetailId", rulesDetailId); + params.put("distributionMode", distributionMode); + params.put("annualAmount", annualAmount); + params.put("legalKey", legalKey); + params.put("welfareKey", welfareKey); + params.put("calcMethod", calcMethod); + params.put("convertMode", convertMode); + params.put("decimalDigit", decimalDigit); + params.put("excludeSubAccount", excludeSubAccount); + params.put("beforeFormal", beforeFormal); + // qc + params.put("operator", operator); + params.put("ruleId", ruleId); + //封装参数 end + + if (distributionMode == 1) { + continue; + } else if (distributionMode == 2 || distributionMode == 3) { + baseAmount = getBaseAmount(params); + } else if (distributionMode == 4) { + baseAmount = getBaseAmountByDis4(params); + } else if (distributionMode == 5) { + continue; + } else if (distributionMode == 6) { + params.put("legalOrWelfare", "legal"); + baseAmount = getBaseAmountByDis6(params); + params.put("legalOrWelfare", "welfare"); + baseAmount2 = getBaseAmountByDis6(params); + } else if (distributionMode == 7) { + baseAmount = getBaseAmountByDis7(params); + } else if (distributionMode == 8) { + params.put("validityRule", validityRule); + if(isprovince.equals("2")){ + getChildrenProvinceId(rulesDetailId,locationid,params); + }else{ + params.put("yearsOld",yearsOld); + } + if (severalChildren==0) { + Map baseAmountMaps = getBaseAmountByDis8(params); + baseAmount = (Double) baseAmountMaps.get("baseAmount"); + addOrUpdate = (boolean) baseAmountMaps.get("addOrUpdate"); + expirationDate = (String) baseAmountMaps.get("expirationDate"); + effectiveDate = (String) baseAmountMaps.get("effectiveDate"); + belongYearNew = (String) baseAmountMaps.get("belongYearNew"); + //这个是去年,育儿假有今年去更新去年的情况,所以对这个所属年份赋值。 + if (addOrUpdate && !belongYearNew.equals("")) { + belongYear = belongYearNew; + } + } else { + getBaseAmountByDis8Num(params); + continue; + } + } + if (beforeFormal == 0 && !status.equals("1")) { + //转正前不允许发放余额 + if (canUpdate) { + baseAmount = 0; + baseAmount2 = 0; + } else { + continue; + } + } + if (excludeSubAccount == 0 && accountType.equals("1")) { + //次账号不允许发放余额 + if (canUpdate) { + baseAmount = 0; + baseAmount2 = 0; + } else { + continue; + } + } + + oldBalanceEntity = (KQBalanceOfLeaveEntity) oldBalanceEntities.get(resourceId); + if (oldBalanceEntity != null) { + //如果假期基数没有发生变化,不需要更新 + if (!addOrUpdate&&oldBalanceEntity.getBaseAmount() == baseAmount && oldBalanceEntity.getBaseAmount2() == baseAmount2) { + continue; + } + //如果是系统自动批处理(默认系统自动批处理不允许修改假期余额基数) + if (!canUpdate) { + if (distributionMode == 8) { + + if (oldBalanceEntity.getExtraAmount() > 0 || oldBalanceEntity.getUsedAmount() > 0) { + if (!addOrUpdate) { + if(resourceId.equals("3858")){ + new BaseBean().writeLog("人员id3858:ExtraAmount="+oldBalanceEntity.getExtraAmount()+ + ";UsedAmount="+ oldBalanceEntity.getUsedAmount() + ); + } + continue; + } + } + } + if (distributionMode != 8&&(oldBalanceEntity.getBaseAmount() > 0 || oldBalanceEntity.getExtraAmount() > 0 || oldBalanceEntity.getUsedAmount() > 0 + || oldBalanceEntity.getBaseAmount2() > 0 + || oldBalanceEntity.getExtraAmount2() > 0 || oldBalanceEntity.getUsedAmount2() > 0)) { + if (calcMethod == 2) { + //但是如果【假期基数计算方式】选择【按最多的计算】时,允许在【工龄or司龄变动日期】更新假期基数 + if (distributionMode == 2) { + String ageLimitChangeDate = belongYear + companyStartDate.substring(4); + if (currentDate.compareTo(ageLimitChangeDate) < 0) { + continue; + } + } else if (distributionMode == 3) { + String ageLimitChangeDate = belongYear + workStartDate.substring(4); + if (currentDate.compareTo(ageLimitChangeDate) < 0) { + continue; + } + } else if (distributionMode == 6) { + String ageLimitChangeDate = belongYear + workStartDate.substring(4); + String ageLimitChangeDate2 = belongYear + companyStartDate.substring(4); + if (currentDate.compareTo(ageLimitChangeDate) < 0 && currentDate.compareTo(ageLimitChangeDate2) < 0) { + continue; + } + } + } else { + if (distributionMode == 6) { + String ageLimitChangeDate = belongYear + workStartDate.substring(4); + String ageLimitChangeDate2 = belongYear + companyStartDate.substring(4); + if (currentDate.compareTo(ageLimitChangeDate) < 0 && currentDate.compareTo(ageLimitChangeDate2) < 0) { + continue; + } + }else{ + if(!addOrUpdate){ + continue; + } + } + } + } + } + } else { + //如果没有生成过假期余额,但是此次生成的假期余额如果为0,则不新增,直接跳过 + if (baseAmount == 0 && baseAmount2 == 0) { + continue; + } + } + + newBalanceEntity = new KQBalanceOfLeaveEntity(); + newBalanceEntity.setResourceId(Util.getIntValue(resourceId)); + newBalanceEntity.setLeaveRulesId(Util.getIntValue(ruleId)); + newBalanceEntity.setBelongYear(belongYear); + newBalanceEntity.setBaseAmount(baseAmount); + newBalanceEntity.setBaseAmount2(baseAmount2); + newBalanceEntity.setEffectiveDate(effectiveDate); + newBalanceEntity.setExpirationDate(expirationDate); + newBalanceEntity.setMinimumUnit(Util.getIntValue(minimumUnit)); + if(addOrUpdate){ + newBalanceEntity.setUsedAmount(baseAmount); + newBalanceEntity.setExtraAmount(baseAmount); + newBalanceEntity.setStatus(1); + }else{ + newBalanceEntity.setStatus(0); + } + newBalanceEntities.add(newBalanceEntity); + belongYear = belongYearTemp; + } + isSuccess = insertOrUpdateBalance(newBalanceEntities, oldBalanceEntities, operator, canUpdate); + } catch (Exception e) { + e.printStackTrace(); + } + return isSuccess; + } + + /** + * 获取指定机构下的人员的假期余额 + * + * @param organizationType 指定机构类型:0-总部、1-分部、2-部门、3-热力资源 + * @param organizationIds 指定机构的ID,用英文逗号分隔 + * @param ruleId 假期类型的ID + * @param belongYear 所属年份 + * @return + */ + private static Map getBalanceEntities(int organizationType, String organizationIds, String ruleId, String belongYear) { + Map balanceEntities = new HashMap(); + try { + KQBalanceOfLeaveEntity balanceEntity = null; + + //假期类型缓存类 + KQLeaveRulesComInfo rulesComInfo = new KQLeaveRulesComInfo(); + //最小请假单位:1-按天请假、2-按半天请假、3-按小时请假、4-按整天请假 + String minimumUnit = rulesComInfo.getMinimumUnit(ruleId); + + RecordSet recordSet = new RecordSet(); + String sql = "select * from kq_BalanceOfLeave where (isDelete is null or isDelete<>1) and leaveRulesId=" + ruleId + " and belongYear=" + belongYear; + if (organizationType == 1) { + sql += " and resourceId in (select id from HrmResource where subCompanyId1 in (" + organizationIds + "))"; + } else if (organizationType == 2) { + sql += " and resourceId in (select id from HrmResource where departmentId in (" + organizationIds + "))"; + } else if (organizationType == 3) { + sql += " and resourceId in (" + organizationIds + ")"; + } + recordSet.executeQuery(sql); + while (recordSet.next()) { + int id = recordSet.getInt("id"); + int resourceId = recordSet.getInt("resourceId"); + int leaveRuleId = recordSet.getInt("leaveRulesId"); + double baseAmount = Util.getDoubleValue(recordSet.getString("baseAmount"), 0.00); + double extraAmount = Util.getDoubleValue(recordSet.getString("extraAmount"), 0.00); + double usedAmount = Util.getDoubleValue(recordSet.getString("usedAmount"), 0.00); + double baseAmount2 = Util.getDoubleValue(recordSet.getString("baseAmount2"), 0.00); + double extraAmount2 = Util.getDoubleValue(recordSet.getString("extraAmount2"), 0.00); + double usedAmount2 = Util.getDoubleValue(recordSet.getString("usedAmount2"), 0.00); + + balanceEntity = new KQBalanceOfLeaveEntity(); + balanceEntity.setId(id); + balanceEntity.setResourceId(resourceId); + balanceEntity.setBelongYear(belongYear); + balanceEntity.setLeaveRulesId(leaveRuleId); + balanceEntity.setBaseAmount(baseAmount); + balanceEntity.setExtraAmount(extraAmount); + balanceEntity.setUsedAmount(usedAmount); + balanceEntity.setBaseAmount2(baseAmount2); + balanceEntity.setExtraAmount2(extraAmount2); + balanceEntity.setUsedAmount2(usedAmount2); + balanceEntity.setMinimumUnit(Util.getIntValue(minimumUnit)); + + balanceEntities.put("" + resourceId, balanceEntity); + } + } catch (Exception e) { + e.printStackTrace(); + } + return balanceEntities; + } + + /** + * 获取指定人员的指定假期的指定年份的假期基数发放日期 + * + * @param resourceId 指定人员的人员ID + * @param ruleId 指定假期类型的ID + * @param belongYear 指定年份 + * @return + */ + private static Calendar getReleaseDate(String resourceId, String ruleId, String belongYear) { + Calendar calendar = null; + try { + //人员缓存类 + ResourceComInfo resourceComInfo = new ResourceComInfo(); + //分部ID + String subcompanyId = resourceComInfo.getSubCompanyID(resourceId); + String departmentId = resourceComInfo.getDepartmentID(resourceId); + + //创建日期 + String createDate = resourceComInfo.getCreatedate(resourceId); + //入职日期 + String companyStartDate = resourceComInfo.getCompanyStartDate(resourceId); + //没有维护入职日期时取创建日期 + companyStartDate = companyStartDate.equals("") ? createDate : companyStartDate; + //参加工作日期 + String workStartDate = resourceComInfo.getWorkStartDate(resourceId); + //没有维护参加工作日期时取创建日期 + workStartDate = workStartDate.equals("") ? createDate : workStartDate; + + /**********************************************************************************************************/ + + //假期规则的缓存类 + KQLeaveRulesDetailComInfo detailComInfo = new KQLeaveRulesDetailComInfo(); + //假期规则的ID + String rulesDetailId = Util.null2String(detailComInfo.getId(ruleId, subcompanyId, departmentId, resourceId)); + //余额发放方式 + int distributionMode = Util.getIntValue(detailComInfo.getDistributionMode(ruleId, subcompanyId, departmentId, resourceId), 1); + //年假基数计算方式: + // 0-假期基数发放日期和假期基数变动日期均为每年的01月01号(但是假期基数是结合 司龄/工龄 变化前后的值按天数比例折算出来的)、 + // 1-假期基数发放日期和假期基数变动日期均为每年的01月01号、 + // 2-假期基数发放日期发放日期为每年的01月01号,假期基数的变动日期为每年的 入职日期/参加工作日期 + int calcMethod = Util.getIntValue(detailComInfo.getCalcMethod(ruleId, subcompanyId, departmentId, resourceId), 1); + + /***********************************************************************************************************/ + + //假期基数发放日期 + String baseAmountReleaseDate = ""; + //工龄or司令的变动日期 + String ageLimitChangeDate = ""; + //入职日期or参加工作日期 + String date4CalcAgeLimit = ""; + if (distributionMode == 1) { + baseAmountReleaseDate = belongYear + "-01-01"; + //默认情况下都是以【假期基数发放日期】作为释放的开始日期 + calendar = DateUtil.getCalendar(baseAmountReleaseDate); + //如果批处理年份等于入职年份,应该以入职日期作为释放的开始日期 + if (belongYear.compareTo(companyStartDate.substring(0, 4)) == 0) { + calendar = DateUtil.getCalendar(companyStartDate); + } + return calendar; + } else if (distributionMode == 2) { + date4CalcAgeLimit = companyStartDate; + //根据假期基数的计算方式得出【假期基数发放日期】、【入职年限/参加工作年限 的变动日期】 + if (calcMethod == 0 || calcMethod == 1) { + baseAmountReleaseDate = belongYear + "-01-01"; + ageLimitChangeDate = belongYear + companyStartDate.substring(4); + } else if (calcMethod == 2) { + baseAmountReleaseDate = belongYear + "-01-01"; + ageLimitChangeDate = belongYear + companyStartDate.substring(4); + } + } else if (distributionMode == 3) { + date4CalcAgeLimit = workStartDate; + //根据假期基数的计算方式得出【假期基数发放日期】、【入职年限/参加工作年限 的变动日期】 + if (calcMethod == 0 || calcMethod == 1) { + baseAmountReleaseDate = belongYear + "-01-01"; + ageLimitChangeDate = belongYear + workStartDate.substring(4); + } else if (calcMethod == 2) { + baseAmountReleaseDate = belongYear + "-01-01"; + ageLimitChangeDate = belongYear + workStartDate.substring(4); + } + } else if (distributionMode == 4) { + baseAmountReleaseDate = belongYear + "-01-01"; + //默认情况下都是以【假期基数发放日期】作为释放的开始日期 + calendar = DateUtil.getCalendar(baseAmountReleaseDate); + //如果批处理年份等于入职年份,应该以入职日期作为释放的开始日期 + if (belongYear.compareTo(companyStartDate.substring(0, 4)) == 0) { + calendar = DateUtil.getCalendar(companyStartDate); + } + return calendar; + } + + //人员在【假期基数发放日期】时对应的【工龄or司龄】 + int ageLimit = getAgeLimit(date4CalcAgeLimit, baseAmountReleaseDate); + //人员在【假期基数发放日期】时应有的【假期基数】 + BigDecimal baseAmount_releaseDate = getAmountByAgeLimit(distributionMode, rulesDetailId, -1, ageLimit, -1, -1, -1, ""); + + //人员在【工龄or司龄变动日期】时对应的【工龄or司龄】 + int ageLimit_ageLimitChangeDate = getAgeLimit(date4CalcAgeLimit, ageLimitChangeDate); + //人员在【工龄or司龄变动日期】时应有的【假期基数】 + BigDecimal baseAmount_ageLimitChangeDate = getAmountByAgeLimit(distributionMode, rulesDetailId, -1, ageLimit_ageLimitChangeDate, -1, -1, -1, ""); + + //默认情况下都是以【假期基数发放日期】作为释放的开始日期 + calendar = DateUtil.getCalendar(baseAmountReleaseDate); + //如果批处理年份等于入职年份,应该以入职日期作为释放的开始日期 + if (belongYear.compareTo(companyStartDate.substring(0, 4)) == 0) { + calendar = DateUtil.getCalendar(companyStartDate); + } + //如果是初始获得年(即年初01-01的时候假期基数为0,但是后面工龄or司龄增加后,假期基数就不再为0了)。应该以【工龄or司龄变动日期】作为释放的开始日期 + if (baseAmount_releaseDate.doubleValue() <= 0 && baseAmount_ageLimitChangeDate.doubleValue() > 0) { + calendar = DateUtil.getCalendar(ageLimitChangeDate); + //比如:参加工作日是:2020-02-01,入职日期是:2021-08-16,没有该处理会按:2021-02-01给用户计算“已释放”数值 + if(belongYear.compareTo(companyStartDate.substring(0, 4)) == 0 && ageLimitChangeDate.compareTo(companyStartDate)<0){ + calendar = DateUtil.getCalendar(companyStartDate); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + return calendar; + } + + /** + * [6-按司龄+工龄自动发放]获取指定人员的指定假期的指定年份的假期基数发放日期 + * + * @param resourceId 指定人员的人员ID + * @param ruleId 指定假期类型的ID + * @param belongYear 指定年份 + * @param legalOrWelfare 是计算[法定年假]还是计算[福利年假]:legal-法定年假、welfare-福利年假 + * @return + */ + private static Calendar getReleaseDateByDis6(String resourceId, String ruleId, String belongYear, String legalOrWelfare) { + Calendar calendar = null; + try { + //人员缓存类 + ResourceComInfo resourceComInfo = new ResourceComInfo(); + //分部ID + String subCompanyId = resourceComInfo.getSubCompanyID(resourceId); + String departmentId = resourceComInfo.getDepartmentID(resourceId); + //创建日期 + String createDate = resourceComInfo.getCreatedate(resourceId); + //入职日期 + String companyStartDate = resourceComInfo.getCompanyStartDate(resourceId); + //没有维护入职日期时取创建日期 + companyStartDate = companyStartDate.equals("") ? createDate : companyStartDate; + //参加工作日期 + String workStartDate = resourceComInfo.getWorkStartDate(resourceId); + //没有维护参加工作日期时取创建日期 + workStartDate = workStartDate.equals("") ? createDate : workStartDate; + + /***********************************************************************************************************/ + + //假期规则的缓存类 + KQLeaveRulesDetailComInfo detailComInfo = new KQLeaveRulesDetailComInfo(); + //假期规则的ID + String rulesDetailId = Util.null2String(detailComInfo.getId(ruleId, subCompanyId, departmentId, resourceId)); + //余额发放方式 + int distributionMode = Util.getIntValue(detailComInfo.getDistributionMode(ruleId, subCompanyId, departmentId, resourceId), 1); + //年假基数计算方式: + // 0-假期基数发放日期和假期基数变动日期均为每年的01月01号(但是假期基数是结合 司龄/工龄 变化前后的值按天数比例折算出来的)、 + // 1-假期基数发放日期和假期基数变动日期均为每年的01月01号、 + // 2-假期基数发放日期发放日期为每年的01月01号,假期基数的变动日期为每年的 入职日期/参加工作日期 + int calcMethod = Util.getIntValue(detailComInfo.getCalcMethod(ruleId, subCompanyId, departmentId, resourceId), 1); + // + int legalKey = Util.getIntValue(detailComInfo.getLegalKey(ruleId, subCompanyId, departmentId, resourceId), 0); + // + int welfareKey = Util.getIntValue(detailComInfo.getWelfareKey(ruleId, subCompanyId, departmentId, resourceId), 1); + + /***********************************************************************************************************/ + + //假期基数发放日期 + String baseAmountReleaseDate = ""; + //工龄变动日期 + String ageLimitChangeDate = ""; + //司龄变动日期 + String ageLimitChangeDate2 = ""; + //根据假期基数的计算方式得出【假期基数发放日期】、【假期基数变动日期】、【工龄变动日期】、【司龄变动日期】 + if (calcMethod == 0 || calcMethod == 1) { + baseAmountReleaseDate = belongYear + "-01-01"; + ageLimitChangeDate = belongYear + workStartDate.substring(4); + ageLimitChangeDate2 = belongYear + companyStartDate.substring(4); + } else if (calcMethod == 2) { + baseAmountReleaseDate = belongYear + "-01-01"; + ageLimitChangeDate = belongYear + workStartDate.substring(4); + ageLimitChangeDate2 = belongYear + companyStartDate.substring(4); + } + + //人员在【假期基数发放日期】时对应的工龄 + int ageLimit_releaseDate = getAgeLimit(workStartDate, baseAmountReleaseDate); + //人员在【假期基数发放日期】时对应的司龄 + int ageLimit2_releaseDate = getAgeLimit(companyStartDate, baseAmountReleaseDate); + //人员在【假期基数发放日期】时对应的假期基数 + BigDecimal baseAmount_releaseDate = getAmountByAgeLimit(distributionMode, rulesDetailId, -1, ageLimit_releaseDate, ageLimit2_releaseDate, legalKey, welfareKey, legalOrWelfare); + + //人员在【工龄变动日期】时对应的工龄 + int ageLimit_ageLimitChangeDate = getAgeLimit(workStartDate, ageLimitChangeDate); + //人员在【工龄变动日期】时对应的司龄 + int ageLimit2_ageLimitChangeDate = getAgeLimit(companyStartDate, ageLimitChangeDate); + //人员在【工龄变动日期】时对应的假期基数 + BigDecimal baseAmount_ageLimitChangeDate = getAmountByAgeLimit(distributionMode, rulesDetailId, -1, ageLimit_ageLimitChangeDate, ageLimit2_ageLimitChangeDate, legalKey, welfareKey, legalOrWelfare); + + //人员在【司龄变动日期】时对应的司龄 + int ageLimit_ageLimitChangeDate2 = getAgeLimit(workStartDate, ageLimitChangeDate2); + //人员在【司龄变动日期】时对应的司龄 + int ageLimit2_ageLimitChangeDate2 = getAgeLimit(companyStartDate, ageLimitChangeDate2); + //人员在【司龄变动日期】时对应的假期基数 + BigDecimal baseAmount_ageLimitChangeDate2 = getAmountByAgeLimit(distributionMode, rulesDetailId, -1, ageLimit_ageLimitChangeDate2, ageLimit2_ageLimitChangeDate2, legalKey, welfareKey, legalOrWelfare); + + //默认情况下都是以【假期基数发放日期】作为释放的开始日期 + calendar = DateUtil.getCalendar(baseAmountReleaseDate); + //如果批处理年份等于入职年份,应该以入职日期作为释放的开始日期 + if (belongYear.compareTo(companyStartDate.substring(0, 4)) == 0) { + calendar = DateUtil.getCalendar(companyStartDate); + } + //如果是初始获得年(即年初01-01的时候假期基数为0,但是后面工龄or司龄增加后,假期基数就不再为0了) + if (ageLimitChangeDate.compareTo(ageLimitChangeDate2) <= 0) { + if (baseAmount_releaseDate.doubleValue() <= 0 && baseAmount_ageLimitChangeDate.doubleValue() > 0) { + calendar = DateUtil.getCalendar(ageLimitChangeDate); + } + if (baseAmount_releaseDate.doubleValue() <= 0 && baseAmount_ageLimitChangeDate.doubleValue() <= 0 && baseAmount_ageLimitChangeDate2.doubleValue() > 0) { + calendar = DateUtil.getCalendar(ageLimitChangeDate2); + } + } else { + if (baseAmount_releaseDate.doubleValue() <= 0 && baseAmount_ageLimitChangeDate2.doubleValue() > 0) { + calendar = DateUtil.getCalendar(ageLimitChangeDate2); + } + if (baseAmount_releaseDate.doubleValue() <= 0 && baseAmount_ageLimitChangeDate2.doubleValue() <= 0 && baseAmount_ageLimitChangeDate.doubleValue() > 0) { + calendar = DateUtil.getCalendar(ageLimitChangeDate2); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + return calendar; + } + + /** + * 计算假期基数 + * + * @param params Map + * belongYear:所属年份 + * createDate:人员创建日期 + * workStartDate:参加工作日期 + * companyStartDate:入职日期 + * rulesDetailId:假期规则的ID + * distributionMode:当前假期规则发放方式 + * annualAmount:当[distributionMode]=[4-每年发放固定天数]时有效 + * legalKey:法定年假规则(当[distributionMode=6]时有效):0-工龄、1-司龄、2-工龄+司龄 + * welfareKey:福利年假规则(当[distributionMode=6]时有效):0-工龄、1-司龄、2-工龄+司龄 + * calcMethod:假期基数计算方式 + * convertMode:折算方式 + * decimalDigit:折算后的假期余额保留几位小数 + * @return + */ + private static double getBaseAmount(Map params) { + BigDecimal baseAmount = new BigDecimal("0"); + int decimalDigit = 2; + try { + //当前日期 + String currentDate = DateUtil.getCurrentDate(); + //当前年份 + String currentYear = currentDate.substring(0, 4); + //批处理年份 + String belongYear = Util.null2String(params.get("belongYear")); + //人员的参加工作日期 + String workStartDate = Util.null2String(params.get("workStartDate")); + //人员的入职日期 + String companyStartDate = Util.null2String(params.get("companyStartDate")); + + //假期规则的ID + String rulesDetailId = Util.null2String(params.get("rulesDetailId")); + //当前假期规则发放方式:1-手动发放、2-按司龄自动发放、3-按工龄自动发放、4-每年自动发放固定天数、5-加班时长自动计入余额、6-按入职时长+工龄自动发放 + int distributionMode = Util.getIntValue("" + params.get("distributionMode"), 1); + //当[distributionMode]=[4-每年发放固定天数]时有效 + double annualAmount = Util.getDoubleValue("" + params.get("annualAmount"), 0); + //法定年假规则(当distributionMode=6时有效):0-工龄、1-司龄、2-工龄+司龄 + int legalKey = Util.getIntValue("" + params.get("legalKey"), 0); + //福利年假规则(当distributionMode=6时有效):0-工龄、1-司龄、2-工龄+司龄 + int welfareKey = Util.getIntValue("" + params.get("welfareKey"), 1); + //年假基数计算方式: + // 0-假期基数发放日期和假期基数变动日期均为每年的01月01号(但是假期基数是结合 司龄/工龄 变化前后的值按天数比例折算出来的)、 + // 1-假期基数发放日期和假期基数变动日期均为每年的01月01号、 + // 2-假期基数发放日期发放日期为每年的01月01号,假期基数的变动日期为每年的 入职日期/参加工作日期 + int calcMethod = Util.getIntValue("" + params.get("calcMethod"), 1); + //假期基数发放日期 + String baseAmountReleaseDate = ""; + //假期基数变动日期 + String baseAmountChangeDate = ""; + //工龄or司龄的变动日期 + String ageLimitChangeDate = ""; + String ageLimitChangeDatetemp = ""; + //入职日期or参加工作日期 + String date4CalcAgeLimit = ""; + if (distributionMode == 2) { + date4CalcAgeLimit = companyStartDate; + //根据假期基数的计算方式得出【假期基数发放日期】、【假期基数变动日期】、【工龄or司龄的变动日期】 + if (calcMethod == 0 || calcMethod == 1) { + baseAmountReleaseDate = belongYear + "-01-01"; + baseAmountChangeDate = belongYear + "-01-01"; + ageLimitChangeDate = belongYear + companyStartDate.substring(4); + } else if (calcMethod == 2) { + baseAmountReleaseDate = belongYear + "-01-01"; + baseAmountChangeDate = belongYear + companyStartDate.substring(4); + ageLimitChangeDate = belongYear + companyStartDate.substring(4); + } + } else if (distributionMode == 3) { + date4CalcAgeLimit = workStartDate; + //根据假期基数的计算方式得出【假期基数发放日期】、【假期基数变动日期】、【工龄or司龄的变动日期】 + if (calcMethod == 0 || calcMethod == 1) { + baseAmountReleaseDate = belongYear + "-01-01"; + baseAmountChangeDate = belongYear + "-01-01"; + ageLimitChangeDate = belongYear + workStartDate.substring(4); + } else if (calcMethod == 2) { + baseAmountReleaseDate = belongYear + "-01-01"; + baseAmountChangeDate = belongYear + workStartDate.substring(4); + ageLimitChangeDate = belongYear + workStartDate.substring(4); + } + //如果是初始获得年,那么,入职日期和参加工作日期,取相对较晚的日期,作为变动日期 + if(companyStartDate.substring(4).compareTo(workStartDate.substring(4)) <= 0){ + ageLimitChangeDatetemp = belongYear + workStartDate.substring(4); + }else{ + ageLimitChangeDatetemp = belongYear + companyStartDate.substring(4); + } + } + + //批处理日期(因为存在当前年份批处理上一年份或者批处理下一年份,所以需要做一些特殊处理) + String date4CalcAmount = ""; + if (belongYear.compareTo(currentYear) < 0) { + date4CalcAmount = belongYear + "-12-31"; + } else if (belongYear.compareTo(currentYear) == 0) { + date4CalcAmount = currentDate; + } else { + date4CalcAmount = baseAmountReleaseDate; + } + //折算方式 + int convertMode = Util.getIntValue("" + params.get("convertMode"), 0); + //折算后的假期余额保留几位小数 + decimalDigit = Util.getIntValue("" + params.get("decimalDigit"), 2); + + //人员在【假期基数发放日期】时对应的【工龄or司龄】 + int ageLimit = getAgeLimit(date4CalcAgeLimit, baseAmountReleaseDate); + //人员在【假期基数发放日期】时应有的【假期基数】 + BigDecimal baseAmount_releaseDate = getAmountByAgeLimit(distributionMode, rulesDetailId, annualAmount, ageLimit, -1, -1, -1, ""); + + //人员在【工龄or司龄变动日期】时对应的【工龄or司龄】 + int ageLimit_ageLimitChangeDate = getAgeLimit(date4CalcAgeLimit, ageLimitChangeDate); + //人员在【工龄or司龄变动日期】时应有的【假期基数】 + BigDecimal baseAmount_ageLimitChangeDate = getAmountByAgeLimit(distributionMode, rulesDetailId, annualAmount, ageLimit_ageLimitChangeDate, -1, -1, -1, ""); + + //如果人员在【假期基数发放日期】时对应的【假期基数】为0,并且【批处理日期】小于【工龄or司龄变动日期】,则假期基数应该是0 + if (baseAmount_releaseDate.doubleValue() <= 0 && date4CalcAmount.compareTo(ageLimitChangeDate) < 0) { + return 0; + } + + //如果【calcMethod】==0?假期基数按比例精确计算 + boolean needCalc0 = false; + //是否需要折算 + boolean needConvert = false; + //以哪个日期来折算 + Calendar calendar = null; + //入职前的假期基数应该为0 + if (date4CalcAmount.compareTo(companyStartDate) < 0) { + return 0; + } + //如果批处理年份等于入职年份,那应该以【入职日期】来折算 + if (belongYear.compareTo(companyStartDate.substring(0, 4)) == 0) { + //需要折算 + needConvert = true; + //以【入职日期来折算】 + calendar = DateUtil.getCalendar(companyStartDate); + } + /** + * 年假基数的计算方法如下: + * 第一种情况:工龄or司龄的变动日期<假期基数发放日期<=假期基数变动日期 + * 批处理日期<假期基数发放日期?假期基数=0 + * 批处理日期>=假期基数基数发放日期?根据假期基数发放日期计算工龄or司龄,然后得出对应的假期基数 + * 第二种情况:假期基数发放日期<=工龄or司龄的变动日期<=假期基数变动日期 + * 批处理日期<假期基数发放日期?假期基数=0 + * 批处理日期=假期基数发放日期?根据假期基数发放日期计算工龄or司龄,然后得出对应的假期基数 + * 批处理日期>假期基数发放日期 && 批处理日期<工龄or司龄的变动日期?根据假期基数发放日期计算工龄or司龄,然后得出对应的假期基数 + * 批处理日期>假期基数发放日期 && 批处理日期>=工龄or司龄的变动日期? + * 如果是初始获得年(即年初01-01的时候假期基数为0,但是后面工龄or司龄增加后,假期基数就不再为0了)?根据【工龄or司龄的变动日期】计算工龄or司龄,然后得出对应的假期基数。此处得到的假期基数需要折算) + * 如果不是初始获得年?批处理日期>=假期基数变动日期?根据【工龄or司龄的变动日期】计算工龄or司龄,然后得出对应的假期基数。此处得到的假期基数不需要折算 + * 第三种情况:假期基数发放日期<假期基数变动日期<工龄or司龄的变动日期 + * 批处理日期<假期基数发放日期?假期基数=0 + * 批处理日期=假期基数发放日期? + * 如果【calcMethod】!=0?根据假期基数发放日期计算工龄or司龄,然后得出对应的假期基数 + * 如果【calcMethod】==0?假期基数按比例精确计算 + * 批处理日期>假期基数发放日期 && 批处理日期<工龄or司龄的变动日期? + * 如果【calcMethod】!=0?根据假期基数发放日期计算工龄or司龄,然后得出对应的假期基数 + * 如果【calcMethod】==0?假期基数按比例精确计算 + * 批处理日期>假期基数发放日期 && 批处理日期>=工龄or司龄的变动日期? + * 如果是初始获得年?根据【工龄or司龄的变动日期】计算工龄or司龄,然后得出对应的假期基数。此处得到的假期基数需要折算 + * 如果不是初始获得年? + * 如果【calcMethod】!=0?根据假期基数发放日期计算工龄or司龄,然后得出对应的假期基数 + * 如果【calcMethod】==0?假期基数按比例精确计算 + */ + if (ageLimitChangeDate.compareTo(baseAmountReleaseDate) < 0 && baseAmountReleaseDate.compareTo(baseAmountChangeDate) <= 0) { + if (date4CalcAmount.compareTo(baseAmountReleaseDate) < 0) { + return 0; + } else if (date4CalcAmount.compareTo(baseAmountReleaseDate) >= 0) { + baseAmount = baseAmount_releaseDate; + } + } else if (baseAmountReleaseDate.compareTo(ageLimitChangeDate) <= 0 && ageLimitChangeDate.compareTo(baseAmountChangeDate) <= 0) { + if (date4CalcAmount.compareTo(baseAmountReleaseDate) < 0) { + return 0; + } else if (date4CalcAmount.compareTo(baseAmountReleaseDate) == 0) { + baseAmount = baseAmount_releaseDate; + } else { + if (date4CalcAmount.compareTo(ageLimitChangeDate) < 0) { + baseAmount = baseAmount_releaseDate; + } else if (date4CalcAmount.compareTo(ageLimitChangeDate) >= 0) { + baseAmount = baseAmount_releaseDate; + if (baseAmount_releaseDate.doubleValue() <= 0) { + needConvert = true; + //如果是当年入职,则按照【入职日期折算】 + if (distributionMode == 3&&belongYear.compareTo(companyStartDate.substring(0, 4)) == 0) { + calendar = DateUtil.getCalendar(ageLimitChangeDatetemp); + }else{ + calendar = DateUtil.getCalendar(ageLimitChangeDate); + } + + baseAmount = baseAmount_ageLimitChangeDate; + } else { + if (date4CalcAmount.compareTo(baseAmountChangeDate) >= 0) { + baseAmount = baseAmount_ageLimitChangeDate; + } + } + } + } + } else if (baseAmountReleaseDate.compareTo(baseAmountChangeDate) <= 0 && baseAmountChangeDate.compareTo(ageLimitChangeDate) < 0) { + if (date4CalcAmount.compareTo(baseAmountReleaseDate) < 0) { + return 0; + } else if (date4CalcAmount.compareTo(baseAmountReleaseDate) == 0) { + baseAmount = baseAmount_releaseDate; + if (calcMethod == 0) { + needCalc0 = true; + } + } else { + if (date4CalcAmount.compareTo(ageLimitChangeDate) < 0) { + baseAmount = baseAmount_releaseDate; + if (calcMethod == 0) { + needCalc0 = true; + } + } else if (date4CalcAmount.compareTo(ageLimitChangeDate) >= 0) { + baseAmount = baseAmount_releaseDate; + if (baseAmount_releaseDate.doubleValue() <= 0) { + needConvert = true; + //如果是当年入职,则按照【入职日期折算】 + if (distributionMode == 3&&belongYear.compareTo(companyStartDate.substring(0, 4)) == 0) { + calendar = DateUtil.getCalendar(ageLimitChangeDatetemp); + }else{ + calendar = DateUtil.getCalendar(ageLimitChangeDate); + } + + baseAmount = baseAmount_ageLimitChangeDate; + } else if (calcMethod == 0) { + needCalc0 = true; + } + } + } + } + + if (needCalc0) { + baseAmount = baseAmount_releaseDate; + + Calendar _calendar1 = DateUtil.getCalendar(baseAmountReleaseDate); + BigDecimal _dayOfYear1 = new BigDecimal("" + (_calendar1.get(Calendar.DAY_OF_YEAR) - 1)); + BigDecimal _actualMaximum = new BigDecimal("" + _calendar1.getActualMaximum(Calendar.DAY_OF_YEAR)); + + Calendar _calendar2 = DateUtil.getCalendar(ageLimitChangeDate); + BigDecimal _dayOfYear2 = new BigDecimal("" + (_calendar2.get(Calendar.DAY_OF_YEAR) - 1)); + + baseAmount = (baseAmount_releaseDate.multiply(_dayOfYear2.subtract(_dayOfYear1)) + .add(baseAmount_ageLimitChangeDate.multiply(_actualMaximum.subtract(_dayOfYear2)))) + .divide(_actualMaximum.subtract(_dayOfYear1), decimalDigit, RoundingMode.HALF_UP); + + if (convertMode == 0) { + if (date4CalcAmount.compareTo(baseAmountReleaseDate) >= 0) { + baseAmount = baseAmount_releaseDate.setScale(decimalDigit, RoundingMode.HALF_UP); + } + if (date4CalcAmount.compareTo(baseAmountChangeDate) >= 0) { + baseAmount = baseAmount_ageLimitChangeDate.setScale(decimalDigit, RoundingMode.HALF_UP); + } + } else if (convertMode == 1) { + baseAmount = baseAmount; + } else if (convertMode == 2) { + baseAmount = baseAmount.setScale(0, RoundingMode.UP); + } else if (convertMode == 3) { + baseAmount = baseAmount.setScale(0, RoundingMode.DOWN); + } else if (convertMode == 4) { + baseAmount = baseAmount.divide(new BigDecimal("0.5"), 0, RoundingMode.UP).multiply(new BigDecimal("0.5")); + } else if (convertMode == 5) { + baseAmount = baseAmount.divide(new BigDecimal("0.5"), 0, RoundingMode.DOWN).multiply(new BigDecimal("0.5")); + } + } + + if (needConvert) { + //这一年一共有多少天 + BigDecimal actualMaximum = new BigDecimal("" + calendar.getActualMaximum(Calendar.DAY_OF_YEAR)); + //年假变动日期是这一天的第几天 + BigDecimal dayOfYear = new BigDecimal("" + (calendar.get(Calendar.DAY_OF_YEAR) - 1)); + + if (convertMode == 0) { + baseAmount = baseAmount; + } else if (convertMode == 1) { + baseAmount = baseAmount.multiply(actualMaximum.subtract(dayOfYear)).divide(actualMaximum, decimalDigit, RoundingMode.HALF_UP); + } else if (convertMode == 2) { + baseAmount = baseAmount.multiply(actualMaximum.subtract(dayOfYear)).divide(actualMaximum, 0, RoundingMode.UP); + } else if (convertMode == 3) { + baseAmount = baseAmount.multiply(actualMaximum.subtract(dayOfYear)).divide(actualMaximum, 0, RoundingMode.DOWN); + } else if (convertMode == 4) { + baseAmount = baseAmount.multiply(actualMaximum.subtract(dayOfYear)).divide(actualMaximum.multiply(new BigDecimal("0.5")), 0, RoundingMode.UP).multiply(new BigDecimal("0.5")); + } else if (convertMode == 5) { + baseAmount = baseAmount.multiply(actualMaximum.subtract(dayOfYear)).divide(actualMaximum.multiply(new BigDecimal("0.5")), 0, RoundingMode.DOWN).multiply(new BigDecimal("0.5")); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + return baseAmount.setScale(decimalDigit, RoundingMode.HALF_UP).doubleValue(); + } + + /** + * [4-每年发放固定天数]计算假期基数 + * + * @param params Map + * belongYear:所属年份 + * createDate:人员创建日期 + * companyStartDate:入职日期 + * distributionMode:当前假期规则发放方式 + * annualAmount:当[distributionMode]=[4-每年发放固定天数]时有效 + * convertMode:折算方式 + * decimalDigit:折算后的假期余额保留几位小数 + * @return + */ + private static double getBaseAmountByDis4(Map params) { + BigDecimal baseAmount = new BigDecimal("0"); + int decimalDigit = 2; + try { + //当前日期 + String currentDate = DateUtil.getCurrentDate(); + //当前年份 + String currentYear = currentDate.substring(0, 4); + //批处理年份 + String belongYear = Util.null2String(params.get("belongYear")); + //人员的入职日期 + String companyStartDate = Util.null2String(params.get("companyStartDate")); + //当前假期规则发放方式:1-手动发放、2-按司龄自动发放、3-按工龄自动发放、4-每年自动发放固定天数、5-加班时长自动计入余额、6-按入职时长+工龄自动发放 + int distributionMode = Util.getIntValue("" + params.get("distributionMode"), 1); + //当[distributionMode]=[4-每年发放固定天数]时有效 + double annualAmount = Util.getDoubleValue("" + params.get("annualAmount"), 0); + //折算方式 + int convertMode = Util.getIntValue("" + params.get("convertMode"), 0); + //折算后的假期余额保留几位小数 + decimalDigit = Util.getIntValue("" + params.get("decimalDigit"), 2); + //批处理日期(因为存在当前年份批处理上一年份或者批处理下一年份,所以需要做一些特殊处理) + String date4CalcAmount = ""; + if (belongYear.compareTo(currentYear) < 0) { + date4CalcAmount = belongYear + "-12-31"; + } else if (belongYear.compareTo(currentYear) == 0) { + date4CalcAmount = currentDate; + } else { + date4CalcAmount = belongYear + "-01-01"; + } + if (distributionMode == 4) { + if (date4CalcAmount.compareTo(companyStartDate) < 0) { + return 0; + } + baseAmount = new BigDecimal("" + annualAmount); + //当批处理年份=入职年份时,需要折算 + if (!"".equals(companyStartDate) && belongYear.equals(companyStartDate.substring(0, 4))) { + //以入职日期来折算 + Calendar calendar = DateUtil.getCalendar(companyStartDate); + //这一年一共有多少天 + BigDecimal actualMaximum = new BigDecimal("" + calendar.getActualMaximum(Calendar.DAY_OF_YEAR)); + //年假变动日期是这一天的第几天 + BigDecimal dayOfYear = new BigDecimal("" + (calendar.get(Calendar.DAY_OF_YEAR) - 1)); + + if (convertMode == 0) { + baseAmount = baseAmount; + } else if (convertMode == 1) { + baseAmount = baseAmount.multiply(actualMaximum.subtract(dayOfYear)).divide(actualMaximum, decimalDigit, RoundingMode.HALF_UP); + } else if (convertMode == 2) { + baseAmount = baseAmount.multiply(actualMaximum.subtract(dayOfYear)).divide(actualMaximum, 0, RoundingMode.UP); + } else if (convertMode == 3) { + baseAmount = baseAmount.multiply(actualMaximum.subtract(dayOfYear)).divide(actualMaximum, 0, RoundingMode.DOWN); + } else if (convertMode == 4) { + baseAmount = baseAmount.multiply(actualMaximum.subtract(dayOfYear)).divide(actualMaximum.multiply(new BigDecimal("0.5")), 0, RoundingMode.UP).multiply(new BigDecimal("0.5")); + } else if (convertMode == 5) { + baseAmount = baseAmount.multiply(actualMaximum.subtract(dayOfYear)).divide(actualMaximum.multiply(new BigDecimal("0.5")), 0, RoundingMode.DOWN).multiply(new BigDecimal("0.5")); + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + return baseAmount.setScale(decimalDigit, RoundingMode.HALF_UP).doubleValue(); + } + + /** + * [6-按司龄+工龄自动发放]计算假期基数 + * + * @param params Map + * belongYear:所属年份 + * createDate:人员创建日期 + * workStartDate:参加工作日期 + * companyStartDate:入职日期 + * rulesDetailId:假期规则的ID + * distributionMode:当前假期规则发放方式 + * legalKey:法定年假规则(当[distributionMode=6]时有效):0-工龄、1-司龄、2-工龄+司龄 + * welfareKey:福利年假规则(当[distributionMode=6]时有效):0-工龄、1-司龄、2-工龄+司龄 + * calcMethod:假期基数计算方式 + * convertMode:折算方式 + * decimalDigit:折算后的假期余额保留几位小数 + * @return + */ + private static double getBaseAmountByDis6(Map params) { + //法定年假 + BigDecimal baseAmount = new BigDecimal("0"); + int decimalDigit = 2; + try { + //当前日期 + String currentDate = DateUtil.getCurrentDate(); + //当前年份 + String currentYear = currentDate.substring(0, 4); + //批处理年份 + String belongYear = Util.null2String(params.get("belongYear")); + //人员的参加工作日期 + String workStartDate = Util.null2String(params.get("workStartDate")); + //人员的入职日期 + String companyStartDate = Util.null2String(params.get("companyStartDate")); + //假期规则的ID + String rulesDetailId = Util.null2String(params.get("rulesDetailId")); + //当前假期规则发放规则:1-手动发放、2-按司龄自动发放、3-按工龄自动发放、4-每年自动发放固定天数、5-加班时长自动计入余额、6-按入职时长+工龄自动发放 + int distributionMode = Util.getIntValue("" + params.get("distributionMode"), 1); + //法定年假规则(当distributionMode=6时有效):0-工龄、1-司龄、2-工龄+司龄 + int legalKey = Util.getIntValue("" + params.get("legalKey"), 0); + //福利年假规则(当distributionMode=6时有效):0-工龄、1-司龄、2-工龄+司龄 + int welfareKey = Util.getIntValue("" + params.get("welfareKey"), 1); + //年假基数计算方式: + // 0-假期基数发放日期和假期基数变动日期均为每年的01月01号(但是假期基数是结合 司龄/工龄 变化前后的值按天数比例折算出来的)、 + // 1-假期基数发放日期和假期基数变动日期均为每年的01月01号、 + // 2-假期基数发放日期发放日期为每年的01月01号,假期基数的变动日期为每年的 入职日期/参加工作日期 + int calcMethod = Util.getIntValue("" + params.get("calcMethod"), 1); + //假期基数发放日期 + String baseAmountReleaseDate = ""; + //工龄变动日期 + String ageLimitChangeDate = ""; + //司龄变动日期 + String ageLimitChangeDate2 = ""; + //根据假期基数的计算方式得出【假期基数发放日期】、【假期基数变动日期】、【工龄变动日期】、【司龄变动日期】 + if (calcMethod == 0 || calcMethod == 1) { + baseAmountReleaseDate = belongYear + "-01-01"; + ageLimitChangeDate = belongYear + workStartDate.substring(4); + ageLimitChangeDate2 = belongYear + companyStartDate.substring(4); + } else if (calcMethod == 2) { + baseAmountReleaseDate = belongYear + "-01-01"; + ageLimitChangeDate = belongYear + workStartDate.substring(4); + ageLimitChangeDate2 = belongYear + companyStartDate.substring(4); + } + //批处理日期(因为存在当前年份批处理上一年份或者批处理下一年份,所以需要做一些特殊处理) + String date4CalcAmount = ""; + if (belongYear.compareTo(currentYear) < 0) { + date4CalcAmount = belongYear + "-12-31"; + } else if (belongYear.compareTo(currentYear) == 0) { + date4CalcAmount = currentDate; + } else { + date4CalcAmount = baseAmountReleaseDate; + } + //获取假期规则的【折算方式】 + int convertMode = Util.getIntValue("" + params.get("convertMode"), 0); + //获取假期规则的【假期余额小数位数】 + decimalDigit = Util.getIntValue("" + params.get("decimalDigit"), 2); + //是计算法定年假还是福利年假 + String legalOrWelfare = Util.null2String(params.get("legalOrWelfare")); + + //人员在【假期基数发放日期】时对应的工龄 + int ageLimit_releaseDate = getAgeLimit(workStartDate, baseAmountReleaseDate); + //人员在【假期基数发放日期】时对应的司龄 + int ageLimit2_releaseDate = getAgeLimit(companyStartDate, baseAmountReleaseDate); + //人员在【假期基数发放日期】时对应的假期基数 + BigDecimal baseAmount_releaseDate = getAmountByAgeLimit(distributionMode, rulesDetailId, -1, ageLimit_releaseDate, ageLimit2_releaseDate, legalKey, welfareKey, legalOrWelfare); + + //人员在【工龄变动日期】时对应的工龄 + int ageLimit_ageLimitChangeDate = getAgeLimit(workStartDate, ageLimitChangeDate); + //人员在【工龄变动日期】时对应的司龄 + int ageLimit2_ageLimitChangeDate = getAgeLimit(companyStartDate, ageLimitChangeDate); + //人员在【工龄变动日期】时对应的假期基数 + BigDecimal baseAmount_ageLimitChangeDate = getAmountByAgeLimit(distributionMode, rulesDetailId, -1, ageLimit_ageLimitChangeDate, ageLimit2_ageLimitChangeDate, legalKey, welfareKey, legalOrWelfare); + + //人员在【司龄变动日期】时对应的司龄 + int ageLimit_ageLimitChangeDate2 = getAgeLimit(workStartDate, ageLimitChangeDate2); + //人员在【司龄变动日期】时对应的司龄 + int ageLimit2_ageLimitChangeDate2 = getAgeLimit(companyStartDate, ageLimitChangeDate2); + //人员在【司龄变动日期】时对应的假期基数 + BigDecimal baseAmount_ageLimitChangeDate2 = getAmountByAgeLimit(distributionMode, rulesDetailId, -1, ageLimit_ageLimitChangeDate2, ageLimit2_ageLimitChangeDate2, legalKey, welfareKey, legalOrWelfare); + + //是否需要精确计算 + boolean needCalc0 = false; + //是否需要折算 + boolean needConvert = false; + //根据什么日期进行折算 + Calendar calendar = null; + //如果【批处理日期】小于【入职日期】,假期基数应该为0 + if (date4CalcAmount.compareTo(companyStartDate) < 0) { + return 0; + } + //如果批处理年份等于入职年份,那应该以【入职日期】来折算 + String ageLimitChangeDatetemp = ""; + if (belongYear.compareTo(companyStartDate.substring(0, 4)) == 0) { + //需要折算 + needConvert = true; + //以【入职日期来折算】 + calendar = DateUtil.getCalendar(companyStartDate); + //如果是按照司龄计算,就只按照司龄折算。 + if(legalKey==1||welfareKey==1){ + ageLimitChangeDatetemp = companyStartDate; + }else{ + //如果是初始获得年,那么,入职日期和参加工作日期,取相对较晚的日期,作为变动日期 + if(companyStartDate.substring(4).compareTo(workStartDate.substring(4)) <= 0){ + ageLimitChangeDatetemp = belongYear + workStartDate.substring(4); + }else{ + ageLimitChangeDatetemp = companyStartDate; + } + } + + + } + for (int i = 0; i < 1; i++) { + //如果【计算假期基数的日期】小于【假期基数发放日期】,假期基数应该为0 + if (date4CalcAmount.compareTo(baseAmountReleaseDate) < 0) { + return 0; + } else if (date4CalcAmount.compareTo(baseAmountReleaseDate) >= 0) { + baseAmount = baseAmount_releaseDate; + //暂定【假期基数发放日期】一定小于等于【工龄变动日期】、【司龄变动日期】 + //【假期基数发放日期】<=【工龄变动日期】<=【司龄变动日期】 + if (baseAmountReleaseDate.compareTo(ageLimitChangeDate) <= 0 && ageLimitChangeDate.compareTo(ageLimitChangeDate2) <= 0) { + if (calcMethod == 0 && baseAmount_releaseDate.doubleValue() > 0) { + Calendar _calendar1 = DateUtil.getCalendar(baseAmountReleaseDate); + BigDecimal _dayOfYear1 = new BigDecimal("" + (_calendar1.get(Calendar.DAY_OF_YEAR) - 1)); + BigDecimal _actualMaximum = new BigDecimal("" + (_calendar1.getActualMaximum(Calendar.DAY_OF_YEAR))); + + Calendar _calender2 = DateUtil.getCalendar(ageLimitChangeDate); + BigDecimal _dayOfYear2 = new BigDecimal("" + (_calender2.get(Calendar.DAY_OF_YEAR) - 1)); + + Calendar _calender3 = DateUtil.getCalendar(ageLimitChangeDate2); + BigDecimal _dayOfYear3 = new BigDecimal("" + (_calender3.get(Calendar.DAY_OF_YEAR) - 1)); + + baseAmount = ((baseAmount_releaseDate.multiply(_dayOfYear2.subtract(_dayOfYear1))) + .add(baseAmount_ageLimitChangeDate.multiply(_dayOfYear3.subtract(_dayOfYear2))) + .add(baseAmount_ageLimitChangeDate2.multiply(_actualMaximum.subtract(_dayOfYear3)))) + .divide(_actualMaximum, decimalDigit, RoundingMode.HALF_UP); + if (convertMode == 0) { + if (date4CalcAmount.compareTo(baseAmountReleaseDate) >= 0) { + baseAmount = baseAmount_releaseDate.setScale(decimalDigit, RoundingMode.HALF_UP); + } + if (date4CalcAmount.compareTo(ageLimitChangeDate) >= 0) { + baseAmount = baseAmount_ageLimitChangeDate.setScale(decimalDigit, RoundingMode.HALF_UP); + } + if (date4CalcAmount.compareTo(ageLimitChangeDate2) >= 0) { + baseAmount = baseAmount_ageLimitChangeDate2.setScale(decimalDigit, RoundingMode.HALF_UP); + } + } else if (convertMode == 1) { + baseAmount = baseAmount; + } else if (convertMode == 2) { + baseAmount = baseAmount.setScale(0, RoundingMode.UP); + } else if (convertMode == 3) { + baseAmount = baseAmount.setScale(0, RoundingMode.DOWN); + } else if (convertMode == 4) { + baseAmount = baseAmount.divide(new BigDecimal("0.5"), 0, RoundingMode.UP).multiply(new BigDecimal("0.5")); + } else if (convertMode == 5) { + baseAmount = baseAmount.divide(new BigDecimal("0.5"), 0, RoundingMode.DOWN).multiply(new BigDecimal("0.5")); + } + break; + } + //【批处理日期】>=【工龄变动日期】&& (人员在【假期基数发放日期】时对应的假期基数是0 || 【假期基数计算方式=2】时) + if ((date4CalcAmount.compareTo(ageLimitChangeDate) >= 0) + && (baseAmount_releaseDate.doubleValue() <= 0 || calcMethod == 2)) { + if (baseAmount_releaseDate.doubleValue() <= 0 && baseAmount_ageLimitChangeDate.doubleValue() > 0) { + needConvert = true; + //如果是当年入职,则按照【入职日期折算】 + if (belongYear.compareTo(companyStartDate.substring(0, 4)) == 0) { + calendar = DateUtil.getCalendar(ageLimitChangeDatetemp); + }else{ + calendar = DateUtil.getCalendar(ageLimitChangeDate); + } + + baseAmount = baseAmount_ageLimitChangeDate; + } else { + if (calcMethod == 2) { + baseAmount = baseAmount_ageLimitChangeDate; + } + } + } + //【批处理日期】>=【司龄变动日期】&& (人员在【工龄变动日期】时对应的假期基数是0||【假期基数计算方式=2】时) + if ((date4CalcAmount.compareTo(ageLimitChangeDate2) >= 0) + && (baseAmount_ageLimitChangeDate.doubleValue() <= 0 || calcMethod == 2)) { + if (baseAmount_ageLimitChangeDate.doubleValue() <= 0 && baseAmount_ageLimitChangeDate2.doubleValue() > 0) { + needConvert = true; + if (belongYear.compareTo(companyStartDate.substring(0, 4)) == 0) { + calendar = DateUtil.getCalendar(ageLimitChangeDatetemp); + }else{ + calendar = DateUtil.getCalendar(ageLimitChangeDate2); + } + baseAmount = baseAmount_ageLimitChangeDate2; + } else { + if (calcMethod == 2) { + baseAmount = baseAmount_ageLimitChangeDate2; + } + } + } + } else if (baseAmountReleaseDate.compareTo(ageLimitChangeDate2) <= 0 && ageLimitChangeDate2.compareTo(ageLimitChangeDate) <= 0) { + if (calcMethod == 0 && baseAmount_releaseDate.doubleValue() > 0) { + Calendar _calendar1 = DateUtil.getCalendar(baseAmountReleaseDate); + BigDecimal _dayOfYear1 = new BigDecimal("" + (_calendar1.get(Calendar.DAY_OF_YEAR) - 1)); + BigDecimal _actualMaximum = new BigDecimal("" + _calendar1.getActualMaximum(Calendar.DAY_OF_YEAR)); + + Calendar _calender2 = DateUtil.getCalendar(ageLimitChangeDate2); + BigDecimal _dayOfYear2 = new BigDecimal("" + (_calender2.get(Calendar.DAY_OF_YEAR) - 1)); + + Calendar _calender3 = DateUtil.getCalendar(ageLimitChangeDate); + BigDecimal _dayOfYear3 = new BigDecimal("" + (_calender3.get(Calendar.DAY_OF_YEAR) - 1)); + + baseAmount = ((baseAmount_releaseDate.multiply(_dayOfYear2.subtract(_dayOfYear1))) + .add(baseAmount_ageLimitChangeDate2.multiply(_dayOfYear3.subtract(_dayOfYear2))) + .add(baseAmount_ageLimitChangeDate.multiply(_actualMaximum.subtract(_dayOfYear3)))) + .divide(_actualMaximum, decimalDigit, RoundingMode.HALF_UP); + if (convertMode == 0) { + if (date4CalcAmount.compareTo(baseAmountReleaseDate) >= 0) { + baseAmount = baseAmount_releaseDate.setScale(decimalDigit, RoundingMode.HALF_UP); + } + if (date4CalcAmount.compareTo(ageLimitChangeDate2) >= 0) { + baseAmount = baseAmount_ageLimitChangeDate2.setScale(decimalDigit, RoundingMode.HALF_UP); + } + if (date4CalcAmount.compareTo(ageLimitChangeDate) >= 0) { + baseAmount = baseAmount_ageLimitChangeDate.setScale(decimalDigit, RoundingMode.HALF_UP); + } + } else if (convertMode == 1) { + baseAmount = baseAmount; + } else if (convertMode == 2) { + baseAmount = baseAmount.setScale(0, RoundingMode.UP); + } else if (convertMode == 3) { + baseAmount = baseAmount.setScale(0, RoundingMode.DOWN); + } else if (convertMode == 4) { + baseAmount = baseAmount.divide(new BigDecimal("0.5"), 0, RoundingMode.UP).multiply(new BigDecimal("0.5")); + } else if (convertMode == 5) { + baseAmount = baseAmount.divide(new BigDecimal("0.5"), 0, RoundingMode.DOWN).multiply(new BigDecimal("0.5")); + } + break; + } + if ((date4CalcAmount.compareTo(ageLimitChangeDate2) >= 0) + && (baseAmount_releaseDate.doubleValue() <= 0 || calcMethod == 2)) { + if (baseAmount_releaseDate.doubleValue() <= 0 && baseAmount_ageLimitChangeDate2.doubleValue() > 0) { + needConvert = true; + if (belongYear.compareTo(companyStartDate.substring(0, 4)) == 0) { + calendar = DateUtil.getCalendar(ageLimitChangeDatetemp); + }else{ + calendar = DateUtil.getCalendar(ageLimitChangeDate2); + } + + baseAmount = baseAmount_ageLimitChangeDate2; + } else { + if (calcMethod == 2) { + baseAmount = baseAmount_ageLimitChangeDate2; + } + } + } + if ((date4CalcAmount.compareTo(ageLimitChangeDate) >= 0) + && (baseAmount_ageLimitChangeDate2.doubleValue() <= 0 || calcMethod == 2)) { + if (baseAmount_ageLimitChangeDate2.doubleValue() <= 0 && baseAmount_ageLimitChangeDate.doubleValue() > 0) { + needConvert = true; + if (belongYear.compareTo(companyStartDate.substring(0, 4)) == 0) { + calendar = DateUtil.getCalendar(ageLimitChangeDatetemp); + }else{ + calendar = DateUtil.getCalendar(ageLimitChangeDate); + } + + baseAmount = baseAmount_ageLimitChangeDate; + } else { + if (calcMethod == 2) { + baseAmount = baseAmount_ageLimitChangeDate; + } + } + } + } + } + } + + if (needConvert) { + //这一年一共有多少天 + BigDecimal actualMaximum = new BigDecimal("" + calendar.getActualMaximum(Calendar.DAY_OF_YEAR)); + //年假变动日期是这一天的第几天 + BigDecimal dayOfYear = new BigDecimal("" + (calendar.get(Calendar.DAY_OF_YEAR) - 1)); + + if (convertMode == 0) { + baseAmount = baseAmount; + } else if (convertMode == 1) { + baseAmount = baseAmount.multiply(actualMaximum.subtract(dayOfYear)).divide(actualMaximum, decimalDigit, RoundingMode.HALF_UP); + } else if (convertMode == 2) { + baseAmount = baseAmount.multiply(actualMaximum.subtract(dayOfYear)).divide(actualMaximum, 0, RoundingMode.UP); + } else if (convertMode == 3) { + baseAmount = baseAmount.multiply(actualMaximum.subtract(dayOfYear)).divide(actualMaximum, 0, RoundingMode.DOWN); + } else if (convertMode == 4) { + baseAmount = baseAmount.multiply(actualMaximum.subtract(dayOfYear)).divide(actualMaximum.multiply(new BigDecimal("0.5")), 0, RoundingMode.UP).multiply(new BigDecimal("0.5")); + } else if (convertMode == 5) { + baseAmount = baseAmount.multiply(actualMaximum.subtract(dayOfYear)).divide(actualMaximum.multiply(new BigDecimal("0.5")), 0, RoundingMode.DOWN).multiply(new BigDecimal("0.5")); + } + } else { + baseAmount = baseAmount; + } + + } catch (Exception e) { + e.printStackTrace(); + } + return baseAmount.setScale(decimalDigit, RoundingMode.HALF_UP).doubleValue(); + } + + /** + * [8-育儿假]计算假期基数 + * + * @param params Map + * belongYear:所属年份 + * createDate:人员创建日期 + * workStartDate:参加工作日期 + * companyStartDate:入职日期 + * rulesDetailId:假期规则的ID + * distributionMode:当前假期规则发放方式 + * annualAmount:当[distributionMode]=[4-每年发放固定天数]时有效 + * legalKey:法定年假规则(当[distributionMode=6]时有效):0-工龄、1-司龄、2-工龄+司龄 + * welfareKey:福利年假规则(当[distributionMode=6]时有效):0-工龄、1-司龄、2-工龄+司龄 + * calcMethod:假期基数计算方式 + * convertMode:折算方式 + * decimalDigit:折算后的假期余额保留几位小数 + * @return + */ + private static Map getBaseAmountByDis8(Map params) { + Map returnMap = Maps.newHashMap(); + + try{ + String resourceId = Util.null2String(params.get("resourceId")); + ArrayList listDates = getParentalLeaveDate(resourceId); + //当前日期 + String currentDate = DateUtil.getCurrentDate(); + //批处理年份 + String belongYear = Util.null2String(params.get("belongYear")); + String belongYearNew = ""; + //当[distributionMode]=[8-每年发放固定天数]时有效 + double annualAmount = Util.getDoubleValue("" + params.get("annualAmount"), 0); + //孩子周岁 + int yearsOld = Util.getIntValue(Util.null2String(params.get("yearsOld")),3); + + + BigDecimal baseAmount = new BigDecimal("0"); + int decimalDigit = 2; + boolean addOrUpdate = false; + String expirationDate = ""; + String expirationDateNew = ""; + //折算后的假期余额保留几位小数 + decimalDigit = Util.getIntValue("" + params.get("decimalDigit"), 2); + //批处理日期(因为存在当前年份批处理上一年份或者批处理下一年份,所以需要做一些特殊处理) + String date4CalcAmount = currentDate; + String effectiveDate = ""; + int validityRule = Util.getIntValue(Util.null2String(params.get("validityRule")),1); + /* + * 1、考虑1个孩子,0年、1年、2年发放 + * 2、考虑2个孩子,0年、1年、2年发放,第一个孩子有效期到期了,才考虑第二个孩子的。如果当前日期在第二个孩子有效期内,那么就存到有效期对应的当前年份 + *第二个孩子的2021年1月1号 + * */ + for (int i = 0; i < listDates.size(); i++) { + String dateOfBirth=listDates.get(i); + + String yearOfBirth=dateOfBirth.substring(0,4); + + String baseAmountReleaseDate = belongYear + dateOfBirth.substring(4); + int ageLimit = getAgeLimit(dateOfBirth, baseAmountReleaseDate); + + if(ageLimit>=0&&ageLimit<=yearsOld-1){ + baseAmount = new BigDecimal("" + annualAmount); + }else{ + baseAmount = new BigDecimal("0"); + } + effectiveDate=baseAmountReleaseDate; +//第二个孩子的情况 + if(!expirationDateNew.equals("")&& belongYear.compareTo(expirationDateNew.substring(0, 4)) == 0){ + if(baseAmountReleaseDate.compareTo(expirationDateNew) > 0){ + if(date4CalcAmount.compareTo(expirationDateNew) > 0&&date4CalcAmount.compareTo(baseAmountReleaseDate) < 0){ + belongYearNew = (Util.getIntValue(belongYear) - 1) + ""; + addOrUpdate = true; + new BaseBean().writeLog("育儿假1:belongYearNew="+belongYearNew); + continue; + }else if(date4CalcAmount.compareTo(expirationDateNew) <= 0){ + baseAmount = new BigDecimal("0"); + new BaseBean().writeLog("育儿假2:baseAmount="+baseAmount); + continue; + } + }else{ + if(date4CalcAmount.compareTo(expirationDateNew) >= 0){ + new BaseBean().writeLog("育儿假3:baseAmount="+baseAmount); + break; + }else{ + baseAmount = new BigDecimal("0"); + new BaseBean().writeLog("育儿假4:baseAmount="+baseAmount); + continue; + } + } + } + expirationDateNew = (Util.getIntValue(yearOfBirth) + yearsOld) + dateOfBirth.substring(4); + + String _expirationDate = (Util.getIntValue(belongYear) + 1) + dateOfBirth.substring(4); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + LocalDate yesterday = LocalDate.parse(_expirationDate, formatter).minusDays(1); + expirationDate = yesterday.toString(); // 过期日期提前了一天 + + if(ageLimit>=0&&ageLimit<=yearsOld-1){ + }else{ + baseAmount = new BigDecimal("0"); + new BaseBean().writeLog("育儿假5:baseAmount="+baseAmount); + continue; + } + + //批处理日期>=假期基数释放日期--出生日期 + if (date4CalcAmount.compareTo(baseAmountReleaseDate) >= 0) { + } else { + baseAmount = new BigDecimal("0"); + } + new BaseBean().writeLog("育儿假6:baseAmount="+baseAmount); + break; + } + new BaseBean().writeLog("育儿假7:baseAmount="+baseAmount); + if (validityRule == 0) { + + expirationDate = "2222-12-31"; + } + returnMap.put("baseAmount", baseAmount.setScale(decimalDigit, RoundingMode.HALF_UP).doubleValue()); + returnMap.put("addOrUpdate",addOrUpdate); + returnMap.put("expirationDate",expirationDate); + returnMap.put("effectiveDate",effectiveDate); + returnMap.put("belongYearNew",belongYearNew); + } catch (Exception e) { + e.printStackTrace(); + } + return returnMap; + } + /** + * [8-育儿假]计算假期基数 + * + * @param params Map + * belongYear:所属年份 + * createDate:人员创建日期 + * workStartDate:参加工作日期 + * companyStartDate:入职日期 + * rulesDetailId:假期规则的ID + * distributionMode:当前假期规则发放方式 + * annualAmount:当[distributionMode]=[4-每年发放固定天数]时有效 + * legalKey:法定年假规则(当[distributionMode=6]时有效):0-工龄、1-司龄、2-工龄+司龄 + * welfareKey:福利年假规则(当[distributionMode=6]时有效):0-工龄、1-司龄、2-工龄+司龄 + * calcMethod:假期基数计算方式 + * convertMode:折算方式 + * decimalDigit:折算后的假期余额保留几位小数 + * @return + */ + private static Map getBaseAmountByDis8Num(Map params) { + Map returnMap = Maps.newHashMap(); + + try{ + String resourceId = Util.null2String(params.get("resourceId")); + String ruleId = Util.null2String(params.get("ruleId")); + String operator = Util.null2String(params.get("operator")); + ArrayList listDates = getParentalLeaveDate(resourceId); + ArrayList listChildId = getChildId(resourceId); + //当前日期 + String currentDate = DateUtil.getCurrentDate(); + + /*获取当前日期,当前时间*/ + Calendar today = Calendar.getInstance(); + String currentTime = Util.add0(today.get(Calendar.HOUR_OF_DAY), 2) + ":" + + Util.add0(today.get(Calendar.MINUTE), 2) + ":" + + Util.add0(today.get(Calendar.SECOND), 2); + //当前年份 + String currentYear = currentDate.substring(0, 4); + //批处理年份 + String belongYear = Util.null2String(params.get("belongYear")); + String belongYearNew = ""; + //当[distributionMode]=[8-每年发放固定天数]时有效 + double annualAmount = Util.getDoubleValue("" + params.get("annualAmount"), 0); + //孩子周岁 + int yearsOld = Util.getIntValue(Util.null2String(params.get("yearsOld")),3); + BigDecimal baseAmount = new BigDecimal("0"); + int decimalDigit = 2; + boolean addOrUpdate = false; + String expirationDate = ""; + String expirationDateNew = currentDate; + + + //折算后的假期余额保留几位小数 + decimalDigit = Util.getIntValue("" + params.get("decimalDigit"), 2); + //批处理日期(因为存在当前年份批处理上一年份或者批处理下一年份,所以需要做一些特殊处理) + String date4CalcAmount = currentDate; + + int validityRule = Util.getIntValue(Util.null2String(params.get("validityRule")),1); + RecordSet rs = new RecordSet(); + // 查询当年育儿假数据 + String sql = "select * from kq_balanceOfLeave where (isDelete is null or isDelete<>1) and leaveRulesId = "+ruleId+" and ( OVERTIMETYPE<>'7' or overtimeType is null ) and resourceId = "+resourceId + " and belongYear = "+belongYear; + KQBalanceOfLeaveEntity balanceEntity = null; + Map balanceEntities = new HashMap(); + rs.executeQuery(sql); + while (rs.next()) { + int id = rs.getInt("id"); + String childId = Util.null2s(rs.getString("childId"), ""); + if(StringUtils.isNotBlank(childId)){ + double baseAmountvalue = Util.getDoubleValue(rs.getString("baseAmount"), 0.00); + double extraAmountvalue = Util.getDoubleValue(rs.getString("extraAmount"), 0.00); + double usedAmountvalue = Util.getDoubleValue(rs.getString("usedAmount"), 0.00); + balanceEntity = new KQBalanceOfLeaveEntity(); + balanceEntity.setId(id); + balanceEntity.setBaseAmount(baseAmountvalue); + balanceEntity.setExtraAmount(extraAmountvalue); + balanceEntity.setUsedAmount(usedAmountvalue); + balanceEntities.put(childId, balanceEntity); + } + } + + for (int i = 0; i < listDates.size(); i++) { + // 孩子的生日 + String dateOfBirth=listDates.get(i); + // 孩子的id + String childId = listChildId.get(i); + String baseAmountReleaseDate = belongYear + dateOfBirth.substring(4); + int ageLimit = getAgeLimit(dateOfBirth, baseAmountReleaseDate); + new BaseBean().writeLog("==getBaseAmountByDis8Num==ageLimit"+ageLimit); + if(ageLimit>=0&&ageLimit<=yearsOld-1) { + baseAmount = new BigDecimal("" + annualAmount); + + // 首先是查询数据库中是否存在这条数据 + // 旧数据是不存在孩子id的,所以现在根据孩子id和是否导入判断删除旧数据 + sql = "select * from kq_balanceOfLeave where (isDelete is null or isDelete<>1) and leaveRulesId = " + ruleId + " and childId IS NULL and ( OVERTIMETYPE<>'7' or overtimeType is null ) and resourceId = " + resourceId + " and belongYear = " + belongYear; + rs.executeQuery(sql); + double usedAmount = 0; + int id = -1; + if (rs.next()) { + // 旧数据使用量 + usedAmount = Util.getDoubleValue(rs.getString("usedamount"), 0.0); + // 旧数据记录id + id = rs.getInt("id"); + rs.writeLog("==lzl==resourceId=" + resourceId + "的旧数据id" + id + "使用情况:usedAmount" + usedAmount); + } + if (id > 0) { + // 删除旧数据 + rs.executeUpdate("DELETE FROM kq_balanceOfLeave WHERE id =" + id); + } + RecordSet recordSet = new RecordSet(); + KQBalanceOfLeaveEntity oldBalanceEntity = (KQBalanceOfLeaveEntity) balanceEntities.get(childId); + if (oldBalanceEntity != null) { + balanceEntities.remove(childId); + //如果假期基数没有发生变化,不需要更新 + if (oldBalanceEntity.getBaseAmount() == baseAmount.doubleValue()) { + continue; + } + // 如果存在数据就更新 baseAmount,为什么需要跟新这个数据呢?这是因为基数是可能发生改变的。 + int balanceOfLeaveId = oldBalanceEntity.getId(); + + String _expirationDate = (Util.getIntValue(belongYear) + 1) + dateOfBirth.substring(4); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + LocalDate yesterday = LocalDate.parse(_expirationDate, formatter).minusDays(1); + expirationDate = yesterday.toString(); // 过期日期提前了一天 + if (validityRule == 0) { + //不限制有效期,默认永久有效(永久有效时有效日期默认为2222-12-31) + expirationDate = "2222-12-31"; + } + String updateSql = "UPDATE kq_balanceOfLeave SET baseAmount = " + baseAmount + ",expirationDate='" + expirationDate + "' WHERE id = " + balanceOfLeaveId; + recordSet.writeLog("==lzl==updateSql" + updateSql); + recordSet.executeUpdate(updateSql); + + /* 执行 update 操作的日志记录 */ + String sql3 = "insert into kq_UsageHistory(leaveRulesId,relatedId,operator,operateDate,operateTime,operateType," + + "belongYear,oldBaseAmount,newBaseAmount,insertOrUpdate,oldMinimumUnit,newMinimumUnit,balanceOfLeaveId)" + + "values(" + ruleId + "," + resourceId + "," + operator + ",'" + currentDate + "','" + currentTime + "',6,'" + belongYear + "'," + oldBalanceEntity.getBaseAmount() + "," + baseAmount + ",'update',1,1," + balanceOfLeaveId + ")"; + recordSet.executeUpdate(sql3); + } else { + // 发放日期的年份加1 + String _expirationDate = (Util.getIntValue(belongYear) + 1) + dateOfBirth.substring(4); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + LocalDate yesterday = LocalDate.parse(_expirationDate, formatter).minusDays(1); + expirationDate = yesterday.toString(); // 过期日期提前了一天 + if (validityRule == 0) { + //不限制有效期,默认永久有效(永久有效时有效日期默认为2222-12-31) + expirationDate = "2222-12-31"; + } + // 解析日期字符串为 LocalDate 对象 + DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + LocalDate releaseDate = LocalDate.parse(baseAmountReleaseDate, dateFormatter); + LocalDate now = LocalDate.parse(currentDate, dateFormatter); + // 比较日期 只有当前日期大于发放日期才可以用 + int comparisonResult = releaseDate.compareTo(now); + if (comparisonResult <= 0) { + String insertSql = "INSERT INTO " + + "kq_balanceOfLeave (LEAVERULESID,RESOURCEID,BELONGYEAR,STATUS,EXPIRATIONDATE,EFFECTIVEDATE,BASEAMOUNT,EXTRAAMOUNT,USEDAMOUNT,BASEAMOUNT2,EXTRAAMOUNT2,USEDAMOUNT2,TIAOXIUAMOUNT,childId,isdelete) " + + "VALUES (" + ruleId + "," + resourceId + ",'" + belongYear + "',0,'" + expirationDate + "','" + baseAmountReleaseDate + "'," + baseAmount + " ,0," + usedAmount + ",0,0,0,0," + childId + ",0)"; + recordSet.writeLog("==lzl==insertSql" + insertSql); + recordSet.executeUpdate(insertSql); + String sql2 = "select * from kq_balanceOfLeave where leaveRulesId = " + ruleId + " and resourceId = " + resourceId + " and childId =" + childId + " and ( OVERTIMETYPE<>'7' or overtimeType is null ) and belongYear = '" + belongYear + "' and (isdelete <> 1 OR isdelete IS NULL)"; + recordSet.executeQuery(sql2); + String balanceOfLeaveId = ""; + if (recordSet.next()) { + balanceOfLeaveId = recordSet.getString("id"); + } + /* 执行 insert 操作的日志记录 */ + String sql3 = "insert into kq_UsageHistory(leaveRulesId,relatedId,operator,operateDate,operateTime,operateType," + + "belongYear,oldBaseAmount,newBaseAmount,insertOrUpdate,oldMinimumUnit,newMinimumUnit,oldExtraAmount,newExtraAmount,oldUsedAmount,newUsedAmount,oldBaseAmount2,newBaseAmount2,oldExtraAmount2,newExtraAmount2,oldUsedAmount2,newUsedAmount2,balanceOfLeaveId)" + + "values(" + ruleId + "," + resourceId + "," + operator + ",'" + currentDate + "','" + currentTime + "',6,'" + belongYear + "'," + 0 + "," + baseAmount + ",'insert',1,1,0,0,0,0,0,0,0,0,0,0," + balanceOfLeaveId + ")"; + recordSet.executeUpdate(sql3); + } + } + } + } + + // 删除不是当前孩子列表中的考勤数据 + + balanceEntities.forEach((key, value) -> { + String chlied = key; + KQBalanceOfLeaveEntity oldBalanceEntity = (KQBalanceOfLeaveEntity) value; + + String deleteSql = "UPDATE kq_balanceOfLeave SET isdelete=1 WHERE id = " + oldBalanceEntity.getId(); + String sql3 = "insert into kq_UsageHistory(leaveRulesId,relatedId,operator,operateDate,operateTime,operateType," + + "belongYear,oldBaseAmount,newBaseAmount,insertOrUpdate,oldMinimumUnit,newMinimumUnit,balanceOfLeaveId)" + + "values(" + ruleId + "," + resourceId + "," + operator + ",'" + currentDate + "','" + currentTime + "',6,'" + belongYear + "'," + oldBalanceEntity.getBaseAmount() + ",0,'update',1,1," + oldBalanceEntity.getId() + ")"; + if (oldBalanceEntity.getExtraAmount() > 0 || + oldBalanceEntity.getUsedAmount() > 0) { + deleteSql = "UPDATE kq_balanceOfLeave SET baseAmount=0 WHERE id = " + oldBalanceEntity.getId(); + } + rs.executeUpdate(deleteSql); + rs.executeUpdate(sql3); + }); + + returnMap.put("baseAmount", baseAmount.setScale(decimalDigit, RoundingMode.HALF_UP).doubleValue()); + returnMap.put("addOrUpdate",addOrUpdate); + returnMap.put("expirationDate",expirationDateNew); + returnMap.put("belongYearNew",belongYearNew); + } catch (Exception e) { + e.printStackTrace(); + } + return returnMap; + } + + + /** + * [7-按司龄自动发放(入职日期当天发放假期余额)]计算假期基数 + * + * @param params Map + * belongYear:所属年份 + * createDate:人员创建日期 + * workStartDate:参加工作日期 + * companyStartDate:入职日期 + * rulesDetailId:假期规则的ID + * distributionMode:当前假期规则发放方式 + * annualAmount:当[distributionMode]=[4-每年发放固定天数]时有效 + * legalKey:法定年假规则(当[distributionMode=6]时有效):0-工龄、1-司龄、2-工龄+司龄 + * welfareKey:福利年假规则(当[distributionMode=6]时有效):0-工龄、1-司龄、2-工龄+司龄 + * calcMethod:假期基数计算方式 + * convertMode:折算方式 + * decimalDigit:折算后的假期余额保留几位小数 + * @return + */ + private static double getBaseAmountByDis7(Map params) { + double baseAmount = 0; + try{ + //当前日期 + String currentDate = DateUtil.getCurrentDate(); + //当前年份 + String currentYear = currentDate.substring(0, 4); + //批处理年份 + String belongYear = Util.null2String(params.get("belongYear")); + //人员的参加工作日期 + String workStartDate = Util.null2String(params.get("workStartDate")); + //人员的入职日期 + String companyStartDate = Util.null2String(params.get("companyStartDate")); + + //假期规则的ID + String rulesDetailId = Util.null2String(params.get("rulesDetailId")); + //当前假期规则发放方式:1-手动发放、2-按司龄自动发放、3-按工龄自动发放、4-每年自动发放固定天数、5-加班时长自动计入余额、6-按入职时长+工龄自动发放 + int distributionMode = Util.getIntValue("" + params.get("distributionMode"), 1); + //假期基数发放日期 + String baseAmountReleaseDate = belongYear + companyStartDate.substring(4); + //默认保留两位小数 + int decimalDigit = Util.getIntValue("" + params.get("decimalDigit"), 2); + + if (distributionMode != 7) { + return baseAmount; + } + + //批处理日期 + String date4CalcAmount = currentDate; + + //人员在【假期基数发放日期】时对应的【司龄】 + int ageLimit = getAgeLimit(companyStartDate, baseAmountReleaseDate); + //人员在【假期基数发放日期】时应有的【假期基数】 + BigDecimal baseAmount_releaseDate = getAmountByAgeLimit(distributionMode, rulesDetailId, 0, ageLimit, -1, -1, -1, ""); + + //批处理日期>=假期基数释放日期 + if (date4CalcAmount.compareTo(baseAmountReleaseDate) >= 0) { + baseAmount = baseAmount_releaseDate.setScale(2, RoundingMode.HALF_UP).doubleValue(); + } else { + baseAmount = 0; + } + }catch (Exception e){ + e.printStackTrace(); + } + return baseAmount; + } + + /** + * 获取调休的余额 + * + * @param ruleId 假期类型的ID + * @param resourceId 人员ID + * @param searchDate 计算是否失效的指定日期 + * @param calcByCurrentDate 是根据当前日期计算还是根据指定日期计算假期是否失效:true-当前日期、false-指定日期 + * @param isAll 是获取所有年份的还是获取指定年份的:true-所有年份的、false-指定年份的 + * @return + */ + private static BigDecimal getRestAmountByDis5(String ruleId, String resourceId, String searchDate, boolean calcByCurrentDate, boolean isAll) { + BigDecimal restAmount = new BigDecimal("0"); + try { + //获取当前日期 + Calendar today = Calendar.getInstance(); + //当前日期 + String currentDate = Util.add0(today.get(Calendar.YEAR), 4) + "-" + + Util.add0(today.get(Calendar.MONTH) + 1, 2) + "-" + + Util.add0(today.get(Calendar.DAY_OF_MONTH), 2); + //所属年份 + String searchYear = searchDate.substring(0, 4); + //根据指定日期(或者根据当前日期)判断假期是否已经过了有效期 + String date = calcByCurrentDate ? currentDate : searchDate; + String sql = ""; + RecordSet recordSet = new RecordSet(); + if (recordSet.getDBType().equalsIgnoreCase("sqlserver") + || recordSet.getDBType().equalsIgnoreCase("mysql")) { + sql = " select sum(tiaoxiuamount) as allTiaoxiuamount,sum(baseAmount) as allBaseAmount,sum(extraAmount) as allExtraAmount,sum(usedAmount) as allUsedAmount from KQ_BalanceOfLeave " + + " where (isDelete is null or isDelete<>1) and resourceId=" + resourceId + " and leaveRulesId=" + ruleId + " and (expirationDate is null or expirationDate='' or expirationDate>='" + date + "') "; + } else { + sql = " select sum(tiaoxiuamount) as allTiaoxiuamount,sum(baseAmount) as allBaseAmount,sum(extraAmount) as allExtraAmount,sum(usedAmount) as allUsedAmount from KQ_BalanceOfLeave " + + " where (isDelete is null or isDelete<>1) and resourceId=" + resourceId + " and leaveRulesId=" + ruleId + " and (expirationDate is null or expirationDate>='" + date + "') "; + } + //是查询所有有效的假期余额还是仅仅查询指定日期当年的 + if(KQSettingsBiz.is_balanceofleave()){//开启开关 + if (!isAll) { + sql += " and belongYear='" + searchYear + "'"; + }else{ + sql += " and belongYear<='" + searchYear + "'"; + } + }else{ + if (!isAll) { + sql += " and belongYear='" + searchYear + "'"; + } + } + recordSet.executeQuery(sql); + while (recordSet.next()) { + BigDecimal _baseAmount = new BigDecimal(Util.null2s(recordSet.getString("allBaseAmount"), "0")); + BigDecimal _extraAmount = new BigDecimal(Util.null2s(recordSet.getString("allExtraAmount"), "0")); + BigDecimal _usedAmount = new BigDecimal(Util.null2s(recordSet.getString("allUsedAmount"), "0")); + BigDecimal _tiaoxiuamount = new BigDecimal(Util.null2s(recordSet.getString("allTiaoxiuamount"), "0"));//加班生成调休 + + restAmount = restAmount.add(_baseAmount).add(_tiaoxiuamount).add(_extraAmount).subtract(_usedAmount); + } + } catch (Exception e) { + e.printStackTrace(); + } + return restAmount; + } + + private static BigDecimal getRestAmountByDis8(String ruleId, String resourceId, String searchDate, boolean calcByCurrentDate, boolean isAll) { + BigDecimal restAmount = new BigDecimal("0"); + try { + //获取当前日期 + Calendar today = Calendar.getInstance(); + //当前日期 + String currentDate = Util.add0(today.get(Calendar.YEAR), 4) + "-" + + Util.add0(today.get(Calendar.MONTH) + 1, 2) + "-" + + Util.add0(today.get(Calendar.DAY_OF_MONTH), 2); + //所属年份 + String searchYear = searchDate.substring(0, 4); + //根据指定日期(或者根据当前日期)判断假期是否已经过了有效期 + String date = calcByCurrentDate ? currentDate : searchDate; + String sql = ""; + RecordSet recordSet = new RecordSet(); + if (recordSet.getDBType().equalsIgnoreCase("sqlserver") + || recordSet.getDBType().equalsIgnoreCase("mysql")) { + sql = " select sum(baseAmount) as allBaseAmount,sum(extraAmount) as allExtraAmount,sum(usedAmount) as allUsedAmount from KQ_BalanceOfLeave " + + " where (isDelete is null or isDelete<>1) and resourceId=" + resourceId + " and leaveRulesId=" + ruleId + " and (expirationDate is null or expirationDate='' or expirationDate>='" + date + "') "; + } else { + sql = " select sum(baseAmount) as allBaseAmount,sum(extraAmount) as allExtraAmount,sum(usedAmount) as allUsedAmount from KQ_BalanceOfLeave " + + " where (isDelete is null or isDelete<>1) and resourceId=" + resourceId + " and leaveRulesId=" + ruleId + " and (expirationDate is null or expirationDate>='" + date + "') "; + } + //是查询所有有效的假期余额还是仅仅查询指定日期当年的 + if(KQSettingsBiz.is_balanceofleave()){//开启开关 + if (!isAll) { + sql += " and belongYear='" + searchYear + "'"; + }else{ + sql += " and belongYear<='" + searchYear + "'"; + } + }else{ + if (!isAll) { + sql += " and belongYear='" + searchYear + "'"; + } + } + recordSet.executeQuery(sql); + while (recordSet.next()) { + BigDecimal _baseAmount = new BigDecimal(Util.null2s(recordSet.getString("allBaseAmount"), "0")); + BigDecimal _extraAmount = new BigDecimal(Util.null2s(recordSet.getString("allExtraAmount"), "0")); + BigDecimal _usedAmount = new BigDecimal(Util.null2s(recordSet.getString("allUsedAmount"), "0")); + restAmount = restAmount.add(_baseAmount).add(_extraAmount).subtract(_usedAmount); + } + } catch (Exception e) { + e.printStackTrace(); + } + return restAmount; + } + /** + * 获取调休的余额 + * + * @param params + * @param user + * @return + */ + public static Map getRestAmountMapByDis5(Map params, User user) { + Map balanceMap = new HashMap(); + try { + /** + * 分页控件返回的值 + * currentPage:当前页数 + * pageSize:每页多少条数据 + * showAll:是显示分页还是显示所有 + */ + int currentPage = Util.getIntValue((String) params.get("currentPage"), 1); + int pageSize = Util.getIntValue((String) params.get("pageSize"), 10); + boolean showAll = Util.null2s((String) params.get("showAll"), "true").equals("true"); + /** + * 时间范围选择的年份 + * dateScope:5-本年、8-上一年 + * selectedYear:指定年份 + */ + String dateScope = Util.null2String(params.get("dateScope")); + String selectedYear = Util.null2String(params.get("selectedYear")); + if (dateScope.equals("5") || dateScope.equals("8")) { + selectedYear = TimeUtil.getDateByOption(dateScope, "0").substring(0, 4); + } + /** + * 数据范围 + * dataScope:0-总部、1-分部、2-分部、3-人员、4-我的下属 + * subcomId:指定分部ID + * deptId:指定部门ID + * resourceId:指定人员ID + * allLevel:是否包含下级下属:0-不包含、1-包含 + */ + String dataScope = Util.null2String(params.get("dataScope")); + String subcomId = Util.null2String(params.get("subcomId")); + String deptId = Util.null2String(params.get("deptId")); + String resourceId = Util.null2String(params.get("resourceId")); + String allLevel = Util.null2String(params.get("allLevel")); + //人员状态 + String resourceStatus = Util.null2String(params.get("status")); + + /** + * isNoAccount:是否显示无账号人员:true-显示、false-不显示 + */ + String isNoAccount = Util.null2String(params.get("isNoAccount")); + /** + * 假期类型的ID + */ + String leaveRulesId = Util.null2String(params.get("leaveRulesId")); + /** + * 当前日期 + */ + String currentDate = DateUtil.getCurrentDate(); + /** + * 获取考勤报表权限共享设置 + */ + KQReportBiz kqReportBiz = new KQReportBiz(); + String rightStr = kqReportBiz.getReportRight("4", "" + user.getUID(), "a"); + + RecordSet recordSet = new RecordSet(); + String sql = "select a.id hrmResourceId,b.* from HrmResource a left join "; + if (recordSet.getDBType().equalsIgnoreCase("sqlserver")) { + sql = "select a.id hrmResourceId,b.*,ROW_NUMBER() OVER(order by dspOrder,a.id) as rn from HrmResource a left join "; + } + if (recordSet.getDBType().equalsIgnoreCase("sqlserver") + || recordSet.getDBType().equalsIgnoreCase("mysql")) { + sql += "(select resourceId, sum(baseAmount) as allBaseAmount, sum(tiaoxiuamount) as allTiaoxiuamount,sum(extraAmount) as allExtraAmount, sum(usedAmount) as allUsedAmount " + + "from kq_balanceOfLeave " + + "where 1=1 and (isDelete is null or isDelete<>1) and (expirationDate is null or expirationDate='' or expirationDate >= '" + currentDate + "') and belongYear='" + selectedYear + "' and leaveRulesId=" + leaveRulesId + " " + + "group by resourceId) b " + + "on a.id = b.resourceId where 1=1 "; + } else { + sql += "(select resourceId, sum(baseAmount) as allBaseAmount, sum(tiaoxiuamount) as allTiaoxiuamount,sum(extraAmount) as allExtraAmount, sum(usedAmount) as allUsedAmount " + + "from kq_balanceOfLeave " + + "where 1=1 and (isDelete is null or isDelete<>1) and (expirationDate is null or expirationDate >= '" + currentDate + "') and belongYear='" + selectedYear + "' and leaveRulesId=" + leaveRulesId + " " + + "group by resourceId) b " + + "on a.id = b.resourceId where 1=1 "; + } + if (dataScope.equals("0")) { + //总部 + } else if (dataScope.equals("1")) { + sql += " and a.subcompanyId1 in (" + subcomId + ") "; + } else if (dataScope.equals("2")) { + sql += " and a.departmentId in (" + deptId + ") "; + } else if (dataScope.equals("3")) { + sql += " and a.id in (" + resourceId + ")"; + } else if (dataScope.equals("4")) { + if (allLevel.equals("1")) { + sql += " and (a.id=" + user.getUID() + " or a.managerStr like '%," + user.getUID() + ",%' )"; + } else { + sql += " and (a.id=" + user.getUID() + " or a.managerid = " + user.getUID() + ")"; + } + } + + if(resourceStatus.length()>0){ + if (!resourceStatus.equals("8") && !resourceStatus.equals("9")) { + sql += " and a.status = "+resourceStatus+ ""; + }else if (resourceStatus.equals("8")) { + sql += " and (a.status = 0 or a.status = 1 or a.status = 2 or a.status = 3) "; + } + } + + if (isNoAccount.equals("false")) { + if (recordSet.getDBType().equalsIgnoreCase("sqlserver") + || recordSet.getDBType().equalsIgnoreCase("mysql")) { + sql += " and (loginId is not null and loginId<>'')"; + } else { + sql += " and (loginId is not null)"; + } + } + //考勤报表共享设置 + if (!rightStr.equals("") && !dataScope.equals("4")) { + sql += rightStr; + } + if (!recordSet.getDBType().equalsIgnoreCase("sqlserver")) { + sql += " order by dspOrder,hrmResourceId "; + } + if (!showAll) { + String pageSql = "select * from (select tmp.*,rownum rn from (" + sql + ") tmp where rownum<=" + (pageSize * currentPage) + ") where rn>=" + (pageSize * (currentPage - 1) + 1); + if (recordSet.getDBType().equalsIgnoreCase("sqlserver")) { + pageSql = "select t.* from (" + sql + ") t where 1=1 and rn>=" + (pageSize * (currentPage - 1) + 1) + " and rn<=" + (pageSize * currentPage); + } else if (recordSet.getDBType().equalsIgnoreCase("mysql")) { + pageSql = sql + " limit " + (currentPage - 1) * pageSize + "," + pageSize; + }else if (recordSet.getDBType().equalsIgnoreCase("postgresql")) { + pageSql = sql + " limit " + pageSize + " offset " + (currentPage - 1) * pageSize; + } + recordSet.executeQuery(pageSql); + } else { + recordSet.executeQuery(sql); + } + while (recordSet.next()) { + String hrmResourceId = Util.null2String(recordSet.getString("hrmResourceId")); + BigDecimal allBaseAmount = new BigDecimal(Util.null2s(recordSet.getString("allBaseAmount"), "0")); + BigDecimal allExtraAmount = new BigDecimal(Util.null2s(recordSet.getString("allExtraAmount"), "0")); + BigDecimal allUsedAmount = new BigDecimal(Util.null2s(recordSet.getString("allUsedAmount"), "0")); + BigDecimal allTiaoxiuamount = new BigDecimal(Util.null2s(recordSet.getString("allTiaoxiuamount"), "0")); + + balanceMap.put(hrmResourceId + "_" + leaveRulesId, allBaseAmount.add(allExtraAmount).add(allTiaoxiuamount).subtract(allUsedAmount)); + } + } catch (Exception e) { + e.printStackTrace(); + } + return balanceMap; + } + + + + /** + * qc 获取育儿假的余额 + * + * @param params + * @param user + * @return + */ + public static Map getRestAmountMapByDis8(Map params, User user) { + Map balanceMap = new HashMap(); + try { + /** + * 分页控件返回的值 + * currentPage:当前页数 + * pageSize:每页多少条数据 + * showAll:是显示分页还是显示所有 + */ + int currentPage = Util.getIntValue((String) params.get("currentPage"), 1); + int pageSize = Util.getIntValue((String) params.get("pageSize"), 10); + boolean showAll = Util.null2s((String) params.get("showAll"), "true").equals("true"); + /** + * 时间范围选择的年份 + * dateScope:5-本年、8-上一年 + * selectedYear:指定年份 + */ + String dateScope = Util.null2String(params.get("dateScope")); + String selectedYear = Util.null2String(params.get("selectedYear")); + if (dateScope.equals("5") || dateScope.equals("8")) { + selectedYear = TimeUtil.getDateByOption(dateScope, "0").substring(0, 4); + } + /** + * 数据范围 + * dataScope:0-总部、1-分部、2-分部、3-人员、4-我的下属 + * subcomId:指定分部ID + * deptId:指定部门ID + * resourceId:指定人员ID + * allLevel:是否包含下级下属:0-不包含、1-包含 + */ + String dataScope = Util.null2String(params.get("dataScope")); + String subcomId = Util.null2String(params.get("subcomId")); + String deptId = Util.null2String(params.get("deptId")); + String resourceId = Util.null2String(params.get("resourceId")); + String allLevel = Util.null2String(params.get("allLevel")); + //人员状态 + String resourceStatus = Util.null2String(params.get("status")); + + /** + * isNoAccount:是否显示无账号人员:true-显示、false-不显示 + */ + String isNoAccount = Util.null2String(params.get("isNoAccount")); + /** + * 假期类型的ID + */ + String leaveRulesId = Util.null2String(params.get("leaveRulesId")); + /** + * 当前日期 + */ + String currentDate = DateUtil.getCurrentDate(); + /** + * 获取考勤报表权限共享设置 + */ + KQReportBiz kqReportBiz = new KQReportBiz(); + String rightStr = kqReportBiz.getReportRight("4", "" + user.getUID(), "a"); + + RecordSet recordSet = new RecordSet(); + String sql = "select a.id hrmResourceId,b.* from HrmResource a left join "; + if (recordSet.getDBType().equalsIgnoreCase("sqlserver")) { + sql = "select a.id hrmResourceId,b.*,ROW_NUMBER() OVER(order by dspOrder,a.id) as rn from HrmResource a left join "; + } + if (recordSet.getDBType().equalsIgnoreCase("sqlserver") + || recordSet.getDBType().equalsIgnoreCase("mysql")) { + sql += "(select resourceId, sum(baseAmount) as allBaseAmount,sum(extraAmount) as allExtraAmount, sum(usedAmount) as allUsedAmount " + + "from kq_balanceOfLeave " + + "where 1=1 and (isDelete is null or isDelete<>1) and (expirationDate is null or expirationDate='' or expirationDate >= '" + currentDate + "') and belongYear='" + selectedYear + "' and leaveRulesId=" + leaveRulesId + " " + + "group by resourceId) b " + + "on a.id = b.resourceId where 1=1 "; + } else { + sql += "(select resourceId, sum(baseAmount) as allBaseAmount,sum(extraAmount) as allExtraAmount, sum(usedAmount) as allUsedAmount " + + "from kq_balanceOfLeave " + + "where 1=1 and (isDelete is null or isDelete<>1) and (expirationDate is null or expirationDate >= '" + currentDate + "') and belongYear='" + selectedYear + "' and leaveRulesId=" + leaveRulesId + " " + + "group by resourceId) b " + + "on a.id = b.resourceId where 1=1 "; + } + if (dataScope.equals("0")) { + //总部 + } else if (dataScope.equals("1")) { + sql += " and a.subcompanyId1 in (" + subcomId + ") "; + } else if (dataScope.equals("2")) { + sql += " and a.departmentId in (" + deptId + ") "; + } else if (dataScope.equals("3")) { + sql += " and a.id in (" + resourceId + ")"; + } else if (dataScope.equals("4")) { + if (allLevel.equals("1")) { + sql += " and (a.id=" + user.getUID() + " or a.managerStr like '%," + user.getUID() + ",%' )"; + } else { + sql += " and (a.id=" + user.getUID() + " or a.managerid = " + user.getUID() + ")"; + } + } + + if(resourceStatus.length()>0){ + if (!resourceStatus.equals("8") && !resourceStatus.equals("9")) { + sql += " and a.status = "+resourceStatus+ ""; + }else if (resourceStatus.equals("8")) { + sql += " and (a.status = 0 or a.status = 1 or a.status = 2 or a.status = 3) "; + } + } + + if (isNoAccount.equals("false")) { + if (recordSet.getDBType().equalsIgnoreCase("sqlserver") + || recordSet.getDBType().equalsIgnoreCase("mysql")) { + sql += " and (loginId is not null and loginId<>'')"; + } else { + sql += " and (loginId is not null)"; + } + } + //考勤报表共享设置 + if (!rightStr.equals("") && !dataScope.equals("4")) { + sql += rightStr; + } + if (!recordSet.getDBType().equalsIgnoreCase("sqlserver")) { + sql += " order by dspOrder,hrmResourceId "; + } + if (!showAll) { + String pageSql = "select * from (select tmp.*,rownum rn from (" + sql + ") tmp where rownum<=" + (pageSize * currentPage) + ") where rn>=" + (pageSize * (currentPage - 1) + 1); + if (recordSet.getDBType().equalsIgnoreCase("sqlserver")) { + pageSql = "select t.* from (" + sql + ") t where 1=1 and rn>=" + (pageSize * (currentPage - 1) + 1) + " and rn<=" + (pageSize * currentPage); + } else if (recordSet.getDBType().equalsIgnoreCase("mysql")) { + pageSql = sql + " limit " + (currentPage - 1) * pageSize + "," + pageSize; + }else if (recordSet.getDBType().equalsIgnoreCase("postgresql")) { + pageSql = sql + " limit " + pageSize + " offset " + (currentPage - 1) * pageSize; + } + recordSet.executeQuery(pageSql); + } else { + recordSet.executeQuery(sql); + } + while (recordSet.next()) { + String hrmResourceId = Util.null2String(recordSet.getString("hrmResourceId")); + BigDecimal allBaseAmount = new BigDecimal(Util.null2s(recordSet.getString("allBaseAmount"), "0")); + BigDecimal allExtraAmount = new BigDecimal(Util.null2s(recordSet.getString("allExtraAmount"), "0")); + BigDecimal allUsedAmount = new BigDecimal(Util.null2s(recordSet.getString("allUsedAmount"), "0")); + + balanceMap.put(hrmResourceId + "_" + leaveRulesId, allBaseAmount.add(allExtraAmount).subtract(allUsedAmount)); + } + } catch (Exception e) { + e.printStackTrace(); + } + return balanceMap; + } + + /** + * 插入或者更新员工假期余额 + * + * @param newBalanceEntities 新假期余额 + * @param oldBalanceEntities 旧假期余额 + * @param operator 操作者 + * @param canUpdate 是否允许更新 + * @return + */ + private static boolean insertOrUpdateBalance(List newBalanceEntities, Map oldBalanceEntities, String operator, boolean canUpdate) { + /*获取今天的日期、此刻的时间*/ + Calendar today = Calendar.getInstance(); + String currentDate = Util.add0(today.get(Calendar.YEAR), 4) + "-" + + Util.add0(today.get(Calendar.MONTH) + 1, 2) + "-" + + Util.add0(today.get(Calendar.DAY_OF_MONTH), 2); + String currentTime = Util.add0(today.get(Calendar.HOUR_OF_DAY), 2) + ":" + + Util.add0(today.get(Calendar.MINUTE), 2) + ":" + + Util.add0(today.get(Calendar.SECOND), 2); + + RecordSet recordSet1 = new RecordSet(); + java.sql.Timestamp date = KQDateUtil.getUpdateTimeStamp(); + String insertSql = "insert into kq_balanceOfLeave(leaveRulesId,resourceId,belongYear,baseAmount,extraAmount,usedAmount,baseAmount2,extraAmount2,usedAmount2,create_time,update_time,creator,effectiveDate,expirationDate) " + + "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + if (recordSet1.getDBType().equals("postgresql")) { + insertSql = "insert into kq_balanceOfLeave(leaveRulesId,resourceId,belongYear,baseAmount,extraAmount,usedAmount,baseAmount2,extraAmount2,usedAmount2,create_time,update_time,creator,effectiveDate,expirationDate) " + + "values(?,?,?,?,?,?,?,?,?,?::timestamp,?::timestamp,?,?,?)"; + } + List insertList = new ArrayList(); + List insertParamList = new ArrayList(); + String updateSql = "update kq_balanceOfLeave set leaveRulesId=?,resourceId=?,belongYear=?,baseAmount=?,baseAmount2=?,update_time=?,effectiveDate=?,expirationDate=? where id=?"; + String updateSql2 ="update kq_balanceOfLeave set leaveRulesId=?,resourceId=?,belongYear=?,baseAmount=?,baseAmount2=?,usedAmount=?,extraAmount=?,update_time=?,effectiveDate=?,expirationDate=? where id=?"; + + if (recordSet1.getDBType().equals("postgresql")) { + updateSql = "update kq_balanceOfLeave set leaveRulesId=?,resourceId=?,belongYear=?,baseAmount=?,baseAmount2=?,update_time=?::timestamp,effectiveDate=?,expirationDate=? where id=?"; + updateSql2 ="update kq_balanceOfLeave set leaveRulesId=?,resourceId=?,belongYear=?,baseAmount=?,baseAmount2=?,usedAmount=?,extraAmount=?,update_time=?::timestamp,effectiveDate=?,expirationDate=? where id=?"; + } + List updateList = new ArrayList(); + List updateParamList = new ArrayList(); + List updateParamList2 = new ArrayList(); + List usageHistoryEntities = new ArrayList(); + KQUsageHistoryEntity usageHistoryEntity = null; + for (KQBalanceOfLeaveEntity newBalanceEntity : newBalanceEntities) { + int resourceId = newBalanceEntity.getResourceId(); + int status = newBalanceEntity.getStatus(); + KQBalanceOfLeaveEntity oldBalanceEntity = (KQBalanceOfLeaveEntity) oldBalanceEntities.get("" + resourceId); + if (status == 1) { + String belongYear = newBalanceEntity.getBelongYear(); + String ruleId = newBalanceEntity.getLeaveRulesId() + ""; + Map oldBalanceEntitiesLast = getBalanceEntities(3, resourceId + "", ruleId, belongYear); + oldBalanceEntity = (KQBalanceOfLeaveEntity) oldBalanceEntitiesLast.get("" + resourceId); + } + if (oldBalanceEntity == null || oldBalanceEntity.getId() <= 0) { + insertList = new ArrayList(); + insertList.add(newBalanceEntity.getLeaveRulesId()); + insertList.add(newBalanceEntity.getResourceId()); + insertList.add(newBalanceEntity.getBelongYear()); + insertList.add(newBalanceEntity.getBaseAmount()); + insertList.add(newBalanceEntity.getExtraAmount()); + insertList.add(newBalanceEntity.getUsedAmount()); + insertList.add(newBalanceEntity.getBaseAmount2()); + insertList.add(newBalanceEntity.getExtraAmount2()); + insertList.add(newBalanceEntity.getUsedAmount2()); + insertList.add(date); + insertList.add(date); + insertList.add(Util.getIntValue(resourceId)); + insertList.add(newBalanceEntity.getEffectiveDate()); + insertList.add(newBalanceEntity.getExpirationDate()); + insertParamList.add(insertList); + + usageHistoryEntity = new KQUsageHistoryEntity(); + usageHistoryEntity.setLeaveRulesId("" + newBalanceEntity.getLeaveRulesId()); + usageHistoryEntity.setRelatedId("" + newBalanceEntity.getResourceId()); + usageHistoryEntity.setOperator("" + operator); + usageHistoryEntity.setOperateDate(currentDate); + usageHistoryEntity.setOperateTime(currentTime); + usageHistoryEntity.setOperateType("6"); + usageHistoryEntity.setBelongYear(newBalanceEntity.getBelongYear()); + usageHistoryEntity.setNewBaseAmount("" + newBalanceEntity.getBaseAmount()); + usageHistoryEntity.setNewExtraAmount("" + newBalanceEntity.getExtraAmount()); + usageHistoryEntity.setNewUsedAmount("" + newBalanceEntity.getUsedAmount()); + usageHistoryEntity.setNewBaseAmount2("" + newBalanceEntity.getBaseAmount2()); + usageHistoryEntity.setNewExtraAmount2("" + newBalanceEntity.getExtraAmount2()); + usageHistoryEntity.setNewUsedAmount2("" + newBalanceEntity.getUsedAmount2()); + usageHistoryEntity.setOldMinimumUnit("" + newBalanceEntity.getMinimumUnit()); + usageHistoryEntity.setNewMinimumUnit("" + newBalanceEntity.getMinimumUnit()); + usageHistoryEntity.setInsertOrUpdate("insert"); + usageHistoryEntities.add(usageHistoryEntity); + } else { + updateList = new ArrayList(); + updateList.add(newBalanceEntity.getLeaveRulesId()); + updateList.add(newBalanceEntity.getResourceId()); + updateList.add(newBalanceEntity.getBelongYear()); + updateList.add(newBalanceEntity.getBaseAmount()); + updateList.add(newBalanceEntity.getBaseAmount2()); + if(status==1){ + updateList.add(newBalanceEntity.getUsedAmount()); + updateList.add(newBalanceEntity.getExtraAmount()); + } + updateList.add(date); + updateList.add(newBalanceEntity.getEffectiveDate()); + updateList.add(newBalanceEntity.getExpirationDate()); + updateList.add(oldBalanceEntity.getId()); + if(status==1){ + updateParamList2.add(updateList); + }else{ + updateParamList.add(updateList); + } + + usageHistoryEntity = new KQUsageHistoryEntity(); + usageHistoryEntity.setLeaveRulesId("" + newBalanceEntity.getLeaveRulesId()); + usageHistoryEntity.setRelatedId("" + newBalanceEntity.getResourceId()); + usageHistoryEntity.setOperator("" + operator); + usageHistoryEntity.setOperateDate(currentDate); + usageHistoryEntity.setOperateTime(currentTime); + usageHistoryEntity.setOperateType("6"); + usageHistoryEntity.setBelongYear(newBalanceEntity.getBelongYear()); + usageHistoryEntity.setOldBaseAmount("" + oldBalanceEntity.getBaseAmount()); + usageHistoryEntity.setNewBaseAmount("" + newBalanceEntity.getBaseAmount()); + if(status==1){ + usageHistoryEntity.setOldUsedAmount("" + oldBalanceEntity.getUsedAmount()); + usageHistoryEntity.setNewUsedAmount("" + newBalanceEntity.getUsedAmount()); + usageHistoryEntity.setOldExtraAmount("" + oldBalanceEntity.getExtraAmount()); + usageHistoryEntity.setNewExtraAmount("" + newBalanceEntity.getExtraAmount()); + } + usageHistoryEntity.setOldBaseAmount2("" + oldBalanceEntity.getBaseAmount2()); + usageHistoryEntity.setNewBaseAmount2("" + newBalanceEntity.getBaseAmount2()); + usageHistoryEntity.setOldMinimumUnit("" + oldBalanceEntity.getMinimumUnit()); + usageHistoryEntity.setNewMinimumUnit("" + newBalanceEntity.getMinimumUnit()); + usageHistoryEntity.setInsertOrUpdate("update"); + usageHistoryEntities.add(usageHistoryEntity); + } + } + + boolean isSuccess = true; + RecordSet recordSet = new RecordSet(); + /*新增员工假期余额数据 start*/ + if (insertParamList.size() > 0) { + isSuccess = recordSet.executeBatchSql(insertSql, insertParamList); + } + /*新增员工假期余额数据 end*/ + + /*更新员工假期余额数据 start*/ + if (updateParamList.size() > 0) { + isSuccess = recordSet.executeBatchSql(updateSql, updateParamList); + } + if (updateParamList2.size() > 0) { + isSuccess = recordSet.executeBatchSql(updateSql2, updateParamList2); + } + /*更新员工假期余额数据 end*/ + + /*记录员工假期余额变更记录 start*/ + KQUsageHistoryBiz kqUsageHistoryBiz = new KQUsageHistoryBiz(); + if (usageHistoryEntities.size() > 0) { + isSuccess = kqUsageHistoryBiz.save(usageHistoryEntities); + } + /*记录员工假期余额变更记录 end*/ + + return isSuccess; + } + + /** + * 根据[工龄]、[司龄]获取对应的假期基数 + * + * @param distributionMode [发放方式] + * @param rulesDetailId [假期规则的ID] + * @param annualAmount [发放方式]=[4-每年发放固定天数]时的[固定天数] + * @param ageLimit [工龄]or[司龄]、当[发放方式]=[6-按司龄+工龄自动发放]时的[工龄] + * @param ageLimit2 当[发放方式]=[6-按司龄+工龄自动发放]时的[司龄] + * @param legalKey [法定年假规则]:当[发放方式]=[6-按司龄+工龄自动发放]时有效 + * @param welfareKey [福利年假规则]:当[发放方式]=[6-按司龄+工龄自动发放]时有效 + * @param legalOrWelfare 是计算[法定年假]还是计算[福利年假]:legal-[法定年假]、welfare-[福利年假] + * @return [假期基数] + */ + private static BigDecimal getAmountByAgeLimit(int distributionMode, String rulesDetailId, double annualAmount, + int ageLimit, int ageLimit2, int legalKey, int welfareKey, String legalOrWelfare) { + BigDecimal amount = new BigDecimal("0"); + try { + RecordSet recordSet = new RecordSet(); + if (distributionMode == 2 || distributionMode == 7) { + String sql = "select * from kq_entryToLeave where leaveRulesId=? and lowerLimit<=? and upperLimit>?"; + recordSet.executeQuery(sql, rulesDetailId, ageLimit, ageLimit); + if (recordSet.next()) { + double _amount = Util.getDoubleValue(recordSet.getString("amount"), 0); + amount = new BigDecimal("" + _amount); + } + } else if (distributionMode == 3) { + String sql = "select * from kq_workingAgeToLeave where leaveRulesId=? and lowerLimit<=? and upperLimit>?"; + recordSet.executeQuery(sql, rulesDetailId, ageLimit, ageLimit); + if (recordSet.next()) { + double _amount = Util.getDoubleValue(recordSet.getString("amount"), 0); + amount = new BigDecimal("" + _amount); + } + } else if (distributionMode == 4) { + amount = new BigDecimal("" + annualAmount); + } else if (distributionMode == 6) { + String sql = ""; + if (legalOrWelfare.equals("legal")) { + sql = "select * from kq_MixModeToLegalLeave where 1=1 and leaveRulesId=" + rulesDetailId; + if (legalKey == 0) { + sql += " and limit1<=" + ageLimit; + } else if (legalKey == 1) { + sql += " and limit2<=" + ageLimit2; + } else if (legalKey == 2) { + sql += " and limit1<=" + ageLimit + " and limit2<=" + ageLimit2; + } + } else { + sql = "select * from kq_MixModeToWelfareLeave where 1=1 and leaveRulesId=" + rulesDetailId; + if (welfareKey == 0) { + sql += " and limit1<=" + ageLimit; + } else if (welfareKey == 1) { + sql += " and limit2<=" + ageLimit2; + } else if (welfareKey == 2) { + sql += " and limit1<=" + ageLimit + " and limit2<=" + ageLimit2; + } + } + sql += " order by id desc "; + recordSet.executeQuery(sql); + if (recordSet.next()) { + double _amount = Util.getDoubleValue(recordSet.getString("amount"), 0); + amount = new BigDecimal("" + _amount); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + return amount; + } + + + private static ThreadLocal simpleDateFormatThreadLocal = new ThreadLocal<>(); + + private static void init() { + if (simpleDateFormatThreadLocal.get() == null) { + simpleDateFormatThreadLocal.set(new SimpleDateFormat("yyyy-MM-dd")); + } + } + + /** + * 获取两个日期之间的时间差距有几年 + * + * @param fromDate 开始时间 + * @param toDate 结束时间 + * @return + */ + public static int getAgeLimit(String fromDate, String toDate) { + init(); + int ageLImit = 0; + try { + if (toDate.compareTo(fromDate) < 0) { + return -1; + } + Date fd = simpleDateFormatThreadLocal.get().parse(fromDate); + Date td = simpleDateFormatThreadLocal.get().parse(toDate); + Instant fInstant = fd.toInstant(); + Instant tInstant = td.toInstant(); + LocalDate localFromDate = LocalDateTime.ofInstant(fInstant, ZoneId.systemDefault()).toLocalDate(); + LocalDate localToDate = LocalDateTime.ofInstant(tInstant, ZoneId.systemDefault()).toLocalDate(); + + //LocalDate localFromDate = LocalDate.parse(fromDate); + //LocalDate localToDate = LocalDate.parse(toDate); + Period period = Period.between(localFromDate, localToDate); + ageLImit = period.getYears(); + } catch (Exception e) { + e.printStackTrace(); + } + return ageLImit; + } + + + /****************************************************下面是正式系统用的****************************************************/ + + /** + * 获取年假、带薪事假、带薪病假、调休的假期余额信息 + * + * @param resourceId 指定人员ID + * @param languageId 当前系统语言 + * @return + */ + public static List getBalanceInfo(String resourceId, int languageId) { + String resultStr = ""; + List dataList = new ArrayList(); + try { + /*获取当前日期,当前时间*/ + Calendar today = Calendar.getInstance(); + String lastDayOfLastYear = Util.add0(today.get(Calendar.YEAR) - 1, 4) + "-12-31"; + String currentDate = Util.add0(today.get(Calendar.YEAR), 4) + "-" + + Util.add0(today.get(Calendar.MONTH) + 1, 2) + "-" + + Util.add0(today.get(Calendar.DAY_OF_MONTH), 2); + + KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo(); + + Map itemMap = new HashMap(); + List itemList = new ArrayList(); + Map dataMap = new HashMap(); + + String sql = "select * from kq_LeaveRules where 1=1 and (isDelete is null or isDelete<>1) and isEnable=1 and leaveCode in ('annualLeave','paidCompassionateLeave','paidSickLeave','vacationLeave')"; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql); + while (recordSet.next()) { + String ruleId = recordSet.getString("id"); + String leaveCode = recordSet.getString("leaveCode"); + + String title = ""; + switch (leaveCode) { + case "annualLeave": + title = SystemEnv.getHtmlLabelName(501313, languageId); + break; + case "paidCompassionateLeave": + title = SystemEnv.getHtmlLabelName(501314, languageId); + break; + case "paidSickLeave": + title = SystemEnv.getHtmlLabelName(501315, languageId); + break; + case "vacationLeave": + title = SystemEnv.getHtmlLabelName(31297, languageId); + break; + default: + break; + } + + String minimumUnit = kqLeaveRulesComInfo.getMinimumUnit(ruleId);//最小请假单位:1-按天请假、2-按半天请假、3-按小时请假、4-按整天请假 + + String currentYearAmount = getRestAmount(resourceId, ruleId, currentDate, true, false);//本年剩余年假时长 + String allAmount = getRestAmount(resourceId, ruleId, currentDate, true, true);//当前剩余年假时长 + String lastYearAmount = String.format("%.2f", Util.getDoubleValue(allAmount, 0) - Util.getDoubleValue(currentYearAmount, 0));;//历年剩余年假时长 + + itemList = new ArrayList(); + if (!leaveCode.equals("vacationLeave")) { + itemMap = new HashMap(); + itemMap.put("name", KQUnitBiz.isLeaveHour(minimumUnit+"") ? SystemEnv.getHtmlLabelName(513286, languageId) : SystemEnv.getHtmlLabelName(513287, languageId)); + itemMap.put("value", lastYearAmount); + itemList.add(itemMap); + itemMap = new HashMap(); + itemMap.put("name", KQUnitBiz.isLeaveHour(minimumUnit+"") ? SystemEnv.getHtmlLabelName(501311, languageId) : SystemEnv.getHtmlLabelName(132012, languageId)); + itemMap.put("value", currentYearAmount); + itemList.add(itemMap); + } + itemMap = new HashMap(); + itemMap.put("name", KQUnitBiz.isLeaveHour(minimumUnit+"") ? SystemEnv.getHtmlLabelName(513288, languageId) : SystemEnv.getHtmlLabelName(513289, languageId)); + itemMap.put("value", allAmount); + itemList.add(itemMap); + + dataMap = new HashMap(); + dataMap.put("detail", itemList); + dataMap.put("title", title); + dataMap.put("leaveCode", leaveCode); + + dataList.add(dataMap); + } + } catch (Exception e) { + e.printStackTrace(); + } + return dataList; + } + + /** + * 获取正式系统请假流程协同区所需的相关数据 + * + * @param resourceId + * @param searchYear + * @return + */ + public static Map getSynergyZoneInfo(String resourceId, String searchYear) { + Map resultMap = new HashMap(); + try { + /*获取当前日期,当前时间*/ + Calendar today = Calendar.getInstance(); + String lastDayOfLastYear = Util.add0(today.get(Calendar.YEAR) - 1, 4) + "-12-31"; + String currentDate = Util.add0(today.get(Calendar.YEAR), 4) + "-" + + Util.add0(today.get(Calendar.MONTH) + 1, 2) + "-" + + Util.add0(today.get(Calendar.DAY_OF_MONTH), 2); + + double usedAmount1 = 0.00;//年假已用 + double restAmount1 = 0.00;//年假剩余 + + String sql = "select * from kq_leaveRules where 1=1 and (isDelete is null or isDelete <>1) and leaveCode='annualLeave'"; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql); + if (recordSet.next()) { + String ruleId = recordSet.getString("id"); + + sql = "select * from kq_BalanceOfLeave where belongYear=? and resourceId=? and leaveRulesId=?"; + recordSet.executeQuery(sql, searchYear, resourceId, ruleId); + if (recordSet.next()) { + usedAmount1 = Util.getDoubleValue(recordSet.getString("usedAmount"), 0.00); + } + restAmount1 = Util.getDoubleValue(getRestAmount(resourceId, ruleId, currentDate, true, false), 0.00); + } + + double usedAmount2 = 0.00;//带薪病假已用 + double restAmount2 = 0.00;//带薪病假剩余 + + sql = "select * from kq_leaveRules where 1=1 and (isDelete is null or isDelete <>1) and leaveCode='paidSickLeave'"; + recordSet.executeQuery(sql); + if (recordSet.next()) { + String ruleId = recordSet.getString("id"); + + sql = "select * from kq_BalanceOfLeave where belongYear=? and resourceId=? and leaveRulesId=?"; + recordSet.executeQuery(sql, searchYear, resourceId, ruleId); + if (recordSet.next()) { + usedAmount2 = Util.getDoubleValue(recordSet.getString("usedAmount"), 0.00); + } + restAmount2 = Util.getDoubleValue(getRestAmount(resourceId, ruleId, currentDate, true, false), 0.00); + } + + double usedAmount3 = 0.00;//带薪事假已用 + sql = "select * from kq_leaveRules where 1=1 and (isDelete is null or isDelete <>1) and leaveCode='paidCompassionateLeave'"; + recordSet.executeQuery(sql); + if (recordSet.next()) { + String ruleId = recordSet.getString("id"); + + sql = "select * from kq_BalanceOfLeave where belongYear=? and resourceId=? and leaveRulesId=?"; + recordSet.executeQuery(sql, searchYear, resourceId, ruleId); + if (recordSet.next()) { + usedAmount3 = Util.getDoubleValue(recordSet.getString("usedAmount"), 0.00); + } + } + + + double restAmount4 = 0.00;//调休剩余 + sql = "select * from kq_leaveRules where 1=1 and (isDelete is null or isDelete <>1) and leaveCode='vacationLeave'"; + recordSet.executeQuery(sql); + if (recordSet.next()) { + String ruleId = recordSet.getString("id"); + + restAmount4 = Util.getDoubleValue(getRestAmount(resourceId, ruleId, currentDate, true, false), 0.00); + } + + resultMap.put("usedAmount1", usedAmount1); + resultMap.put("restAmount1", restAmount1); + resultMap.put("usedAmount2", usedAmount2); + resultMap.put("restAmount2", restAmount2); + resultMap.put("usedAmount3", usedAmount3); + resultMap.put("restAmount4", restAmount4); + } catch (Exception e) { + e.printStackTrace(); + } + return resultMap; + } + + /** + * 获取年假开始日期 + * + * @param resourceId 人员ID + * @return + */ + private static String getAnnualDate(String resourceId) { + String result = ""; + try { + String sql = "select t2.field3 annualDate from hrmResource t1 left join cus_fielddata t2 on t1.id=t2.id and t2.scope='HrmCustomFieldByInfoType' and t2.scopeid=-1 where t1.id=" + resourceId; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql); + if (recordSet.next()) { + String annualDate = recordSet.getString("annualDate"); + if (annualDate.contains("\\/")) { + try { + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/M/dd"); + Date date = simpleDateFormat.parse(annualDate); + simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); + annualDate = simpleDateFormat.format(date); + } catch (Exception e) { + e.printStackTrace(); + annualDate = ""; + } + } + Pattern pattern = Pattern.compile("^\\d{4}\\-\\d{2}\\-\\d{2}$"); + Matcher matcher_1 = pattern.matcher(annualDate); + if (!annualDate.equals("") && matcher_1.matches()) { + result = annualDate; + } + } + } catch (Exception e) { + e.printStackTrace(); + } + return result; + } + + public static void logOvertimeMap(Map overtimeLogMap,Object params, String keys){ + if(overtimeLogMap != null){ + overtimeLogMap.put(keys, params); + } + } + /** + * 获取育儿假开始日期 + * + * @param resourceId 人员ID + * @return + */ + public static ArrayList getParentalLeaveDate(String resourceId) { + ArrayList list = new ArrayList<>(); + try { + String sql = "select birthday from hrmfamilyinfo where WhetherChildren=1 and resourceid=? order by birthday "; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql,resourceId); + while (recordSet.next()) { + String annualDate = recordSet.getString("birthday"); + if (annualDate.contains("\\/")) { + try { + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/M/dd"); + Date date = simpleDateFormat.parse(annualDate); + simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); + annualDate = simpleDateFormat.format(date); + } catch (Exception e) { + e.printStackTrace(); + annualDate = ""; + } + } + Pattern pattern = Pattern.compile("^\\d{4}\\-\\d{2}\\-\\d{2}$"); + Matcher matcher_1 = pattern.matcher(annualDate); + if (!annualDate.equals("") && matcher_1.matches()) { + list.add(annualDate); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + return list; + } + + /** + * 获取人员的省份 + * @return + */ + private static void getChildrenProvinceId(String leaveRulesId, String locationid, Map params ) { + RecordSet rs = new RecordSet(); + String provinceid = "0"; + params.put("yearsOld","0"); + params.put("annualAmount","0"); + try { + if(StringUtil.isNotNull(locationid)){ + String sql = "select * from hrmcity where id in (select locationcity from HrmLocations where id = " + locationid + " )"; + rs.executeSql(sql); + while (rs.next()) { + provinceid = Util.null2s(rs.getString("provinceid"),"0"); + } + } + if(!provinceid.equals("0")){ + String sql = "select * from kq_provinceToLeave where leaveRulesId = " + leaveRulesId + " and provinceid= " + provinceid; + rs.executeQuery(sql); + if (rs.next()) { + int yearsOldValue = rs.getInt("yearsOld"); + double amount = Util.getDoubleValue(rs.getString("amount"), 0); + params.put("yearsOld",yearsOldValue); + params.put("annualAmount",amount); + } + } + } catch (Exception e) { + rs.writeLog(e); + } + } + + // qc 获取孩子的记录id + public static ArrayList getChildId(String resourceId) { + ArrayList list = new ArrayList<>(); + try { + String sql = "select id from hrmfamilyinfo where WhetherChildren=1 and resourceid=? order by birthday "; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql,resourceId); + while (recordSet.next()) { + String id = recordSet.getString("id"); + list.add(id); + } + } catch (Exception e) { + e.printStackTrace(); + } + return list; + } + public static ArrayList getChildBean(String resourceId) { + ArrayList list = new ArrayList<>(); + try { + String sql = "select id,birthday,member from hrmfamilyinfo where WhetherChildren=1 and resourceid=? order by birthday "; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql,resourceId); + KQChildrenBean bean = null; + while (recordSet.next()) { + bean = new KQChildrenBean(); + String id = recordSet.getString("id"); + String birthday = recordSet.getString("birthday"); + String title = recordSet.getString("member"); + bean.setId(id); + bean.setBirthday(birthday); + bean.setTitle(title); + bean.setResourceid(resourceId); + list.add(bean); + } + } catch (Exception e) { + e.printStackTrace(); + } + return list; + } + + +} diff --git a/领悦二开new/src/com/engine/kq/biz/KQChildrenComInfo.java b/领悦二开new/src/com/engine/kq/biz/KQChildrenComInfo.java new file mode 100644 index 0000000..b83815d --- /dev/null +++ b/领悦二开new/src/com/engine/kq/biz/KQChildrenComInfo.java @@ -0,0 +1,81 @@ +package com.engine.kq.biz; + +import weaver.cache.CacheBase; +import weaver.cache.CacheColumn; +import weaver.cache.CacheColumnType; +import weaver.cache.PKColumn; + +/** + * 假期规则缓存类 + */ +public class KQChildrenComInfo extends CacheBase { + + /** + * 数据来源 + */ + protected static String TABLE_NAME = "hrmfamilyinfo"; + /** + * sql中的where信息,不要以where开始 + */ + protected static String TABLE_WHERE = " WhetherChildren=1 "; + /** + * sql中的order by信息,不要以order by开始 + */ + protected static String TABLE_ORDER = " id "; + + /** + * 主键 + */ + @PKColumn(type = CacheColumnType.NUMBER) + protected static String PK_NAME = "id"; + + /** + * 出生日期 + */ + @CacheColumn(name = "birthday") + protected static int birthday; + /** + * 姓名 + */ + @CacheColumn(name = "member") + protected static int member; + /** + * 家长id + */ + @CacheColumn(name = "resourceid") + protected static int resourceid; + + + public String getId(){ + return (String)getRowValue(PK_INDEX); + } + + public String getChildrenName() { + return (String)getRowValue(member); + } + + public String getChildrenName(String key){ + return (String) getValue(member,key); + } + + public String getBirthday() { + return (String)getRowValue(birthday); + } + + public String getBirthday(String key){ + return (String) getValue(birthday,key); + } + + public String getResourceid() { + return (String)getRowValue(resourceid); + } + + public String getResourceid(String key){ + return (String) getValue(resourceid,key); + } + + @Override + public void removeCache() { + super.removeCache(); + } +} diff --git a/领悦二开new/src/com/engine/kq/biz/KQFormatBiz.java b/领悦二开new/src/com/engine/kq/biz/KQFormatBiz.java new file mode 100644 index 0000000..451af0d --- /dev/null +++ b/领悦二开new/src/com/engine/kq/biz/KQFormatBiz.java @@ -0,0 +1,339 @@ +package com.engine.kq.biz; + +import com.engine.kq.entity.TimeScopeEntity; +import com.engine.kq.entity.WorkTimeEntity; +import com.engine.kq.log.KQLog; +import weaver.common.DateUtil; +import weaver.conn.BatchRecordSet; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.Util; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 考勤数据格式化 + */ +public class KQFormatBiz extends BaseBean { + private String today = DateUtil.getCurrentDate(); + protected KQLog kqLog = new KQLog(); + + /** + * 考勤报表格式化 + * + * @param lsFormatParams + */ + public void format(List> lsFormatParams) { + format(lsFormatParams, -1); + } + + /** + * 考勤报表格式化 + * @param lsFormatParams + * @param formatType -1: 其他; 11:右键重新计算考勤数据; 12: 考勤自动和手动同步;13:钉钉同步或者导入; 14:云桥考勤同步 15: 考勤导入;16:排班更新 + */ + public void format(List> lsFormatParams, int formatType) { + BatchRecordSet bRs = new BatchRecordSet(); + String sql = ""; + List params = null; + try { + for(List list : lsFormatParams) { + list.add(formatType); + } + if (KQSettingsBiz.getKqformatthread()) { + sql = " insert into kq_format_pool (resourceid, kqdate, formattype) values (?,?,?)"; + if (KQSettingsBiz.getKqformatAccurate()){ + sql = " insert into kq_format_pool (resourceid, kqdate, exectime,formattype) values (?,?,?,?)"; + lsFormatParams = processFormatParams(lsFormatParams); + } + bRs.executeBatchSqlNew(sql, lsFormatParams); + } else { + String resourceid = ""; + String kqdate = ""; + for (int i = 0; lsFormatParams != null && i < lsFormatParams.size(); i++) { + params = lsFormatParams.get(i); + resourceid = Util.null2String(params.get(0)); + kqdate = Util.null2String(params.get(1)); + new KQFormatData().formatKqDateByLock(resourceid, kqdate,formatType); + } + } + } catch (Exception e) { + writeLog(" KQFormatData.formatKqDate lsFormatParams >>>>>>>>>" + e); + } + } + + public void formatDateByKQDate(String kqdate) { + String sql = ""; + RecordSet rs = new RecordSet(); + List> lsFormatParams = new ArrayList<>(); + List formatParams = null; + try { + if (DateUtil.timeInterval(kqdate, today) < 0) { + kqLog.info("今天之后的无需处理的数据:kqdate==" + kqdate + "today==" + today); + return;//今天之后的无需处理 + } + + sql = " SELECT distinct resourceid FROM ( " + + new KQGroupBiz().getGroupMemberSql() + ") t "; + rs.executeQuery(sql); + while (rs.next()) { + String resourceid = rs.getString("resourceid"); + if(Util.null2String(kqdate).length()!=10)return; + formatParams = new ArrayList<>(); + formatParams.add(resourceid); + formatParams.add(kqdate); + lsFormatParams.add(formatParams); + } + this.format(lsFormatParams); + } catch (Exception e) { + writeLog(e); + kqLog.info(e); + } + } + + public void formatDateByGroupId(String groupid, String kqdate) { + String sql = ""; + RecordSet rs = new RecordSet(); + List> lsFormatParams = new ArrayList<>(); + List formatParams = null; + try { + if (DateUtil.timeInterval(kqdate, today) < 0) { + kqLog.info("今天之后的无需处理的数据:groupid==" + groupid + "kqdate==" + kqdate + "today==" + today); + return;//今天之后的无需处理 + } + KQGroupComInfo kqGroupComInfo = new KQGroupComInfo(); + KQGroupBiz kqGroupBiz = new KQGroupBiz(); + String kqtype = kqGroupComInfo.getKqtype(groupid); + if (kqtype.equals("2")) {//排班 + sql = "select resourceid, kqdate from kq_shiftschedule where groupid=" + groupid + " and kqdate='" + kqdate + "' and (isdelete is null or isdelete <> '1') "; + } else { + sql = "select resourceid,'" + kqdate + "' from (" + kqGroupBiz.getGroupMemberSql(groupid) + ") t "; + } + rs.executeQuery(sql); + while (rs.next()) { + String resourceid = rs.getString("resourceid"); + if(Util.null2String(kqdate).length()!=10)return; + formatParams = new ArrayList<>(); + formatParams.add(resourceid); + formatParams.add(kqdate); + lsFormatParams.add(formatParams); + } + this.format(lsFormatParams); + } catch (Exception e) { + writeLog(e); + kqLog.info(e); + } + } + + public void formatDate(String resourceid, String kqdate) { + List> lsFormatParams = new ArrayList<>(); + List formatParams = null; + try { + if (DateUtil.timeInterval(kqdate, today) < 0) { + kqLog.info("今天之后的无需处理的数据:resourceid==" + resourceid + "kqdate==" + kqdate + "today==" + today); + return;//今天之后的无需处理 + } + if(Util.null2String(kqdate).length()!=10)return; + formatParams = new ArrayList<>(); + formatParams.add(resourceid); + formatParams.add(kqdate); + lsFormatParams.add(formatParams); + this.format(lsFormatParams); + } catch (Exception e) { + writeLog(e); + kqLog.info(e); + } + } + + public void delFormatData(String resourceid, String kqdate) { + RecordSet rs = new RecordSet(); + String sql = ""; + try { + sql = " delete from kq_format_detail where resourceid =? and kqdate = ? ";//删除非工作日数据 + rs.executeUpdate(sql, resourceid, kqdate); + + sql = " delete from kq_format_total where resourceid =? and kqdate = ? ";//删除非工作日数据 + rs.executeUpdate(sql, resourceid, kqdate); + } catch (Exception e) { + writeLog(e); + kqLog.info(e); + } + } + + public void clearFormatPool() { + RecordSet rs = new RecordSet(); + String sql = ""; + try { + //删除三天前的数据格式化数据 + if (rs.getDBType().equals("sqlserver")) { + sql = " delete from kq_format_pool where status = 1 and datediff(day,created,getdate()) > 1"; + } else if (rs.getDBType().equals("mysql")) { + sql = " delete from kq_format_pool where status = 1 and datediff(now(),created) > 1"; + } + else if (rs.getDBType().equals("postgresql")) { + sql = " delete from kq_format_pool where status = 1 and datediff(now(),created) > 1"; + } + else if (rs.getOrgindbtype().equals("st")) { + sql = " delete from kq_format_pool where status = 1 and to_number(trunc(sysdate) - trunc(created)) > 1"; + } else { + sql = " delete from kq_format_pool where status = 1 and trunc(sysdate) - trunc(created) > 1"; + } + rs.executeUpdate(sql); + } catch (Exception e) { + writeLog(e); + } + } + + public Map getDefinedField(){ + Map retMap = new HashMap<>(); + String definedField = ""; + String definedFieldSum = ""; + String definedParam = ""; + String definedParamSum = ""; + KQReportFieldComInfo kqReportFieldComInfo = new KQReportFieldComInfo(); + while (kqReportFieldComInfo.next()) { + if (!Util.null2String(kqReportFieldComInfo.getIsenable()).equals("1")) continue; + if (Util.null2String(kqReportFieldComInfo.getIsSystem()).equals("1")) continue; + if(KQReportFieldComInfo.cascadekey2fieldname.keySet().contains(kqReportFieldComInfo.getFieldname()))continue; + + if(definedField.length()>0)definedField+=","; + definedField+=kqReportFieldComInfo.getFieldname(); + + if(definedFieldSum.length()>0)definedFieldSum+=","; + definedFieldSum+="sum("+kqReportFieldComInfo.getFieldname()+") as "+kqReportFieldComInfo.getFieldname(); + + if(definedParam.length()>0)definedParam+=","; + definedParam+="?"; + + if(definedParamSum.length()>0)definedParamSum+=","; + definedParamSum+="sum("+kqReportFieldComInfo.getFieldname()+")"; + + String[] cascadekeys = Util.splitString(Util.null2String(kqReportFieldComInfo.getCascadekey()),","); + for(int i=0;cascadekeys!=null&&i0)definedField+=","; + definedField+=fieldname; + + if(definedFieldSum.length()>0)definedFieldSum+=","; + definedFieldSum+="sum("+fieldname+") as "+fieldname; + + if(definedParam.length()>0)definedParam+=","; + definedParam+="?"; + + if(definedParamSum.length()>0)definedParamSum+=","; + definedParamSum+="sum("+fieldname+")"; + } + } + retMap.put("definedField",definedField); + retMap.put("definedFieldSum",definedFieldSum); + retMap.put("definedParam",definedParam); + retMap.put("definedParamSum",definedParamSum); + return retMap; + } + + public boolean needCal(String workDate, String workTime){ + boolean needCalForgotCheckMins = true; + if (KQSettingsBiz.getKqformatAccurate()) { + workTime = new KQTimesArrayComInfo().turn48to24Time(workTime); + if (workDate.length() > 0 && workTime.length() > 0) { + String currentFullTime = DateUtil.getFullDate(); + String endTime = workDate + " " + workTime; + if (DateUtil.timeInterval(currentFullTime, endTime) > 0) { + //当前时间之后的状态无效计算 + needCalForgotCheckMins = false; + } + kqLog.writeLog("currentFullTime:"+currentFullTime+"wroktime:"+endTime+"needCalForgotCheckMins:"+needCalForgotCheckMins); + } + } + return needCalForgotCheckMins; + } + + public boolean needCal(String workDate, String workTime,String isneedcal){ + boolean needCalForgotCheckMins = true; + boolean isneedformat = "1".equals(isneedcal); + if (isneedformat) { + workTime = new KQTimesArrayComInfo().turn48to24Time(workTime); + if (workDate.length() > 0 && workTime.length() > 0) { + String currentFullTime = DateUtil.getFullDate(); + String endTime = workDate + " " + workTime; + if (DateUtil.timeInterval(currentFullTime, endTime) > 0) { + //当前时间之后的状态无效计算 + needCalForgotCheckMins = false; + } + } + } + return needCalForgotCheckMins; + } + + private List> processFormatParams(List> lsFormatParams) { + List> lsFormatParamsTmp = new ArrayList<>(); + try { + KQTimesArrayComInfo kqTimesArrayComInfo = new KQTimesArrayComInfo(); + KQWorkTime kqWorkTime = new KQWorkTime(); + List formatParams = null; + for(int i=0;i 2) { + formattype = Util.null2String(formatParams.get(2)); + } + + formatParams = new ArrayList<>(); + formatParams.add(resourceId); + formatParams.add(kqDate); + formatParams.add(new java.sql.Timestamp(DateUtil.getCalendar(DateUtil.getFullDate()).getTimeInMillis())); + formatParams.add(formattype); + lsFormatParamsTmp.add(formatParams); + + String nextDate = DateUtil.addDate(kqDate, 1);//下一天日期 + WorkTimeEntity workTime = kqWorkTime.getWorkTime(resourceId, kqDate); + List lsWorkTime = new ArrayList<>(); + if (workTime != null) { + lsWorkTime = workTime.getWorkTime();//工作时间 + for (int j = 0; lsWorkTime != null && j < lsWorkTime.size(); j++) { + TimeScopeEntity workTimeScope = lsWorkTime.get(j); + String workBeginDateTime = workTimeScope.getBeginTimeAcross() ? nextDate : kqDate; + workBeginDateTime+=" "+kqTimesArrayComInfo.turn48to24Time(workTimeScope.getBeginTime())+":00:00"; + String workEndDateTime = workTimeScope.getEndTimeAcross() ? nextDate : kqDate; + workEndDateTime+=" "+kqTimesArrayComInfo.turn48to24Time(workTimeScope.getEndTime())+":00:00"; + + formatParams = new ArrayList<>(); + formatParams.add(resourceId); + formatParams.add(kqDate); + formatParams.add(new java.sql.Timestamp(DateUtil.getCalendar(workBeginDateTime).getTimeInMillis())); + formatParams.add(formattype); + lsFormatParamsTmp.add(formatParams); + + formatParams = new ArrayList<>(); + formatParams.add(resourceId); + formatParams.add(kqDate); + formatParams.add(new java.sql.Timestamp(DateUtil.getCalendar(workEndDateTime).getTimeInMillis())); + formatParams.add(formattype); + lsFormatParamsTmp.add(formatParams); + } + }else{ + formatParams = new ArrayList<>(); + formatParams.add(resourceId); + formatParams.add(kqDate); + formatParams.add(formattype); + lsFormatParamsTmp.add(formatParams); + } + } + + }catch (Exception e) { + StringWriter errorsWriter = new StringWriter(); + e.printStackTrace(new PrintWriter(errorsWriter)); + kqLog.info(errorsWriter.toString()); + } + return lsFormatParamsTmp; + } +} diff --git a/领悦二开new/src/com/engine/kq/biz/KQFormatData.java b/领悦二开new/src/com/engine/kq/biz/KQFormatData.java new file mode 100644 index 0000000..36d9ba6 --- /dev/null +++ b/领悦二开new/src/com/engine/kq/biz/KQFormatData.java @@ -0,0 +1,1698 @@ +package com.engine.kq.biz; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.engine.kq.biz.chain.shiftinfo.ShiftInfoBean; +import com.engine.kq.entity.KQShiftRuleEntity; +import com.engine.kq.entity.TimeScopeEntity; +import com.engine.kq.entity.WorkTimeEntity; +import com.engine.kq.enums.FlowReportTypeEnum; +import com.engine.kq.jucailin.genid.IdGenerator; +import com.engine.kq.log.KQLog; +import com.engine.kq.util.KQLockAttendaUtil; +import com.engine.lingyue.util.KqUtil; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.googlecode.aviator.AviatorEvaluator; +import com.googlecode.aviator.Expression; +import org.apache.commons.lang3.StringUtils; +import weaver.common.DateUtil; +import weaver.conn.BatchRecordSet; +import weaver.conn.RecordSet; +import weaver.conn.RecordSetTrans; +import weaver.file.Prop; +import weaver.formmode.setup.ModeRightInfo; +import weaver.general.BaseBean; +import weaver.general.InitServer; +import weaver.general.Util; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.sql.Timestamp; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * 考勤数据格式化 + */ +public class KQFormatData extends BaseBean { + private String today = DateUtil.getCurrentDate(); + private KQLog kqLog = new KQLog(); + private boolean writeLog = false; + private LinkedHashMap logInfo = new LinkedHashMap<>(); + + private static final String LOCK_DEGREE = Util.null2String(Prop.getPropValue("kqLockAttenda", "LOCK_DEGREE")); + + public Map formatKqDateByLock(String userId, String kqDate, int formatType) { + Map resultMap = new HashMap<>(); + + //-1: 其他; 11:右键重新计算考勤数据; 12: 考勤自动和手动同步;13:钉钉同步或者导入; 14:云桥考勤同步 15: 考勤导入;16:排班更新 + //17:考勤流程;18testkq.jsp直接触发的;19:考勤设置升级;20:计划任务执行。 + //①在途的考勤流程可以正常提交归档报表能统计,管理员干预归档的流程报表能统计。 + //②关账不影响考勤导入打卡数据,正常的打卡数据进入报表,导入、同步。 + //③其他操作报表更新控制不生效,比如重新计算考勤,自动计算考勤。 + +// if (LOCK_DEGREE.equals("0")&&new KQLockAttendaUtil().checkLockStatus(userId, kqDate)) { +// kqLog.info("锁定程度强控:人员考勤数据已被锁定,"+"userId:"+userId+":kqDate:"+kqDate+";formatType="+formatType); +// if(formatType==12||formatType==13||formatType==14||formatType==15||formatType==17){ +// return formatKqDate(userId, kqDate); +// } +// return resultMap; +// } + //最新确认逻辑:弱控只控制流程在锁定范围内不能提交,其他都可以重新计算考勤报表。 + return formatKqDate(userId, kqDate); + } + + /*** + * 该方法不允许直接调用 + * @param userId + * @param kqDate + * @return + */ + public Map formatKqDate(String userId, String kqDate) { + //考勤报表增加锁定功能:弱控 + //1、考勤流程控制,请假、出差、公出、补卡、加班、销假、考勤变更新建的流程不能提交,在途的流程可以正常提交归档报表能统计,管理员干预归档的流程报表能统计。 + //2、关账不影响考勤导入打卡数据,正常的打卡数据进入报表。 + //3、强控就是前2点锁定日期后也不能进入报表了 + List> lsParam = new ArrayList<>(); + boolean isKqReportHalfOpen = "1".equals(new KQSettingsComInfo().getMain_val("kq_report_half")); + //非工作日处理 + List nonlsParam = null; + Map resultMap = new HashMap<>(); + BatchRecordSet bRs = new BatchRecordSet(); + KQGroupComInfo kqGroupComInfo = new KQGroupComInfo(); + RecordSet rs = new RecordSet(); + String sql = ""; + try { + kqLog.info("formatKqDate in userId=" + userId + "kqDate==" + kqDate); + if (DateUtil.timeInterval(kqDate, today) < 0) {//今天之后的无需处理 + kqLog.info("今天之后的无需处理的数据:resourceid=="+userId+"kqdate=="+kqDate+"today=="+today); + return resultMap; + } + // 强控 + if (LOCK_DEGREE.equals("1")&&new KQLockAttendaUtil().checkLockStatus(userId, kqDate)) { + kqLog.info("锁定程度强控:人员考勤数据已被锁定,"+"userId:"+userId+":kqDate:"+kqDate); + return resultMap; + } + String uuid = UUID.randomUUID().toString(); + KQFormatFreeData kqFormatFreeData = new KQFormatFreeData(); + KQWorkTime kqWorkTime = new KQWorkTime(); + kqWorkTime.setIsFormat(true); + String kqDateNext = DateUtil.addDate(kqDate, 1); + + KQFlowDataBiz kqFlowDataBiz = new KQFlowDataBiz.FlowDataParamBuilder().resourceidParam(userId).fromDateParam(kqDate).toDateParam(kqDateNext).build(); + Map workFlowInfo = new HashMap<>();//userid|date--工作流程 + kqFlowDataBiz.getAllFlowData(workFlowInfo,false); + WorkTimeEntity workTime = kqWorkTime.getWorkTime(userId, kqDate); + kqLog.info("userId:"+userId+":kqDate:"+kqDate+":formatKqDate workTime=" + JSONObject.toJSONString(workTime)+"::uuid::"+uuid); + kqLog.info("userId:"+userId+":kqDate:"+kqDate+":formatKqDate workFlowInfo=" + JSONObject.toJSONString(workFlowInfo)+"::uuid::"+uuid); + + if(this.writeLog) { + logInfo.put("userId",userId); + logInfo.put("kqDate",kqDate); + logInfo.put(""+weaver.systeminfo.SystemEnv.getHtmlLabelName(16253,weaver.general.ThreadVarLanguage.getLang())+"",workTime); + logInfo.put(""+weaver.systeminfo.SystemEnv.getHtmlLabelName(126871,weaver.general.ThreadVarLanguage.getLang())+"",workFlowInfo); + } + + new KQFormatBiz().delFormatData(userId, kqDate); + + String excludecount = Util.null2String(kqGroupComInfo.getExcludecount(workTime.getGroupId()));//是否参与考勤报表统计 + if (workTime.getIsExclude()) {//无需考勤人员没有异常状态 + if(!excludecount.equals("1")){ + kqLog.info("无需考勤人员没有异常状态 workTime.getIsExclude()="+workTime.getIsExclude()+"excludecount=="+excludecount); + return resultMap; + } + } + if( Util.null2String(workTime.getGroupId()).length()==0){ + //没有考勤组不需格式化 + return resultMap; + } + if (workTime == null || (workTime != null && workTime.getWorkMins() == 0 && workTime.getNonWorkShift() != 1)) { + kqLog.info("workTime == null || workTime.getWorkMins() == 0 插入空记录"); + nonlsParam = new ArrayList<>(); + formatNonWork(userId, kqDate,nonlsParam,workTime, workFlowInfo); + + if(!nonlsParam.isEmpty()){ + sql = " insert into kq_format_detail(resourceid,kqdate,groupid,serialnumber,signindate,signintime,signinid,signoutdate,signouttime,signoutid,leaveMins,leaveinfo,evectionMins,outMins,day_type,create_time,update_time,id,flowinfo)values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) "; + rs.executeUpdate(sql, nonlsParam); + + Long id = IdGenerator.generate(); + String baseField = ""; + if ("mysql".equalsIgnoreCase(rs.getDBType())){ + baseField = "sysdate(),sysdate(),"+id; + }else if ("oracle".equalsIgnoreCase(rs.getDBType())){ + baseField = "SYSDATE,SYSDATE,"+id; + }else if ("postgresql".equalsIgnoreCase(rs.getDBType())){ + baseField = "now(),now(),"+id; + }else{ + baseField = "GETDATE(),GETDATE(),"+id; + } + sql = " insert into kq_format_total(resourceid,kqdate,subcompanyid,departmentid,jobtitle,groupid,serialid,workdays," + + " workmins,attendancedays,attendancemins,signdays,signmins,belate,belatemins,gravebelate,gravebelatemins,leaveeearly,leaveearlymins," + + " graveleaveearly,graveleaveearlymins,absenteeism,absenteeismmins,forgotcheck, forgotcheckMins,leaveMins,evectionMins,outMins,create_time,update_time,id)" + + " select a.resourceid,kqdate,b.subcompanyid1,b.departmentid,b.jobtitle,groupid,serialid," + + " case when sum(workmins)>0 then 1 end as workdays, sum(workmins) as workmins," + + " 0 as attendancedays, sum(attendanceMins) as attendanceMins," + + " 0 as signdays, sum(signmins) as signmins," + + " sum(case when belatemins> 0 then 1 else 0 end) as belate,sum(belatemins) as belatemins," + + " sum(case when graveBeLateMins> 0 then 1 else 0 end) as graveBeLate,sum(graveBeLateMins) as graveBeLateMins," + + " sum(case when leaveearlymins> 0 then 1 else 0 end) as leaveearly,sum(leaveearlymins) as leaveearlymins," + + " sum(case when graveLeaveEarlyMins> 0 then 1 else 0 end) as graveLeaveEarly,sum(graveLeaveEarlyMins) as graveLeaveEarlyMins,"; +// if(isKqReportHalfOpen) { +// sql+=" sum((on_absenteeismmins+off_absenteeismmins)) as absenteeism,sum(absenteeismmins) as absenteeismmins,"; +// } else { + sql+=" sum(case when absenteeismmins> 0 then 1 else 0 end) as absenteeism,sum(absenteeismmins) as absenteeismmins,"; +// } + sql+=" sum(case when forgotcheckmins> 0 then 1 else 0 end) as forgotcheck,sum(forgotcheckmins) as forgotcheckmins, " + + " sum(leaveMins) as leaveMins, sum(evectionMins) as evectionMins, sum(outMins) as outMins," +baseField+ + " from kq_format_detail a, hrmresource b" + + " where a.resourceid = b.id and resourceid =? and kqdate=?" + + " group by resourceid,kqdate,b.subcompanyid1,b.departmentid,b.jobtitle,groupid,serialid,workmins"; + rs.executeUpdate(sql, userId, kqDate); + } + }else{ + Map definedFieldInfo = new KQFormatBiz().getDefinedField(); + String definedField = ""; + String definedParam = ""; + String definedParamSum = ""; + String convertAttendDay = workTime != null ? Util.null2s(workTime.getConvertAttendDay(),"1.0") : "1.0"; + if (workTime.getKQType().equals("3")) {//自由工时 + lsParam.addAll(kqFormatFreeData.format(userId, kqDate, workFlowInfo)); + } else { + definedField = Util.null2String(definedFieldInfo.get("definedField")); + definedParam = Util.null2String(definedFieldInfo.get("definedParam")); + definedParamSum = Util.null2String(definedFieldInfo.get("definedParamSum")); + lsParam.addAll(format(userId, kqDate, workTime, workFlowInfo,uuid)); + } + + if (lsParam.size() > 0) { + if (rs.getDBType().equals("postgresql")) { + sql = " insert into kq_format_detail( " + + " resourceid,kqdate,groupid,serialid,serialnumber,workbegindate,workbegintime,workenddate,workendtime,workmins," + + " signindate,signintime,signinid,signoutdate,signouttime,signoutid,signMins," + + " attendanceMins,belatemins,graveBeLateMins,leaveearlymins,graveLeaveEarlyMins,absenteeismmins,forgotcheckMins," + + " leaveMins,leaveinfo,evectionMins,outMins,forgotbeginworkcheckmins,otherinfo"+(definedField.length()>0?","+definedField+"":"")+",day_type,create_time,update_time,id,flowinfo,on_absenteeismmins,off_absenteeismmins) " + + " values(?,?,?,?,?,?,?,?,?,?, ?,?,?,?,?,?,?, ?,?,?,?,?,?,?,?,?,?,?,?,?"+(definedField.length()>0?","+definedParam+"":"")+",?,?::timestamp,?::timestamp,?,?,?,?)"; + + }else{ + sql = " insert into kq_format_detail( " + + " resourceid,kqdate,groupid,serialid,serialnumber,workbegindate,workbegintime,workenddate,workendtime,workmins," + + " signindate,signintime,signinid,signoutdate,signouttime,signoutid,signMins," + + " attendanceMins,belatemins,graveBeLateMins,leaveearlymins,graveLeaveEarlyMins,absenteeismmins,forgotcheckMins," + + " leaveMins,leaveinfo,evectionMins,outMins,forgotbeginworkcheckmins,otherinfo"+(definedField.length()>0?","+definedField+"":"")+",day_type,create_time,update_time,id,flowinfo,on_absenteeismmins,off_absenteeismmins) " + + " values(?,?,?,?,?,?,?,?,?,?, ?,?,?,?,?,?,?, ?,?,?,?,?,?,?,?,?,?,?,?,?"+(definedField.length()>0?","+definedParam+"":"")+",?,?,?,?,?,?,?)"; + } + for (int i = 0; i < lsParam.size(); i++) { + List param = lsParam.get(i); + boolean isok = rs.executeUpdate(sql, param); + kqLog.info("插入记录:userId:"+userId+":kqDate:"+kqDate+":param:"+JSON.toJSONString(param)+":isok:"+isok+"::uuid::"+uuid); + } + String attendancedaysF = " (cast(sum(attendanceMins)AS decimal(10, 2))*"+Util.getDoubleValue(convertAttendDay)+")/sum(workmins) as attendancedays, sum(attendanceMins) as attendanceMins, "; + String workF = " case when sum(workmins)>0 then "+convertAttendDay+" end as workdays, sum(workmins) as workmins,"; + String belateminsF = " sum(case when belatemins> 0 then 1 else 0 end) as belate,sum(belatemins) as belatemins,"; + String graveBeLateMinsF = " sum(case when graveBeLateMins> 0 then 1 else 0 end) as graveBeLate,sum(graveBeLateMins) as graveBeLateMins,"; + String leaveearlyminsF = " sum(case when leaveearlymins> 0 then 1 else 0 end) as leaveearly,sum(leaveearlymins) as leaveearlymins,"; + String graveLeaveEarlyMinsF = " sum(case when graveLeaveEarlyMins> 0 then 1 else 0 end) as graveLeaveEarly,sum(graveLeaveEarlyMins) as graveLeaveEarlyMins, "; + String absenteeismminsF = " sum(case when absenteeismmins> 0 then 1 else 0 end) as absenteeism,sum(absenteeismmins) as absenteeismmins, "; + String forgotcheckminsF = " sum(case when forgotcheckmins> 0 then 1 else 0 end) as forgotcheck,sum(forgotcheckmins) as forgotcheckmins,"; + String forgotbeginworkcheckminsF = " sum(case when forgotbeginworkcheckmins> 0 then 1 else 0 end) as forgotbeginworkcheck,sum(forgotbeginworkcheckmins) as forgotbeginworkcheckmins "; + String signF = " cast(sum(signmins)AS decimal(10, 2))/sum(workmins) as signdays, sum(signmins) as signmins,"; + String onoffAbsenteeismminsF= " sum(case when on_absenteeismmins> 0 then 1 else 0 end) as on_absenteeismmins,sum(case when off_absenteeismmins> 0 then 1 else 0 end) as off_absenteeismmins "; + if(1 == workTime.getNonWorkShift()){ + attendancedaysF = " 0 as attendancedays, 0 as attendanceMins, "; + workF = " 0 as workdays, 0 as workmins,"; + belateminsF = " 0 as belate,0 as belatemins,"; + graveBeLateMinsF = " 0 as graveBeLate,0 as graveBeLateMins,"; + leaveearlyminsF = " 0 as leaveearly,0 as leaveearlymins,"; + graveLeaveEarlyMinsF = " 0 as graveLeaveEarly,0 as graveLeaveEarlyMins, "; + absenteeismminsF = " 0 as absenteeism,0 as absenteeismmins,"; + forgotcheckminsF = " 0 as forgotcheck,0 as forgotcheckmins,"; + forgotbeginworkcheckminsF = " 0 as forgotbeginworkcheck,0 as forgotbeginworkcheckmins "; + signF = " 0 as signdays, 0 as signmins,"; + onoffAbsenteeismminsF = " 0 as on_absenteeismmins, 0 as off_absenteeismmins "; + } + + Long id = IdGenerator.generate(); + String baseField = ""; + if ("mysql".equalsIgnoreCase(rs.getDBType())){ + baseField = " now(),now(),"+id; + }else if ("oracle".equalsIgnoreCase(rs.getDBType())){ + baseField = " sysdate,sysdate,"+id; + }else if ("postgresql".equalsIgnoreCase(rs.getDBType())){ + baseField = " now(),now(),"+id; + }else{ + baseField = " getdate(),getdate(),"+id; + } + + sql = " insert into kq_format_total(resourceid,kqdate,subcompanyid,departmentid,jobtitle,groupid,serialid,workdays,workmins," + + " attendancedays,attendancemins,signdays,signmins,belate,belatemins,gravebelate,gravebelatemins,leaveeearly,leaveearlymins,graveleaveearly," + + " graveleaveearlymins,absenteeism,absenteeismmins,forgotcheck,forgotcheckmins," + + " leaveMins,evectionMins,outMins,forgotbeginworkcheck,forgotbeginworkcheckmins"+(definedField.length()>0?","+definedField+"":"")+",create_time,update_time,id,on_absenteeismmins,off_absenteeismmins) " + + " select a.resourceid,kqdate,b.subcompanyid1,b.departmentid,b.jobtitle,groupid,serialid," + + workF + + attendancedaysF + + signF + + belateminsF + + graveBeLateMinsF + + leaveearlyminsF + + graveLeaveEarlyMinsF + + absenteeismminsF + + forgotcheckminsF+ + " sum(leaveMins) as leaveMins," + + " sum(evectionMins) as evectionMins,sum(outMins) as outMins, " + + forgotbeginworkcheckminsF + + (definedField.length()>0?","+definedParamSum+"":"")+","+baseField+","+onoffAbsenteeismminsF+ + " from kq_format_detail a, hrmresource b" + + " where a.resourceid = b.id and resourceid = ? and kqdate=?" + + " group by resourceid,kqdate,b.subcompanyid1,b.departmentid,b.jobtitle,groupid,serialid"; + rs.executeUpdate(sql, userId, kqDate); + BaseBean bb = new BaseBean(); + + String sjcqts = geSjcqts(userId,kqDate); + + //节假日工作天数 + String jjrts = "0"; + int changeType = -1;//默认没有设置过节假日(节假日设置的类型:1-公众假日、2-调配工作日、3-调配休息日) + KQHolidaySetComInfo kqHolidaySetComInfo = new KQHolidaySetComInfo(); + String tmpChangetype = kqHolidaySetComInfo.getChangeType("3", kqDate); + if(null != tmpChangetype){ + changeType = Util.getIntValue(tmpChangetype, -1); + } + if(changeType == 1){ + jjrts = sjcqts; + } + //工程值班天数 + Integer gczb = 0; + String serialid = Util.null2String(workTime.getSerialId()); + boolean checkYd = checkYc(userId,kqDate); + + if(checkGczb(serialid)){ + //是工程值班 + gczb = 1; + bb.writeLog(userId+"是工程值班"+kqDate); + } + if(checkYd){ + gczb = 0; + bb.writeLog(userId+"下班卡存在异常"+kqDate); + } + + bb.writeLog("userIdY"+userId+"kqDate"+kqDate+"checkYd"+checkYd+"gczb"+gczb); + + boolean checkM = checkKqModeInfo(userId,kqDate); + bb.writeLog("checkM"+checkM); + if(checkM){ + bb.writeLog("已存在更新"); + //更新台账数据 + updateKqModeInfo(userId,kqDate,gczb,jjrts); + }else{ + //格式化数据台账生成-二开 + createKqModeInfo(userId,kqDate,gczb,jjrts); + } + } + } + }catch (Exception e) { + kqLog.info("考勤重算报错:KQFormatData.Exception:"); + StringWriter errorsWriter = new StringWriter(); + e.printStackTrace(new PrintWriter(errorsWriter)); + kqLog.info(errorsWriter.toString()); + } + return resultMap; + } + + public List> format(String userId, String kqDate, WorkTimeEntity workTime, + Map workFlowInfo, String uuid) { + List> lsParam = new ArrayList<>(); + List params = null; + HashMap middleMap = new HashMap<>(); + try { + Timestamp date = new Timestamp(System.currentTimeMillis()); + KQSettingsComInfo kqSettingsComInfo = new KQSettingsComInfo(); + String nosign_is_absent = Util.null2String(kqSettingsComInfo.getMain_val("nosign_is_absent"),"1"); + //默认不开启半天的特殊规则,如果开启,那么只要是半天的单位,并且申请考勤流程半天,那么实际出勤就是0.5天,不考虑迟到和早退。当天旷工的情况需要考虑,即如果另外半天是旷工,那么实际出勤自然也是0 + String is_half = Util.null2String(kqSettingsComInfo.getMain_val("is_half"),"0"); + String early_one_mins = Util.null2String(kqSettingsComInfo.getMain_val("early_one_mins"),"0"); + KQTimesArrayComInfo kqTimesArrayComInfo = new KQTimesArrayComInfo(); + KQFormatShiftRule kqFormatShiftRule = new KQFormatShiftRule(); + String preDate = DateUtil.addDate(kqDate, -1);//上一天日期 + String nextDate = DateUtil.addDate(kqDate, 1);//下一天日期 + String dateKey = userId + "|" + kqDate; + String nextDateKey = userId + "|" + nextDate; + ArrayList hostIps = InitServer.getRealIp(); + boolean oneSign = false; + List lsSignTime = new ArrayList<>(); + List lsWorkTime = new ArrayList<>(); + List lsRestTime = new ArrayList<>(); + List workFlow = null; + int restShift = 0; + int signoutOnlyoff = 0; + if (workTime != null) { + lsSignTime = workTime.getSignTime();//允许打卡时间 + lsWorkTime = workTime.getWorkTime();//工作时间 + lsRestTime = workTime.getRestTime();//休息时段时间 + oneSign = lsWorkTime!=null&&lsWorkTime.size()==1; + restShift = workTime.getNonWorkShift(); + signoutOnlyoff = workTime.getSignoutOnlyoff(); + } + kqLog.info("format in >>>>>userId" + userId + "kqDate==" + kqDate+":restShift:"+restShift+":signoutOnlyoff:"+signoutOnlyoff+":hostIps:"+hostIps+":uuid::"+uuid); + + if(this.writeLog) { + logInfo.put("signoutOnlyoff",signoutOnlyoff); + } + + + int[] dayMins = new int[2880];//一天所有分钟数 + Arrays.fill(dayMins, -1); + + //处理半天班次冲销问题 + int[] dayMinsNew = new int[2880];//一天所有分钟数 + Arrays.fill(dayMinsNew, -1); + int workMins4leave = 0; + int middleMins = 0;//班次的半天时长 + int middleMins_final = 0;//班次的半天时长 + int shiftNums = lsWorkTime == null ? 0 : lsWorkTime.size(); + + // 一天4次打卡单独做判断,如果是上午下班打卡和下午上班打卡时间重叠,那么上午的下班卡取最早的,下午的上班卡取最晚的。用shiftCount是否等于-1判断,-1就走标准不重叠。2就表示重叠走新的逻辑 + int shiftCount = lsWorkTime == null ? 0 : lsWorkTime.size(); + int shiftI = 0; + String signEndDateTimeZero = ""; + for (int i = 0; lsWorkTime != null && i < lsWorkTime.size(); i++) { + shiftI = i; + TimeScopeEntity signTimeScope = lsSignTime.get(i); + TimeScopeEntity workTimeScope = lsWorkTime.get(i); + String signBeginDateTime = signTimeScope.getBeginTimeAcross() ? nextDate : kqDate; + if(signTimeScope.isBeginTimePreAcross()){ + signBeginDateTime = preDate; + } + signBeginDateTime+=" "+kqTimesArrayComInfo.turn48to24Time(signTimeScope.getBeginTime())+":00"; + String signEndDateTime = signTimeScope.getEndTimeAcross() ? nextDate : kqDate; + signEndDateTime+=" "+kqTimesArrayComInfo.turn48to24Time(signTimeScope.getEndTime())+":59"; + if (shiftCount == 2 && shiftI == 0) { + signEndDateTimeZero = signEndDateTime; + } + if (shiftCount == 2 && shiftI == 1) { + shiftCount = signBeginDateTime.compareTo(signEndDateTimeZero) <= 0 ? shiftCount : -1; + } + + String workBeginTime = Util.null2String(workTimeScope.getBeginTime()); + String ori_workBeginTime = workBeginTime; + int workBeginIdx = kqTimesArrayComInfo.getArrayindexByTimes(workBeginTime); + boolean workBenginTimeAcross = workTimeScope.getBeginTimeAcross(); + String workEndTime = Util.null2String(workTimeScope.getEndTime()); + String ori_workEndTime = workEndTime; + int workEndIdx = kqTimesArrayComInfo.getArrayindexByTimes(workEndTime); + boolean workEndTimeAcross = workTimeScope.getEndTimeAcross(); + int workMins = workTimeScope.getWorkMins(); + + String workBeginDate = workBenginTimeAcross ? nextDate : kqDate; + String workEndDate = workEndTimeAcross ? nextDate : kqDate; + if(lsRestTime != null && !lsRestTime.isEmpty()){ + for(int k = 0 ; k < lsRestTime.size(); k++){ + TimeScopeEntity restTimeScope = lsRestTime.get(k); + if (restTimeScope!=null) { + String restBeginTime = Util.null2String(restTimeScope.getBeginTime()); + String restEndTime = Util.null2String(restTimeScope.getEndTime()); + int beginIdx = kqTimesArrayComInfo.getArrayindexByTimes(restBeginTime); + int endIdx = kqTimesArrayComInfo.getArrayindexByTimes(restEndTime); + if (endIdx > beginIdx) { + Arrays.fill(dayMinsNew, beginIdx, endIdx, -11);//休息时间 + } + } + } + int all_rest_cnt = kqTimesArrayComInfo.getCnt(dayMinsNew, workBeginIdx, workEndIdx, -11); + if(all_rest_cnt >= 0){ + workMins = workMins-(all_rest_cnt); + } + } + workMins4leave += workMins; + } + middleMins = workMins4leave>0?workMins4leave/2:0; + middleMins_final = middleMins; + int split_time_index = middleMins_final; // 半天时间index,用于考勤汇总报表区分上下午 + if(oneSign) { + List halfWorkIndex = workTime.getHalfWorkIndex(); + if(halfWorkIndex != null && !halfWorkIndex.isEmpty()) { + int[] halfWorkIndexs = halfWorkIndex.get(0); + split_time_index = halfWorkIndexs[1];//半天的时间 + } + } + + for (int i = 0; lsWorkTime != null && i < lsWorkTime.size(); i++) { + shiftI = i; + params = new ArrayList<>(); + TimeScopeEntity signTimeScope = lsSignTime.get(i); + TimeScopeEntity workTimeScope = lsWorkTime.get(i); + //TimeScopeEntity restTimeScope = lsRestTime.isEmpty()?null:lsRestTime.get(i); + String workBeginTime = Util.null2String(workTimeScope.getBeginTime()); + String ori_workBeginTime = workBeginTime; + int workBeginIdx = kqTimesArrayComInfo.getArrayindexByTimes(workBeginTime); + boolean workBenginTimeAcross = workTimeScope.getBeginTimeAcross(); + String workEndTime = Util.null2String(workTimeScope.getEndTime()); + String ori_workEndTime = workEndTime; + int workEndIdx = kqTimesArrayComInfo.getArrayindexByTimes(workEndTime); + boolean workEndTimeAcross = workTimeScope.getEndTimeAcross(); + int workMins = workTimeScope.getWorkMins(); + + String workBeginDate = workBenginTimeAcross ? nextDate : kqDate; + String workEndDate = workEndTimeAcross ? nextDate : kqDate; + + Arrays.fill(dayMins, workBeginIdx, workEndIdx, 1);//工作时段标识 1 + + int beginIdx = 0; + int endIdx = 0; + int checkIn = 0; + int checkOut = 0; + String signInId = ""; + String signInDate = ""; + String signInTime = ""; + String signOutId = ""; + String signOutDate = ""; + String signOutTime = ""; + int earlyInMins = 0;//早到分钟数 + int lateOutMins = 0;//晚走分钟数 + int signMins = 0;//签到签退时长 + int tmpAttendanceMins = 0;//出勤分钟数(流程抵扣来的) + int attendanceMins = 0; + int beLateMins = 0; + int graveBeLateMins = 0; + int leaveEarlyMins = 0; + int graveLeaveEarlyMins = 0; + int absenteeismMins = 0; + int on_absenteeismMins = 0; + int off_absenteeismMins = 0; + int leaveMins = 0;//请假时长 + Map leaveInfo = new HashMap<>();//请假信息 + Map otherinfo = new HashMap<>();//存一些用得到的信息 + Map flowinfo = new HashMap<>();//流程信息 + int evectionMins = 0;//出差时长 + int outMins = 0;//公出时长 + int otherMins = 0;//异常流程时长 + int forgotCheckMins = 0; + int forgotBeginWorkCheckMins = 0;//上班漏签 + int signInTimeIndx = -1; + int flowSignInTimeIndx = -1; + int signInTimeOutdx = -1; + //用来计算实际打卡时长用的 + int signInTimeIndx4Sign = -1; + int signInTimeOutdx4Sign = -1; + + String signBeginDateTime = signTimeScope.getBeginTimeAcross() ? nextDate : kqDate; + if(signTimeScope.isBeginTimePreAcross()){ + signBeginDateTime = preDate; + } + signBeginDateTime+=" "+kqTimesArrayComInfo.turn48to24Time(signTimeScope.getBeginTime())+":00"; + String signEndDateTime = signTimeScope.getEndTimeAcross() ? nextDate : kqDate; + signEndDateTime+=" "+kqTimesArrayComInfo.turn48to24Time(signTimeScope.getEndTime())+":59"; + String workBeginDateTime = workTimeScope.getBeginTimeAcross() ? nextDate : kqDate; + workBeginDateTime+=" "+kqTimesArrayComInfo.turn48to24Time(workTimeScope.getBeginTime())+":00"; + String workEndDateTime = workTimeScope.getEndTimeAcross() ? nextDate : kqDate; + workEndDateTime+=" "+kqTimesArrayComInfo.turn48to24Time(workTimeScope.getEndTime())+":00"; + + kqLog.info("signBeginDateTime" + signBeginDateTime+"::userId" + userId + "kqDate==" + kqDate+":hostIps:"+hostIps+":uuid::"+uuid); + kqLog.info("signEndDateTime" + signEndDateTime+"::userId" + userId + "kqDate==" + kqDate+":hostIps:"+hostIps+":uuid::"+uuid); + kqLog.info("workBeginDateTime" + workBeginDateTime+"::userId" + userId + "kqDate==" + kqDate+":hostIps:"+hostIps+":uuid::"+uuid); + kqLog.info("workEndDateTime" + workEndDateTime+"::userId" + userId + "kqDate==" + kqDate+":hostIps:"+hostIps+":uuid::"+uuid); + + Map shifRuleMap = Maps.newHashMap(); + if (1 != restShift) { + if(oneSign){ + //个性化设置只支持一天一次上下班 + ShiftInfoBean shiftInfoBean = new ShiftInfoBean(); + shiftInfoBean.setSplitDate(kqDate); + shiftInfoBean.setShiftRuleMap(workTime.getShiftRuleInfo()); + shiftInfoBean.setSignTime(lsSignTime); + shiftInfoBean.setWorkTime(lsWorkTime); + shiftInfoBean.setSignoutOnlyoff(signoutOnlyoff); + List logList = Lists.newArrayList(); + KQShiftRuleInfoBiz.getShiftRuleInfo(shiftInfoBean, userId, shifRuleMap,logList); + if(!shifRuleMap.isEmpty()){ + if(!logList.isEmpty()){ + otherinfo.put("logList", logList); + } + + otherinfo.put("shiftRule", shifRuleMap); + if(shifRuleMap.containsKey("shift_beginworktime")){ + String shift_beginworktime = Util.null2String(shifRuleMap.get("shift_beginworktime")); + if(shift_beginworktime.length() > 0){ + workBeginTime = Util.null2String(shift_beginworktime); + workBeginIdx = kqTimesArrayComInfo.getArrayindexByTimes(workBeginTime); + workTimeScope.setBeginTime(workBeginTime); + workTimeScope.setBeginTimeAcross(workBeginIdx>=1440?true:false); + } + } + if(this.writeLog) { + logInfo.put("before.workEndIdx",workEndIdx); + } + if(shifRuleMap.containsKey("shift_endworktime")){ + String shift_endworktime = Util.null2String(shifRuleMap.get("shift_endworktime")); + if(shift_endworktime.length() > 0){ + workEndTime = Util.null2String(shift_endworktime); + workEndIdx = kqTimesArrayComInfo.getArrayindexByTimes(workEndTime); + workTimeScope.setEndTime(workEndTime); + workTimeScope.setEndTimeAcross(workEndIdx>=1440?true:false); + } + } + } + kqLog.info("个性化之后 signBeginDateTime" + signBeginDateTime); + kqLog.info("个性化之后 signEndDateTime" + signEndDateTime); + kqLog.info("个性化之后 workBeginDateTime" + workBeginDateTime); + kqLog.info("个性化之后 workEndDateTime" + workEndDateTime); + } + } + if(this.writeLog) { + logInfo.put("after.workEndIdx",workEndIdx); + } + + List lsCheckInfo = new KQFormatSignData().getSignInfo(userId,signTimeScope,workTimeScope,kqDate,preDate,nextDate,kqTimesArrayComInfo,hostIps,uuid,shiftCount,shiftI,signoutOnlyoff); + kqLog.info("lsCheckInfo" + JSONObject.toJSONString(lsCheckInfo)+"::userId" + userId + "kqDate==" + kqDate+":hostIps:"+hostIps+":uuid::"+uuid); + if(this.writeLog) { + logInfo.put(""+weaver.systeminfo.SystemEnv.getHtmlLabelName(10005297,weaver.general.ThreadVarLanguage.getLang())+"",signBeginDateTime); + logInfo.put(""+weaver.systeminfo.SystemEnv.getHtmlLabelName(10005298,weaver.general.ThreadVarLanguage.getLang())+"",signEndDateTime); + logInfo.put(""+weaver.systeminfo.SystemEnv.getHtmlLabelName(1940,weaver.general.ThreadVarLanguage.getLang())+"",workBeginDateTime); + logInfo.put(""+weaver.systeminfo.SystemEnv.getHtmlLabelName(10005299,weaver.general.ThreadVarLanguage.getLang())+"",workEndDateTime); + logInfo.put(""+weaver.systeminfo.SystemEnv.getHtmlLabelName(10005300,weaver.general.ThreadVarLanguage.getLang())+"",lsCheckInfo); + } + for (int j = 0; lsCheckInfo != null && j < lsCheckInfo.size(); j++) { + Map checkInfo = (Map) lsCheckInfo.get(j); + String signStatus = Util.null2String(checkInfo.get("signStatus")); + String signId = Util.null2String(checkInfo.get("signId")); + String signDate = Util.null2String(checkInfo.get("signDate")); + String signTime = Util.null2String(checkInfo.get("signTime")); + String deduct_signintime = Util.null2String(checkInfo.get("deduct_signintime")); + String deduct_signofftime = Util.null2String(checkInfo.get("deduct_signofftime")); + String flow_signInTime = ""; + String flow_signOutTime = ""; + if(kqDate.compareTo(signDate) < 0)endIdx+=1440; + if (signTime.length() > 8) { + signTime = signTime.substring(0, 8); + } + if (checkInfo.get("signType").equals("1")) {//签到 + checkIn++; + //如果流程抵扣存在,打卡时长也存在,那么相互比较得到出勤时长和打卡时长 暂不这样处理,还是按照漏签的逻辑来处理 + if(signTime.length() > 0){ + signInTimeIndx4Sign = kqTimesArrayComInfo.getArrayindexByTimes(signTime); + } + signInId = signId; + signInDate = signDate; + signInTime = signTime; + signInTimeIndx = kqTimesArrayComInfo.getArrayindexByTimes(signInTime); + if(this.writeLog) { + logInfo.put(j+">>>signInTime",signInTime); + logInfo.put(j+">>>signInTimeIndx",signInTimeIndx); + logInfo.put(j+">>>kqDate",kqDate+"|"+signDate); + } + if(deduct_signintime.length() > 0){ + if(signTime.length() > 0){ + if(deduct_signintime.compareTo(signTime) < 0){ + flow_signInTime = deduct_signintime; + } + }else{ + flow_signInTime = deduct_signintime; + } + } + if(flow_signInTime.length() > 0){ + flowSignInTimeIndx = kqTimesArrayComInfo.getArrayindexByTimes(flow_signInTime); + } + if(kqDate.compareTo(signDate) < 0) { + signInTimeIndx += 1440; + flowSignInTimeIndx += 1440; + }else if(kqDate.compareTo(signDate) > 0){ + signInTimeIndx -= 1440; + signInTimeIndx = signInTimeIndx < 0 ? 0 : signInTimeIndx; + flowSignInTimeIndx -= 1440; + flowSignInTimeIndx = flowSignInTimeIndx < 0 ? 0 : flowSignInTimeIndx; + } + } else if (checkInfo.get("signType").equals("2")) {//签退 + checkOut++; + //如果流程抵扣存在,打卡时长也存在,那么相互比较得到出勤时长和打卡时长 暂不这样处理,还是按照漏签的逻辑来处理 + if(signTime.length() > 0){ + signInTimeOutdx4Sign = kqTimesArrayComInfo.getArrayindexByTimes(signTime); + } + signOutId = signId; + signOutDate = signDate; + signOutTime = signTime; + signInTimeOutdx = kqTimesArrayComInfo.getArrayindexByTimes(signOutTime); + if(deduct_signofftime.length() > 0){ + if(signTime.length() > 0){ + if(deduct_signofftime.compareTo(signTime) > 0){ + flow_signOutTime = deduct_signofftime; + } + }else{ + flow_signOutTime = deduct_signofftime; + } + } + if(flow_signOutTime.length() > 0){ + signInTimeOutdx = kqTimesArrayComInfo.getArrayindexByTimes(flow_signOutTime); + } + if(kqDate.compareTo(signDate) < 0){ + signInTimeOutdx+=1440; + }else if(kqDate.compareTo(signDate) > 0){ + signInTimeOutdx -= 1440; + signInTimeOutdx = signInTimeOutdx < 0 ? 0 : signInTimeOutdx; + } + if(oneSign){ + if(signInTimeOutdx>workEndIdx) { + lateOutMins = signInTimeOutdx-workEndIdx; + } + } + } + if (checkInfo.get("signType").equals("1")) {//签到 + if(signTime.length() > 0){ + String signMinTime = signTime.substring(0,5)+":00"; + endIdx = kqTimesArrayComInfo.getArrayindexByTimes(signTime); + if(signTime.compareTo(signMinTime) > 0){ + //如果签到时间是带秒的且是迟到,那么签到时间多一秒和多一分钟是一样的 + endIdx += 1; + signInTimeIndx = signInTimeIndx + 1;//如果是带秒的打卡数据不应该影响流程抵扣的数据的下标 + } + if(kqDate.compareTo(signDate) < 0){ + endIdx+=1440; + }else if(kqDate.compareTo(signDate) > 0){ + endIdx -= 1440; + endIdx = endIdx < 0 ? 0 : endIdx; + } + if (endIdx > workBeginIdx) { + if(flow_signInTime.length() > 0){ + if(flowSignInTimeIndx > workBeginIdx){ + //增加一个判断,流程抵扣打卡如果开启了并且有抵扣上班打卡,那么也就不是迟到了 + Arrays.fill(dayMins, workBeginIdx, endIdx, 2);//迟到时段标识 2 + } + }else{ + Arrays.fill(dayMins, workBeginIdx, endIdx, 2);//迟到时段标识 2 + } + } + } + } else if (checkInfo.get("signType").equals("2")) {//签退 + if(signTime.length() > 0){ + beginIdx = kqTimesArrayComInfo.getArrayindexByTimes(signTime); + if(this.writeLog) { + logInfo.put(j+".signTime",signDate+"|"+signTime); + logInfo.put(j+".beginIdx",beginIdx); + logInfo.put(j+".workEndIdx",workEndIdx); + } + if(StringUtils.isNotBlank(signDate) && signDate.compareTo(kqDate) > 0){ + beginIdx+=1440; + }else if(kqDate.compareTo(signDate) > 0){ + beginIdx -= 1440; + beginIdx = beginIdx < 0 ? 0 : beginIdx; + } + if (workEndIdx > beginIdx) { + if(flow_signOutTime.length() > 0){ + if (workEndIdx > signInTimeOutdx) { + //增加一个判断,流程抵扣打卡如果开启了并且有抵扣下班打卡,那么也就不是早退了 + Arrays.fill(dayMins, beginIdx, workEndIdx, 3);//早退时段标识 3 + } + }else{ + + Arrays.fill(dayMins, beginIdx, workEndIdx, 3);//早退时段标识 3 + } + } + } + } + } + + //打卡时长=签退时间-签到时间(有签到签退才计算) + if(checkIn==1&&checkOut==1){ + if(signInTimeIndx4Sign > -1 && signInTimeOutdx4Sign > -1){ + if(DateUtil.dayDiff(signInDate,signOutDate)==0){//同一天签到和签退 + signMins=signInTimeOutdx4Sign - signInTimeIndx4Sign; + }else if(DateUtil.dayDiff(signInDate,signOutDate)==1) {//第一天签到,第二天签退 + if(signInTimeOutdx4Sign workBeginIdx) { + Arrays.fill(dayMins, workBeginIdx, workEndIdx, 4);//旷工时段标识 4 + } + } + + if (checkOut == 0 && checkIn > 0) {//漏签(有签到无签退) + if(signInTimeIndx > -1){ + if (workEndIdx > signInTimeIndx) { + //漏签就是从本次时段内的打卡到下班点 + //上班漏签应该是从签到到签到结束时间,不过这里可以不用管,只是一个次数 + Arrays.fill(dayMins, signInTimeIndx, workEndIdx, 6);//上班漏签时段标识 6 + } else { + //签到晚于本次时段结束时间,也算漏签 + forgotCheckMins++; + } + }else if(flowSignInTimeIndx > -1){ + if (workEndIdx > flowSignInTimeIndx) { + //漏签就是从本次时段内的打卡到下班点 + //上班漏签应该是从签到到签到结束时间,不过这里可以不用管,只是一个次数 + Arrays.fill(dayMins, flowSignInTimeIndx, workEndIdx, 6);//上班漏签时段标识 6 + } else { + //签到晚于本次时段结束时间,也算漏签 + forgotCheckMins++; + } + } + } + + if (checkIn == 0 && checkOut > 0) {//漏签(有签退无签到) + if(signInTimeOutdx > 0){ + if(workBeginIdx < signInTimeOutdx) { + //下班漏签应该是从签退到签退开始时间,不过这里可以不用管,只是一个次数 + Arrays.fill(dayMins, workBeginIdx, signInTimeOutdx, 66);//下班漏签时段标识 66,66呼应前面的漏签的6 + }else{ + //这种数据理论上不会存在,也记下吧 + forgotBeginWorkCheckMins++; + } + } + } + + if (workFlowInfo.get(dateKey) != null) { + workFlow = (List) workFlowInfo.get(dateKey); + } + + boolean isHandle1 = false; + boolean isHandle2 = false; + List flowList = Lists.newArrayList(); + for (int j = 0; workFlow != null && j < workFlow.size(); j++) { + Map data = (Map) workFlow.get(j); + String flowType = Util.null2String(data.get("flowtype")); + String newLeaveType = Util.null2String(data.get("newleavetype")); + String signtype = Util.null2String(data.get("signtype")); + String durationrule = Util.null2String(data.get("durationrule")); + String ishalf = Util.null2String(data.get("ishalf")); + double duration = Util.getDoubleValue(Util.null2String(data.get("duration"))); + if(flowType.equalsIgnoreCase(FlowReportTypeEnum.LEAVE.getFlowType())){ + duration = Util.getDoubleValue(Util.null2String(data.get(newLeaveType))); + } + String serial = Util.null2String(data.get("serial")); + String requestId = Util.null2String(data.get("requestId")); + String begintime = Util.null2String(data.get("begintime")); + String endtime = Util.null2String(data.get("endtime")); + beginIdx = kqTimesArrayComInfo.getArrayindexByTimes(begintime); + endIdx = kqTimesArrayComInfo.getArrayindexByTimes(endtime); + if (beginIdx >= endIdx) { + continue; + } + Map flowMap = Maps.newHashMap(); + flowMap.put("newLeaveType", newLeaveType); + flowMap.put("begintime", begintime); + flowMap.put("endtime", endtime); + List> flowMapList = Lists.newArrayList(); + if(flowinfo.containsKey(flowType)){ + List> tmpFlowMapList = (List>) flowinfo.get(flowType); + tmpFlowMapList.add(flowMap); + }else{ + flowMapList.add(flowMap); + flowinfo.put(flowType, flowMapList); + } + int middleIdx = (workBeginIdx+workEndIdx)/2;//工作时段标识 1 + + if(flowType.equals(FlowReportTypeEnum.EVECTION.getFlowType())){ + if("2".equals(durationrule) && "true".equals(ishalf)){ + isHandle2 = true; + } + Arrays.fill(dayMins, beginIdx, endIdx, 7);//出差抵扣时段标识 7 + }else if(flowType.equals(FlowReportTypeEnum.OUT.getFlowType())){ + if("2".equals(durationrule) && "true".equals(ishalf)){ + isHandle2 = true; + } + Arrays.fill(dayMins, beginIdx, endIdx, 8);//公出抵扣时段标识 8 + }else if(flowType.equalsIgnoreCase(FlowReportTypeEnum.LEAVE.getFlowType())){ + if("2".equals(durationrule) && "true".equals(ishalf)){ + isHandle1 = true; + } + if (endIdx > beginIdx) { + Arrays.fill(dayMins, beginIdx, endIdx, 5);//流程抵扣时段标识 5 + int tmpBeginIdx = beginIdx; + int tmpEndIdx = endIdx; + Integer val = 0; + + if(beginIdx>=workEndIdx){ + continue; + } + if(endIdx<=workBeginIdx){ + continue; + } + + if(leaveInfo.get(newLeaveType)==null){ + leaveInfo.put(newLeaveType,val); + }else{ + val = (Integer) leaveInfo.get(newLeaveType); + } + + if(beginIdxworkEndIdx)tmpEndIdx=endIdx; + if(tmpEndIdx>tmpBeginIdx){ + leaveInfo.put(newLeaveType,val+(tmpEndIdx-tmpBeginIdx)); + } + } + }else{ + if (endIdx > beginIdx) { + Arrays.fill(dayMins, beginIdx, endIdx, 99);//异常流程抵扣时段标识99 + } + } + } + + + if (workEndTimeAcross && false) {//跨天需要加入一天的流程 + workFlow = null; + if (workFlowInfo.get(nextDateKey) != null) { + workFlow = (List) workFlowInfo.get(nextDateKey); + } + + for (int j = 0; workFlow != null && j < workFlow.size(); j++) { + Map data = (Map) workFlow.get(j); + String flowType = Util.null2String(data.get("flowtype")); + beginIdx = kqTimesArrayComInfo.getArrayindexByTimes(Util.null2String(data.get("begintime")))+1440; + endIdx = kqTimesArrayComInfo.getArrayindexByTimes(Util.null2String(data.get("endtime")))+1440; + if(endIdx>=2880){ + endIdx = 2880; + } + if(flowType.equals(FlowReportTypeEnum.EVECTION.getFlowType())){ + Arrays.fill(dayMins, beginIdx, endIdx, 7);//出差抵扣时段标识 7 + }else if(flowType.equals(FlowReportTypeEnum.OUT.getFlowType())){ + Arrays.fill(dayMins, beginIdx, endIdx, 8);//公出抵扣时段标识 8 + }else if(flowType.equalsIgnoreCase(FlowReportTypeEnum.LEAVE.getFlowType())){ + if (endIdx > beginIdx) { + Arrays.fill(dayMins, beginIdx, endIdx, 5);//流程抵扣时段标识 5 + + } + }else{ + if (endIdx > beginIdx) { + Arrays.fill(dayMins, beginIdx, endIdx, 99);//异常流程抵扣时段标识99 + } + } + } + } + + if(lsRestTime != null && !lsRestTime.isEmpty()){ + for(int k = 0 ; k < lsRestTime.size(); k++){ + TimeScopeEntity restTimeScope = lsRestTime.get(k); + if (restTimeScope!=null) { + String restBeginTime = Util.null2String(restTimeScope.getBeginTime()); + String restEndTime = Util.null2String(restTimeScope.getEndTime()); + beginIdx = kqTimesArrayComInfo.getArrayindexByTimes(restBeginTime); + endIdx = kqTimesArrayComInfo.getArrayindexByTimes(restEndTime); + if (endIdx > beginIdx) { + Arrays.fill(dayMins, beginIdx, endIdx, -11);//休息时间 + } + } + } + int all_rest_cnt = kqTimesArrayComInfo.getCnt(dayMins, workBeginIdx, workEndIdx, -11); + if(all_rest_cnt >= 0){ + workMins = workMins-(all_rest_cnt); + } + } + + for (int j = workBeginIdx; j < workEndIdx; j++) { + switch (dayMins[j]) { + case 1: + tmpAttendanceMins++; + break; + case 2: + beLateMins++; + break; + case 3: + leaveEarlyMins++; + break; + case 4: + if(j 0){ + //如果没有个性化的旷工,那就是全天旷工 + isAmAbsent = true; + } + if(off_absenteeismMins > 0) { + isPmAbsent = true; + } + + KQShiftRuleEntity kqShiftRuleEntity = new KQShiftRuleEntity(); + kqShiftRuleEntity.setUserId(userId); + kqShiftRuleEntity.setKqDate(kqDate); + kqShiftRuleEntity.setBelatemins(beLateMins); + kqShiftRuleEntity.setLeaveearlymins(leaveEarlyMins); + kqShiftRuleEntity.setAbsenteeismmins(absenteeismMins); + kqShiftRuleEntity.setForgotcheckmins(forgotCheckMins); + kqShiftRuleEntity.setForgotBeginWorkCheckMins(forgotBeginWorkCheckMins); + kqShiftRuleEntity.setEarlyInMins(earlyInMins); + kqShiftRuleEntity.setLateOutMins(lateOutMins); + kqShiftRuleEntity.setAMAbsent(isAmAbsent); + kqShiftRuleEntity.setPMAbsent(isPmAbsent); + kqShiftRuleEntity.setNosign_is_absent(nosign_is_absent); + kqShiftRuleEntity.setSignInTime(signInTime); + kqShiftRuleEntity.setSignOutTime(signOutTime); + kqShiftRuleEntity.setEarly_one_mins(early_one_mins); + kqLog.info("人性化规则处理前数据" + JSONObject.toJSONString(kqShiftRuleEntity)); + if(this.writeLog) { + logInfo.put(""+weaver.systeminfo.SystemEnv.getHtmlLabelName(10005301,weaver.general.ThreadVarLanguage.getLang())+"",kqShiftRuleEntity); + } + //人性化规则 + kqShiftRuleEntity = kqFormatShiftRule.doShiftRule(workTime,kqShiftRuleEntity); + kqLog.info("人性化规则处理后数据" + JSONObject.toJSONString(kqShiftRuleEntity)); + if(this.writeLog) { + logInfo.put(""+weaver.systeminfo.SystemEnv.getHtmlLabelName(10005302,weaver.general.ThreadVarLanguage.getLang())+"",kqShiftRuleEntity); + } + beLateMins = kqShiftRuleEntity.getBelatemins(); + graveBeLateMins = kqShiftRuleEntity.getGravebelatemins(); + leaveEarlyMins = kqShiftRuleEntity.getLeaveearlymins(); + graveLeaveEarlyMins = kqShiftRuleEntity.getGraveleaveearlymins(); + absenteeismMins = kqShiftRuleEntity.getAbsenteeismmins(); + forgotCheckMins = kqShiftRuleEntity.getForgotcheckmins(); + forgotBeginWorkCheckMins = kqShiftRuleEntity.getForgotBeginWorkCheckMins(); + int shiftOn_absenteeismMins = Util.getIntValue(kqShiftRuleEntity.getOn_absenteeismMins()); + if(shiftOn_absenteeismMins > 0) { + on_absenteeismMins = shiftOn_absenteeismMins; + } + int shiftOff_absenteeismMins = Util.getIntValue(kqShiftRuleEntity.getOff_absenteeismMins()); + if(shiftOff_absenteeismMins > 0) { + off_absenteeismMins = shiftOff_absenteeismMins; + } + + boolean isondutyfreecheck =false; + boolean isoffdutyfreecheck =false; + Map model_ShiftRule = kqFormatShiftRule.getModel_ShiftRule(i, workTime.getSerialId()); + Iterator iter = model_ShiftRule.entrySet().iterator(); + while (iter.hasNext()) { + Map.Entry entry = (Map.Entry) iter.next(); + String key = Util.null2String(entry.getKey()); + String value = Util.null2String(entry.getValue()); + if(key.equals("start")&&value.equals("1")){ + isondutyfreecheck = true; + } + if(key.equals("end")&&value.equals("1")){ + isoffdutyfreecheck = true; + } + } + boolean beforeBegin = !new KQFormatBiz().needCal(workBeginDate,workBeginTime); + if(beforeBegin) {//还未到上班时间,不用计算任何状态 + kqLog.writeLog("还未到上班时间,不用计算任何状态"); + beLateMins = 0; + graveBeLateMins = 0; + leaveEarlyMins = 0; + graveLeaveEarlyMins = 0; + absenteeismMins = 0; + forgotCheckMins = 0; + forgotBeginWorkCheckMins = 0; + isAmAbsent = false; + isPmAbsent = false; + on_absenteeismMins = 0; + off_absenteeismMins = 0; + }else if(!new KQFormatBiz().needCal(workEndDate,workEndTime)) {//还未到下班时间 + kqLog.writeLog("还未到上班时间"); + leaveEarlyMins = 0; + graveLeaveEarlyMins = 0; + forgotCheckMins = 0; + isPmAbsent = false; + off_absenteeismMins = 0; + } + + if (1 == restShift || workTime.getIsExclude()) {//休息日班次或者无需考勤人员没有异常状态 + beLateMins = 0; + graveBeLateMins = 0; + leaveEarlyMins = 0; + graveLeaveEarlyMins = 0; + absenteeismMins = 0; + forgotCheckMins = 0; + forgotBeginWorkCheckMins = 0; + isAmAbsent = false; + isPmAbsent = false; + on_absenteeismMins = 0; + off_absenteeismMins = 0; + } + if (1 == restShift) {//非工作日班次連打卡時長和出勤时长也不給了 + workMins = 0; + signMins = 0; + isAmAbsent = false; + isPmAbsent = false; + on_absenteeismMins = 0; + off_absenteeismMins = 0; + } + //允许下班不打卡 ,如果上班也没有打卡,那么算上班旷工0.5天 + if (isoffdutyfreecheck) { + if (checkIn == 0) {//(无签到),就会有上班漏签,如果有下班卡,那么上班漏签 + if(forgotBeginWorkCheckMins==0&&absenteeismMins>0){ + forgotBeginWorkCheckMins= absenteeismMins ; + } + } + absenteeismMins = 0; + forgotCheckMins = 0; + off_absenteeismMins = 0; + } + //允许上班不打卡,如果下班也没有打卡,那么算漏签 + if(isondutyfreecheck){ + if (checkOut == 0) {//(无签退) + if(forgotCheckMins==0&&absenteeismMins>0){ + forgotCheckMins= absenteeismMins ; + } + } + absenteeismMins = 0; + forgotBeginWorkCheckMins = 0; + on_absenteeismMins = 0; + } + if(isondutyfreecheck&&isoffdutyfreecheck){ + absenteeismMins = 0; + forgotCheckMins = 0; + forgotBeginWorkCheckMins = 0; + on_absenteeismMins = 0; + off_absenteeismMins = 0; + } + //计算实际出勤时间(出差公出算出勤)=应出勤-旷工-请假-迟到-早退 +// attendanceMins = workMins - absenteeismMins-leaveMins-beLateMins-graveBeLateMins-leaveEarlyMins-graveLeaveEarlyMins; + /** update by wangcf 2025-01-06 start 实际出勤时长 不去除 迟到、严重迟到、早退、严重早退 **/ + attendanceMins = workMins - absenteeismMins - leaveMins; + kqLog.info("======== KQFormatData format attendanceMins ========== "+ attendanceMins); + /** update by wangcf 2025-01-06 end 实际出勤时长 不去除 迟到、严重迟到、早退、严重早退 **/ + + /** update by wangcf 2025-06-06 start 如果请的哺乳假,要加回去,也就是不扣减哺乳假 **/ + int breastMins = KqUtil.getBreastMins(kqDate,kqDate,userId); + kqLog.info("======== KQFormatData format breastMins ========== "+ breastMins); + if(breastMins > 0){ + attendanceMins += breastMins; + } + /** update by wangcf 2025-06-06 start 如果请的哺乳假,要加回去,也就是不扣减哺乳假 **/ + + if(this.writeLog) { + logInfo.put("is_half",is_half); + logInfo.put("shiftNums",shiftNums); + logInfo.put("isHandle2",isHandle2); + logInfo.put("isHandle1",isHandle1); + logInfo.put("workMins"+i,workMins); + logInfo.put("absenteeismMins"+i,absenteeismMins); + logInfo.put("middleMins"+i,middleMins); + } + //如果开启半天特殊处理的,请假是需要扣除0.5天 + //说明没有打卡的情况,因为有打卡肯定是有迟到、早退、漏签这些异常的,不考虑迟到算旷工,早退算旷工的情况 + //只处理1天1次,和1天2次的情况,因为1天3次的中间点可能在第二段,需要考虑有没有打卡,以及有打卡第三次是否需要处理等情况,和上下午半天的概念不太适用 + if("1".equals(is_half)){ + boolean absentFlag_1 = false;//请假, + boolean absentFlag_2 = false;//公出或出差 + if(isHandle1 || isHandle2){ + if(absenteeismMins>0 && !(beLateMins >0||graveBeLateMins > 0||leaveEarlyMins > 0||graveLeaveEarlyMins > 0||forgotCheckMins > 0||forgotBeginWorkCheckMins >0)){ + if(isHandle1){ + absentFlag_1 = true;//可以理解为是1天3次和1天1次的情况,因为1天2次的情况,如果有旷工,那么另外半天才是有请假, + } + if(isHandle2){ + absentFlag_2 = true;//可以理解为是1天3次和1天1次的情况,因为1天2次的情况,如果有旷工,那么另外半天才是有公出或者出差 + } + } + } + if(this.writeLog) { + logInfo.put("tmp_absenteeismMins"+i,absenteeismMins); + logInfo.put("absentFlag_1"+i,absentFlag_1); + logInfo.put("absentFlag_2"+i,absentFlag_2); + } + /*1次---上午3小时,下午5小时 + 上午公出,下午旷工 + 上午公出,下午打卡 + 上午旷工,下午公出 + 上午打卡,下午公出 + + 2次---上午3小时,下午5小时 + 上午公出,下午旷工--需处理实际出勤、旷工时长 + 上午公出,下午打卡--需处理实际出勤 + 上午旷工,下午公出--需处理实际出勤、旷工时长 + 上午打卡,下午公出--需处理实际出勤 + */ + if(isHandle2){ + if(shiftNums ==1){ + absenteeismMins = absentFlag_2?middleMins_final:0; + attendanceMins = workMins - absenteeismMins; + }else if(shiftNums == 2){ + if(workMins>middleMins_final && middleMins_final>0){ + absenteeismMins = (absenteeismMins > middleMins_final)?middleMins_final:((absentFlag_2||outMins>0||evectionMins>0)?Math.abs(workMins - middleMins_final):0); + absenteeismMins = (i==1 && middleMap.get("attendanceMins0")>0)?(absentFlag_2?absenteeismMins:0):absenteeismMins;//上午打卡3小时,下午公出5小时,下午的就不要显示旷工1小时了 + } + attendanceMins = workMins - absenteeismMins; + } + } + if(this.writeLog) { + logInfo.put("absenteeismMins_1"+i,absenteeismMins); + logInfo.put("attendanceMins_1"+i,attendanceMins); + } + + /*1次---上午3小时,下午5小时 + 上午请假,下午旷工 + 上午请假,下午打卡 + 上午旷工,下午请假 + 上午打卡,下午请假 + + 2次---上午3小时,下午5小时 + 上午请假,下午旷工--需处理实际出勤、旷工时长 + 上午请假,下午打卡--需处理实际出勤 + 上午旷工,下午请假--需处理实际出勤、旷工时长 + 上午打卡,下午请假--需处理实际出勤 + */ + + if(isHandle1){ + if(shiftNums == 1){ + absenteeismMins = absentFlag_1?middleMins_final:0; + attendanceMins = workMins - absenteeismMins - (leaveMins>0?middleMins_final:(absentFlag_1?(workMins - middleMins_final):0)); + attendanceMins = (leaveMins==workMins&&leaveMins>0) ? 0 : attendanceMins; + }else if(shiftNums == 2){ + if(workMins>middleMins_final && middleMins_final>0){ + absenteeismMins = (absenteeismMins > middleMins_final)?middleMins_final:((absentFlag_1||leaveMins>0)?Math.abs(workMins - middleMins_final):0); + absenteeismMins = (i==1 && middleMap.get("attendanceMins0")>0)?0:absenteeismMins;//上午打卡3小时,下午请假5小时,下午的就不要显示旷工1小时了 + } + attendanceMins = workMins - absenteeismMins - (leaveMins>0?middleMins_final:(absentFlag_1?Math.abs(workMins - middleMins_final):0)); + attendanceMins = attendanceMins>middleMins_final?middleMins_final:attendanceMins;//上午请假3小时,下午打卡5小时 + }else if(shiftNums == 3){//比如一天三次上下班,那么中间点在第二次上下班区间 +// if(workMins>middleMins && middleMins>0){ +// absenteeismMins = (absenteeismMins > middleMins_final)?middleMins_final:((absentFlag_1||leaveMins>0)?(workMins - middleMins):0); +// absenteeismMins = (i>=1 && middleMap.get("attendanceMins"+(i-1))>0)?0:absenteeismMins; +// } +// attendanceMins = workMins - absenteeismMins - (leaveMins>0?middleMins_final:(absentFlag_1?Math.abs(workMins - middleMins_final):0)); +// attendanceMins = attendanceMins>middleMins_final?middleMins_final:attendanceMins;//上午请假3小时,下午打卡5小时 +// if(workMins < middleMins){//客户可能是一天2次,或者3次,那么workmins有可能是小于半天的请假时间 +// middleMins = middleMins-workMins; +// }else { +// middleMins = 0; +// } + } + if(absenteeismMins > middleMins_final){//客户可能是一天2次,或者3次 + absenteeismMins = middleMins_final; + } + } + middleMap.put("attendanceMins"+i,attendanceMins); + middleMap.put("absenteeismMins"+i,absenteeismMins); + middleMap.put("workMins"+i,workMins); + middleMap.put("leaveMins"+i,leaveMins); + middleMap.put("outMins"+i,outMins); + middleMap.put("evectionMins"+i,evectionMins); + middleMap.put("isHandle1"+i,isHandle1?1:0); + middleMap.put("isHandle2"+i,isHandle2?1:0); + middleMap.put("absentFlag_1"+i,absentFlag_1?1:0);//1表示有旷工 + middleMap.put("absentFlag_2"+i,absentFlag_2?1:0);//1表示有旷工 + } + + // 如果没有开启"漏签是否算实际出勤"开关,则漏签不算实际出勤时长 + if("0".equals(nosign_is_absent)) { + attendanceMins = attendanceMins-forgotCheckMins-forgotBeginWorkCheckMins; + } + if(beforeBegin || attendanceMins < 0) {//还未到上班时间,不用计算任何状体 + attendanceMins = 0; + } + + /** + * 汇总报表的日历显示是有旷工就不显示漏签了,如果这里还统计漏签,张总表示日历也需要修改,改不动了 + * 在处理完实际出勤之后,将漏签还原 + */ + String nosign_ishandle = Util.null2String(kqShiftRuleEntity.getNosign_ishandle()); + if("1".equals(nosign_ishandle)){ + forgotCheckMins = 0; + }else if("2".equals(nosign_ishandle)){ + forgotCheckMins = 0; + forgotBeginWorkCheckMins = 0; + } + + kqLog.info("实际出勤计算公式" + "实际出勤=应出勤- 旷工-请假-迟到-早退 userId" + userId + "kqDate==" + kqDate+":hostIps:"+hostIps+":uuid::"+uuid); + kqLog.info("实际出勤计算结果" + attendanceMins + "=" + workMins + "- " + absenteeismMins + "-" + leaveMins + "-" + (beLateMins + graveBeLateMins) + "-" + (leaveEarlyMins - graveLeaveEarlyMins)+" userId" + userId + "kqDate==" + kqDate+":hostIps:"+hostIps+":uuid::"+uuid); + if(this.writeLog) { + logInfo.put(""+weaver.systeminfo.SystemEnv.getHtmlLabelName(10005303,weaver.general.ThreadVarLanguage.getLang())+"",""+weaver.systeminfo.SystemEnv.getHtmlLabelName(130566,weaver.general.ThreadVarLanguage.getLang())+"="+weaver.systeminfo.SystemEnv.getHtmlLabelName(132056,weaver.general.ThreadVarLanguage.getLang())+"- "+weaver.systeminfo.SystemEnv.getHtmlLabelName(20085,weaver.general.ThreadVarLanguage.getLang())+"-"+weaver.systeminfo.SystemEnv.getHtmlLabelName(670,weaver.general.ThreadVarLanguage.getLang())+"-"+weaver.systeminfo.SystemEnv.getHtmlLabelName(20081,weaver.general.ThreadVarLanguage.getLang())+"-"+weaver.systeminfo.SystemEnv.getHtmlLabelName(20082,weaver.general.ThreadVarLanguage.getLang())+""); + logInfo.put(""+weaver.systeminfo.SystemEnv.getHtmlLabelName(10005304,weaver.general.ThreadVarLanguage.getLang())+"",attendanceMins+"="+workMins+"- "+absenteeismMins+"-"+leaveMins+"-"+(beLateMins+graveBeLateMins)+"-"+(leaveEarlyMins-graveLeaveEarlyMins)); + } + //判断当天考勤状态 +// if (beLateMins > 0) { +// status = ButtonStatusEnum.BELATE.getStatusCode(); +// } else if (leaveEarlyMins > 0) { +// status = ButtonStatusEnum.LEAVEERALY.getStatusCode(); +// } else if (absenteeismMins > 0) { +// status = ButtonStatusEnum.ABSENT.getStatusCode(); +// } else if (forgotCheckMins > 0) { +// status = ButtonStatusEnum.NOSIGN.getStatusCode(); +// } else { +// status = ButtonStatusEnum.NORMAL.getStatusCode(); +// } + + String groupid = Util.null2String(workTime.getGroupId()); + String serialid = Util.null2String(workTime.getSerialId()); + + params.add(userId); + params.add(kqDate); + params.add(groupid.length() == 0 ? null : groupid); + params.add(serialid.length() == 0 ? null : serialid); + params.add(i); + params.add(workBeginDate); + params.add(kqTimesArrayComInfo.turn48to24Time(ori_workBeginTime)); + params.add(workEndDate); + params.add(kqTimesArrayComInfo.turn48to24Time(ori_workEndTime)); + params.add(workMins); + params.add(signInDate); + params.add(signInTime); + params.add(signInId.length() == 0 ? null : signInId); + params.add(signOutDate); + params.add(signOutTime); + params.add(signOutId.length() == 0 ? null : signOutId); + kqLog.info("format in >>>>>userId" + userId + "kqDate==" + kqDate+":hostIps:"+hostIps+":uuid::"+uuid + +":signInDate:"+signInDate+":signInTime::"+signInTime+":signOutDate:"+signOutDate+":signOutTime::"+signOutTime); + params.add(signMins); + params.add(attendanceMins); + params.add(beLateMins); + params.add(graveBeLateMins); + params.add(leaveEarlyMins); + params.add(graveLeaveEarlyMins); + params.add(absenteeismMins); + params.add(forgotCheckMins); + params.add(leaveMins); + params.add(JSONObject.toJSONString(leaveInfo)); + params.add(evectionMins); + params.add(outMins); + params.add(forgotBeginWorkCheckMins); + params.add(JSONObject.toJSONString(otherinfo)); + + Map definedFieldInfo = new KQFormatBiz().getDefinedField(); + String[] definedFields = Util.splitString(Util.null2String(definedFieldInfo.get("definedField")),","); + KQReportFieldComInfo kqReportFieldComInfo = new KQReportFieldComInfo(); + for (int tmpIdx = 0; tmpIdx env = new HashMap<>(); + String keyname = ""; + while (matcher.find()) { + String key = matcher.group(0); + keyname = key.substring(2, key.length() - 1).trim(); + expression = matcher.replaceAll(keyname); + env.put(keyname, keyname.equals("beLateMins")?beLateMins:leaveEarlyMins); + } + Expression compiledExp = AviatorEvaluator.compile(expression,true); + String value = Util.null2String(compiledExp.execute(env)); + params.add(value); + if(value.equals("1")) { + params.add(keyname.equals("beLateMins") ? beLateMins : leaveEarlyMins); + }else{ + params.add("0"); + } + } + kqLog.info("format in >>>>>userId" + userId + "kqDate==" + kqDate+":hostIps:"+hostIps+":uuid::"+uuid + +":params:"+JSON.toJSONString(params)); + Long id = IdGenerator.generate(); + params.add(workTime.getDayType()); + params.add(date); + params.add(date); + params.add(id); + params.add(JSONObject.toJSONString(flowinfo)); +// if(isAmAbsent){ +// params.add(1); +// }else { +// params.add(0); +// } +// if(isPmAbsent){ +// params.add(1); +// }else { +// params.add(0); +// } + params.add(on_absenteeismMins); + params.add(off_absenteeismMins); + lsParam.add(params); + } + } catch (Exception e) { + kqLog.info("考勤格式化生成数据报错:KQFormatData:"); + StringWriter errorsWriter = new StringWriter(); + e.printStackTrace(new PrintWriter(errorsWriter)); + kqLog.info(errorsWriter.toString()); + } + return lsParam; + } + + public void setWriteLog(boolean writeLog) { + this.writeLog = writeLog; + } + + public Map getLogInfo() { + return logInfo; + } + + public void formatDateByKQDate(String kqdate) { + KQFormatBiz kqFormatBiz = new KQFormatBiz(); + kqFormatBiz.formatDateByKQDate(kqdate); + } + + public void formatDateByGroupId(String groupid, String kqdate) { + KQFormatBiz kqFormatBiz = new KQFormatBiz(); + kqFormatBiz.formatDateByGroupId(groupid, kqdate); + } + + public void formatDate(String resourceid, String kqdate) { + KQFormatBiz kqFormatBiz = new KQFormatBiz(); + kqFormatBiz.formatDate(resourceid, kqdate); + } + + public void delFormatData(String resourceid, String kqdate) { + KQFormatBiz kqFormatBiz = new KQFormatBiz(); + kqFormatBiz.delFormatData(resourceid, kqdate); + } + + /** + * 非工作日格式化考勤报表 + * @param userId + * @param kqDate + * @param nonlsParam + * @param workTime + * @param workFlowInfo + */ + public void formatNonWork(String userId, String kqDate, List nonlsParam, WorkTimeEntity workTime, Map workFlowInfo) { + String signInId = ""; + String signInDate = ""; + String signInTime = ""; + String signOutId = ""; + String signOutDate = ""; + String signOutTime = ""; + int beginIdx = 0; + int endIdx = 0; + int leaveMins = 0;//请假时长 + Map flowinfo = new HashMap<>();//流程信息 + Map leaveInfo = new HashMap<>();//请假信息 + int evectionMins = 0;//出差时长 + int outMins = 0;//公出时长 + int otherMins = 0;//异常流程时长 + int[] dayMins = new int[2880];//一天所有分钟数 + List workFlow = null; + String dateKey = userId + "|" + kqDate; + KQTimesArrayComInfo kqTimesArrayComInfo = new KQTimesArrayComInfo(); + + String preDate = DateUtil.addDate(kqDate, -1);//上一天日期 + String nextDate = DateUtil.addDate(kqDate, 1);//下一天日期 + WorkTimeEntity pre_workTime = new KQWorkTime().getWorkTime(userId, preDate); + List pre_lsSignTime = new ArrayList<>(); + + if (pre_workTime != null) { + pre_lsSignTime = pre_workTime.getSignTime();//允许打卡时间 + pre_lsSignTime = pre_lsSignTime != null ? pre_lsSignTime : new ArrayList<>(); + } + WorkTimeEntity next_workTime = new KQWorkTime().getWorkTime(userId, nextDate); + List next_lsSignTime = new ArrayList<>(); + + if (next_workTime != null) { + next_lsSignTime = next_workTime.getSignTime();//允许打卡时间 + next_lsSignTime = next_lsSignTime != null ? next_lsSignTime : new ArrayList<>(); + } + + List lsCheckInfo = new KQFormatSignData().getNonWorkSignInfo(userId,preDate,kqDate,pre_lsSignTime,next_lsSignTime); + + for (int j = 0; lsCheckInfo != null && j < lsCheckInfo.size(); j++) { + Map checkInfo = (Map) lsCheckInfo.get(j); + String signStatus = Util.null2String(checkInfo.get("signStatus")); + String signId = Util.null2String(checkInfo.get("signId")); + String signDate = Util.null2String(checkInfo.get("signDate")); + String signTime = Util.null2String(checkInfo.get("signTime")); + if (checkInfo.get("signType").equals("1")) {//签到 + signInId = signId; + signInDate = signDate; + signInTime = signTime; + } else if (checkInfo.get("signType").equals("2")) {//签退 + signOutId = signId; + signOutDate = signDate; + signOutTime = signTime; + } + } + + if (workFlowInfo.get(dateKey) != null) { + workFlow = (List) workFlowInfo.get(dateKey); + } + + for (int j = 0; workFlow != null && j < workFlow.size(); j++) { + Map data = (Map) workFlow.get(j); + String flowType = Util.null2String(data.get("flowtype")); + String newLeaveType = Util.null2String(data.get("newleavetype")); + String begintime = Util.null2String(data.get("begintime")); + String endtime = Util.null2String(data.get("endtime")); + beginIdx = kqTimesArrayComInfo.getArrayindexByTimes(begintime); + endIdx = kqTimesArrayComInfo.getArrayindexByTimes(endtime); + + if (beginIdx > endIdx) { + continue; + } + Map flowMap = Maps.newHashMap(); + flowMap.put("newLeaveType", newLeaveType); + flowMap.put("begintime", begintime); + flowMap.put("endtime", endtime); + List> flowMapList = Lists.newArrayList(); + if(flowinfo.containsKey(flowType)){ + List> tmpFlowMapList = (List>) flowinfo.get(flowType); + tmpFlowMapList.add(flowMap); + }else{ + flowMapList.add(flowMap); + flowinfo.put(flowType, flowMapList); + } + if(flowType.equals(FlowReportTypeEnum.EVECTION.getFlowType())){ + Arrays.fill(dayMins, beginIdx, endIdx, 7);//出差抵扣时段标识 7 + }else if(flowType.equals(FlowReportTypeEnum.OUT.getFlowType())){ + Arrays.fill(dayMins, beginIdx, endIdx, 8);//公出抵扣时段标识 8 + }else if(flowType.equalsIgnoreCase(FlowReportTypeEnum.LEAVE.getFlowType())){ + if (endIdx > beginIdx) { + Arrays.fill(dayMins, beginIdx, endIdx, 5);//流程抵扣时段标识 5 + int tmpBeginIdx = beginIdx; + int tmpEndIdx = endIdx; + Integer val = 0; + if(leaveInfo.get(newLeaveType)==null){ + leaveInfo.put(newLeaveType,val); + }else{ + val = (Integer) leaveInfo.get(newLeaveType); + } + if(tmpEndIdx>tmpBeginIdx){ + leaveInfo.put(newLeaveType,val+(tmpEndIdx-tmpBeginIdx)); + } + } + }else{ + if (endIdx > beginIdx) { + Arrays.fill(dayMins, beginIdx, endIdx, 99);//异常流程抵扣时段标识99 + } + } + } + + for (int j = 0; j < 2880; j++) { + switch (dayMins[j]) { + case 5: + leaveMins++; + break; + case 7: + evectionMins++; + break; + case 8: + outMins++; + break; + case 99: + otherMins++; + break; + default: + break; + } + } + + nonlsParam.add(userId); + nonlsParam.add(kqDate); + nonlsParam.add(workTime.getGroupId()); + nonlsParam.add(0); + nonlsParam.add(signInDate); + nonlsParam.add(signInTime); + nonlsParam.add(signInId.length() == 0 ? null : signInId); + nonlsParam.add(signOutDate); + nonlsParam.add(signOutTime); + nonlsParam.add(signOutId.length() == 0 ? null : signOutId); + nonlsParam.add(leaveMins); + nonlsParam.add(JSONObject.toJSONString(leaveInfo)); + nonlsParam.add(evectionMins); + nonlsParam.add(outMins); + nonlsParam.add(workTime.getDayType()); + Timestamp date = new Timestamp(System.currentTimeMillis()); + Long id = IdGenerator.generate(); + nonlsParam.add(date); + nonlsParam.add(date); + nonlsParam.add(id); + nonlsParam.add(JSONObject.toJSONString(flowinfo)); + } + + /** + * 判断当天是否有考勤数据 + * @param userId + * @param date + * @return + */ + private static Boolean checkKqModeInfo(String userId,String date){ + RecordSet rs = new RecordSet(); + String sql = "select * from uf_kqgshsj where xm = "+userId+" and rq = '"+date+"'"; + rs.execute(sql); + Boolean check = false; + if (rs.getCounts()>0){ + check = true; + } + return check; + } + + /** + * 更新台账数据 + */ + public synchronized static void updateKqModeInfo(String userId,String date,Integer gcyjzbts,String fdjbtians){ + RecordSetTrans rst = new RecordSetTrans(); + rst.setAutoCommit(false); + try { + String sql = "update uf_kqgshsj set gcyjzbts=?,fdjbtians=? where xm=? and rq=?"; + boolean isdelete2 = rst.executeUpdate(sql,gcyjzbts,fdjbtians,userId,date); + new BaseBean().writeLog("usrId"+userId+"kqd"+date+"gcyjzbts"+gcyjzbts+"isdelete2"+isdelete2); + rst.commit(); + } catch (Exception e) { + rst.rollback(); + e.printStackTrace(); + } + } + + /** + * 根据建模表名获取formModeId + * + * @param cubeName 建模表明 + * @return int formModeId + */ + private static int getFormModeIdByCubeName(String cubeName) { + RecordSet rs = new RecordSet(); + rs.executeQuery("select t1.id from modeinfo t1\n" + + " left join workflow_bill t2\n" + + " on t1.formid=t2.id\n" + + " where t2.tablename='" + cubeName + "'"); + rs.next(); + return rs.getInt("id"); + } + + /** + * 判断是否是工程值班 + * @param serialid + * @return + */ + private static Boolean checkGczb(String serialid){ + RecordSet rs = new RecordSet(); + String sql = "select * from kq_ShiftManagement where id = "+serialid+" and serial like '%工值%'"; + rs.execute(sql); + Boolean check = false; + if (rs.getCounts()>0){ + check = true; + } + return check; + } + + /** + * 格式化生成台账数据 + * @param userId + * @param date + */ + public synchronized static void createKqModeInfo(String userId,String date,Integer gcyjzbts,String fdjbtians){ + RecordSetTrans rst = new RecordSetTrans(); + BaseBean bb = new BaseBean(); + bb.writeLog("createKqModeInfo == >userId:"+userId+" date:"+date); + //插入 + try { + String idNew = ""; + int modeid = getFormModeIdByCubeName("uf_kqgshsj"); + SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd"); + SimpleDateFormat sdfTime = new SimpleDateFormat("HH:mm:ss"); + String modedatacreatedate = sdfDate.format(new Date()); + String modedatacreatetime = sdfTime.format(new Date()); + rst.setAutoCommit(false); + String sqlMode = "insert into uf_kqgshsj (xm,rq,gcyjzbts,fdjbtians,FORMMODEID,MODEDATACREATER,MODEDATACREATERTYPE,MODEDATACREATEDATE,MODEDATACREATETIME) \n" + + "values (?,?,?,?,?,?,?,?,?)"; + rst.executeUpdate(sqlMode, userId,date,gcyjzbts,fdjbtians,modeid, userId, "0", modedatacreatedate, modedatacreatetime); + rst.commit(); + + RecordSet findNew = new RecordSet(); + String sqlFindnew ="select Id from uf_kqgshsj where xm = "+userId+" and rq = '"+date+"' order by" + + " modedatacreatedate desc,modedatacreatetime desc"; + findNew.execute(sqlFindnew); + bb.writeLog("findSqlNew:"+sqlFindnew); + if (findNew.next()){ + idNew = Util.null2String(findNew.getString("id")); + } + bb.writeLog("idNew:"+idNew); + // 权限重构 + int dataId = 0; + if(StringUtils.isNotBlank(idNew)){ + dataId = Integer.valueOf(idNew); + } + + ModeRightInfo modeRightInfo = new ModeRightInfo(); + modeRightInfo.editModeDataShare(Integer.valueOf(userId), modeid, dataId); + } catch (Exception e) { + rst.rollback(); + e.printStackTrace(); + } + } + + + /** + * 获取实际出勤天数 + * @param userId + * @param date + * @return + */ + public static String geSjcqts(String userId,String date){ + String sjtsDay = ""; + RecordSet rs = new RecordSet(); + String sql = " select attendancedays from kq_format_total where resourceid ="+userId+" and kqdate = '"+date+"'"; + rs.executeQuery(sql); + if(rs.next()){ + sjtsDay = Util.null2String(rs.getString("attendancedays")); + } + return sjtsDay; + } + + + /** + * 判断是否是工程值班 + * @param userId + * @param kqdate + * @return + */ + private static Boolean checkYc(String userId,String kqdate){ + RecordSet rs = new RecordSet(); + String sql = "select * from kq_format_detail where resourceid = "+userId+" and kqdate = '"+kqdate+"' and serialnumber = 1 and (leaveearlymins > 0 or graveLeaveEarlyMins > 0 or forgotCheckMins > 0 or absenteeismMins > 0 or leaveMins > 0)"; + new BaseBean().writeLog("checkYcSQL"+sql); + rs.execute(sql); + Boolean check = false; + if (rs.getCounts()>0){ + check = true; + } + return check; + } +} diff --git a/领悦二开new/src/com/engine/kq/biz/KQFormatShiftRule.java b/领悦二开new/src/com/engine/kq/biz/KQFormatShiftRule.java new file mode 100644 index 0000000..0561547 --- /dev/null +++ b/领悦二开new/src/com/engine/kq/biz/KQFormatShiftRule.java @@ -0,0 +1,562 @@ +package com.engine.kq.biz; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.engine.kq.biz.chain.shiftinfo.ShiftInfoBean; +import com.engine.kq.cmd.attendanceButton.ButtonStatusEnum; +import com.engine.kq.entity.KQShiftRuleEntity; +import com.engine.kq.entity.TimeScopeEntity; +import com.engine.kq.entity.TimeSignScopeEntity; +import com.engine.kq.entity.WorkTimeEntity; +import com.engine.kq.log.KQLog; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import org.apache.commons.lang3.StringUtils; +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.Util; + +import java.util.*; + +/** + * 格式化数据 人性化规则 + */ +public class KQFormatShiftRule extends BaseBean { + private KQLog kqLog = new KQLog(); + + public KQShiftRuleEntity doShiftRule(WorkTimeEntity workTime, KQShiftRuleEntity kqShiftRuleEntity) { + Map shiftRuleInfo = workTime.getShiftRuleInfo(); + //人性化处理 + if (shiftRuleInfo != null && shiftRuleInfo.size() > 0) { + Map ruleDetail = (Map) shiftRuleInfo.get("ruleDetail"); + //允许迟到分钟数 + boolean usepermitlateminutes = Util.null2String(shiftRuleInfo.get("permitlatestatus")).equals("1"); + int permitlateminutes = Util.getIntValue(Util.null2String(shiftRuleInfo.get("permitlateminutes")), 0); + boolean enableexcludelate = Util.null2String(shiftRuleInfo.get("enableexcludelate")).equals("1"); + //允许早退分钟数 + boolean usepermitleaveearlyminutes = Util.null2String(shiftRuleInfo.get("permitleaveearlystatus")).equals("1"); + int permitleaveearlyminutes = Util.getIntValue(Util.null2String(shiftRuleInfo.get("permitleaveearlyminutes")), 0); + boolean enableexcludeleaveearly = Util.null2String(shiftRuleInfo.get("enableexcludeleaveearly")).equals("1"); + + //严重迟到分钟数 + boolean useseriouslateminutes = Util.null2String(shiftRuleInfo.get("seriouslatestatus")).equals("1"); + int seriouslateminutes = Util.getIntValue(Util.null2String(shiftRuleInfo.get("seriouslateminutes")), 0); + //严重早退分钟数 + boolean useseriousleaveearlyminutes = Util.null2String(shiftRuleInfo.get("seriousleaveearlystatus")).equals("1"); + int seriousleaveearlyminutes = Util.getIntValue(Util.null2String(shiftRuleInfo.get("seriousleaveearlyminutes")), 0); + //迟到多少钟数算旷工 + boolean uselateabsentminutes = Util.null2String(shiftRuleInfo.get("lateabsentstatus")).equals("1"); + int lateabsentminutes = Util.getIntValue(Util.null2String(shiftRuleInfo.get("lateabsentminutes")), 0); + //早退多少钟数算旷工 + boolean useleaveearlyabsentminutes = Util.null2String(shiftRuleInfo.get("leaveearlyabsentstatus")).equals("1"); + int leaveearlyabsentminutes = Util.getIntValue(Util.null2String(shiftRuleInfo.get("leaveearlyabsentminutes")), 0); + //允许下班不打卡 + boolean isoffdutyfreecheck = Util.null2String(shiftRuleInfo.get("isoffdutyfreecheck")).equals("1"); + + String userId = kqShiftRuleEntity.getUserId(); + String kqDate = kqShiftRuleEntity.getKqDate(); + int beLateMins = kqShiftRuleEntity.getBelatemins(); + int graveBeLateMins = 0; + int leaveEarlyMins = kqShiftRuleEntity.getLeaveearlymins(); + int graveLeaveEarlyMins = 0; + int absenteeismMins = kqShiftRuleEntity.getAbsenteeismmins(); + int forgotcheckMins = kqShiftRuleEntity.getForgotcheckmins(); + int forgotBeginWorkCheckMins = kqShiftRuleEntity.getForgotBeginWorkCheckMins(); + int earlyInMins = kqShiftRuleEntity.getEarlyInMins(); + int lateOutMins = kqShiftRuleEntity.getLateOutMins(); + String nosign_is_absent = kqShiftRuleEntity.getNosign_is_absent(); + String early_one_mins = kqShiftRuleEntity.getEarly_one_mins(); + String signInTime = kqShiftRuleEntity.getSignInTime(); + String signOutTime = kqShiftRuleEntity.getSignOutTime(); + + + + List earlyinearlyout = null;//早到早走规则 + List lateinlateout = null;//晚到晚走规则 + List lateoutlatein = null;//晚走晚到规则 + + //这里个性化没法处理流程数据,逻辑改为在前面直接虚拟改掉了上下班时间 + if (ruleDetail != null && ruleDetail.size() > 0 && false) {//处理人性化设置其他规则 + earlyinearlyout = (List) ruleDetail.get("earlyinearlyout"); + lateinlateout = (List) ruleDetail.get("lateinlateout"); + lateoutlatein = (List) ruleDetail.get("lateoutlatein"); + + if (earlyinearlyout != null && earlyinearlyout.size() > 0 && leaveEarlyMins > 0) { + for (int i = 0; earlyInMins > 0 && i < earlyinearlyout.size(); i++) { + Map rule = (Map) earlyinearlyout.get(i); + if (Util.null2String(rule.get("enable")).equals("1")) { + int advancetime = new Double((Util.getDoubleValue(Util.null2String(rule.get("advancetime"))))).intValue();//早到时间 + int postponetime = new Double((Util.getDoubleValue(Util.null2String(rule.get("postponetime"))))).intValue();//允许早走时间 + if (Util.null2String(rule.get("enablesame")).equals("1")) { + if (earlyInMins > postponetime) { + leaveEarlyMins -= postponetime; + if (leaveEarlyMins < 0) leaveEarlyMins = 0; + } else { + leaveEarlyMins -= earlyInMins; + if (leaveEarlyMins < 0) leaveEarlyMins = 0; + } + break; + } else { + if (earlyInMins >= advancetime) { + leaveEarlyMins -= postponetime; + if (leaveEarlyMins < 0) leaveEarlyMins = 0; + break; + } + } + } + } + } + + if (lateinlateout != null && lateinlateout.size() > 0 && beLateMins > 0) { + for (int i = 0; lateOutMins > 0 && i < lateinlateout.size(); i++) { + Map rule = (Map) lateinlateout.get(i); + if (Util.null2String(rule.get("enable")).equals("1")) { + int advancetime = new Double((Util.getDoubleValue(Util.null2String(rule.get("advancetime"))))).intValue();//晚到时间 + int postponetime = new Double((Util.getDoubleValue(Util.null2String(rule.get("postponetime"))))).intValue();//需要晚走时间 + if (Util.null2String(rule.get("enablesame")).equals("1")) { + if (lateOutMins > postponetime) { + beLateMins -= postponetime; + if (beLateMins < 0) beLateMins = 0; + } else { + beLateMins -= lateOutMins; + if (beLateMins < 0) beLateMins = 0; + } + break; + } else { + if (lateOutMins >= postponetime) { + beLateMins -= advancetime; + if (beLateMins < 0) beLateMins = 0; + break; + } + } + } + } + } + + if (lateoutlatein != null && lateoutlatein.size() > 0 && beLateMins > 0) { + int preDayLateOutMins = getPreDayLateOutMins(userId, kqDate); + for (int i = 0; preDayLateOutMins > 0 && i < lateoutlatein.size(); i++) { + Map rule = (Map) lateoutlatein.get(i); + if (Util.null2String(rule.get("enable")).equals("1")) { + int advancetime = new Double((Util.getDoubleValue(Util.null2String(rule.get("advancetime"))))).intValue();//晚走时间 + int postponetime = new Double((Util.getDoubleValue(Util.null2String(rule.get("postponetime"))))).intValue();//允许晚到时间 + + if (Util.null2String(rule.get("enablesame")).equals("1")) { + if (preDayLateOutMins > postponetime) { + beLateMins -= postponetime; + if (beLateMins < 0) beLateMins = 0; + } else { + beLateMins -= preDayLateOutMins; + if (beLateMins < 0) beLateMins = 0; + } + break; + } else { + if (preDayLateOutMins >= advancetime) { + beLateMins -= postponetime; + if (beLateMins < 0) beLateMins = 0; + break; + } + } + } + } + } + } + + if (beLateMins > 0) {//迟到人性化设置 + if (usepermitlateminutes) {//允许迟到分钟数 + if (permitlateminutes >= beLateMins) { + beLateMins = 0; + } else if (enableexcludelate) { + beLateMins = beLateMins - permitlateminutes; + } + } + + if (uselateabsentminutes && beLateMins >= lateabsentminutes) {//旷工 + absenteeismMins += beLateMins; + beLateMins = 0; + kqShiftRuleEntity.setOn_absenteeismMins(absenteeismMins); + kqShiftRuleEntity.setAMAbsent(true); + //leaveEarlyMins = 0; + if ("1".equals(nosign_is_absent)) { + /** + * 在漏签算实际出勤的情况,才需要清空漏签时长(forgotcheckMins),原由如下:比如09:00--18:00,这是11:00打上班卡,下班卡没有打卡 + * 情况1:没有开启迟到或者早退算旷工的情况,正常应该显示:【迟到120分钟 漏签】,这时候实际出勤应该是0 + * 情况2:开启了迟到60分钟算旷工之后,应该显示【旷工120分钟 漏签】,这时候实际出勤应该是0。而如果清空漏签时长(forgotcheckMins) ,那么就有实际出勤时长了,因为实际出勤=应出勤-迟到-早退-旷工-请假-漏签时长 + * 所以:在漏签算实际出勤的时候才需要清空,也就原标准逻辑,反之不需要清空 + * , + */ + forgotcheckMins = 0; + } else { + kqShiftRuleEntity.setNosign_ishandle("1"); + } + } else if (useseriouslateminutes && beLateMins >= seriouslateminutes) {//严重迟到 + graveBeLateMins += beLateMins; + //TODO 这有个问题,严重迟到了,还要不要算迟到?这两个是同时存在的吗? + beLateMins = 0; + } + } + + if (leaveEarlyMins > 0) {//早退人性化设置 + if (usepermitleaveearlyminutes) {//允许早退分钟数 + if (permitleaveearlyminutes >= leaveEarlyMins) { + leaveEarlyMins = 0; + } else if (enableexcludeleaveearly) { + leaveEarlyMins = leaveEarlyMins - permitleaveearlyminutes; + } + } + if (useleaveearlyabsentminutes && leaveEarlyMins >= leaveearlyabsentminutes) {//旷工 + absenteeismMins += leaveEarlyMins; + //beLateMins = 0; + leaveEarlyMins = 0; + kqShiftRuleEntity.setOff_absenteeismMins(absenteeismMins); + kqShiftRuleEntity.setPMAbsent(true); + if ("1".equals(nosign_is_absent)) { + /** + * 在漏签算实际出勤的情况,才需要清空漏签时长(forgotcheckMins),原由如下:比如09:00--18:00,这是11:00打上班卡,下班卡没有打卡 + * 情况1:没有开启迟到或者早退算旷工的情况,正常应该显示:【迟到120分钟 漏签】,这时候实际出勤应该是0 + * 情况2:开启了迟到60分钟算旷工之后,应该显示【旷工120分钟 漏签】,这时候实际出勤应该是0。而如果清空漏签时长(forgotcheckMins) ,那么就有实际出勤时长了,因为实际出勤=应出勤-迟到-早退-旷工-请假-漏签时长 + * 所以:在漏签算实际出勤的时候才需要清空,也就原标准逻辑,反之不需要清空 + * , + */ + forgotcheckMins = 0; + forgotBeginWorkCheckMins = 0; + } else { + kqShiftRuleEntity.setNosign_ishandle("2"); + } + + } else if (useseriousleaveearlyminutes && leaveEarlyMins >= seriousleaveearlyminutes) {//严重早退 + graveLeaveEarlyMins += leaveEarlyMins; + //TODO 这有个问题,严重早退了,还要不要算早退?这两个是同时存在的吗? + leaveEarlyMins = 0; + } + } + //允许下班不打卡 + if (isoffdutyfreecheck) { + forgotcheckMins = 0; + } + + /** + * 含泪加上 + * 晚到晚走导致的早退1分钟特殊处理下, + * 2024-02-28 上班时间是:2024-02-28 08:30:00,签到时间是:2024-02-28 08:34:26,晚到5分钟, 开启了晚到晚走,相对时间 + * 所以2024-02-28的上班时间和下班时间变化了,上班时间变成了:2024-02-28 08:35,下班时间变成了:2024-02-28 17:35 + * 现在签到是08:34:26,签退是17:34:48,导致早退1分钟 + */ + if("1".equals(early_one_mins)){ + if (ruleDetail != null && ruleDetail.size() > 0) {//处理人性化设置其他规则 + earlyinearlyout = (List) ruleDetail.get("earlyinearlyout"); + lateinlateout = (List) ruleDetail.get("lateinlateout"); + } + + String signInTime_Sec = (signInTime != null && signInTime.length() == 8) ? signInTime.substring(6, 8) : ""; + String signOutTime_Sec = (signOutTime != null && signOutTime.length() == 8) ? signOutTime.substring(6, 8) : ""; + writeLog("signInTime="+signInTime+",signInTime_Sec="+signInTime_Sec+",signOutTime="+signOutTime+",signOutTime_Sec="+signOutTime_Sec+",leaveEarlyMins="+leaveEarlyMins); +// writeLog("leaveEarlyMins="+leaveEarlyMins+",lateinlateout="+JSONObject.toJSONString(lateinlateout)); + if (((lateinlateout != null && lateinlateout.size() > 0)||(earlyinearlyout != null && earlyinearlyout.size() > 0)) + && leaveEarlyMins == 1) { + if (signInTime_Sec.compareTo(signOutTime_Sec) <= 0) { + leaveEarlyMins = 0; + } + } + } +// writeLog("leaveEarlyMins="+leaveEarlyMins+",early_one_mins="+early_one_mins); + + kqShiftRuleEntity.setBelatemins(beLateMins); + kqShiftRuleEntity.setGravebelatemins(graveBeLateMins); + kqShiftRuleEntity.setLeaveearlymins(leaveEarlyMins); + kqShiftRuleEntity.setGraveleaveearlymins(graveLeaveEarlyMins); + kqShiftRuleEntity.setAbsenteeismmins(absenteeismMins); + kqShiftRuleEntity.setForgotcheckmins(forgotcheckMins); + kqShiftRuleEntity.setForgotBeginWorkCheckMins(forgotBeginWorkCheckMins); + } + return kqShiftRuleEntity; + } + + public int getEarlyInMins(String userId, String kqDate) { + return getEarlyInMins(userId,kqDate,0); + } + + public int getEarlyInMins(String userId, String kqDate,int signoutOnlyoff) { + int earlyInMins = 0; + boolean oneSign = false; + String preDate = DateUtil.addDate(kqDate, -1);//上一天日期 + String nextDate = DateUtil.addDate(kqDate, 1);//下一天日期 + KQWorkTime kqWorkTime = new KQWorkTime(); + WorkTimeEntity workTime = kqWorkTime.getWorkTime(userId, kqDate); + List lsSignTime = new ArrayList<>(); + List lsWorkTime = new ArrayList<>(); + if (workTime != null) { + lsSignTime = workTime.getSignTime();//允许打卡时间 + lsWorkTime = workTime.getWorkTime();//工作时间 + oneSign = lsWorkTime != null && lsWorkTime.size() == 1; + } + + if (oneSign) { + KQTimesArrayComInfo kqTimesArrayComInfo = new KQTimesArrayComInfo(); + TimeScopeEntity signTimeScope = lsSignTime.get(0); + TimeScopeEntity workTimeScope = lsWorkTime.get(0); + int workBeginIdx = kqTimesArrayComInfo.getArrayindexByTimes(workTimeScope.getBeginTime()); + + List lsCheckInfo = new KQFormatSignData().getSignInfo(userId, signTimeScope, workTimeScope, kqDate, preDate, nextDate, kqTimesArrayComInfo + ,Lists.newArrayList(), "",0,0,signoutOnlyoff); + for (int j = 0; lsCheckInfo != null && j < lsCheckInfo.size(); j++) { + Map checkInfo = (Map) lsCheckInfo.get(j); + String signDate = Util.null2String(checkInfo.get("signDate")); + String signTime = Util.null2String(checkInfo.get("signTime")); + String deduct_signintime = Util.null2String(checkInfo.get("deduct_signintime")); + if (checkInfo.get("signType").equals("1")) {//签到 + //有签到但是没有signTime是因为开启了流程抵扣打卡 + if (null == signTime || signTime.length() < 5) { + continue; + } else { + writeLog("signDate:" + signDate + ",signTime=" + signTime + ",checkInfo=" + checkInfo.toString()); + } + String signMinTime = signTime.substring(0, 5) + ":00"; + boolean signInWorkBeginTime = false; + if (signTime.compareTo(signMinTime) > 0) { + //如果签到时间是带秒的且是迟到,那么签到时间多一秒和多一分钟是一样的 + signInWorkBeginTime = true; + } + String signInTime = signTime; + int signInTimeIndx = kqTimesArrayComInfo.getArrayindexByTimes(signInTime); + String flow_signInTime = ""; + if (deduct_signintime.length() > 0) { + if (signTime.length() > 0) { + if (deduct_signintime.compareTo(signTime) < 0) { + flow_signInTime = deduct_signintime; + } + } else { + flow_signInTime = deduct_signintime; + } + } + if (flow_signInTime.length() > 0) { + signInTimeIndx = kqTimesArrayComInfo.getArrayindexByTimes(flow_signInTime); + } + if (kqDate.compareTo(signDate) < 0) signInTimeIndx += 1440; + if (signInWorkBeginTime) { + signInTimeIndx = signInTimeIndx + 1; + } + if (workBeginIdx > signInTimeIndx) { + earlyInMins = workBeginIdx - signInTimeIndx; + } + } + } + } + return earlyInMins; + } + + public int getLateOutMins(String userId, String kqDate) { + return getLateOutMins(userId,kqDate,0); + } + + public int getLateOutMins(String userId, String kqDate,int signoutOnlyoff) { + int lateOutMins = 0; + boolean oneSign = false; + String preDate = DateUtil.addDate(kqDate, -1);//上一天日期 + String nextDate = DateUtil.addDate(kqDate, 1);//下一天日期 + KQWorkTime kqWorkTime = new KQWorkTime(); + WorkTimeEntity workTime = kqWorkTime.getWorkTime(userId, kqDate); + List lsSignTime = new ArrayList<>(); + List lsWorkTime = new ArrayList<>(); + if (workTime != null) { + lsSignTime = workTime.getSignTime();//允许打卡时间 + lsWorkTime = workTime.getWorkTime();//工作时间 + oneSign = lsWorkTime != null && lsWorkTime.size() == 1; + } + + if (oneSign) { + KQTimesArrayComInfo kqTimesArrayComInfo = new KQTimesArrayComInfo(); + TimeScopeEntity signTimeScope = lsSignTime.get(0); + TimeScopeEntity workTimeScope = lsWorkTime.get(0); + int workEndIdx = kqTimesArrayComInfo.getArrayindexByTimes(workTimeScope.getEndTime()); + + List lsCheckInfo = new KQFormatSignData().getSignInfo(userId, signTimeScope, workTimeScope, kqDate, preDate, nextDate, kqTimesArrayComInfo + ,Lists.newArrayList(), "",0,0,signoutOnlyoff); + for (int j = 0; lsCheckInfo != null && j < lsCheckInfo.size(); j++) { + Map checkInfo = (Map) lsCheckInfo.get(j); + String signDate = Util.null2String(checkInfo.get("signDate")); + String signTime = Util.null2String(checkInfo.get("signTime")); + String deduct_signofftime = Util.null2String(checkInfo.get("deduct_signofftime")); + if (checkInfo.get("signType").equals("2")) {//签退 + String signOutTime = signTime; + int signInTimeOutdx = kqTimesArrayComInfo.getArrayindexByTimes(signOutTime); + String flow_signOutTime = signOutTime; + if (deduct_signofftime.length() > 0) { + if (signTime.length() > 0) { + if (deduct_signofftime.compareTo(signTime) > 0) { + flow_signOutTime = deduct_signofftime; + } + } else { + flow_signOutTime = deduct_signofftime; + } + } + if (flow_signOutTime.length() > 0) { + signInTimeOutdx = kqTimesArrayComInfo.getArrayindexByTimes(flow_signOutTime); + } + if (kqDate.compareTo(signDate) < 0) signInTimeOutdx += 1440; + if (signInTimeOutdx > workEndIdx) { + lateOutMins = signInTimeOutdx - workEndIdx; + } + } + } + } + return lateOutMins; + } + + public int getPreDayLateOutMins(String userId, String kqDate) { + return getPreDayLateOutMins(userId, kqDate, Lists.newArrayList()); + } + public int getPreDayLateOutMins(String userId, String kqDate, List logList) { + return getPreDayLateOutMins(userId, kqDate,logList,0); + } + + /** + * 前一天晚走分钟数 + */ + public int getPreDayLateOutMins(String userId, String kqDate, List logList,int signoutOnlyoff) { + int preDayLateOutMins = 0; + + boolean oneSign = false; + KQWorkTime kqWorkTime = new KQWorkTime(); + //前一天是非工作日,往前取到工作日 + String tmpKQPreDate = DateUtil.addDate(kqDate, -1); + for (int i = 0; i < 31; i++) { + WorkTimeEntity workTime = kqWorkTime.getWorkTime(userId, tmpKQPreDate); + if (workTime.getWorkMins() > 0) { + kqDate = DateUtil.addDate(tmpKQPreDate, 1); + break; + } + tmpKQPreDate = DateUtil.addDate(tmpKQPreDate, -1); + } + String kqPreDate = DateUtil.addDate(kqDate, -1); + ; + String kqPrePreDate = DateUtil.addDate(kqDate, -2); + WorkTimeEntity workTime = kqWorkTime.getWorkTime(userId, kqPreDate); + List lsSignTime = new ArrayList<>(); + List lsWorkTime = new ArrayList<>(); + if (workTime != null) { + lsSignTime = workTime.getSignTime();//允许打卡时间 + lsWorkTime = workTime.getWorkTime();//工作时间 + oneSign = lsWorkTime != null && lsWorkTime.size() == 1; + } + + if (oneSign) { + KQTimesArrayComInfo kqTimesArrayComInfo = new KQTimesArrayComInfo(); + TimeScopeEntity signTimeScope = lsSignTime.get(0); + TimeScopeEntity workTimeScope = lsWorkTime.get(0); + String signBeginDateTime = signTimeScope.getBeginTimeAcross() ? kqPrePreDate : kqPreDate; + signBeginDateTime += " " + kqTimesArrayComInfo.turn48to24Time(signTimeScope.getBeginTime()) + ":00"; + String signEndDateTime = signTimeScope.getEndTimeAcross() ? kqDate : kqPreDate; + signEndDateTime += " " + kqTimesArrayComInfo.turn48to24Time(signTimeScope.getEndTime()) + ":00"; + String workBeginDateTime = workTimeScope.getBeginTimeAcross() ? kqPrePreDate : kqPreDate; + workBeginDateTime += " " + kqTimesArrayComInfo.turn48to24Time(workTimeScope.getBeginTime()) + ":00"; + String workEndDateTime = workTimeScope.getEndTimeAcross() ? kqDate : kqPreDate; + workEndDateTime += " " + kqTimesArrayComInfo.turn48to24Time(workTimeScope.getEndTime()) + ":00"; + + Map shifRuleMap = Maps.newHashMap(); + String shif_workEndTime = ""; + getPre_ShiftRuleInfo(kqPreDate, workTime, lsSignTime, lsWorkTime, userId, shifRuleMap, logList); + if (!shifRuleMap.isEmpty()) { + if (shifRuleMap.containsKey("shift_endworktime")) { + String shift_endworktime = Util.null2String(shifRuleMap.get("shift_endworktime")); + if (shift_endworktime.length() > 0) { + shif_workEndTime = Util.null2String(shift_endworktime); + } + } + } + + List lsCheckInfo = new KQFormatSignData().getSignInfo(userId, signTimeScope, workTimeScope, kqPreDate, kqPrePreDate, kqDate, kqTimesArrayComInfo + ,Lists.newArrayList(), "",0,0,signoutOnlyoff); + Map checkInfo = null; + if (lsCheckInfo.size() == 2) { + for (int i = 0; i < lsCheckInfo.size(); i++) { + checkInfo = (Map) lsCheckInfo.get(i); + String signType = Util.null2String(checkInfo.get("signType")); + if ("2".equalsIgnoreCase(signType)) { + break; + } + } + String signDate = Util.null2String(checkInfo.get("signDate")); + String signTime = Util.null2String(checkInfo.get("signTime")); + String workEndTime = Util.null2String(workTimeScope.getEndTime()); + int workEndIdx = kqTimesArrayComInfo.getArrayindexByTimes(workEndTime); + if (shif_workEndTime.length() > 0) { + workEndIdx = kqTimesArrayComInfo.getArrayindexByTimes(shif_workEndTime); + } + if (!kqPreDate.equals(signDate)) { //跨天 + signTime = kqTimesArrayComInfo.turn24to48Time(signTime); + } + int signOutTimeIdx = kqTimesArrayComInfo.getArrayindexByTimes(signTime); + if (signOutTimeIdx > workEndIdx) { + preDayLateOutMins = signOutTimeIdx - workEndIdx; + logList.add("签退时间是:" + (signDate + " " + kqTimesArrayComInfo.turn48to24Time(signTime)) + ",晚走了" + preDayLateOutMins + "分钟"); + } + } else if (!lsCheckInfo.isEmpty()) { + for (int i = 0; i < lsCheckInfo.size(); i++) { + Map checkInfoMap = (Map) lsCheckInfo.get(i); + String signType = Util.null2String(checkInfoMap.get("signType")); + if ("2".equalsIgnoreCase(signType)) { + String signDate = Util.null2String(checkInfoMap.get("signDate")); + String signTime = Util.null2String(checkInfoMap.get("signTime")); + String workEndTime = Util.null2String(workTimeScope.getEndTime()); + int workEndIdx = kqTimesArrayComInfo.getArrayindexByTimes(workEndTime); + if (shif_workEndTime.length() > 0) { + workEndIdx = kqTimesArrayComInfo.getArrayindexByTimes(shif_workEndTime); + } + if (!kqPreDate.equals(signDate)) { //跨天 + signTime = kqTimesArrayComInfo.turn24to48Time(signTime); + } + int signOutTimeIdx = kqTimesArrayComInfo.getArrayindexByTimes(signTime); + if (signOutTimeIdx > workEndIdx) { + preDayLateOutMins = signOutTimeIdx - workEndIdx; + logList.add(",签退时间是:" + (signDate + " " + signTime) + ",晚走了" + preDayLateOutMins + "分钟"); + } + } + } + } + } + return preDayLateOutMins; + } + + /** + * 获取前一天的弹性时间 + * + * @param kqPreDate + * @param workTime + * @param lsSignTime + * @param lsWorkTime + * @param userId + * @param logList + */ + public void getPre_ShiftRuleInfo(String kqPreDate, WorkTimeEntity workTime, + List lsSignTime, List lsWorkTime, String userId, + Map shifRuleMap, List logList) { + ShiftInfoBean shiftInfoBean = new ShiftInfoBean(); + shiftInfoBean.setSplitDate(kqPreDate); + shiftInfoBean.setShiftRuleMap(workTime.getShiftRuleInfo()); + shiftInfoBean.setSignTime(lsSignTime); + shiftInfoBean.setWorkTime(lsWorkTime); + KQShiftRuleInfoBiz.getShiftRuleInfo(shiftInfoBean, userId, shifRuleMap, false, logList); + } + + /** + * 获取班次设置里面的上下班不打卡数据 + * + * @param i + * @param serialId + */ + public Map getModel_ShiftRule(int i, String serialId) { + RecordSet rs = new RecordSet(); + HashMap sectionMap = new HashMap<>(); + String getStartWorkSections = "select * from kq_ShiftOnOffWorkSections where SERIALID=? and record=? "; + rs.executeQuery(getStartWorkSections, serialId, i); + while (rs.next()) { + String onoffworktype = Util.null2String(rs.getString("onoffworktype")); + String clockinnot = Util.null2s(Util.null2String(rs.getString("clockinnot")), "0"); + sectionMap.put(onoffworktype, clockinnot); + } + return sectionMap; + } + +} diff --git a/领悦二开new/src/com/engine/kq/biz/KQFormatSignData.java b/领悦二开new/src/com/engine/kq/biz/KQFormatSignData.java new file mode 100644 index 0000000..c416925 --- /dev/null +++ b/领悦二开new/src/com/engine/kq/biz/KQFormatSignData.java @@ -0,0 +1,758 @@ +package com.engine.kq.biz; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.engine.kq.cmd.attendanceButton.ButtonStatusEnum; +import com.engine.kq.entity.TimeScopeEntity; +import com.engine.kq.entity.TimeSignScopeEntity; +import com.engine.kq.log.KQLog; +import com.engine.kq.util.UtilKQ; +import com.engine.kq.wfset.util.KQSignUtil; +import com.google.common.collect.Lists; + +import java.io.PrintWriter; +import java.io.StringWriter; + +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.Util; + +import java.util.*; + +/** + * 获取班次打卡数据 + */ +public class KQFormatSignData extends BaseBean { + private KQLog kqLog = new KQLog(); + + public List getSignInfo(String userId, TimeScopeEntity signTimeScope, + TimeScopeEntity workTimeScope, String kqDate, String preDate, + String nextDate, KQTimesArrayComInfo kqTimesArrayComInfo) { + return getSignInfo(userId, signTimeScope, workTimeScope, kqDate, preDate, nextDate, kqTimesArrayComInfo, + Lists.newArrayList(), ""); + } + + public List getSignInfo(String userId, TimeScopeEntity signTimeScope, + TimeScopeEntity workTimeScope, String kqDate, String preDate, + String nextDate, KQTimesArrayComInfo kqTimesArrayComInfo, ArrayList hostIps, String uuid) { + return getSignInfo(userId, signTimeScope, workTimeScope, kqDate, preDate, nextDate, kqTimesArrayComInfo, hostIps, uuid, 0, 0); + } + + public List getSignInfo(String userId, TimeScopeEntity signTimeScope, + TimeScopeEntity workTimeScope, String kqDate, String preDate, + String nextDate, KQTimesArrayComInfo kqTimesArrayComInfo, ArrayList hostIps, String uuid, int shiftCount, int shiftI) { + return getSignInfo(userId, signTimeScope, workTimeScope, kqDate, preDate, nextDate, kqTimesArrayComInfo, hostIps, uuid, shiftCount, shiftI, 0); + } + + /*** + * 获取班次打卡数据 + * @param userId + * @param signTimeScope + * @param workTimeScope + * @param kqDate + * @param preDate + * @param nextDate + * @param kqTimesArrayComInfo + * @return + */ + public List getSignInfo(String userId, TimeScopeEntity signTimeScope, + TimeScopeEntity workTimeScope, String kqDate, String preDate, + String nextDate, KQTimesArrayComInfo kqTimesArrayComInfo, ArrayList hostIps, String uuid, int shiftCount, int shiftI, int signoutOnlyoff) { + kqLog.info("in getSignInfo ::userId" + userId + "kqDate==" + kqDate + ":hostIps:" + hostIps + ":uuid::" + uuid + " in "); + List lsCheckInfo = new ArrayList<>(); + String count4NoonStartDateTime = ""; + String count4NoonEndDateTime = ""; + try { + Map checkInfo = null; + String base_sql = ""; + RecordSet rs = new RecordSet(); + String dbtype = rs.getDBType(); + + //获取工作上下班时间 + String workBeginDateTime = workTimeScope.getBeginTimeAcross() ? nextDate : kqDate; + workBeginDateTime += " " + kqTimesArrayComInfo.turn48to24Time(workTimeScope.getBeginTime()) + ":00"; + kqLog.info("in getSignInfo ::userId" + userId + "kqDate==" + kqDate + ":hostIps:" + hostIps + ":uuid::" + uuid + "::workBeginDateTime::" + workBeginDateTime); + + //获取工作上下班时间 + String workEndDateTime = workTimeScope.getEndTimeAcross() ? nextDate : kqDate; + workEndDateTime += " " + kqTimesArrayComInfo.turn48to24Time(workTimeScope.getEndTime()) + ":00"; + kqLog.info("in getSignInfo ::userId" + userId + "kqDate==" + kqDate + ":hostIps:" + hostIps + ":uuid::" + uuid + "::workEndDateTime::" + workEndDateTime); + + Map flow_deduct_card_map = getflowDeductCardSql(userId, kqDate, workTimeScope.getBeginTime(), workTimeScope.getEndTime()); + + kqLog.info("in getSignInfo ::userId" + userId + "kqDate==" + kqDate + ":hostIps:" + hostIps + ":uuid::" + uuid + "::flow_deduct_card_map::" + flow_deduct_card_map); + kqLog.info("in getSignInfo ::userId" + userId + "kqDate==" + kqDate + ":hostIps:" + hostIps + ":uuid::" + uuid + "::signTimeScope::" + JSON.toJSONString(signTimeScope)); + + List> sqlConditions = getCanSignInfo(signTimeScope, kqDate, preDate, nextDate, kqTimesArrayComInfo, workTimeScope, shiftCount, shiftI, signoutOnlyoff); + base_sql = signSignSql(rs); + new KQLog().info("sqlConditions:(userId:" + userId + ":base_sql" + base_sql + ":::userId" + userId + "kqDate==" + kqDate + ":hostIps:" + hostIps + ":uuid::" + uuid + "::flow_deduct_card_map::" + flow_deduct_card_map + "::sqlConditions::" + JSONObject.toJSONString(sqlConditions)); + if (sqlConditions != null && !sqlConditions.isEmpty()) { + if (shiftCount == 2) { + String fieldName = ""; + if (shiftI == 0) { + fieldName = "signEndDateTime"; + } else if (shiftI == 1) { + fieldName = "signBeginDateTime"; + } + Map sqlMap = sqlConditions.get(0); + count4NoonStartDateTime = Util.null2String(sqlMap.get(fieldName)); + if (count4NoonStartDateTime.length() == 19) { + count4NoonStartDateTime = count4NoonStartDateTime.substring(0, 17) + "00"; + } + sqlMap = sqlConditions.get(0); + count4NoonEndDateTime = Util.null2String(sqlMap.get(fieldName)); + if (sqlConditions.size() >= 2) { + sqlMap = sqlConditions.get(1); + count4NoonEndDateTime = Util.null2String(sqlMap.get(fieldName)); + } + } + + boolean hasSignIn = false; + for (Map sqlMap : sqlConditions) { + String sql = ""; + String orderSql = ""; + int idx = 0; + String signBeginDateTime = Util.null2String(sqlMap.get("signBeginDateTime")); + String signEndDateTime = Util.null2String(sqlMap.get("signEndDateTime")); + String type = Util.null2String(sqlMap.get("type")); + String signoutOnlyoff_flag = Util.null2String(sqlMap.get("signoutOnlyoff")); + if (type.length() > 0) { + if ("signoff".equalsIgnoreCase(type)) { + orderSql = " order by signdate desc, signtime desc "; + } else if ("signin".equalsIgnoreCase(type)) { + orderSql = " order by signdate asc, signtime asc "; + } + if ("oracle".equalsIgnoreCase(dbtype)) { + sql = "select * from (" + base_sql + " " + orderSql + ") a where rownum=1"; + } else if ("mysql".equalsIgnoreCase(dbtype)) { + sql = "select * from (" + base_sql + " " + orderSql + ") a limit 0,1"; + } else if ("postgresql".equalsIgnoreCase(dbtype)) { + sql = "select * from (" + base_sql + " " + orderSql + ") a limit 1 offset 0"; + } else if ("sqlserver".equalsIgnoreCase(dbtype)) { + sql = "select top 1 * from (" + base_sql + ") a " + " " + orderSql; + } else { + sql = "select * from (" + base_sql + " " + orderSql + ") a where rownum=1"; + } + } else { + orderSql = " order by signdate asc, signtime asc "; + sql = base_sql + " " + orderSql; + } + rs.executeQuery(sql, userId, signBeginDateTime, signEndDateTime); + new KQLog().info("getSignInfo:(userId:" + userId + ":signBeginDateTime:" + + signBeginDateTime + ":signEndDateTime:" + signEndDateTime + "):sql" + sql + ":counts:" + rs.getCounts() + ":::userId" + userId + "kqDate==" + kqDate + ":hostIps:" + hostIps + ":uuid::" + uuid + "::flow_deduct_card_map::" + flow_deduct_card_map); + while (rs.next()) { + String signId = Util.null2String(rs.getString("id")); + String signdate = Util.null2String(rs.getString("signdate")); + String signtime = Util.null2String(rs.getString("signtime")); + + checkInfo = new HashMap<>(); + checkInfo.put("signId", signId);//签到签退标识 + checkInfo.put("signDate", signdate);//签到签退日期 + checkInfo.put("signTime", signtime);//签到签退时间 + String signDateTime = signdate + " " + signtime; + idx++; + if (type.length() > 0) { + if ("signin".equalsIgnoreCase(type)) { + checkInfo.put("signType", "1"); + if (workBeginDateTime.length() > 0) { + checkInfo.put("signStatus", UtilKQ.getSignStatus("1", signDateTime, workBeginDateTime)); + } + if (!Util.null2String(checkInfo.get("signStatus")).equalsIgnoreCase(ButtonStatusEnum.NORMAL.getStatusCode())) { + if (flow_deduct_card_map.containsKey("signin")) { + String deduct_signintime = Util.null2String(flow_deduct_card_map.get("signin")); + if (deduct_signintime.length() > 0) { + signDateTime = signdate + " " + deduct_signintime; + checkInfo.put("deduct_signintime", deduct_signintime);//流程抵扣作为打卡时间 + checkInfo.put("signStatus", UtilKQ.getSignStatus("1", signDateTime, workBeginDateTime)); + } + } + } + lsCheckInfo.add(checkInfo); + } else { + checkInfo.put("signType", "2"); + if (workEndDateTime.length() > 0) { + checkInfo.put("signStatus", UtilKQ.getSignStatus("2", signDateTime, workEndDateTime)); + } + if (!Util.null2String(checkInfo.get("signStatus")).equalsIgnoreCase(ButtonStatusEnum.NORMAL.getStatusCode())) { + if (flow_deduct_card_map.containsKey("signoff")) { + String deduct_signofftime = Util.null2String(flow_deduct_card_map.get("signoff")); + if (deduct_signofftime.length() > 0) { + signDateTime = signdate + " " + deduct_signofftime; + checkInfo.put("deduct_signofftime", deduct_signofftime);//流程抵扣作为打卡时间 + checkInfo.put("signStatus", UtilKQ.getSignStatus("2", signDateTime, workEndDateTime)); + } + } + } + lsCheckInfo.add(checkInfo); + } + } else { + if (signoutOnlyoff_flag.length()>0) { + if("signin".equals(signoutOnlyoff_flag) && idx == 1){ + checkInfo.put("signType", "1"); + if (workBeginDateTime.length() > 0) { + checkInfo.put("signStatus", UtilKQ.getSignStatus("1", signDateTime, workBeginDateTime)); + } + if (!Util.null2String(checkInfo.get("signStatus")).equalsIgnoreCase(ButtonStatusEnum.NORMAL.getStatusCode())) { + if (flow_deduct_card_map.containsKey("signin")) { + String deduct_signintime = Util.null2String(flow_deduct_card_map.get("signin")); + if (deduct_signintime.length() > 0) { + signDateTime = signdate + " " + deduct_signintime; + checkInfo.put("deduct_signintime", deduct_signintime);//流程抵扣作为打卡时间 + checkInfo.put("signStatus", UtilKQ.getSignStatus("1", signDateTime, workBeginDateTime)); + } + } + } + lsCheckInfo.add(checkInfo); + hasSignIn = true; + } + if("signoff".equals(signoutOnlyoff_flag)){ + if ((hasSignIn && idx == rs.getCounts() && idx > 1) || (!hasSignIn && idx == rs.getCounts())) {//第一条可能是签到卡需要处理下,否则可能会导致一条上班卡同时识别为上班卡和下班卡 + checkInfo.put("signType", "2"); + if (workEndDateTime.length() > 0) { + checkInfo.put("signStatus", UtilKQ.getSignStatus("2", signDateTime, workEndDateTime)); + } + if (!Util.null2String(checkInfo.get("signStatus")).equalsIgnoreCase(ButtonStatusEnum.NORMAL.getStatusCode())) { + if (flow_deduct_card_map.containsKey("signoff")) { + String deduct_signofftime = Util.null2String(flow_deduct_card_map.get("signoff")); + if (deduct_signofftime.length() > 0) { + signDateTime = signdate + " " + deduct_signofftime; + checkInfo.put("deduct_signofftime", deduct_signofftime);//流程抵扣作为打卡时间 + checkInfo.put("signStatus", UtilKQ.getSignStatus("2", signDateTime, workEndDateTime)); + } + } + } + lsCheckInfo.add(checkInfo); + } + } + } else { + if (idx == 1) {//第一条算签到 + checkInfo.put("signType", "1"); + if (workBeginDateTime.length() > 0) { + checkInfo.put("signStatus", UtilKQ.getSignStatus("1", signDateTime, workBeginDateTime)); + } + if (!Util.null2String(checkInfo.get("signStatus")).equalsIgnoreCase(ButtonStatusEnum.NORMAL.getStatusCode())) { + if (flow_deduct_card_map.containsKey("signin")) { + String deduct_signintime = Util.null2String(flow_deduct_card_map.get("signin")); + if (deduct_signintime.length() > 0) { + signDateTime = signdate + " " + deduct_signintime; + checkInfo.put("deduct_signintime", deduct_signintime);//流程抵扣作为打卡时间 + checkInfo.put("signStatus", UtilKQ.getSignStatus("1", signDateTime, workBeginDateTime)); + } + } + } + lsCheckInfo.add(checkInfo); + hasSignIn = true; + } else if (idx == rs.getCounts()) {//最后一条算签退 + checkInfo.put("signType", "2"); + if (workEndDateTime.length() > 0) { + checkInfo.put("signStatus", UtilKQ.getSignStatus("2", signDateTime, workEndDateTime)); + } + if (!Util.null2String(checkInfo.get("signStatus")).equalsIgnoreCase(ButtonStatusEnum.NORMAL.getStatusCode())) { + if (flow_deduct_card_map.containsKey("signoff")) { + String deduct_signofftime = Util.null2String(flow_deduct_card_map.get("signoff")); + if (deduct_signofftime.length() > 0) { + signDateTime = signdate + " " + deduct_signofftime; + checkInfo.put("deduct_signofftime", deduct_signofftime);//流程抵扣作为打卡时间 + checkInfo.put("signStatus", UtilKQ.getSignStatus("2", signDateTime, workEndDateTime)); + } + } + } + lsCheckInfo.add(checkInfo); + } + } + } + } + } + } + //如果签到,签退不成对,流程抵扣异常存在,那么需要判断下是不是可以补足 + if (lsCheckInfo.size() < 2 && !flow_deduct_card_map.isEmpty()) { + if (lsCheckInfo.isEmpty()) { + if (flow_deduct_card_map.containsKey("signin")) { + String deduct_signintime = Util.null2String(flow_deduct_card_map.get("signin")); + if (deduct_signintime.length() > 0) { + checkInfo = new HashMap<>(); + String[] workBeginDateTimes = workBeginDateTime.split(" "); + String tmp_workBeginDate = workBeginDateTimes[0]; + String tmp_workBeginTime = workBeginDateTimes[1]; + checkInfo.put("signType", "1"); + checkInfo.put("signDate", tmp_workBeginDate);//签到签退日期 + checkInfo.put("signTime", "");//签到签退时间 + checkInfo.put("deduct_signintime", tmp_workBeginTime);//流程抵扣作为打卡时间 + checkInfo.put("signStatus", ButtonStatusEnum.NORMAL.getStatusCode()); + lsCheckInfo.add(checkInfo); + } + } + if (flow_deduct_card_map.containsKey("signoff")) { + String deduct_signofftime = Util.null2String(flow_deduct_card_map.get("signoff")); + if (deduct_signofftime.length() > 0) { + checkInfo = new HashMap<>(); + String[] workEndDateTimes = workEndDateTime.split(" "); + String tmp_workEndDate = workEndDateTimes[0]; + String tmp_workEndTime = workEndDateTimes[1]; + checkInfo.put("signType", "2"); + checkInfo.put("signDate", tmp_workEndDate);//签到签退日期 + checkInfo.put("signTime", "");//签到签退时间 + checkInfo.put("deduct_signofftime", tmp_workEndTime);//流程抵扣作为打卡时间 + checkInfo.put("signStatus", ButtonStatusEnum.NORMAL.getStatusCode()); + lsCheckInfo.add(checkInfo); + } + } + } else { + Map checkCardMap = (Map) lsCheckInfo.get(0); + if (!checkCardMap.isEmpty()) { + String signType = Util.null2String(checkCardMap.get("signType")); + if ("1".equalsIgnoreCase(signType)) { + //如果签到数据有了,检测下是不是有签退的流程抵扣打卡 + if (flow_deduct_card_map.containsKey("signoff")) { + String deduct_signofftime = Util.null2String(flow_deduct_card_map.get("signoff")); + if (deduct_signofftime.length() > 0) { + checkInfo = new HashMap<>(); + String[] workEndDateTimes = workEndDateTime.split(" "); + String tmp_workEndDate = workEndDateTimes[0]; + String tmp_workEndTime = workEndDateTimes[1]; + checkInfo.put("signType", "2"); + checkInfo.put("signDate", tmp_workEndDate);//签到签退日期 + checkInfo.put("signTime", "");//签到签退时间 + checkInfo.put("deduct_signofftime", tmp_workEndTime);//流程抵扣作为打卡时间 + checkInfo.put("signStatus", ButtonStatusEnum.NORMAL.getStatusCode()); + lsCheckInfo.add(checkInfo); + } + } + } else { + if (flow_deduct_card_map.containsKey("signin")) { + String deduct_signintime = Util.null2String(flow_deduct_card_map.get("signin")); + if (deduct_signintime.length() > 0) { + checkInfo = new HashMap<>(); + String[] workBeginDateTimes = workBeginDateTime.split(" "); + String tmp_workBeginDate = workBeginDateTimes[0]; + String tmp_workBeginTime = workBeginDateTimes[1]; + checkInfo.put("signType", "1"); + checkInfo.put("signDate", tmp_workBeginDate);//签到签退日期 + checkInfo.put("signTime", "");//签到签退时间 + checkInfo.put("deduct_signintime", tmp_workBeginTime);//流程抵扣作为打卡时间 + checkInfo.put("signStatus", ButtonStatusEnum.NORMAL.getStatusCode()); + lsCheckInfo.add(checkInfo); + } + } + } + } + } + } + // 上午的签退取中间时段的第一次打卡 + if (shiftCount == 2 && shiftI == 0) { + String noonSignTimeSql = KQSignUtil.buildSignSql(count4NoonStartDateTime, count4NoonEndDateTime); + String baseSql = "select * from hrmschedulesign where 1=1 and isInCom='1' and userid=" + userId + " "; + String sql = baseSql; + sql += " and " + noonSignTimeSql + " order by signdate, signtime"; + rs.executeQuery(sql); + if (rs.next()) { + String signId = Util.null2String(rs.getString("id")); + String signDate = Util.null2String(rs.getString("signdate")); + String signTime = Util.null2String(rs.getString("signtime")); + String signDateTime = signDate + " " + signTime; + for (int j = 0; lsCheckInfo != null && j < lsCheckInfo.size(); j++) { + Map checkInfoInner = (Map) lsCheckInfo.get(j); + if (checkInfoInner.get("signType").equals("2")) {//签退 + String signDateInner = Util.null2String(checkInfoInner.get("signDate")); + String signTimeInner = Util.null2String(checkInfoInner.get("signTime")); + String deduct_signofftime = Util.null2String(checkInfoInner.get("deduct_signofftime")); + if (!"".equals(signTimeInner)) { + String signDateTimeInner = signDateInner + " " + signTimeInner; + if (signDateTime.compareTo(signDateTimeInner) < 0) { + checkInfoInner.put("signId", signId);//签到签退标识 + checkInfoInner.put("signType", "2"); + checkInfoInner.put("signDate", signDateInner);//签到签退日期 + checkInfoInner.put("signTime", signTime);//签到签退时间 + checkInfoInner.put("deduct_signofftime", deduct_signofftime);//流程抵扣作为打卡时间 + checkInfoInner.put("signStatus", ButtonStatusEnum.NORMAL.getStatusCode()); + } + } + } + } + } + } else if (shiftCount == 2 && shiftI == 1) { // 下午的签到取中间时段的第二次打卡 + String noonSignTimeSql = KQSignUtil.buildSignSql(count4NoonStartDateTime, count4NoonEndDateTime); + String baseSql = "select * from hrmschedulesign where 1=1 and isInCom='1' and userid=" + userId + " "; + String sql = baseSql; + sql += " and " + noonSignTimeSql + " order by signdate, signtime"; + rs.executeQuery(sql); + int count = 0; + int counts = rs.getCounts(); + if (counts == 1) { + lsCheckInfo.clear(); + } + while (rs.next()) { + if (count == 0) { + count++; + continue; + } + String signId = Util.null2String(rs.getString("id")); + String signTime = Util.null2String(rs.getString("signtime")); + for (int j = 0; lsCheckInfo != null && j < lsCheckInfo.size(); j++) { + Map checkInfoInner = (Map) lsCheckInfo.get(j); + if (checkInfoInner.get("signType").equals("1")) {//签退 + String signDateInner = Util.null2String(checkInfoInner.get("signDate")); + String signTimeInner = Util.null2String(checkInfoInner.get("signTime")); + String deduct_signofftime = Util.null2String(checkInfoInner.get("deduct_signofftime")); + checkInfoInner.put("signId", signId);//签到签退标识 + checkInfoInner.put("signType", "1"); + checkInfoInner.put("signDate", signDateInner);//签到签退日期 + checkInfoInner.put("signTime", signTime);//签到签退时间 + checkInfoInner.put("deduct_signofftime", deduct_signofftime);//流程抵扣作为打卡时间 + checkInfoInner.put("signStatus", ButtonStatusEnum.NORMAL.getStatusCode()); + } + } + break; + } + } + } catch (Exception e) { + + kqLog.info("报表错:getSignInfo:"); + StringWriter errorsWriter = new StringWriter(); + e.printStackTrace(new PrintWriter(errorsWriter)); + kqLog.info(errorsWriter.toString()); + } + + //writeLog(sql,userId +"=="+ signBeginDateTime+"=="+signEndDateTime); + return lsCheckInfo; + } + + /** + * 根据上下班时间获取到是否有流程抵扣打卡的数据 + * + * @param userId + * @param kqDate + * @param workBeginDateTime + * @param workEndDateTime + */ + public Map getflowDeductCardSql(String userId, String kqDate, String workBeginDateTime, String workEndDateTime) { + Map flow_deduct_card_map = new HashMap<>(); + RecordSet rs = new RecordSet(); + String flow_deduct_card_sql = "select * from kq_flow_deduct_card where 1=1 and (isclear is null or isclear<>1) "; + if (userId.length() > 0) { + flow_deduct_card_sql += " and resourceid=" + userId; + } + if (kqDate.length() > 0) { + flow_deduct_card_sql += " and belongDate='" + kqDate + "'"; + } + if (workBeginDateTime.length() > 0) { + flow_deduct_card_sql += " and workBeginTime='" + workBeginDateTime + "'"; + } + if (workEndDateTime.length() > 0) { + flow_deduct_card_sql += " and workEndTime='" + workEndDateTime + "'"; + } + rs.executeQuery(flow_deduct_card_sql); + while (rs.next()) { + String signtype = rs.getString("signtype"); + if ("1".equalsIgnoreCase(signtype)) { + flow_deduct_card_map.put("signin", workBeginDateTime); + } + if ("2".equalsIgnoreCase(signtype)) { + flow_deduct_card_map.put("signoff", workEndDateTime); + } + } + return flow_deduct_card_map; + } + + /** + * 根据打卡的范围生成上班,下班数据获取的sql + * + * @param signTimeScope + * @param kqDate + * @param preDate + * @param nextDate + * @param kqTimesArrayComInfo + * @return + */ + public List> getCanSignInfo(TimeScopeEntity signTimeScope, String kqDate, String preDate, String nextDate, KQTimesArrayComInfo kqTimesArrayComInfo) { + return getCanSignInfo(signTimeScope, kqDate, preDate, nextDate, kqTimesArrayComInfo, null); + } + + public List> getCanSignInfo(TimeScopeEntity signTimeScope, String kqDate, String preDate, String nextDate, KQTimesArrayComInfo kqTimesArrayComInfo,TimeScopeEntity workTimeScope,int signoutOnlyoff) { + return getCanSignInfo(signTimeScope, kqDate, preDate, nextDate, kqTimesArrayComInfo, workTimeScope, 0, 0, signoutOnlyoff); + } + + public List> getCanSignInfo(TimeScopeEntity signTimeScope, String kqDate, String preDate, String nextDate, KQTimesArrayComInfo kqTimesArrayComInfo, TimeScopeEntity workTimeScope) { + return getCanSignInfo(signTimeScope, kqDate, preDate, nextDate, kqTimesArrayComInfo, workTimeScope, 0, 0); + } + + public List> getCanSignInfo(TimeScopeEntity signTimeScope, String kqDate, String preDate, String nextDate, KQTimesArrayComInfo kqTimesArrayComInfo, TimeScopeEntity workTimeScope, int shiftCount, int shiftI) { + return getCanSignInfo(signTimeScope, kqDate, preDate, nextDate, kqTimesArrayComInfo, workTimeScope, shiftCount, shiftI, 0); + } + + public List> getCanSignInfo(TimeScopeEntity signTimeScope, String kqDate, String preDate, String nextDate, KQTimesArrayComInfo kqTimesArrayComInfo, TimeScopeEntity workTimeScope, int shiftCount, int shiftI, int signoutOnlyoff) { + + List> sqlConditions = new ArrayList<>(); + Map conditionMap = new HashMap<>(); + + TimeSignScopeEntity timeSignScopeEntity = signTimeScope.getTimeSignScopeEntity(); + + String signBeginDateTime = ""; + String signEndDateTime = ""; + signBeginDateTime = signTimeScope.getBeginTimeAcross() ? nextDate : kqDate; + if (signTimeScope.isBeginTimePreAcross()) { + signBeginDateTime = preDate; + } + signBeginDateTime += " " + kqTimesArrayComInfo.turn48to24Time(signTimeScope.getBeginTime()) + ":00"; + + signEndDateTime = signTimeScope.getEndTimeAcross() ? nextDate : kqDate; + +// if (workTimeScope != null && workTimeScope.getEndTimeAcross() && signTimeScope.getEndTimeAcross() ) { +// if(workTimeScope.getEndTime().compareTo(signTimeScope.getEndTime())>=0){ +// signEndDateTime = DateUtil.addDate(kqDate, 2);//下下一天日期; +// } +// } + signEndDateTime += " " + kqTimesArrayComInfo.turn48to24Time(signTimeScope.getEndTime()) + ":59"; + + + if (timeSignScopeEntity == null) { + //没有设置 签到最晚时间和签退最早时间,比如是09:00-18:00,打卡范围是【08:00---19:00】 + if (signoutOnlyoff == 1 && workTimeScope != null) {//开启了下班后只能签退的按钮,那么考勤格式化的打卡数据查询范围也搞一下 + String signBeginDateEndTime = ""; + String signEndDateStartTime = ""; + String workEndTime = workTimeScope.getEndTime(); + boolean workEndTimeAcross = workTimeScope.getEndTimeAcross(); + + String workEndTimeNew = kqTimesArrayComInfo.getTimesByArrayindex(kqTimesArrayComInfo.getArrayindexByTimes(workEndTime) - 1);//17:59 + signBeginDateEndTime = workEndTimeAcross ? nextDate : kqDate; + signBeginDateEndTime += " " + kqTimesArrayComInfo.turn48to24Time(workEndTimeNew) + ":59";//17:59:59 + + conditionMap = new HashMap<>(); + conditionMap.put("signBeginDateTime", signBeginDateTime);//08:00:00 + conditionMap.put("signEndDateTime", signBeginDateEndTime);//17:59:59 +// conditionMap.put("type", "signin"); + conditionMap.put("signoutOnlyoff", "signin"); + sqlConditions.add(conditionMap); + + conditionMap = new HashMap<>(); + conditionMap.put("signBeginDateTime", signBeginDateTime);//08:00:00,这里为什么从上班开始打卡时间起算,因为存在上班有打卡,连续打卡的情况,那么需要将除上班卡之后的打卡都识别为下班卡 + conditionMap.put("signEndDateTime", signEndDateTime);//19:00:59 + //这里不能传type=signoff,否则上班打卡可能会同时识别为上班卡和下班卡 + conditionMap.put("signoutOnlyoff", "signoff"); + sqlConditions.add(conditionMap); + + } else {//走标准原逻辑 + conditionMap = new HashMap<>(); + conditionMap.put("signBeginDateTime", signBeginDateTime); + conditionMap.put("signEndDateTime", signEndDateTime); + sqlConditions.add(conditionMap); + } + + } else { + String beginTimeEnd = timeSignScopeEntity.getBeginTimeEnd(); + boolean beginTimeEndAcross = timeSignScopeEntity.isBeginTimeEndAcross(); + + String endTimeStart = timeSignScopeEntity.getEndTimeStart(); + boolean endTimeStartAcross = timeSignScopeEntity.isEndTimeStartAcross(); + + if (beginTimeEnd.length() > 0) { + //如果设置了 上班结束时间 + if (endTimeStart.length() > 0) { + //设置了下班开始时间 + String signBeginDateEndTime = ""; + String signEndDateStartTime = ""; + signBeginDateEndTime = beginTimeEndAcross ? nextDate : kqDate; + signBeginDateEndTime += " " + kqTimesArrayComInfo.turn48to24Time(beginTimeEnd) + ":59"; + + //张总表示设了打卡归属,以设置的为准,这个开关相当于不起作用,代码含泪注释 +// if(signoutOnlyoff == 1 && workTimeScope != null){//开启了下班后只能签退的按钮,那么考勤格式化的打卡数据查询范围也搞一下 +// String workEndTime = workTimeScope.getEndTime(); +// boolean workEndTimeAcross = workTimeScope.getEndTimeAcross(); +// signBeginDateEndTime = workEndTimeAcross ? nextDate : kqDate; +// signBeginDateEndTime+=" "+kqTimesArrayComInfo.turn48to24Time(workEndTime)+":59"; +// conditionMap = new HashMap<>(); +// conditionMap.put("signBeginDateTime", signBeginDateTime); +// conditionMap.put("signEndDateTime", signBeginDateEndTime); +// conditionMap.put("type", "signin"); +// sqlConditions.add(conditionMap); +// +// conditionMap = new HashMap<>(); +// conditionMap.put("signBeginDateTime", signBeginDateEndTime); +// conditionMap.put("signEndDateTime", signEndDateTime); +// conditionMap.put("type", "signoff"); +// sqlConditions.add(conditionMap); +// +// }else{ + conditionMap = new HashMap<>(); + conditionMap.put("signBeginDateTime", signBeginDateTime); + conditionMap.put("signEndDateTime", signBeginDateEndTime); + conditionMap.put("type", "signin"); + sqlConditions.add(conditionMap); + + signEndDateStartTime = endTimeStartAcross ? nextDate : kqDate; + signEndDateStartTime += " " + kqTimesArrayComInfo.turn48to24Time(endTimeStart) + ":00"; + + conditionMap = new HashMap<>(); + conditionMap.put("signBeginDateTime", signEndDateStartTime); + conditionMap.put("signEndDateTime", signEndDateTime); + conditionMap.put("type", "signoff"); + sqlConditions.add(conditionMap); +// } + } else { + //没有设置下班开始时间 + String signBeginDateEndTime = ""; + String signEndDateStartTime = ""; + signBeginDateEndTime = beginTimeEndAcross ? nextDate : kqDate; + signBeginDateEndTime += " " + kqTimesArrayComInfo.turn48to24Time(beginTimeEnd) + ":59"; + + conditionMap = new HashMap<>(); + conditionMap.put("signBeginDateTime", signBeginDateTime); + conditionMap.put("signEndDateTime", signBeginDateEndTime); + conditionMap.put("type", "signin"); + sqlConditions.add(conditionMap); + + //如果设置了上班结束时间,相当于下班开始时间也被限定了 + String endTimeByBeginTime = kqTimesArrayComInfo.getTimesByArrayindex(kqTimesArrayComInfo.getArrayindexByTimes(beginTimeEnd) + 1); + signEndDateStartTime = beginTimeEndAcross ? nextDate : kqDate; + signEndDateStartTime += " " + kqTimesArrayComInfo.turn48to24Time(endTimeByBeginTime) + ":00"; + + conditionMap = new HashMap<>(); + conditionMap.put("signBeginDateTime", signEndDateStartTime); + conditionMap.put("signEndDateTime", signEndDateTime); + conditionMap.put("type", "signoff"); + sqlConditions.add(conditionMap); + } + } else if (endTimeStart.length() > 0) { + //如果没有设置上班结束时间,设置了下班开始时间 + String signBeginDateEndTime = ""; + String signEndDateStartTime = ""; + + //如果设置了下班开始时间,相当于上班结束时间也被限定了 + String BeginTimeByendTime = kqTimesArrayComInfo.getTimesByArrayindex(kqTimesArrayComInfo.getArrayindexByTimes(endTimeStart) - 1); + signBeginDateEndTime = endTimeStartAcross ? nextDate : kqDate; + signBeginDateEndTime += " " + kqTimesArrayComInfo.turn48to24Time(BeginTimeByendTime) + ":59"; + + conditionMap = new HashMap<>(); + conditionMap.put("signBeginDateTime", signBeginDateTime); + conditionMap.put("signEndDateTime", signBeginDateEndTime); + conditionMap.put("type", "signin"); + sqlConditions.add(conditionMap); + + signEndDateStartTime = endTimeStartAcross ? nextDate : kqDate; + signEndDateStartTime += " " + kqTimesArrayComInfo.turn48to24Time(endTimeStart) + ":00"; + + conditionMap = new HashMap<>(); + conditionMap.put("signBeginDateTime", signEndDateStartTime); + conditionMap.put("signEndDateTime", signEndDateTime); + conditionMap.put("type", "signoff"); + sqlConditions.add(conditionMap); + } + } + return sqlConditions; + } + + public String signSignSql(RecordSet rs) { + String sql = ""; + if (rs.getDBType().equals("oracle")) { + sql = " select id,signdate,signtime from hrmschedulesign where isincom=1 and userid = ? and signdate||' '||signtime >= ? and signdate||' '||signtime <= ? " + + " "; + } else if ("sqlserver".equals(rs.getDBType())) { + sql = " select id,signdate,signtime from hrmschedulesign where isincom=1 and userid = ? and signdate + ' ' + signtime >= ? and signdate + ' ' + signtime <= ? " + + " "; + } else { + sql = " select id,signdate,signtime from hrmschedulesign where isincom=1 and userid = ? and concat(signdate,' ',signtime) >= ? and concat(signdate,' ',signtime) <= ? " + + " "; + } + return sql; + } + + public List getSignInfoForAll(String userId, String signBeginDateTime, String signEndDateTime, String workBeginDateTime, String workEndDateTime) { + List lsCheckInfo = new ArrayList<>(); + Map checkInfo = null; + String sql = ""; + RecordSet rs = new RecordSet(); + + int idx = 0; + if (rs.getDBType().equals("oracle")) { + sql = " select id,signdate,signtime from hrmschedulesign where isincom=1 and userid = ? and signdate||' '||signtime >= ? and signdate||' '||signtime <= ? " + + " order by signdate asc, signtime asc "; + } else if ("sqlserver".equals(rs.getDBType())) { + sql = " select id,signdate,signtime from hrmschedulesign where isincom=1 and userid = ? and signdate + ' ' + signtime >= ? and signdate + ' ' + signtime <= ? " + + " order by signdate asc, signtime asc "; + } else { + sql = " select id,signdate,signtime from hrmschedulesign where isincom=1 and userid = ? and concat(signdate,' ',signtime) >= ? and concat(signdate,' ',signtime) <= ? " + + " order by signdate asc, signtime asc "; + } + rs.executeQuery(sql, userId, signBeginDateTime, signEndDateTime); + //writeLog(sql,userId +"=="+ signBeginDateTime+"=="+signEndDateTime); + while (rs.next()) { + String signId = Util.null2String(rs.getString("id")); + String signdate = Util.null2String(rs.getString("signdate")); + String signtime = Util.null2String(rs.getString("signtime")); + + checkInfo = new HashMap<>(); + checkInfo.put("signId", signId);//签到签退标识 + checkInfo.put("signDate", signdate);//签到签退日期 + checkInfo.put("signTime", signtime);//签到签退时间 + String signDateTime = signdate + " " + signtime; + + idx++; + if (idx % 2 == 1) { + checkInfo.put("signType", "1"); + } else { + checkInfo.put("signType", "2"); + } + lsCheckInfo.add(checkInfo); + } + return lsCheckInfo; + } + + public List getNonWorkSignInfo(String userId, String preDate, String kqDate, + List pre_lsSignTime, + List next_lsSignTime) { + List lsCheckInfo = new ArrayList<>(); + Map checkInfo = null; + RecordSet rs = new RecordSet(); + String pre_Worktime4Today = ""; + if (!pre_lsSignTime.isEmpty()) { + TimeScopeEntity pre_signTimeScope = pre_lsSignTime.get(pre_lsSignTime.size() - 1); + if (pre_signTimeScope.getEndTimeAcross()) { + pre_Worktime4Today = pre_signTimeScope.getEndTime(); + } + } + String next_Worktime4Today = ""; + if (!next_lsSignTime.isEmpty()) { + TimeScopeEntity next_signTimeScope = next_lsSignTime.get(next_lsSignTime.size() - 1); + if (next_signTimeScope.isBeginTimePreAcross()) { + next_Worktime4Today = next_signTimeScope.getBeginTime(); + } + } + String sql = "select * from hrmschedulesign where userid=" + userId + " and signdate = '" + kqDate + "' "; + if (pre_Worktime4Today.length() > 0) { + if (pre_Worktime4Today.length() == 5) { + pre_Worktime4Today += ":59"; + } + sql += " and signtime > '" + pre_Worktime4Today + "'"; + } + if (next_Worktime4Today.length() > 0) { + if (next_Worktime4Today.length() == 5) { + next_Worktime4Today += ":00"; + } + sql += " and signtime < '" + next_Worktime4Today + "'"; + } + sql += " order by signdate asc,signtime asc "; + rs.executeQuery(sql); + int idx = 0; + while (rs.next()) { + String signId = Util.null2String(rs.getString("id")); + String signdate = Util.null2String(rs.getString("signdate")); + String signtime = Util.null2String(rs.getString("signtime")); + + checkInfo = new HashMap<>(); + checkInfo.put("signId", signId);//签到签退标识 + checkInfo.put("signDate", signdate);//签到签退日期 + checkInfo.put("signTime", signtime);//签到签退时间 + idx++; + if (idx == 1) {//第一条算签到 + checkInfo.put("signType", "1"); + lsCheckInfo.add(checkInfo); + } else if (idx == rs.getCounts()) {//最后一条算签退 + checkInfo.put("signType", "2"); + lsCheckInfo.add(checkInfo); + } + } + return lsCheckInfo; + } + +} \ No newline at end of file diff --git a/领悦二开new/src/com/engine/kq/biz/KQGroupBiz.java b/领悦二开new/src/com/engine/kq/biz/KQGroupBiz.java new file mode 100644 index 0000000..542c21a --- /dev/null +++ b/领悦二开new/src/com/engine/kq/biz/KQGroupBiz.java @@ -0,0 +1,714 @@ +package com.engine.kq.biz; + +import com.engine.kq.entity.KQGroupEntity; +import com.engine.kq.log.KQLog; +import com.google.common.collect.Lists; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.IpUtils; +import weaver.general.Util; +import weaver.hrm.common.database.dialect.DbDialectFactory; +import weaver.hrm.common.database.dialect.IDbDialectSql; + +import java.util.*; + +public class KQGroupBiz extends BaseBean { + + private static final double EARTH_RADIUS = 6378137;// 地球半径 + public static final String GROUPMEMBER_VALIDATE_FROMDATE="2000-01-01"; + public static final String GROUPMEMBER_VALIDATE_TODATE="2999-12-31"; + + public String getGroupMemberSql() { + return getGroupMemberSql(""); + } + + public String getGroupMemberSql(String groupId) { + Map params = new HashMap<>(); + params.put("groupId",groupId); + return this.getGroupMemberSql(params); + } + + public String getGroupMemberSql(Map params) { + String sql = ""; + try { + String groupId = Util.null2String(params.get("groupId")); + String isNoAccount = Util.null2String(params.get("isNoAccount")); + if(Util.null2String(groupId).length()>0){ + sql = " SELECT distinct resourceid, groupid FROM ( " + + " SELECT a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b " + + " WHERE a.id=b.typevalue and b.type =1 and (b.isdelete is null or b.isdelete <> '1') " + + " UNION ALL " + + " SELECT a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b " + + " WHERE a.subcompanyid1 = b.typevalue AND b.type=2 AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto and (b.isdelete is null or b.isdelete <> '1') " + + " UNION ALL " + + " SELECT a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b " + + " WHERE a.departmentid = b.typevalue AND b.type=3 AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto and (b.isdelete is null or b.isdelete <> '1') " + + " UNION ALL " + + " SELECT a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b " + + " WHERE a.jobtitle = b.typevalue AND b.type=5 " + + " AND (b.jobtitlelevel=1 OR (b.jobtitlelevel=2 AND a.subcompanyid1 IN(b.jobtitlelevelvalue)) OR (b.jobtitlelevel=3 AND a.departmentid IN(b.jobtitlelevelvalue))) " + + " and (b.isdelete is null or b.isdelete <> '1') " + + " UNION ALL " + + " SELECT a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b " + + " WHERE b.type=6 AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto and (b.isdelete is null or b.isdelete <> '1') ) t" + + " where 1=1 "; + if(!Util.null2String(isNoAccount).equals("1")){ + sql += " and t.status in (0,1,2,3) "; + } + sql += " and t.groupid = "+groupId; + }else{ + sql = " SELECT distinct resourceid, groupid FROM ( " + + " SELECT a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b,kq_group c " + + " WHERE a.id=b.typevalue and b.type =1 and (b.isdelete is null or b.isdelete <> '1') and (c.isdelete is null or c.isdelete <> '1') and c.id=b.groupid " + + " UNION ALL " + + " SELECT a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b,kq_group c " + + " WHERE a.subcompanyid1 = b.typevalue AND b.type=2 AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto and (b.isdelete is null or b.isdelete <> '1') and (c.isdelete is null or c.isdelete <> '1') and c.id=b.groupid " + + " UNION ALL " + + " SELECT a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b,kq_group c " + + " WHERE a.departmentid = b.typevalue AND b.type=3 AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto and (b.isdelete is null or b.isdelete <> '1') and (c.isdelete is null or c.isdelete <> '1') and c.id=b.groupid " + + " UNION ALL " + + " SELECT a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b,kq_group c " + + " WHERE a.jobtitle = b.typevalue AND b.type=5 " + + " AND (b.jobtitlelevel=1 OR (b.jobtitlelevel=2 AND a.subcompanyid1 IN(b.jobtitlelevelvalue)) OR (b.jobtitlelevel=3 AND a.departmentid IN(b.jobtitlelevelvalue))) " + + " and (b.isdelete is null or b.isdelete <> '1') and (c.isdelete is null or c.isdelete <> '1') and c.id=b.groupid " + + " UNION ALL " + + " SELECT a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b,kq_group c " + + " WHERE b.type=6 AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto and (b.isdelete is null or b.isdelete <> '1') and (c.isdelete is null or c.isdelete <> '1') and c.id=b.groupid ) t" + + " where 1=1 "; + if(!Util.null2String(isNoAccount).equals("1")){ + sql += " and t.status in (0,1,2,3) "; + } + } + } catch (Exception e) { + writeLog(e); + } + + return sql; + } + + public List getGroupMembers(String groupId) { + Map params = new HashMap<>(); + params.put("groupId",groupId); + return this.getGroupMembers(params); + } + + public List getGroupMembers(Map params) { + RecordSet rs = new RecordSet(); + List members = new ArrayList<>(); + try { + String sql = this.getGroupMemberSql(params); + rs.executeQuery(sql); + while (rs.next()) { + members.add(rs.getString("resourceid")); + } + } catch (Exception e) { + writeLog(e); + } + + return members; + } + + //根据传入的班次id,然后判断是否有考勤组引用这个班次 + public boolean serialIdIsUesed(String serialid) { + boolean serialIdUesed = false; + RecordSet rs = new RecordSet(); + String sql = ""; + IDbDialectSql dialectSql = DbDialectFactory.get(rs.getDBType()) ; + String isDeleteField = dialectSql.isNull("isdelete",0) ; + try { + sql = " select count(1) " + + " from (select distinct serialid from kq_fixedschedulce where serialid in ( ? ) and ("+isDeleteField+" !=1 ) "+ + " union " + + " select distinct serialid from kq_shiftschedule where serialid in ( ? ) and ("+isDeleteField+" !=1 ) ) t"; + rs.executeQuery(sql,serialid,serialid); + if (rs.next()){ + if(rs.getInt(1)>0){ + serialIdUesed = true; + } + } + + if(!serialIdUesed){ + + + if(rs.getDBType().equals("oracle")||rs.getDBType().equals("postgresql")) { + sql = " select count(1) from kq_group where ((','||serialids||',') like '%," + serialid + ",%' or (','||shiftcycleserialids||',') like '%," + serialid + ",%') and (isdelete is null or isdelete <> '1')"; + }else if(rs.getDBType().equals("mysql")){ + String serialidsConcatContion = dialectSql.concatStr("','","serialids","','") ; + String shiftcycleSerialidsConcatConditon = dialectSql.concatStr("','","shiftcycleserialids","','") ; + String groupIsDeleteCondition = dialectSql.isNull("isdelete",0) ; + String likeValue = "%,"+serialid+",%" ; + + sql = String.format(" select count(1) from kq_group where ((%s) like '%s' or (%s) like '%s') and (%s!=1)", + serialidsConcatContion,likeValue, + shiftcycleSerialidsConcatConditon,likeValue, + groupIsDeleteCondition) ; + }else{ + sql = " select count(1) from kq_group where (','+serialids+',' like '%," + serialid + ",%' or ','+shiftcycleserialids+',' like '%," + serialid + ",%') and (isdelete is null or isdelete <> '1')"; + } + + + + rs.executeQuery(sql); + if (rs.next()){ + if(rs.getInt(1)>0){ + serialIdUesed = true; + } + } + } + } catch (Exception e) { + writeLog(e); + } + return serialIdUesed; + } + + /** + * 根据传入的班次id,引用此班次的考勤组 + * @param serialid + * @return + */ + public List getGroupIdByUesedSerialId(String serialid) { + RecordSet rs = new RecordSet(); + List groupList = Lists.newArrayList(); + String sql = ""; + IDbDialectSql dialectSql = DbDialectFactory.get(rs.getDBType()) ; + String isDeleteField = dialectSql.isNull("isdelete",0) ; + try { + sql = " select serialid,groupid " + + " from (select distinct serialid,groupid from kq_fixedschedulce where serialid in ( ? ) and ("+isDeleteField+" !=1 ) "+ + " union " + + " select distinct serialid,groupid from kq_shiftschedule where serialid in ( ? ) and ("+isDeleteField+" !=1 ) ) t"; + rs.executeQuery(sql,serialid,serialid); + while (rs.next()){ + String tmp_groupId = rs.getString("groupid"); + if(!groupList.contains(tmp_groupId)){ + groupList.add(tmp_groupId); + } + } + + if(rs.getDBType().equals("oracle")||rs.getDBType().equals("postgresql")) { + sql = " select id from kq_group where ((','||serialids||',') like '%," + serialid + ",%' or (','||shiftcycleserialids||',') like '%," + serialid + ",%') and (isdelete is null or isdelete <> '1')"; + }else if(rs.getDBType().equals("mysql")){ + String serialidsConcatContion = dialectSql.concatStr("','","serialids","','") ; + String shiftcycleSerialidsConcatConditon = dialectSql.concatStr("','","shiftcycleserialids","','") ; + String groupIsDeleteCondition = dialectSql.isNull("isdelete",0) ; + String likeValue = "%,"+serialid+",%" ; + + sql = String.format(" select id from kq_group where ((%s) like '%s' or (%s) like '%s') and (%s!=1)", + serialidsConcatContion,likeValue, + shiftcycleSerialidsConcatConditon,likeValue, + groupIsDeleteCondition) ; + }else{ + sql = " select id from kq_group where (','+serialids+',' like '%," + serialid + ",%' or ','+shiftcycleserialids+',' like '%," + serialid + ",%') and (isdelete is null or isdelete <> '1')"; + } + + rs.executeQuery(sql); + while (rs.next()){ + String tmp_groupId = rs.getString("id"); + if(!groupList.contains(tmp_groupId)){ + groupList.add(tmp_groupId); + } + } + } catch (Exception e) { + writeLog(e); + } + return groupList; + } + + public Map getLocationWifiInfo(String userid,String showWifiList) { + Map result = new HashMap<>(); + Map locationInfo = new HashMap<>(); + Map wifiInfo = new HashMap<>(); + KQGroupComInfo kqGroupComInfo = new KQGroupComInfo(); + KQGroupMemberComInfo kqGroupMemberComInfo = new KQGroupMemberComInfo(); + KQLoactionComInfo kqLoactionComInfo = new KQLoactionComInfo(); + String groupid = Util.null2String(kqGroupMemberComInfo.getKQGroupId(userid)); + List datas = null; + Map data = null; + + if(groupid.length()>0){ + datas = new ArrayList(); + while(kqLoactionComInfo.next()){ + if(!kqLoactionComInfo.getGroupid().equals(groupid))continue; + data = new HashMap<>(); + data.put("id",kqLoactionComInfo.getId()); + data.put("locationname",Util.null2String(kqLoactionComInfo.getLocationname())); + data.put("longitude",Util.null2String(kqLoactionComInfo.getLongitude())); + data.put("latitude",Util.null2String(kqLoactionComInfo.getLatitude())); + data.put("address",Util.null2String(kqLoactionComInfo.getAddress())); + data.put("checkscope",Util.null2String(kqLoactionComInfo.getCheckscope())); + data.put("groupid",Util.null2String(kqLoactionComInfo.getGroupid())); + datas.add(data); + } + locationInfo.put("locationcheck",Util.null2String(kqGroupComInfo.getLocationcheck(groupid)).equals("1")); + locationInfo.put("locationcheckscope",Util.null2String(kqGroupComInfo.getLocationcheckscope(groupid))); + locationInfo.put("locations",datas); + + datas = new ArrayList(); + if("1".equalsIgnoreCase(showWifiList)){ + KQWifiComInfo kqWifiComInfo = new KQWifiComInfo(); + while(kqWifiComInfo.next()){ + if(!kqWifiComInfo.getGroupid().equals(groupid))continue; + data = new HashMap<>(); + data.put("id",kqWifiComInfo.getId()); + data.put("wifiname",Util.null2String(kqWifiComInfo.getWifiname())); + data.put("mac",Util.null2String(kqWifiComInfo.getMac())); + data.put("groupid",Util.null2String(kqWifiComInfo.getGroupid())); + datas.add(data); + } + } + wifiInfo.put("wificheck",Util.null2String(kqGroupComInfo.getWificheck(groupid)).equals("1")); + wifiInfo.put("wifis",datas); + + result.put("locationInfo",locationInfo); + result.put("wifiInfo",wifiInfo); + result.put("status","1"); + + String show_position = "show_position"; + KQSettingsComInfo kqSettingsComInfo = new KQSettingsComInfo(); + String positioncheck = Util.null2String(kqSettingsComInfo.getMain_val(show_position),"0"); + result.put("positioncheck",positioncheck); + } + return result; + } + /** + * 用户考勤地点 WIFI限制信息 + * @param userid + * @return + */ + public Map getLocationWifiInfo(String userid) { + return getLocationWifiInfo(userid,"1"); + } + + /** + *判断办公地点范围 + * @return + */ + public Map checkLocationScope(String userId, String longitude, String latitude){ + Map retmap = new HashMap<>(); + Map loactionInfo = null; + try { + boolean inScope = false; + KQGroupMemberComInfo kqGroupMemberComInfo = new KQGroupMemberComInfo(); + KQGroupEntity kqGroupEntity = kqGroupMemberComInfo.getUserKQGroupInfo(userId); + KQLoactionComInfo kqLoactionComInfo = new KQLoactionComInfo(); + Map locationTrueInfo = new HashMap<>(); + double distance = EARTH_RADIUS; + if (kqGroupEntity != null && kqGroupEntity.getLocationcheck().equals("1")) { + while (kqLoactionComInfo.next()) { + if (Util.null2String(kqLoactionComInfo.getGroupid()).equals(kqGroupEntity.getId())) { + double lng1 = Util.getDoubleValue(longitude);//经度 + double lat1 = Util.getDoubleValue(latitude);//纬度 + double lng2 = Util.getDoubleValue(kqLoactionComInfo.getLongitude());//经度 + double lat2 = Util.getDoubleValue(kqLoactionComInfo.getLatitude());//纬度 + int checkscope = Util.getIntValue(kqLoactionComInfo.getCheckscope());//有效范围 + double geo_distance = geo_distance(lng1, lat1, lng2, lat2); + if (distance > geo_distance) { + distance = geo_distance; + locationTrueInfo.put("lng2", lng2); + locationTrueInfo.put("lat2", lat2); + locationTrueInfo.put("checkscope", checkscope); + locationTrueInfo.put("geo_distance", geo_distance); +// locationTrueInfo = lng2 + "#" + lat2 + "#" + checkscope + "#" + geo_distance; + } + if (geo_distance < checkscope) { + inScope = true; + loactionInfo = new HashMap<>(); + loactionInfo.put("locationname", kqLoactionComInfo.getLocationname()); + loactionInfo.put("longitude", kqLoactionComInfo.getLongitude()); + loactionInfo.put("latitude", kqLoactionComInfo.getLatitude()); + loactionInfo.put("address", kqLoactionComInfo.getAddress()); + loactionInfo.put("id", kqLoactionComInfo.getId()); + loactionInfo.put("longitudefromoa", lng2); + loactionInfo.put("latitudefromoa", lat2); + loactionInfo.put("lengthfromoa", checkscope); + loactionInfo.put("lengthfromem", geo_distance); + break; + } + } + } + } else {//未开启开关 + inScope = true; + } + retmap.put("needCheck", kqGroupEntity != null ? Util.null2String(kqGroupEntity.getLocationcheck()) : "0");//是否开启办公地点验证 + retmap.put("inScope", inScope);//是否在考勤范围内 + retmap.put("locationshowaddress", kqGroupEntity != null ? Util.null2String(kqGroupEntity.getLocationshowaddress()) : "0");//有效识别半径内显示同一地址 + if (!inScope && locationTrueInfo != null && !locationTrueInfo.isEmpty()) { + if(loactionInfo == null) { + loactionInfo = new HashMap<>(); + } + loactionInfo.put("longitudefromoa", Util.null2String(locationTrueInfo.get("lng2"))); + loactionInfo.put("latitudefromoa", Util.null2String(locationTrueInfo.get("lat2"))); + loactionInfo.put("lengthfromoa", Util.null2String(locationTrueInfo.get("checkscope"))); + loactionInfo.put("lengthfromem", Util.null2String(locationTrueInfo.get("geo_distance"))); + } + }catch (Exception e) { + writeLog(e); + } + retmap.put("loactionInfo", loactionInfo);//考勤范围相关信息 + return retmap; + } + + /** + * 计算两个经度纬度(WGS-84)之间的距离 + * @param lng1 坐标1经度 + * @param lat1 坐标1纬度EARTH_RADIUS + * @param lng2 坐标2经度 + * @param lat2 坐标2纬度 + * @return 2个坐标之间距离,单位:米 + */ + private double geo_distance(double lng1, double lat1, double lng2, double lat2) { + double radLat1 = Math.toRadians(lat1); + double radLat2 = Math.toRadians(lat2); + double a = Math.abs(radLat1 - radLat2); + double b = Math.abs(Math.toRadians(lng1) - Math.toRadians(lng2)); + double distance = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2))); + distance = distance * EARTH_RADIUS; + distance = Math.round(distance * 10000) / 10000; + return distance; + } + + /** + *判断Wifi范围 + * @return + */ + public Map checkWifiScope(String userId, String wifiName, String mac){ + Map retmap = new HashMap<>(); + Map wifiInfo = null; + boolean inScope = false; + KQGroupMemberComInfo kqGroupMemberComInfo = new KQGroupMemberComInfo(); + KQGroupEntity kqGroupEntity = kqGroupMemberComInfo.getUserKQGroupInfo(userId); + KQWifiComInfo kqWifiComInfo = new KQWifiComInfo(); + + if(kqGroupEntity.getWificheck().equals("1")){ + try{ + List lst = new ArrayList<>(Arrays.asList(mac.split(":"))); + for(int i = 0; i < lst.size(); i++){ + String s = lst.get(i); + if(s.length() == 1) + lst.set(i, "0" + s); + } + mac = String.join(":", lst); + }catch (Exception ex){ + ex.printStackTrace(); + } + while(kqWifiComInfo.next()){ + if(Util.null2String(kqWifiComInfo.getGroupid()).equals(kqGroupEntity.getId())){ + if(Util.null2String(kqWifiComInfo.getWifiname().toLowerCase()).equals(wifiName.toLowerCase())){ + String wifi_cominfo_mac = Util.null2String(kqWifiComInfo.getMac().toLowerCase()); + String param_mac = mac.toLowerCase(); + int last_wifi_mac_index = wifi_cominfo_mac.lastIndexOf(":"); + int param_mac_index = param_mac.lastIndexOf(":"); + if(last_wifi_mac_index > 0 && param_mac_index > 0){ + wifi_cominfo_mac = wifi_cominfo_mac.substring(0,last_wifi_mac_index); + param_mac = param_mac.substring(0,param_mac_index); + } + if(wifi_cominfo_mac.equals(param_mac)){ + inScope = true; + wifiInfo = new HashMap<>(); + wifiInfo.put("wifiname",kqWifiComInfo.getWifiname()); + wifiInfo.put("mac",kqWifiComInfo.getMac()); + break; + } + } + } + } + }else{//未开启开关 + inScope = true; + } + retmap.put("needCheck",Util.null2String(kqGroupEntity.getWificheck()));//是否开启wifi验证 + retmap.put("inScope",inScope);//是否在考勤范围内 + retmap.put("wifiInfo",wifiInfo);//考勤范围相关信息 + return retmap; + } + + /** + * 校验ipv4和v6范围 + * @param userId + * @param clientAddress + * @param ismobile + * @return + */ + public boolean getIsInScopeV4V6(String userId, String clientAddress,String ismobile) { + boolean isInScope = false; + clientAddress = Util.null2String(clientAddress).trim(); + if (clientAddress.length() == 0) { + return isInScope; + } + + RecordSet rs = new RecordSet(); + KQGroupComInfo kqGroupComInfo = new KQGroupComInfo(); + KQGroupMemberComInfo kqGroupMemberComInfo = new KQGroupMemberComInfo(); + String groupid = Util.null2String(kqGroupMemberComInfo.getKQGroupId(userId)); + String signIpScope = Util.null2String(kqGroupComInfo.getIpscope(groupid)).trim();//格式:10.*.*.*;10.16.0.12;10.16.0.13-10.16.0.18 + String signIpscope_v4_em = Util.null2String(kqGroupComInfo.getIpscope_v4_em(groupid)).trim(); + String signIpscope_v4_pc = Util.null2String(kqGroupComInfo.getIpscope_v4_pc(groupid)).trim(); + String signIpscope_v6_em = Util.null2String(kqGroupComInfo.getIpscope_v6_em(groupid)).trim(); + String signIpscope_v6_pc = Util.null2String(kqGroupComInfo.getIpscope_v6_pc(groupid)).trim(); + if (signIpscope_v4_em.length() == 0 && signIpscope_v4_pc.length() == 0 + && signIpscope_v6_em.length() == 0 && signIpscope_v6_pc.length() == 0) { + return true; + } + + new KQLog().info("getIsInScopeV4V6:ismobile:"+ismobile+":signIpscope_v4_em:"+signIpscope_v4_em+":signIpscope_v6_em:"+signIpscope_v6_em + +":signIpscope_v4_pc:"+signIpscope_v4_pc+":signIpscope_v6_pc:"+signIpscope_v6_pc); + if("1".equalsIgnoreCase(ismobile)){ + if(signIpscope_v4_em.length() > 0){ + return checkIps(signIpscope_v4_em,clientAddress,"IPv4"); + }else if(signIpscope_v6_em.length() > 0){ + return checkIps(signIpscope_v6_em,clientAddress,"IPv6"); + }else{ + return true; + } + }else{ + if(signIpscope_v4_pc.length() > 0){ + return checkIps(signIpscope_v4_pc,clientAddress,"IPv4"); + }else if(signIpscope_v6_pc.length() > 0){ + return checkIps(signIpscope_v6_pc,clientAddress,"IPv6"); + }else{ + return true; + } + } + } + + + private boolean checkIps(String signIpScope, String clientAddress,String ipType) { + boolean isInScope = false; + List signIpScopeList = Util.TokenizerString(signIpScope, ";"); + String signIpScopeSingle = ""; + for (int i = 0; i < signIpScopeList.size(); i++) { + signIpScopeSingle = Util.null2String((String) signIpScopeList.get(i)); + signIpScopeSingle = signIpScopeSingle.trim(); + if("IPv4".equalsIgnoreCase(ipType)){ + isInScope = checkIpV4(signIpScopeSingle,clientAddress); + if(isInScope){ + break; + } + }else if("IPv6".equalsIgnoreCase(ipType)){ + isInScope = checkIpV6(signIpScopeSingle,clientAddress); + if(isInScope){ + break; + } + } + } + return isInScope; + } + + private boolean checkIpV6(String signIpScopeSingle, String clientAddress) { + + boolean isInScope = false; + if (signIpScopeSingle.indexOf("-") > -1) { + String signIpFrom = signIpScopeSingle.substring(0, signIpScopeSingle.indexOf("-")); + signIpFrom = Util.null2String(signIpFrom).trim(); + String signIpTo = ""; + if (!signIpScopeSingle.endsWith("-")) { + signIpTo = signIpScopeSingle.substring(signIpScopeSingle.indexOf("-") + 1); + } + signIpTo = Util.null2String(signIpTo).trim(); + String tempClientAddress = IpUtils.parseAbbreviationToFullIPv6(clientAddress); + signIpFrom = addToThreeFigure(signIpFrom, "signIpFrom"); + signIpTo = addToThreeFigure(signIpTo, "signIpTo"); + + signIpFrom = IpUtils.parseAbbreviationToFullIPv6(signIpFrom); + signIpTo = IpUtils.parseAbbreviationToFullIPv6(signIpTo); + + if (signIpFrom.equals("") && signIpTo.equals("")) { + isInScope = true; + } + if (signIpFrom.equals("") && !signIpTo.equals("")) { + if (tempClientAddress.compareTo(signIpTo) <= 0) { + isInScope = true; + } + } + + if (!signIpFrom.equals("") && signIpTo.equals("")) { + if (tempClientAddress.compareTo(signIpFrom) >= 0) { + isInScope = true; + } + } + if (!signIpFrom.equals("") && !signIpTo.equals("")) { + if (tempClientAddress.compareTo(signIpFrom) >= 0 && tempClientAddress.compareTo(signIpTo) <= 0) { + isInScope = true; + } + } + } else { + String tempClientAddress = IpUtils.parseAbbreviationToFullIPv6(clientAddress); + if (tempClientAddress.equals(signIpScopeSingle)) { + isInScope = true; + } + } + return isInScope; + } + + public boolean checkIpV4(String signIpScopeSingle,String clientAddress) { + + boolean isInScope = false; + if (signIpScopeSingle.indexOf("*") > -1) {//如果单个ip范围的格式为10.*.*.* + List signIpScopeSingleList = Util.TokenizerString(signIpScopeSingle, "."); + List clientAddressList = Util.TokenizerString(clientAddress, "."); + if (signIpScopeSingleList.size() == 4 + && clientAddressList.size() == 4 + && ("*".equals((String) signIpScopeSingleList.get(0)) + || Util.null2String((String) clientAddressList.get(0)).equals((String) signIpScopeSingleList.get(0))) + && ("*".equals((String) signIpScopeSingleList.get(1)) + || Util.null2String((String) clientAddressList.get(1)).equals((String) signIpScopeSingleList.get(1))) + && ("*".equals((String) signIpScopeSingleList.get(2)) + || Util.null2String((String) clientAddressList.get(2)).equals((String) signIpScopeSingleList.get(2))) + && ("*".equals((String) signIpScopeSingleList.get(3)) + || Util.null2String((String) clientAddressList.get(3)).equals((String) signIpScopeSingleList.get(2))) + ) { + isInScope = true; + } + } else if (signIpScopeSingle.indexOf("-") > -1) {//如果单个ip范围的格式为10.16.0.13-10.16.0.18 + String signIpFrom = signIpScopeSingle.substring(0, signIpScopeSingle.indexOf("-")); + signIpFrom = Util.null2String(signIpFrom).trim(); + String signIpTo = ""; + if (!signIpScopeSingle.endsWith("-")) { + signIpTo = signIpScopeSingle.substring(signIpScopeSingle.indexOf("-") + 1); + } + signIpTo = Util.null2String(signIpTo).trim(); + String tempClientAddress = addToThreeFigure(clientAddress, "clientAddress"); + signIpFrom = addToThreeFigure(signIpFrom, "signIpFrom"); + signIpTo = addToThreeFigure(signIpTo, "signIpTo"); + + if (signIpFrom.equals("") && signIpTo.equals("")) { + isInScope = true; + } + if (signIpFrom.equals("") && !signIpTo.equals("")) { + if (tempClientAddress.compareTo(signIpTo) <= 0) { + isInScope = true; + } + } + + if (!signIpFrom.equals("") && signIpTo.equals("")) { + if (tempClientAddress.compareTo(signIpFrom) >= 0) { + isInScope = true; + } + } + if (!signIpFrom.equals("") && !signIpTo.equals("")) { + if (tempClientAddress.compareTo(signIpFrom) >= 0 && tempClientAddress.compareTo(signIpTo) <= 0) { + isInScope = true; + } + } + } else {//否则单个ip范围的格式为10.16.0.12 + if (clientAddress.equals(signIpScopeSingle)) { + isInScope = true; + } + } + return isInScope; + } + + + /** + * 校验ip范围 + * @param clientAddress + * @return + */ + public boolean getIsInScope(String userId, String clientAddress) { + boolean isInScope = false; + clientAddress = Util.null2String(clientAddress).trim(); + if (clientAddress.length() == 0) { + return isInScope; + } + + RecordSet rs = new RecordSet(); + KQGroupComInfo kqGroupComInfo = new KQGroupComInfo(); + KQGroupMemberComInfo kqGroupMemberComInfo = new KQGroupMemberComInfo(); + String groupid = Util.null2String(kqGroupMemberComInfo.getKQGroupId(userId)); + String signIpScope = Util.null2String(kqGroupComInfo.getIpscope(groupid)).trim();//格式:10.*.*.*;10.16.0.12;10.16.0.13-10.16.0.18 + if (signIpScope.length() == 0) { + return true; + } + + List signIpScopeList = Util.TokenizerString(signIpScope, ";"); + String signIpScopeSingle = ""; + for (int i = 0; i < signIpScopeList.size(); i++) { + signIpScopeSingle = Util.null2String((String) signIpScopeList.get(i)); + signIpScopeSingle = signIpScopeSingle.trim(); + if (signIpScopeSingle.indexOf("*") > -1) {//如果单个ip范围的格式为10.*.*.* + List signIpScopeSingleList = Util.TokenizerString(signIpScopeSingle, "."); + List clientAddressList = Util.TokenizerString(clientAddress, "."); + if (signIpScopeSingleList.size() == 4 + && clientAddressList.size() == 4 + && ("*".equals((String) signIpScopeSingleList.get(0)) + || Util.null2String((String) clientAddressList.get(0)).equals((String) signIpScopeSingleList.get(0))) + && ("*".equals((String) signIpScopeSingleList.get(1)) + || Util.null2String((String) clientAddressList.get(1)).equals((String) signIpScopeSingleList.get(1))) + && ("*".equals((String) signIpScopeSingleList.get(2)) + || Util.null2String((String) clientAddressList.get(2)).equals((String) signIpScopeSingleList.get(2))) + && ("*".equals((String) signIpScopeSingleList.get(3)) + || Util.null2String((String) clientAddressList.get(3)).equals((String) signIpScopeSingleList.get(2))) + ) { + isInScope = true; + break; + } + + } else if (signIpScopeSingle.indexOf("-") > -1) {//如果单个ip范围的格式为10.16.0.13-10.16.0.18 + String signIpFrom = signIpScopeSingle.substring(0, signIpScopeSingle.indexOf("-")); + signIpFrom = Util.null2String(signIpFrom).trim(); + String signIpTo = ""; + if (!signIpScopeSingle.endsWith("-")) { + signIpTo = signIpScopeSingle.substring(signIpScopeSingle.indexOf("-") + 1); + } + signIpTo = Util.null2String(signIpTo).trim(); + String tempClientAddress = addToThreeFigure(clientAddress, "clientAddress"); + signIpFrom = addToThreeFigure(signIpFrom, "signIpFrom"); + signIpTo = addToThreeFigure(signIpTo, "signIpTo"); + + if (signIpFrom.equals("") && signIpTo.equals("")) { + isInScope = true; + break; + } + if (signIpFrom.equals("") && !signIpTo.equals("")) { + if (tempClientAddress.compareTo(signIpTo) <= 0) { + isInScope = true; + break; + } + } + + if (!signIpFrom.equals("") && signIpTo.equals("")) { + if (tempClientAddress.compareTo(signIpFrom) >= 0) { + isInScope = true; + break; + } + } + if (!signIpFrom.equals("") && !signIpTo.equals("")) { + if (tempClientAddress.compareTo(signIpFrom) >= 0 && tempClientAddress.compareTo(signIpTo) <= 0) { + isInScope = true; + break; + } + } + } else {//否则单个ip范围的格式为10.16.0.12 + if (clientAddress.equals(signIpScopeSingle)) { + isInScope = true; + break; + } + } + } + return isInScope; + } + /** + * 将IP地址填充为3位数 + * 如 "192.168.0.25"填充为3位数后为"192.168.000.025" + * @return String 填充为3位数后的IP地址 + */ + private String addToThreeFigure(String IPAddress, String IPType) { + if (IPAddress == null || IPAddress.trim().equals("") || IPType == null || IPType.trim().equals("")) { + return ""; + } + String returnString = ""; + List IPAddressList = Util.TokenizerString(IPAddress, "."); + String IPAddressPart = ""; + for (int i = 0; i < IPAddressList.size(); i++) { + IPAddressPart = Util.null2String(IPAddressList.get(i)); + if (IPType.equals("signIpTo")) { + returnString += "." + Util.add0(Util.getIntValue(IPAddressPart, 255), 3); + } else { + returnString += "." + Util.add0(Util.getIntValue(IPAddressPart, 0), 3); + } + } + if (!returnString.equals("")) { + returnString = returnString.substring(1); + } + return returnString; + } +} \ No newline at end of file diff --git a/领悦二开new/src/com/engine/kq/biz/KQGroupComInfo.java b/领悦二开new/src/com/engine/kq/biz/KQGroupComInfo.java new file mode 100644 index 0000000..e2868af --- /dev/null +++ b/领悦二开new/src/com/engine/kq/biz/KQGroupComInfo.java @@ -0,0 +1,466 @@ +package com.engine.kq.biz; + +import weaver.cache.CacheBase; +import weaver.cache.CacheColumn; +import weaver.cache.CacheColumnType; +import weaver.cache.PKColumn; + +public class KQGroupComInfo extends CacheBase{ + protected static String TABLE_NAME = "kq_group"; + /** sql中的where信息,不要以where开始 */ + protected static String TABLE_WHERE = null; + /** sql中的order by信息,不要以order by开始 */ + protected static String TABLE_ORDER = "id"; + + @PKColumn(type = CacheColumnType.NUMBER) + protected static String PK_NAME = "id"; + + @CacheColumn(name = "groupname") + protected static int groupname; + + @CacheColumn(name = "excludeid") + protected static int excludeid; + + @CacheColumn(name = "excludecount") + protected static int excludecount; + + @CacheColumn(name = "subcompanyid") + protected static int subcompanyid; + + @CacheColumn(name = "kqtype") + protected static int kqtype; + + @CacheColumn(name = "serialids") + protected static int serialids; + + @CacheColumn(name = "weekday") + protected static int weekday; + + @CacheColumn(name = "signstart") + protected static int signstart; + + @CacheColumn(name = "workhour") + protected static int workhour; + + @CacheColumn(name = "isdelete") + protected static int isdelete; + + @CacheColumn(name = "signintype") + protected static int signintype; + + @CacheColumn(name = "ipscope") + protected static int ipscope; + + @CacheColumn(name = "locationcheck") + protected static int locationcheck; + + @CacheColumn(name = "locationcheckscope") + protected static int locationcheckscope; + + @CacheColumn(name = "wificheck") + protected static int wificheck; + + @CacheColumn(name = "outsidesign") + protected static int outsidesign; + + @CacheColumn(name = "outsignapprove") + protected static int outsignapprove; + + @CacheColumn(name = "validity") + protected static int validity; + + @CacheColumn(name = "validityfromdate") + protected static int validityfromdate; + + @CacheColumn(name = "validityenddate") + protected static int validityenddate; + + @CacheColumn(name = "locationfacecheck") + protected static int locationfacecheck; + + @CacheColumn(name = "locationfacechecktype") + protected static int locationfacechecktype; + + @CacheColumn(name = "locationshowaddress") + protected static int locationshowaddress; + + @CacheColumn(name = "wififacecheck") + protected static int wififacecheck; + + @CacheColumn(name = "wififacechecktype") + protected static int wififacechecktype; + + @CacheColumn(name = "ipscope_v4_pc") + protected static int ipscope_v4_pc; + + @CacheColumn(name = "ipscope_v4_em") + protected static int ipscope_v4_em; + + @CacheColumn(name = "ipscope_v6_pc") + protected static int ipscope_v6_pc; + + @CacheColumn(name = "ipscope_v6_em") + protected static int ipscope_v6_em; + + @CacheColumn(name = "auto_checkin") + protected static int auto_checkin; + + @CacheColumn(name = "auto_checkin_before") + protected static int auto_checkin_before; + + @CacheColumn(name = "auto_checkin_after") + protected static int auto_checkin_after; + + @CacheColumn(name = "auto_checkout") + protected static int auto_checkout; + + @CacheColumn(name = "auto_checkout_before") + protected static int auto_checkout_before; + + @CacheColumn(name = "auto_checkout_after") + protected static int auto_checkout_after; + + @CacheColumn(name = "calmethod") + protected static int calmethod; + + @CacheColumn(name = "isPhotoPunchEnabled") + protected static int isPhotoPunchEnabled; + + /** + * 启用员工自我排班 + */ + @CacheColumn(name = "self_shift") + protected static int self_shift; + /** + * 0表示默认统一设置,1表示按照班次设置 + */ + @CacheColumn(name = "overtime_type") + protected static int overtime_type; + + + @CacheColumn(name = "abnormalremind") + protected static int abnormalremind; + + public String getId() { + return (String) getRowValue(PK_INDEX); + } + + public String getGroupname() { + return (String) getRowValue(groupname); + } + + public String getGroupname(String key) { + return (String) getValue(groupname, key); + } + + public String getExcludeid() { + return (String) getRowValue(excludeid); + } + + public String getExcludeid(String key) { + return (String) getValue(excludeid, key); + } + + public String getExcludecount() { + return (String) getRowValue(excludecount); + } + + public String getExcludecount(String key) { + return (String) getValue(excludecount, key); + } + + public String getSubcompanyid() { + return (String) getRowValue(subcompanyid); + } + + public String getSubcompanyid(String key) { + return (String) getValue(subcompanyid, key); + } + + public String getKqtype() { + return (String) getRowValue(kqtype); + } + + public String getKqtype(String key) { + return (String) getValue(kqtype, key); + } + + public String getSerialids() { + return (String) getRowValue(serialids); + } + + public String getSerialids(String key) { + return (String) getValue(serialids, key); + } + + public String getWeekday() { + return (String) getRowValue(weekday); + } + + public String getWeekday(String key) { + return (String) getValue(weekday, key); + } + + public String getSignstart() { + return (String) getRowValue(signstart); + } + + public String getSignstart(String key) { + return (String) getValue(signstart, key); + } + + public String getWorkhour() { + return (String) getRowValue(workhour); + } + + public String getWorkhour(String key) { + return (String) getValue(workhour, key); + } + + public String getIsdelete() { + return (String) getRowValue(isdelete); + } + + public String getIsdelete(String key) { + return (String) getValue(isdelete, key); + } + + public String getSignintype() { + return (String) getRowValue(signintype); + } + + public String getSignintype(String key) { + return (String) getValue(signintype, key); + } + + public String getIpscope() { + return (String) getRowValue(ipscope); + } + + public String getIpscope(String key) { + return (String) getValue(ipscope, key); + } + + public String getLocationcheck() { + return (String) getRowValue(locationcheck); + } + + public String getLocationcheck(String key) { + return (String) getValue(locationcheck, key); + } + + public String getLocationcheckscope() { + return (String) getRowValue(locationcheckscope); + } + + public String getLocationcheckscope(String key) { + return (String) getValue(locationcheckscope, key); + } + + public String getWificheck() { + return (String) getRowValue(wificheck); + } + + public String getWificheck(String key) { + return (String) getValue(wificheck, key); + } + + public String getOutsidesign() { + return (String) getRowValue(outsidesign); + } + + public String getOutsidesign(String key) { + return (String) getValue(outsidesign, key); + } + + public String getOutsignApprove() { + return (String) getRowValue(outsignapprove); + } + + public String getOutsignApprove(String key) { + return (String) getValue(outsignapprove, key); + } + + public String getValidity() { + return (String) getRowValue(validity); + } + + public String getValidity(String key) { + return (String) getValue(validity, key); + } + + public String getValidityfromdate() { + return (String) getRowValue(validityfromdate); + } + + public String getValidityfromdate(String key) { + return (String) getValue(validityfromdate, key); + } + + public String getValidityenddate() { + return (String) getRowValue(validityenddate); + } + + public String getValidityenddate(String key) { + return (String) getValue(validityenddate, key); + } + + public String getLocationfacecheck() { + return (String) getRowValue(locationfacecheck); + } + + public String getLocationfacecheck(String key) { + return (String) getValue(locationfacecheck, key); + } + + public String getLocationfacechecktype() { + return (String) getRowValue(locationfacechecktype); + } + + public String getLocationfacechecktype(String key) { + return (String) getValue(locationfacechecktype, key); + } + + public String getLocationshowaddress() { + return (String) getRowValue(locationshowaddress); + } + + public String getLocationshowaddress(String key) { + return (String) getValue(locationshowaddress, key); + } + + public String getWififacecheck() { + return (String) getRowValue(wififacecheck); + } + + public String getWififacecheck(String key) { + return (String) getValue(wififacecheck, key); + } + + public String getWififacechecktype() { + return (String) getRowValue(wififacechecktype); + } + + public String getWififacechecktype(String key) { + return (String) getValue(wififacechecktype, key); + } + + public String getIpscope_v4_pc() { + return (String) getRowValue(ipscope_v4_pc); + } + + public String getIpscope_v4_pc(String key) { + return (String) getValue(ipscope_v4_pc, key); + } + + public String getIpscope_v4_em() { + return (String) getRowValue(ipscope_v4_em); + } + + public String getIpscope_v4_em(String key) { + return (String) getValue(ipscope_v4_em, key); + } + + public String getIpscope_v6_pc() { + return (String) getRowValue(ipscope_v6_pc); + } + + public String getIpscope_v6_pc(String key) { + return (String) getValue(ipscope_v6_pc, key); + } + + public String getIpscope_v6_em() { + return (String) getRowValue(ipscope_v6_em); + } + + public String getIpscope_v6_em(String key) { + return (String) getValue(ipscope_v6_em, key); + } + + public String getAuto_checkin() { + return (String) getRowValue(auto_checkin); + } + + public String getAuto_checkin(String key) { + return (String) getValue(auto_checkin, key); + } + + public String getAuto_checkin_before() { + return (String) getRowValue(auto_checkin_before); + } + + public String getAuto_checkin_before(String key) { + return (String) getValue(auto_checkin_before, key); + } + + public String getAuto_checkin_after() { + return (String) getRowValue(auto_checkin_after); + } + + public String getAuto_checkin_after(String key) { + return (String) getValue(auto_checkin_after, key); + } + + public String getAuto_checkout() { + return (String) getRowValue(auto_checkout); + } + + public String getAuto_checkout(String key) { + return (String) getValue(auto_checkout, key); + } + + public String getAuto_checkout_before() { + return (String) getRowValue(auto_checkout_before); + } + + public String getAuto_checkout_before(String key) { + return (String) getValue(auto_checkout_before, key); + } + + public String getAuto_checkout_after() { + return (String) getRowValue(auto_checkout_after); + } + + public String getAuto_checkout_after(String key) { + return (String) getValue(auto_checkout_after, key); + } + + public String getOvertime_type() { + return (String) getRowValue(overtime_type); + } + + public String getOvertime_type(String key) { + return (String) getValue(overtime_type, key); + } + + public String getCalmethod() { + return (String) getRowValue(calmethod); + } + + public String getCalmethod(String key) { + return (String) getValue(calmethod, key); + } + + public String getSelf_shift() { + return (String) getRowValue(self_shift); + } + + public String getSelf_shift(String key) { + return (String) getValue(self_shift, key); + } + + public String getIsPhotoPunchEnabled() { + return (String) getRowValue(isPhotoPunchEnabled); + } + + public String getIsPhotoPunchEnabled(String key) { + return (String) getValue(isPhotoPunchEnabled, key); + } + public String getAbnormalremind() { + return (String)getRowValue(abnormalremind); + } + + public String getAbnormalremind(String key) { + return (String)getValue(abnormalremind,key); + } +} \ No newline at end of file diff --git a/领悦二开new/src/com/engine/kq/biz/KQGroupMemberComInfo.java b/领悦二开new/src/com/engine/kq/biz/KQGroupMemberComInfo.java new file mode 100644 index 0000000..9452fbf --- /dev/null +++ b/领悦二开new/src/com/engine/kq/biz/KQGroupMemberComInfo.java @@ -0,0 +1,981 @@ +package com.engine.kq.biz; + +import com.engine.kq.entity.KQGroupEntity; +import com.engine.kq.log.KQLog; +import weaver.cache.*; +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.general.StaticObj; +import weaver.general.Util; +import weaver.hrm.resource.ResourceComInfo; + +import java.io.Serializable; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; + +public class KQGroupMemberComInfo extends CacheBase implements Serializable { + /* + * 需要关注 : 如果完全在 initCache 自己定义数据初始化, 这个字段可以不定义 + */ + protected static String TABLE_NAME = ""; + + /* + * 需要关注 : 如果完全在 initCache 自己定义数据初始化,或者不需要指定固定的条件, 这个字段可以不定义 + * sql中的where信息,不要以where开始 + */ + protected static String TABLE_WHERE = null; + + /* + * 需要关注 : 如果完全在 initCache 自己定义数据初始化,或者不需要指定顺序, 这个字段可以不定义 sql中的order + * by信息,不要以order by开始 + * + */ + protected static String TABLE_ORDER = null; + + @PKColumn(type = CacheColumnType.NUMBER) + protected static String PK_NAME = "id"; + + @CacheColumn + protected static int group; + + private KQLog kqLog = new KQLog(); + + private boolean isFormat = false; + + @Override + protected boolean autoInitIfNotFound() { + return false; + } + + private StaticObj staticobj = null; + + @Override + public CacheItem initCache(String key) { + + if (key == null || "".equals(key.trim())) { + return null; + } + + RecordSet rs = new RecordSet(); + String sql = ""; + kqLog = new KQLog(); + ConcurrentHashMap resourceKQGroups = new ConcurrentHashMap<>(); + //考勤组优先级 + try { + ResourceComInfo resourceComInfo = new ResourceComInfo(); + + String subcompanyid = Util.null2String(resourceComInfo.getSubCompanyID(key));//分部 + String departmentid = Util.null2String(resourceComInfo.getDepartmentID(key));//部门 + String jobtitle = Util.null2String(resourceComInfo.getJobTitle(key));//岗位 + + //人员 + sql = " SELECT distinct a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b, kq_group c " + + " WHERE a.id=b.typevalue and b.type =1 and b.groupid=c.id and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1')" + + " and a.id = "+key+ + " order by b.groupid desc "; + rs.executeQuery(sql); + while (rs.next()) { + setMemberGroup(resourceKQGroups, rs.getString("resourceid"), rs.getString("groupid")); + } + + //部门 + if(departmentid.length()>0) { + sql = " SELECT distinct a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b , kq_group c" + + " WHERE a.departmentid = b.typevalue AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto AND b.type=3 " + + " and b.groupid=c.id and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1') " + + " and a.departmentid = " + departmentid + + " and a.id="+key+ + " order by b.groupid desc"; + rs.executeQuery(sql); + while (rs.next()) { + setMemberGroup(resourceKQGroups, rs.getString("resourceid"), rs.getString("groupid")); + } + } + + //分部 + if(subcompanyid.length()>0) { + sql = " SELECT distinct a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b, kq_group c " + + " WHERE a.subcompanyid1 = b.typevalue AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto AND b.type=2 " + + " and b.groupid=c.id and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1') " + + " and a.subcompanyid1 = " + subcompanyid + + " and a.id="+key+ + " order by b.groupid desc "; + rs.executeQuery(sql); + while (rs.next()) { + setMemberGroup(resourceKQGroups, rs.getString("resourceid"), rs.getString("groupid")); + } + } + + //岗位 + if(jobtitle.length()>0) { + sql = " SELECT distinct a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b, kq_group c " + + " WHERE a.jobtitle = b.typevalue AND b.type=5 " + + " AND (b.jobtitlelevel=1 OR (b.jobtitlelevel=2 AND a.subcompanyid1 IN(b.jobtitlelevelvalue)) OR (b.jobtitlelevel=3 AND a.departmentid IN(b.jobtitlelevelvalue))) " + + " and b.groupid=c.id and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1') " + + " and a.jobtitle = " + jobtitle + + " and a.id="+key+ + " order by b.groupid desc "; + rs.executeQuery(sql); + while (rs.next()) { + setMemberGroup(resourceKQGroups, rs.getString("resourceid"), rs.getString("groupid")); + } + } + + //所有人 + sql = " SELECT distinct a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b, kq_group c " + + " WHERE (b.type=6 AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto) and b.groupid=c.id " + + " and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1') " + + " and a.id = "+key+ + " order by b.groupid desc "; + rs.executeQuery(sql); + while (rs.next()) { + setMemberGroup(resourceKQGroups, rs.getString("resourceid"), rs.getString("groupid")); + } + + if(resourceKQGroups.size()>0){ + CacheItem cacheItem = createCacheItem(); + Iterator> iterator = resourceKQGroups.entrySet().iterator(); + while (iterator.hasNext()) { + Map.Entry entry = iterator.next(); + String id = entry.getKey(); + List value = entry.getValue(); + cacheItem.set(PK_INDEX, id); + cacheItem.set(group, value); + modifyCacheItem(key, cacheItem); + } + return cacheItem; + } + } catch (Exception e) { + kqLog.info(e); + } + return null; + } + + private void getHasValidateGroupInfo() { + RecordSet rs = new RecordSet(); + String backFields = " b.groupid, b.typevalue, b.validatefrom as validatefrom, b.validateto as validateto,b.seclevel as groupseclevel,b.seclevelto as groupseclevelto "; + String sqlWhere = " and ((validatefrom <>'"+KQGroupBiz.GROUPMEMBER_VALIDATE_FROMDATE+"') or (validateto <>'"+KQGroupBiz.GROUPMEMBER_VALIDATE_TODATE+"'))"; + //人员 + String sql = " SELECT "+backFields+" FROM HrmResource a, kq_groupmember b, kq_group c " + + " WHERE a.id=b.typevalue and b.type =1 and b.groupid=c.id and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1')" + + sqlWhere + " order by b.groupid desc "; + rs.executeQuery(sql); +// rs.writeLog("sql:::::::::"+sql); + List userGroupList = null; + while (rs.next()) { + String param = "type#1#"+rs.getString("typevalue"); + String groupId = rs.getString("groupid"); + String validatefrom = Util.null2String(rs.getString("validatefrom"), KQGroupBiz.GROUPMEMBER_VALIDATE_FROMDATE); + String validateto = Util.null2String(rs.getString("validateto"), KQGroupBiz.GROUPMEMBER_VALIDATE_TODATE); + String valueParam = groupId+"#"+validatefrom+"#"+validateto; + if(staticobj.getObject("User&GroupMember") == null) { + userGroupList = new ArrayList<>(); + } else { + userGroupList = (List)staticobj.getRecordFromObj("User&GroupMember",param); + if(userGroupList == null) { + userGroupList = new ArrayList<>(); + } + } + if(!userGroupList.contains(valueParam)) { + userGroupList.add(valueParam); + staticobj.putRecordToObj("User&GroupMember",param,userGroupList); + } +// rs.writeLog("userGroupList:::::::::"+JSON.toJSONString(userGroupList)); + } + //部门 + sql = " SELECT "+backFields+" FROM HrmResource a, kq_groupmember b , kq_group c" + + " WHERE a.departmentid = b.typevalue AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto AND b.type=3 " + + " and b.groupid=c.id and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1') " + + sqlWhere + + " order by b.groupid desc"; + rs.executeQuery(sql); + List departGroupList = null; + while (rs.next()) { + String param = "type#3#"+rs.getString("typevalue"); + String groupId = rs.getString("groupid"); + String validatefrom = Util.null2String(rs.getString("validatefrom"), KQGroupBiz.GROUPMEMBER_VALIDATE_FROMDATE); + String validateto = Util.null2String(rs.getString("validateto"), KQGroupBiz.GROUPMEMBER_VALIDATE_TODATE); + String groupseclevel = Util.null2String(rs.getString("groupseclevel")); + String groupseclevelto = Util.null2String(rs.getString("groupseclevelto")); + String valueParam = groupId+"#"+validatefrom+"#"+validateto+"#"+groupseclevel+"#"+groupseclevelto; + if(staticobj.getObject("Department&GroupMember") == null) { + departGroupList = new ArrayList<>(); + } else { + departGroupList = (List)staticobj.getRecordFromObj("Department&GroupMember",param); + if(departGroupList == null) { + departGroupList = new ArrayList<>(); + } + } + if(!departGroupList.contains(valueParam)) { + departGroupList.add(valueParam); + staticobj.putRecordToObj("Department&GroupMember",param,departGroupList); + } + } + //分部 + sql = " SELECT "+backFields+" FROM HrmResource a, kq_groupmember b, kq_group c " + + " WHERE a.subcompanyid1 = b.typevalue AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto AND b.type=2 " + + " and b.groupid=c.id and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1') " + + sqlWhere + + " order by b.groupid desc "; + rs.executeQuery(sql); + List subCompanyGroupList = null; + while (rs.next()) { + String param = "type#2#"+rs.getString("typevalue"); + String groupId = rs.getString("groupid"); + String validatefrom = Util.null2String(rs.getString("validatefrom"), KQGroupBiz.GROUPMEMBER_VALIDATE_FROMDATE); + String validateto = Util.null2String(rs.getString("validateto"), KQGroupBiz.GROUPMEMBER_VALIDATE_TODATE); + String groupseclevel = Util.null2String(rs.getString("groupseclevel")); + String groupseclevelto = Util.null2String(rs.getString("groupseclevelto")); + String valueParam = groupId+"#"+validatefrom+"#"+validateto+"#"+groupseclevel+"#"+groupseclevelto; + if(staticobj.getObject("SubCompany&GroupMember") == null) { + subCompanyGroupList = new ArrayList<>(); + } else { + subCompanyGroupList = (List)staticobj.getRecordFromObj("SubCompany&GroupMember",param); + if(subCompanyGroupList == null) { + subCompanyGroupList = new ArrayList<>(); + } + } + if(!subCompanyGroupList.contains(valueParam)) { + subCompanyGroupList.add(valueParam); + staticobj.putRecordToObj("SubCompany&GroupMember",param,subCompanyGroupList); + } + } + //岗位 + sql = " SELECT "+backFields+" FROM HrmResource a, kq_groupmember b, kq_group c " + + " WHERE a.jobtitle = b.typevalue AND b.type=5 " + + " AND (b.jobtitlelevel=1 OR (b.jobtitlelevel=2 AND a.subcompanyid1 IN(b.jobtitlelevelvalue)) OR (b.jobtitlelevel=3 AND a.departmentid IN(b.jobtitlelevelvalue))) " + + " and b.groupid=c.id and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1') " + + sqlWhere + + " order by b.groupid desc "; + rs.executeQuery(sql); + List jobtitleGroupList = null; + while (rs.next()) { + String param = "type#5#"+rs.getString("typevalue"); + String groupId = rs.getString("groupid"); + String validatefrom = Util.null2String(rs.getString("validatefrom"), KQGroupBiz.GROUPMEMBER_VALIDATE_FROMDATE); + String validateto = Util.null2String(rs.getString("validateto"), KQGroupBiz.GROUPMEMBER_VALIDATE_TODATE); + String groupseclevel = Util.null2String(rs.getString("groupseclevel")); + String groupseclevelto = Util.null2String(rs.getString("groupseclevelto")); + String valueParam = groupId+"#"+validatefrom+"#"+validateto+"#"+groupseclevel+"#"+groupseclevelto; + if(staticobj.getObject("Jobtitle&GroupMember") == null) { + jobtitleGroupList = new ArrayList<>(); + } else { + jobtitleGroupList = (List)staticobj.getRecordFromObj("Jobtitle&GroupMember",param); + if(jobtitleGroupList == null) { + jobtitleGroupList = new ArrayList<>(); + } + } + if(!jobtitleGroupList.contains(valueParam)) { + jobtitleGroupList.add(valueParam); + staticobj.putRecordToObj("Jobtitle&GroupMember",param,jobtitleGroupList); + } + } + //所有人 + sql = " SELECT "+backFields+" FROM HrmResource a, kq_groupmember b, kq_group c " + + " WHERE (b.type=6 AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto) and b.groupid=c.id " + + " and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1') " + + sqlWhere + + " order by b.groupid desc "; + rs.executeQuery(sql); + rs.executeQuery(sql); + List allGroupList = null; + while (rs.next()) { + String param = "type#6#"+rs.getString("typevalue"); + String groupId = rs.getString("groupid"); + String validatefrom = Util.null2String(rs.getString("validatefrom"), KQGroupBiz.GROUPMEMBER_VALIDATE_FROMDATE); + String validateto = Util.null2String(rs.getString("validateto"), KQGroupBiz.GROUPMEMBER_VALIDATE_TODATE); + String groupseclevel = Util.null2String(rs.getString("groupseclevel")); + String groupseclevelto = Util.null2String(rs.getString("groupseclevelto")); + String valueParam = groupId+"#"+validatefrom+"#"+validateto+"#"+groupseclevel+"#"+groupseclevelto; + if(staticobj.getObject("All&GroupMember") == null) { + allGroupList = new ArrayList<>(); + } else { + allGroupList = (List)staticobj.getRecordFromObj("All&GroupMember",param); + if(allGroupList == null) { + allGroupList = new ArrayList<>(); + } + } + if(!allGroupList.contains(valueParam)) { + allGroupList.add(valueParam); + staticobj.putRecordToObj("All&GroupMember",param,allGroupList); + } + } + } + + @Override + public CacheMap initCache() { +// writeLog("KQGroupMemberComInfo::::::in:::::::2222::::::"); + staticobj = StaticObj.getInstance(); + staticobj.removeObject("User&GroupMember"); + staticobj.removeObject("Department&GroupMember"); + staticobj.removeObject("SubCompany&GroupMember"); + staticobj.removeObject("Jobtitle&GroupMember"); + staticobj.removeObject("All&GroupMember"); + getHasValidateGroupInfo(); + + CacheMap localData = createCacheMap(); + RecordSet rs = new RecordSet(); + String sql = ""; + kqLog = new KQLog(); + ConcurrentHashMap resourceKQGroups = new ConcurrentHashMap<>(); + //考勤组优先级 + try { + //人员 + sql = " SELECT distinct a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b, kq_group c " + + " WHERE a.id=b.typevalue and b.type =1 and b.groupid=c.id and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1') order by b.groupid desc "; + rs.executeQuery(sql); + while (rs.next()) { + setMemberGroup(resourceKQGroups, rs.getString("resourceid"), rs.getString("groupid")); + } + + //部门 + sql = " SELECT distinct a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b , kq_group c" + + " WHERE a.departmentid = b.typevalue AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto AND b.type=3 " + + " and b.groupid=c.id and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1') order by b.groupid desc"; + rs.executeQuery(sql); + while (rs.next()) { + setMemberGroup(resourceKQGroups, rs.getString("resourceid"), rs.getString("groupid")); + } + + //分部 + sql = " SELECT distinct a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b, kq_group c " + + " WHERE a.subcompanyid1 = b.typevalue AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto AND b.type=2 " + + " and b.groupid=c.id and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1') order by b.groupid desc "; + rs.executeQuery(sql); + while (rs.next()) { + setMemberGroup(resourceKQGroups, rs.getString("resourceid"), rs.getString("groupid")); + } + + //岗位 + sql = " SELECT distinct a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b, kq_group c " + + " WHERE a.jobtitle = b.typevalue AND b.type=5 " + + " AND (b.jobtitlelevel=1 OR (b.jobtitlelevel=2 AND a.subcompanyid1 IN(b.jobtitlelevelvalue)) OR (b.jobtitlelevel=3 AND a.departmentid IN(b.jobtitlelevelvalue))) " + + " and b.groupid=c.id and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1') order by b.groupid desc "; + rs.executeQuery(sql); + while (rs.next()) { + setMemberGroup(resourceKQGroups, rs.getString("resourceid"), rs.getString("groupid")); + } + + //所有人 + sql = " SELECT distinct a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b, kq_group c " + + " WHERE (b.type=6 AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto) and b.groupid=c.id " + + " and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1') order by b.groupid desc "; + rs.executeQuery(sql); + while (rs.next()) { + setMemberGroup(resourceKQGroups, rs.getString("resourceid"), rs.getString("groupid")); + } + + if(resourceKQGroups.size()>0) { + Iterator> iterator = resourceKQGroups.entrySet().iterator(); + while (iterator.hasNext()) { + Map.Entry entry = iterator.next(); + String id = entry.getKey(); + List value = entry.getValue(); + CacheItem cacheItem = createCacheItem(); + cacheItem.set(PK_INDEX, id); + cacheItem.set(group, value); + modifyCacheItem(id, cacheItem); + localData.put(id, cacheItem); + } + } + } catch (Exception e) { + kqLog.writeLog(e); + } + return localData; + } + + private void setMemberGroup(ConcurrentHashMap resourceKQGroups, String resourceid, String groupid) { + try { + List kqGroups = null; + if (resourceKQGroups.get(resourceid) == null) { + kqGroups = new ArrayList<>(); + } else { + kqGroups = (List) resourceKQGroups.get(resourceid); + } + kqGroups.add(groupid); + resourceKQGroups.put(resourceid, kqGroups); + } catch (Exception e) { + kqLog.info(e); + } + } + + public String getKQGroupId(String userId) { + String workDate = DateUtil.getCurrentDate(); + return getKQGroupId(userId, workDate); + } + + /** + * 根据user获取考勤组id + * + * @param userId + * @return + */ + public String getKQGroupId(String userId, String workDate) { + return getKQGroupId(userId, workDate, true); + } + + /** + * 是否在考勤组的有效期范围内 + * @param tmpGroupId + * @param workDate + * @return + */ + private boolean isInKqGroupValidate(String tmpGroupId, String workDate) { + boolean flag = true; + KQGroupComInfo kqGroupComInfo = new KQGroupComInfo(); + String kqtype = kqGroupComInfo.getKqtype(tmpGroupId); + String validity = kqGroupComInfo.getValidity(tmpGroupId); + String validityfromdate = kqGroupComInfo.getValidityfromdate(tmpGroupId); + String validityenddate = kqGroupComInfo.getValidityenddate(tmpGroupId); + if (validity.equals("1")) { + if (!DateUtil.isInDateRange(workDate, validityfromdate, validityenddate)) { + flag = false; + } + } + return flag; + } + /*** + * 根据user获取考勤组id + * @param userId + * @param workDate + * @param containFixed 取不到排班取固定班 + * @return + */ + public String getKQGroupId(String userId, String workDate, boolean containFixed) { + String groupId = ""; + Map> allKqGroupsExceptSql = new HashMap<>(); + List kqGroups = getGroupBefore(userId, workDate, allKqGroupsExceptSql); + if(kqGroups.size() > 0) { + String tmpGroupId = kqGroups.get(0); + if(isInKqGroupValidate(tmpGroupId, workDate)) { + return tmpGroupId; + } + } + KQGroupComInfo kqGroupComInfo = new KQGroupComInfo(); + List lsGroupIds = this.getKQGroups(userId, workDate); + lsGroupIds.removeIf(allKqGroupsExceptSql::containsKey); + for (int i = 0; i < lsGroupIds.size(); i++) { + String tmpGroupId = Util.null2String((String) lsGroupIds.get(i)); + if(isInKqGroupValidate(tmpGroupId, workDate)) { + groupId = tmpGroupId; + } else { + continue; + } + String kqtype = kqGroupComInfo.getKqtype(tmpGroupId); +// String validity = kqGroupComInfo.getValidity(tmpGroupId); +// String validityfromdate = kqGroupComInfo.getValidityfromdate(tmpGroupId); +// String validityenddate = kqGroupComInfo.getValidityenddate(tmpGroupId); +// if (validity.equals("1")) { +// if (DateUtil.isInDateRange(workDate, validityfromdate, validityenddate)) { +// groupId = tmpGroupId; +// }else{ +// //超过有效期 +// continue; +// } +// } else { +// groupId = tmpGroupId; +// } + + //考勤组如果排班为空,取下一个考勤组 + if (groupId.length() > 0) { + if (containFixed && kqtype.equals("2")) { + KQShiftScheduleComInfo kqShiftScheduleComInfo = new KQShiftScheduleComInfo(); + kqShiftScheduleComInfo.setShiftGroupId(Util.getIntValue(groupId)); + if (Util.null2String(kqShiftScheduleComInfo.getSerialId(userId, workDate)).length() > 0 && + Util.null2String(kqShiftScheduleComInfo.getGroupId(userId, workDate)).equals(groupId)) { + break; + } + } else { + break; + } + } + } + return groupId; + } + + public List getKQGroups(String userId, String kqDate) { +// if(!this.isFormat){ +// return (List) getObjValue(group, userId); +// } + RecordSet rs = new RecordSet(); + String sql = ""; + kqLog = new KQLog(); + List kqGroups = new ArrayList<>(); +// Map> allKqGroupsExceptSql = new HashMap<>(); + //考勤组优先级 + try { +// Map> sqlWhereMap = sqlWhereMap(); + ResourceComInfo resourceComInfo = new ResourceComInfo(); +// kqGroups = getGroupBefore(userId, kqDate, allKqGroupsExceptSql); +// if(kqGroups.size() > 0) { +// return kqGroups; +// } + String subcompanyid = Util.null2String(resourceComInfo.getSubCompanyID(userId));//分部 + String departmentid = Util.null2String(resourceComInfo.getDepartmentID(userId));//部门 + String jobtitle = Util.null2String(resourceComInfo.getJobTitle(userId));//岗位 + String sqlWhere = " and ('"+kqDate+"' between b.validatefrom and b.validateto) "; +// if(rs.getDBType().equalsIgnoreCase("oracle")) { +// sqlWhere = " and ('"+kqDate+"' between nvl(b.validatefrom,'2000-01-01') and nvl(b.validateto,'2999-12-31')) "; +// }else if((rs.getDBType()).equalsIgnoreCase("mysql")){ +// sqlWhere = " and ('"+kqDate+"' between ifnull(b.validatefrom,'2000-01-01') and ifnull(b.validateto,'2999-12-31')) "; +// }else { +// sqlWhere = " and ('"+kqDate+"' between isnull(b.validatefrom,'2000-01-01') and isnull(b.validateto,'2999-12-31')) "; +// } + + //人员 + sql = " SELECT distinct a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b, kq_group c " + + " WHERE a.id=b.typevalue and b.type =1 and b.groupid=c.id and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1')" + + " and a.id = ?"+sqlWhere+ + " order by b.groupid desc "; + rs.executeQuery(sql,userId); + while (rs.next()) { + kqGroups.add(rs.getString("groupid")); + } + + //部门 + if(departmentid.length()>0) { + sql = " SELECT distinct a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b , kq_group c" + + " WHERE a.departmentid = b.typevalue AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto AND b.type=3 " + + " and b.groupid=c.id and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1') " + + " and a.departmentid = ? "+ + " and a.id= ? "+sqlWhere+ + " order by b.groupid desc"; + rs.executeQuery(sql,departmentid,userId); + while (rs.next()) { + kqGroups.add(rs.getString("groupid")); + } + } + + //分部 + if(subcompanyid.length()>0) { + sql = " SELECT distinct a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b, kq_group c " + + " WHERE a.subcompanyid1 = b.typevalue AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto AND b.type=2 " + + " and b.groupid=c.id and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1') " + + " and a.subcompanyid1 = ? " + + " and a.id= ? "+sqlWhere+ + " order by b.groupid desc "; + rs.executeQuery(sql,subcompanyid,userId); + while (rs.next()) { + kqGroups.add(rs.getString("groupid")); + } + } + + //岗位 + if(jobtitle.length()>0) { + sql = " SELECT distinct a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b, kq_group c " + + " WHERE a.jobtitle = b.typevalue AND b.type=5 " + + " AND (b.jobtitlelevel=1 OR (b.jobtitlelevel=2 AND a.subcompanyid1 IN(b.jobtitlelevelvalue)) OR (b.jobtitlelevel=3 AND a.departmentid IN(b.jobtitlelevelvalue))) " + + " and b.groupid=c.id and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1') " + + " and a.jobtitle = ? " + + " and a.id= ? "+sqlWhere+ + " order by b.groupid desc "; + rs.executeQuery(sql,jobtitle,userId); + while (rs.next()) { + kqGroups.add(rs.getString("groupid")); + } + } + + //所有人 + sql = " SELECT distinct a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b, kq_group c " + + " WHERE (b.type=6 AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto) and b.groupid=c.id " + + " and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1') " + + " and a.id = ? "+sqlWhere+ + " order by b.groupid desc "; + rs.executeQuery(sql,userId); + while (rs.next()) { + kqGroups.add(rs.getString("groupid")); + } + } catch (Exception e) { + kqLog.info(e); + } +// kqGroups.removeIf(allKqGroupsExceptSql::containsKey); + return kqGroups; + } + + /** + * 如果设置了有效期,且查询在有效期范围内的,直接用 + * @return + */ + private List getGroupBefore(String userId, String kqDate, Map> allKqGroupsExceptSql) { + StaticObj groupMemberStaticObj = StaticObj.getInstance(); + RecordSet rs = new RecordSet(); + List kqGroups = new ArrayList<>(); + try { + ResourceComInfo resourceComInfo = new ResourceComInfo(); + String subcompanyid = Util.null2String(resourceComInfo.getSubCompanyID(userId));//分部 + String departmentid = Util.null2String(resourceComInfo.getDepartmentID(userId));//部门 + String jobtitle = Util.null2String(resourceComInfo.getJobTitle(userId));//岗位 + // 人员 + String param = "type#1#"+userId; + if(groupMemberStaticObj.getObject("User&GroupMember") != null) { + List userGroupList = (List)groupMemberStaticObj.getRecordFromObj("User&GroupMember",param); +// writeLog("userGroupList::::"+ JSON.toJSONString(userGroupList)); + if(userGroupList != null) { + for (String userGourp : userGroupList) { + String groupId = userGourp.split("#")[0]; + handle(allKqGroupsExceptSql, groupId, userId, "resourceId"); + String validateFrom = userGourp.split("#")[1]; + String validateTo = userGourp.split("#")[2]; + if (kqDate.compareTo(validateFrom) >= 0 && kqDate.compareTo(validateTo) <= 0) { + kqGroups.add(groupId); + } + } + if (kqGroups.size() > 0) { + return kqGroups; + } + } + } + //部门 + if (departmentid.length() > 0) { + param = "type#3#" + departmentid; + if (groupMemberStaticObj.getObject("Department&GroupMember") != null) { + List departGroupList = (List) groupMemberStaticObj.getRecordFromObj("Department&GroupMember", param); +// writeLog("departGroupList::::" + JSON.toJSONString(departGroupList)); + if (departGroupList != null) { + for (String departGroup : departGroupList) { + String groupId = departGroup.split("#")[0]; + String validateFrom = departGroup.split("#")[1]; + String validateTo = departGroup.split("#")[2]; + String groupseclevel = departGroup.split("#")[3]; + String groupseclevelto = departGroup.split("#")[4]; + int userSeclevel = Util.getIntValue(resourceComInfo.getSeclevel(userId)); + if (kqDate.compareTo(validateFrom) >= 0 && kqDate.compareTo(validateTo) <= 0 && userSeclevel>=Util.getIntValue(groupseclevel) + && userSeclevel<=Util.getIntValue(groupseclevelto)) { + if (allKqGroupsExceptSql.containsKey(groupId)) { + continue; + } + handle(allKqGroupsExceptSql, groupId, departmentid, "departmentId"); + kqGroups.add(groupId); + } + } + } + if (kqGroups.size() > 0) { + return kqGroups; + } + } + } + + //分部 + if (subcompanyid.length() > 0) { + param = "type#2#" + subcompanyid; + if (groupMemberStaticObj.getObject("SubCompany&GroupMember") != null) { + List subCompanyGroupList = (List) groupMemberStaticObj.getRecordFromObj("SubCompany&GroupMember", param); +// writeLog("subCompanyGroupList::::" + JSON.toJSONString(subCompanyGroupList)); + if (subCompanyGroupList != null) { + for (String subCompanyGroup : subCompanyGroupList) { + String groupId = subCompanyGroup.split("#")[0]; + String validateFrom = subCompanyGroup.split("#")[1]; + String validateTo = subCompanyGroup.split("#")[2]; + String groupseclevel = subCompanyGroup.split("#")[3]; + String groupseclevelto = subCompanyGroup.split("#")[4]; + int userSeclevel = Util.getIntValue(resourceComInfo.getSeclevel(userId)); + if (kqDate.compareTo(validateFrom) >= 0 && kqDate.compareTo(validateTo) <= 0 && userSeclevel>=Util.getIntValue(groupseclevel) + && userSeclevel<=Util.getIntValue(groupseclevelto)) { + if (allKqGroupsExceptSql.containsKey(groupId)) { + continue; + } + handle(allKqGroupsExceptSql, groupId, subcompanyid, "subcompanyId"); + kqGroups.add(groupId); + } + } + } + if (kqGroups.size() > 0) { + return kqGroups; + } + } + } + + //岗位 + if (jobtitle.length() > 0) { + param = "type#5#" + jobtitle; + if (groupMemberStaticObj.getObject("Jobtitle&GroupMember") != null) { + List jobtitleGroupList = (List) groupMemberStaticObj.getRecordFromObj("Jobtitle&GroupMember", param); +// writeLog("jobtitleGroupList::::" + JSON.toJSONString(jobtitleGroupList)); + if (jobtitleGroupList != null) { + for (String jobtitleGroup : jobtitleGroupList) { + String groupId = jobtitleGroup.split("#")[0]; + String validateFrom = jobtitleGroup.split("#")[1]; + String validateTo = jobtitleGroup.split("#")[2]; + String groupseclevel = jobtitleGroup.split("#")[3]; + String groupseclevelto = jobtitleGroup.split("#")[4]; + int userSeclevel = Util.getIntValue(resourceComInfo.getSeclevel(userId)); + if (kqDate.compareTo(validateFrom) >= 0 && kqDate.compareTo(validateTo) <= 0 && userSeclevel>=Util.getIntValue(groupseclevel) + && userSeclevel<=Util.getIntValue(groupseclevelto)) { + if (allKqGroupsExceptSql.containsKey(groupId)) { + continue; + } + handle(allKqGroupsExceptSql, groupId, jobtitle, "jobtitleId"); + kqGroups.add(groupId); + } + } + } + if (kqGroups.size() > 0) { + return kqGroups; + } + } + } + + //所有人 + param = "type#6#0"; + if (groupMemberStaticObj.getObject("All&GroupMember") != null) { + List allGroupList = (List) groupMemberStaticObj.getRecordFromObj("All&GroupMember", param); +// writeLog("allGroupList::::" + JSON.toJSONString(allGroupList)); + if (allGroupList != null) { + for (String allGroup : allGroupList) { + String groupId = allGroup.split("#")[0]; + String validateFrom = allGroup.split("#")[1]; + String validateTo = allGroup.split("#")[2]; + String groupseclevel = allGroup.split("#")[3]; + String groupseclevelto = allGroup.split("#")[4]; + int userSeclevel = Util.getIntValue(resourceComInfo.getSeclevel(userId)); + if (kqDate.compareTo(validateFrom) >= 0 && kqDate.compareTo(validateTo) <= 0 && userSeclevel>=Util.getIntValue(groupseclevel) + && userSeclevel<=Util.getIntValue(groupseclevelto)) { + if (allKqGroupsExceptSql.containsKey(groupId)) { + continue; + } + handle(allKqGroupsExceptSql, groupId, "0", "all"); + kqGroups.add(groupId); + } + } + if (kqGroups.size() > 0) { + return kqGroups; + } + } + } + }catch (Exception e) { + writeLog(e); + } + return kqGroups; + } + + private Map> sqlWhereMap() { + // 先把所有的groupid找到 + RecordSet rs = new RecordSet(); + Map> allKqGroupsExceptSql = new HashMap<>(); + String sql = "select * from kq_groupmember where (isDelete is null or isDelete<>1)"; + rs.executeQuery(sql); + while (rs.next()) { + String groupId = rs.getString("id"); + int groupType = rs.getInt("type"); + String groupTypeValue = rs.getString("typevalue"); + + switch (groupType) { + case 1: + handle(allKqGroupsExceptSql, groupId, groupTypeValue, "resourceId"); + break; + case 2: + handle(allKqGroupsExceptSql, groupId, groupTypeValue, "subcompanyId"); + break; + case 3: + handle(allKqGroupsExceptSql, groupId, groupTypeValue, "departmentId"); + break; + case 5: + handle(allKqGroupsExceptSql, groupId, groupTypeValue, "jobTitleId"); + break; + case 6: + handle(allKqGroupsExceptSql, groupId, groupTypeValue, "all"); + break; + default: + break; + } + + } + return allKqGroupsExceptSql; + } + + private void handle(Map> allKqGroupsExceptSql, String groupId, String groupTypeValue, String key) { + Map sqlWhereMap = null; + String sqlWhereValue = groupTypeValue; + if(allKqGroupsExceptSql.containsKey(groupId)) { + sqlWhereMap = allKqGroupsExceptSql.get(groupId); + if (sqlWhereMap.containsKey(key)) { + sqlWhereValue = sqlWhereMap.get(key) + "," + groupTypeValue; + } + } else { + sqlWhereMap = new HashMap<>(); + } + sqlWhereMap.put(key, sqlWhereValue); + allKqGroupsExceptSql.put(groupId, sqlWhereMap); + } + /** + * 根据user获取所有考勤组 + * + * @param userId + * @return + */ + private List getKQGroups(String userId) { + if(!this.isFormat){ + return (List) getObjValue(group, userId); + } + RecordSet rs = new RecordSet(); + String sql = ""; + kqLog = new KQLog(); + List kqGroups = new ArrayList<>(); + //考勤组优先级 + try { + ResourceComInfo resourceComInfo = new ResourceComInfo(); + + String subcompanyid = Util.null2String(resourceComInfo.getSubCompanyID(userId));//分部 + String departmentid = Util.null2String(resourceComInfo.getDepartmentID(userId));//部门 + String jobtitle = Util.null2String(resourceComInfo.getJobTitle(userId));//岗位 + + //人员 + sql = " SELECT distinct a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b, kq_group c " + + " WHERE a.id=b.typevalue and b.type =1 and b.groupid=c.id and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1')" + + " and a.id = ?"+ + " order by b.groupid desc "; + rs.executeQuery(sql,userId); + while (rs.next()) { + kqGroups.add(rs.getString("groupid")); + } + + //部门 + if(departmentid.length()>0) { + sql = " SELECT distinct a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b , kq_group c" + + " WHERE a.departmentid = b.typevalue AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto AND b.type=3 " + + " and b.groupid=c.id and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1') " + + " and a.departmentid = ? "+ + " and a.id= ? "+ + " order by b.groupid desc"; + rs.executeQuery(sql,departmentid,userId); + while (rs.next()) { + kqGroups.add(rs.getString("groupid")); + } + } + + //分部 + if(subcompanyid.length()>0) { + sql = " SELECT distinct a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b, kq_group c " + + " WHERE a.subcompanyid1 = b.typevalue AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto AND b.type=2 " + + " and b.groupid=c.id and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1') " + + " and a.subcompanyid1 = ? " + + " and a.id= ? "+ + " order by b.groupid desc "; + rs.executeQuery(sql,subcompanyid,userId); + while (rs.next()) { + kqGroups.add(rs.getString("groupid")); + } + } + + //岗位 + if(jobtitle.length()>0) { + sql = " SELECT distinct a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b, kq_group c " + + " WHERE a.jobtitle = b.typevalue AND b.type=5 " + + " AND (b.jobtitlelevel=1 OR (b.jobtitlelevel=2 AND a.subcompanyid1 IN(b.jobtitlelevelvalue)) OR (b.jobtitlelevel=3 AND a.departmentid IN(b.jobtitlelevelvalue))) " + + " and b.groupid=c.id and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1') " + + " and a.jobtitle = ? " + + " and a.id= ? "+ + " order by b.groupid desc "; + rs.executeQuery(sql,jobtitle,userId); + while (rs.next()) { + kqGroups.add(rs.getString("groupid")); + } + } + + //所有人 + sql = " SELECT distinct a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b, kq_group c " + + " WHERE (b.type=6 AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto) and b.groupid=c.id " + + " and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1') " + + " and a.id = ? "+ + " order by b.groupid desc "; + rs.executeQuery(sql,userId); + while (rs.next()) { + kqGroups.add(rs.getString("groupid")); + } + } catch (Exception e) { + kqLog.info(e); + } + return kqGroups; + } + + /** + * 根据user获取所有考勤组id + * + * @param userId + * @return + */ + public String getKQGroupIds(String userId) { + String groupId = ""; + String kqDate = DateUtil.getCurrentDate(); + List lsGroupIds = this.getKQGroups(userId, kqDate); + if (lsGroupIds != null) { + groupId = String.join(",", lsGroupIds); + } + return groupId; + } + + public String getKQGroupIds(String userId, String kqDate) { + String groupId = ""; + List lsGroupIds = this.getKQGroups(userId, kqDate); + if (lsGroupIds != null) { + groupId = String.join(",", lsGroupIds); + } + return groupId; + } + + + public KQGroupEntity getUserKQGroupInfo(String userId) { + String workDate = DateUtil.getCurrentDate(); + return getUserKQGroupInfo(userId, workDate); + } + + /** + * 获取考勤组相关信息 + * + * @param userId + * @return + */ + public KQGroupEntity getUserKQGroupInfo(String userId, String workDate) { + return getUserKQGroupInfo(userId, workDate, true); + } + + /*** + * 获取考勤组相关信息 + * @param userId + * @param workDate + * @param containFixed 取不到排班取固定班 + * @return + */ + public KQGroupEntity getUserKQGroupInfo(String userId, String workDate, boolean containFixed) { + KQGroupEntity kqGroupEntity = null; + KQGroupComInfo kqGroupComInfo = new KQGroupComInfo(); + try { + String groupid = Util.null2String(this.getKQGroupId(userId, workDate, containFixed)); + if (groupid.length() > 0) { + kqGroupEntity = new KQGroupEntity(); + kqGroupEntity.setId(groupid); + kqGroupEntity.setGroupname(kqGroupComInfo.getGroupname(groupid)); + kqGroupEntity.setExcludeid(kqGroupComInfo.getExcludeid(groupid)); + kqGroupEntity.setSubcompanyid(kqGroupComInfo.getSubcompanyid(groupid)); + kqGroupEntity.setKqtype(kqGroupComInfo.getKqtype(groupid)); + kqGroupEntity.setSerialids(kqGroupComInfo.getSerialids(groupid)); + kqGroupEntity.setWeekday(kqGroupComInfo.getWeekday(groupid)); + kqGroupEntity.setSignstart(kqGroupComInfo.getSignstart(groupid)); + kqGroupEntity.setWorkhour(kqGroupComInfo.getWorkhour(groupid)); + kqGroupEntity.setIsdelete(kqGroupComInfo.getIsdelete(groupid)); + kqGroupEntity.setSignintype(kqGroupComInfo.getSignintype(groupid)); + kqGroupEntity.setIpscope(kqGroupComInfo.getIpscope(groupid)); + kqGroupEntity.setLocationcheck(kqGroupComInfo.getLocationcheck(groupid)); + kqGroupEntity.setLocationcheckscope(kqGroupComInfo.getLocationcheckscope(groupid)); + kqGroupEntity.setWificheck(kqGroupComInfo.getWificheck(groupid)); + kqGroupEntity.setOutsidesign(kqGroupComInfo.getOutsidesign(groupid)); + kqGroupEntity.setOutsignapprove(kqGroupComInfo.getOutsignApprove(groupid)); + kqGroupEntity.setCalmethod(kqGroupComInfo.getCalmethod(groupid)); + kqGroupEntity.setLocationshowaddress(kqGroupComInfo.getLocationshowaddress(groupid)); + kqGroupEntity.setAbnormalremind(kqGroupComInfo.getAbnormalremind(groupid)); + } + } catch (Exception e) { + kqLog.info(e); + } + return kqGroupEntity; + } + + public void removeCache() { + super.removeCache(); + + } + + public void setIsFormat(boolean isFormat){ + this.isFormat = isFormat; + } +} \ No newline at end of file diff --git a/领悦二开new/src/com/engine/kq/biz/KQHolidaySetBiz.java b/领悦二开new/src/com/engine/kq/biz/KQHolidaySetBiz.java new file mode 100644 index 0000000..f3560aa --- /dev/null +++ b/领悦二开new/src/com/engine/kq/biz/KQHolidaySetBiz.java @@ -0,0 +1,499 @@ +package com.engine.kq.biz; + +import com.engine.integration.util.MyX509TrustManager; +import com.engine.kq.log.KQLog; +import net.sf.json.JSONObject; +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.hrm.User; +import weaver.systeminfo.SystemEnv; + +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSocketFactory; +import javax.net.ssl.TrustManager; +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.util.*; + +/** + * 节假日设置相关接口数据 + */ +public class KQHolidaySetBiz { + + private static KQLog logger = new KQLog(); + + /** + * 获取指定考勤组ID获取节假日设置数据 + * + * @param resourceId 指定人员的ID + * @param year 指定年份 + * @param month 指定月份 指定月份为空时查询指定年份一整年的数据 + * @return + */ + public static List getGroupHolidaySetList(String groupId, String year, String month) { + List> valueList = new ArrayList>(); + Map valueMap = new HashMap(); + /*指定年月*/ + String startDate = year; + String endDate = month; + if (month.length() == 0) { + startDate = year + "-01" + "-01"; + endDate = year + "-12" + "-31"; + } else if (month.length() == 1) { + startDate = year + "-0" + month + "-01"; + endDate = year + "-0" + month + "-31"; + } else if (month.length() == 2) { + startDate = year + "-" + month + "-01"; + endDate = year + "-" + month + "-31"; + } + RecordSet recordSet = new RecordSet(); + KQGroupMemberComInfo kqGroupMemberComInfo = new KQGroupMemberComInfo(); + KQHolidaySetComInfo holidaySetComInfo = new KQHolidaySetComInfo(); + boolean isEnd = false; + for (String date = startDate; !isEnd; ) { + if (date.compareTo(endDate) >= 0) { + isEnd = true; + } + + String changeType = holidaySetComInfo.getChangeType(groupId, date); + String holidayDesc = holidaySetComInfo.getHolidayDesc(groupId, date); + if (!changeType.equals("")) { + valueMap = new HashMap(); + valueMap.put("date", date); + valueMap.put("name", holidayDesc); + valueMap.put("type", changeType); + valueList.add(valueMap); + } + date = DateUtil.getDate(date, 1); + } + return valueList; + } + + /** + * 获取指定考勤组ID获取节假日设置数据 + * + * @param resourceId 指定人员的ID + * @param year 指定年份 + * @param month 指定月份 指定月份为空时查询指定年份一整年的数据 + * @return + */ + public static List getKQHolidaySetList(String resourceId, String year, String month) { + + List> valueList = new ArrayList>(); + + /*指定年月*/ + String startDate = year; + String endDate = month; + if (month.length() == 0) { + startDate = year + "-01" + "-01"; + endDate = year + "-12" + "-31"; + } else if (month.length() == 1) { + startDate = year + "-0" + month + "-01"; + endDate = year + "-0" + month + "-31"; + } else if (month.length() == 2) { + startDate = year + "-" + month + "-01"; + endDate = year + "-" + month + "-31"; + } + valueList = getHolidaySetListByScope(resourceId, startDate, endDate); + return valueList; + } + + /** + * 根据日期范围获取节假日数据 + * + * @param resourceId 指定人员的ID + * @param startDate 指定日期范围的起点 + * @param endDate 指定日期范围的终点 + * @return + */ + public static List getHolidaySetListByScope(String resourceId, String startDate, String endDate) { + Map valueMap = new HashMap(); + List> valueList = new ArrayList>(); + + + KQGroupMemberComInfo kqGroupMemberComInfo = new KQGroupMemberComInfo(); + KQHolidaySetComInfo holidaySetComInfo = new KQHolidaySetComInfo(); + + boolean isEnd = false; + for (String date = startDate; !isEnd; ) { + if (date.compareTo(endDate) >= 0) { + isEnd = true; + } + + /*获取考勤组的ID,因为考勤组有有效期,所以需要传入日期*/ + String groupId = kqGroupMemberComInfo.getKQGroupId(resourceId, date); + + String changeType = holidaySetComInfo.getChangeType(groupId, date); + String holidayDesc = holidaySetComInfo.getHolidayDesc(groupId, date); + if (!changeType.equals("")&&!getWorkDay(resourceId, date)) { + valueMap = new HashMap(); + valueMap.put("date", date); + valueMap.put("name", holidayDesc); + valueMap.put("type", changeType); + valueList.add(valueMap); + } + date = DateUtil.getDate(date, 1); + } + return valueList; + } + + + /** + * 判断某天是否是节假日(公众假日+调配休息日) + * + * @param resourceId 指定人员ID + * @param date 指定日期 + * @return true-节假日、false、不是节假日 + */ + public static boolean isHoliday(String resourceId, String date) { + return isHoliday(resourceId, date, false); + } + + /** + * 判断某天是否是节假日(公众假日+调配休息日+周末) + * + * @param resourceId 指定人员ID + * @param date 指定日期 + * @param containWeekend 是否包含周末 为true包含周末、false不包含 + * @return true-节假日、false、不是节假日 + */ + public static boolean isHoliday(String resourceId, String date, boolean containWeekend) { + boolean flag = false; + if(getWorkDay(resourceId, date)){ + return flag; + } + /*获取考勤组的ID,因为考勤组有有效期,所以需要传入日期*/ + KQGroupMemberComInfo kqGroupMemberComInfo = new KQGroupMemberComInfo(); + String groupId = kqGroupMemberComInfo.getKQGroupId(resourceId, date); + + int changeType = getChangeType(groupId, date); + /*如果需要包含周末,判断传入的日期是不是周末*/ + if (containWeekend && changeType != 2 && (DateUtil.getWeek(date) == 6 || DateUtil.getWeek(date) == 7)) { + flag = true; + } + if (changeType == 1 || changeType == 3) { + flag = true; + } + return flag; + } + + /** + * 判断某天是否是节假日(公众假日+调配休息日+周末) + * + * @param resourceId 指定人员ID + * @param date 指定日期 + * @return true-节假日、false、不是节假日 + */ + public static boolean isDouble(String resourceId, String date) { + boolean flag = false; + /*获取考勤组的ID,因为考勤组有有效期,所以需要传入日期*/ + KQGroupMemberComInfo kqGroupMemberComInfo = new KQGroupMemberComInfo(); + String groupId = kqGroupMemberComInfo.getKQGroupId(resourceId, date); + + int changeType = getChangeType(groupId, date); + if (changeType == 1 || changeType == 3) { + flag = true; + } + return flag; + } + + /** + * 获取人员指定日期是否有排班的考勤排班:(当考勤组属于排班制时) + * + * @param resourceId 指定人员的ID + * @param date 指定日期 + * @return + */ + public static boolean getWorkDay(String resourceId, String date) { + boolean flag = false; + /*获取考勤组的ID,因为考勤组有有效期,所以需要传入日期*/ + KQGroupMemberComInfo kqGroupMemberComInfo = new KQGroupMemberComInfo(); + String groupId = kqGroupMemberComInfo.getKQGroupId(resourceId, date); + KQSettingsComInfo kqSettingsComInfo = new KQSettingsComInfo(); + String holiday_is_priority = Util.null2String(kqSettingsComInfo.getMain_val("holiday_is_priority"),"0"); + if("0".equals(holiday_is_priority)) { + return flag; + } + /*排班制不支持调配节假日数据*/ + KQGroupComInfo kqGroupComInfo = new KQGroupComInfo(); + String KQType = kqGroupComInfo.getKqtype(groupId);//考勤类型:1-固定班制、2-排班制、3-自由班制 + if (KQType.equals("2")) { + flag = true; + } + return flag; + } + /** + * 获取当前日期是何种类型(这里只考虑节假日设置) + * + * @param groupId 考勤组ID + * @param date 指定日期 + * @return 1-节假日、2-工作日、3-休息日、-1-没有设置过数据 + */ + public static int getChangeType(String groupId, String date) { + int changeType = -1;//默认没有设置过节假日(节假日设置的类型:1-公众假日、2-调配工作日、3-调配休息日) + KQHolidaySetComInfo kqHolidaySetComInfo = new KQHolidaySetComInfo(); + String tmpChangetype = kqHolidaySetComInfo.getChangeType(groupId, date); + if(null != tmpChangetype){ + changeType = Util.getIntValue(tmpChangetype, -1); + } + + return changeType; + } + + /** + * 获取调配工作日时的指定工作日(当考勤组不属于排班制时) + * + * @param resourceId 指定人员的ID + * @param date 指定日期 + * @return + */ + public static int getRelatedDay(String resourceId, String date) { + int relatedDay = -1; + + /*获取考勤组的ID,因为考勤组有有效期,所以需要传入日期*/ + KQGroupMemberComInfo kqGroupMemberComInfo = new KQGroupMemberComInfo(); + String groupId = kqGroupMemberComInfo.getKQGroupId(resourceId, date); + + /*排班制不支持调配节假日数据*/ + KQGroupComInfo kqGroupComInfo = new KQGroupComInfo(); + String KQType = kqGroupComInfo.getKqtype(groupId);//考勤类型:1-固定班制、2-排班制、3-自由班制 + if (KQType.equals("2")) { + return relatedDay; + } + + /*只有当调配工作日时才有对应工作日*/ + KQHolidaySetComInfo kqHolidaySetComInfo = new KQHolidaySetComInfo(); + int changeType = Util.getIntValue(kqHolidaySetComInfo.getChangeType(groupId, date), -1); + if (changeType == 2) { + relatedDay = Util.getIntValue(kqHolidaySetComInfo.getRelatedDay(groupId, date), 0); + } + + return relatedDay; + } + + /** + * 指定的考勤组初始化节假日设置数据(只初始化固定班制和自由班制) + * + * @param groupIds 指定考勤组ID(多个ID之间用,分隔) + * @param year 指定年份 + * @return + */ + public static Map initHolidaySet(String groupIds, String year, User user) { + Map resultMap = new HashMap(); + List errInfoList = new ArrayList();//错误信息集合 + /** + * 调用网上的节假日API,数据格式如下(不是JSON字符串):(此后如果原来的节假日API不能用了,只要调整将新的API接口调整成如下格式即可) + * status:1-成功、0-失败 + * sketch:'简要描述错误原因' + * holidayList:[{holidayDate:'',changeType:'',holidayDesc:''},……,{holidayDate:'',changeType:'',holidayDesc:''}] + */ + String url = Prop.getInstance().getPropValue("kq_settings", "KQHolidaySetUrl"); + Map tempMap = httpRequest(url +"?year="+year+"&key="+Util.getEncrypt(Util.getRandom()), user); + if ("0".equals((String) tempMap.get("status"))) { + resultMap.put("status", "0"); + resultMap.put("sketch", (String) tempMap.get("sketch")); + return resultMap; + } + List holidayDateList = new ArrayList(); + try { + List groupIdList = Util.TokenizerString(groupIds, ",");//考勤组ID集合 + for (int i = 0; i < groupIdList.size(); i++) { + String groupId = groupIdList.get(i); + /** + * 预先加载此考勤组已经调整了哪些日期了,如果某日期在初始化之前已经调整过了,删除掉原来的数据,插入新的数据 + */ + List dateList = new ArrayList(); + KQHolidaySetComInfo kqHolidaySetComInfo = new KQHolidaySetComInfo(); + kqHolidaySetComInfo.setTofirstRow(); + while (kqHolidaySetComInfo.next()) { + if (kqHolidaySetComInfo.getGroupId().equals(groupId)) { + dateList.add(kqHolidaySetComInfo.getHolidayDate()); + } + } + + /** + * 预先加载固定班制周一~周日这一周中一天开始上班的是周几 + */ + int relatedDay = 0; + for (int x = 0; x < 7; x++) { + KQFixedSchedulceComInfo kqFixedSchedulceComInfo = new KQFixedSchedulceComInfo(); + String serialId = Util.null2String(kqFixedSchedulceComInfo.getSerialid(groupId, x)); + if (!serialId.equals("")) { + relatedDay = x; + break; + } + } + + /** + * 初始化改考勤组的节假日数据(只初始化) + */ + boolean flag = true; + RecordSet recordSet = new RecordSet(); + KQGroupComInfo kqGroupComInfo = new KQGroupComInfo(); + + List> holidayList = (List>) tempMap.get("holidayList"); + Map holidayMap = new HashMap(); + + if(holidayList.size()>0){ + String tmpsql = "delete from kq_HolidaySet where groupId='"+groupId+"' and holidayDate>='"+year+"-01-01' and holidayDate<='"+year+"-12-31' "; + recordSet.executeUpdate(tmpsql); + } + + for (int j = 0; j < holidayList.size(); j++) { + holidayMap = holidayList.get(j); + + String holidayDate = year + "-" + (String) holidayMap.get("holidayDate"); + if (!holidayDateList.contains(holidayDate)) { + holidayDateList.add(holidayDate); + } + int changeType = (int) holidayMap.get("changeType"); + if (kqGroupComInfo.getKqtype(groupId).equals("2")&&changeType == 2 ) { + //排班制的考勤组不能初始化调配工作日 + continue; + } + String holidayDesc = (String) holidayMap.get("holidayDesc"); + if (dateList.contains(holidayDate)) { + String deleteSql = "delete from kq_HolidaySet where groupId=? and holidayDate=?"; + recordSet.executeUpdate(deleteSql, groupId, holidayDate); + } + + String sql = "insert into kq_HolidaySet(groupId,holidayDate,changeType,holidayDesc,relatedDay) values(?,?,?,?,?)"; + flag = recordSet.executeUpdate(sql, groupId, holidayDate, changeType, holidayDesc, relatedDay); + if (!flag) { + errInfoList.add(SystemEnv.getHtmlLabelName(5056701, user.getLanguage()).replace("$groupName$", kqGroupComInfo.getGroupname(groupId)).replace("$holidayDate$", holidayDate)); + } + } + } + + /** + * 如果没有错误信息则代表初始化成功 + */ + if (errInfoList.size() > 0) { + resultMap.put("status", "0"); + resultMap.put("sketch", SystemEnv.getHtmlLabelName(125960, user.getLanguage())); + resultMap.put("description", errInfoList); + } else { + resultMap.put("status", "1"); + resultMap.put("sketch", SystemEnv.getHtmlLabelName(20196, user.getLanguage())); + } + } catch (Exception e) { + resultMap.put("status", "0"); + resultMap.put("sketch", SystemEnv.getHtmlLabelName(382661, user.getLanguage())); + resultMap.put("desscription", errInfoList); + } finally { + /*刷新缓存*/ + KQHolidaySetComInfo kqHolidaySetComInfo = new KQHolidaySetComInfo(); + kqHolidaySetComInfo.removeCache(); + + /*刷新考勤报表*/ + logger.info("初始化节假日数据,格式化考勤报表。groupIdList=" + com.alibaba.fastjson.JSONObject.toJSONString(groupIds) + + "。holidayDateList=" + com.alibaba.fastjson.JSONObject.toJSONString(holidayDateList)); + List groupIdList = Util.TokenizerString(groupIds, ",");//考勤组ID集合 + new KQHolidaySetThread(groupIdList,holidayDateList).start(); + } + return resultMap; + } + + /** + * 请求网络上的节假日API接口,获取节假日设置数据 + * + * @param requestUrl + * @return + */ + private static Map httpRequest(String requestUrl, User user) { + Map resultMap = new HashMap(); + //buffer用于接受返回的字符 + StringBuffer buffer = new StringBuffer(); + try { + TrustManager[] tm = {new MyX509TrustManager()}; + SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); + sslContext.init(null, tm, new java.security.SecureRandom()); + SSLSocketFactory ssf = sslContext.getSocketFactory(); + + URL url= new URL(null, requestUrl, new sun.net.www.protocol.https.Handler()); + HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection(); + httpUrlConn.setSSLSocketFactory(ssf); + + httpUrlConn.setDoOutput(true); + httpUrlConn.setDoInput(true); + httpUrlConn.setUseCaches(false); + httpUrlConn.setRequestMethod("GET"); + httpUrlConn.connect(); + + //获得输入 + InputStream inputStream = httpUrlConn.getInputStream(); + InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8"); + BufferedReader bufferedReader = new BufferedReader(inputStreamReader); + + //将bufferReader的值给放到buffer里 + String str = null; + while ((str = bufferedReader.readLine()) != null) { + buffer.append(str); + } + //关闭bufferReader和输入流 + bufferedReader.close(); + inputStreamReader.close(); + inputStream.close(); + inputStream = null; + //断开连接 + httpUrlConn.disconnect(); + + /** + * 解析JSON字符串 + */ + String jsonStr = buffer.toString(); + JSONObject jsonObject = JSONObject.fromObject(jsonStr).getJSONObject("data"); + int code = jsonObject.optInt("code");//0服务正常。-1服务出错 + if (code != 0) { + //初始化节假日失败,获取网络服务出错 + resultMap.put("status", "0"); + resultMap.put("sketch", SystemEnv.getHtmlLabelName(520011, user.getLanguage())); + return resultMap; + } + JSONObject holiday = jsonObject.getJSONObject("holiday"); + if (holiday.size() == 0) { + //初始化节假日失败,暂未获取到所选年份的节假日数据 + resultMap.put("status", "0"); + resultMap.put("sketch", SystemEnv.getHtmlLabelName(505673, user.getLanguage())); + return resultMap; + } + Map holidayMap = new HashMap(); + List> holidayList = new ArrayList>(); + Iterator iterator = holiday.keys(); + while (iterator.hasNext()) { + holidayMap = new HashMap(); + + String holidayDate = (String) iterator.next(); + holidayMap.put("holidayDate", holidayDate);//日期 + JSONObject detailInfo = holiday.getJSONObject(holidayDate); + int wage = detailInfo.optInt("wage"); + if (wage == 1) { + holidayMap.put("changeType", 2);//调配工作日 + } else if (wage == 2) { + holidayMap.put("changeType", 3);//调配休息日 + } else if (wage == 3) { + holidayMap.put("changeType", 1);//公众假日 + } + String holidayDesc = detailInfo.getString("name"); + holidayMap.put("holidayDesc", holidayDesc);//说明 + + holidayList.add(holidayMap); + } + resultMap.put("status", "1"); + resultMap.put("sketch", SystemEnv.getHtmlLabelName(505674, user.getLanguage())); + resultMap.put("holidayList", holidayList); + } catch (Exception e) { + e.printStackTrace(); + resultMap.put("status", "0"); + resultMap.put("sketch", SystemEnv.getHtmlLabelName(520011, user.getLanguage())); + return resultMap; + } + return resultMap; + } + +} diff --git a/领悦二开new/src/com/engine/kq/biz/KQLeaveRulesBiz.java b/领悦二开new/src/com/engine/kq/biz/KQLeaveRulesBiz.java new file mode 100644 index 0000000..b0c4b4c --- /dev/null +++ b/领悦二开new/src/com/engine/kq/biz/KQLeaveRulesBiz.java @@ -0,0 +1,1307 @@ +package com.engine.kq.biz; + +import com.alibaba.fastjson.JSONObject; +import com.api.hrm.util.ServiceUtil; +import com.engine.kq.entity.KQBalanceOfLeaveEntity; +import com.engine.kq.log.KQLog; +import com.engine.kq.util.KQTransMethod; +import com.weaver.general.TimeUtil; +import org.apache.commons.lang.StringUtils; +import weaver.conn.RecordSet; +import weaver.general.StringUtil; +import weaver.general.Util; +import weaver.hrm.User; +import weaver.hrm.common.Tools; +import weaver.hrm.resource.ResourceComInfo; +import weaver.systeminfo.SystemEnv; + +import java.util.*; + +public class KQLeaveRulesBiz { + + public static final ThreadLocal THREAD_LOCAL = new ThreadLocal<>(); + + + /** + * 记录日志 + */ + private static KQLog logger = new KQLog(); + + /** + * 根据假期规则ID获取假期规则名称 + * + * @param ruleId 假期规则的ID + * @return + */ + public static String getLeaveName(String ruleId) { + String leaveName = ""; + KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo(); + leaveName = kqLeaveRulesComInfo.getLeaveName(ruleId); + return leaveName; + } + + /** + * 判断是否具有假期余额 + * + * @param ruleId + * @return + */ + public static boolean getBalanceEnable(String ruleId) { + int balanceEnable = 0; + KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo(); + balanceEnable = Util.getIntValue(kqLeaveRulesComInfo.getBalanceEnable(ruleId), 0); + if (balanceEnable == 1) { + return true; + } else { + return false; + } + } + /** + * 判断优先假期类型id字符串 + * + * @param ruleId + * @return + */ + public static String getLeaveids(String ruleId) { + int schevacationON = 0; + String schevacation = "-1"; + + KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo(); + schevacationON = Util.getIntValue(kqLeaveRulesComInfo.getSchevacationON(ruleId), 0); + if (schevacationON == 1) { + schevacation=Util.null2s(kqLeaveRulesComInfo.getSchevacation(ruleId), "-1"); + } + return schevacation; + + } + + /** + * 判断人员的假期类型id字符串 + * + * @param scheLeaveids + * @param resourceId + * @return + */ + public static String getusedLeaveids(String scheLeaveids, String resourceId) { + try { + ResourceComInfo resourceComInfo = new ResourceComInfo(); + String subcompanyId = resourceComInfo.getSubCompanyID(resourceId); + String departmentId = resourceComInfo.getDepartmentID(resourceId); + + List scheLeaveidsList = Util.splitString2List(scheLeaveids, ","); + + /** + * 加载应用范围为总部的以及应用范围为分部(但是范围中包含了所属分部ID)的假期规则 + */ + RecordSet recordSet = new RecordSet(); + String sql = "select * from kq_LeaveRules "; + String sqlWhere = " where (isDelete is null or isDelete <>1) and isEnable=1 and balanceEnable=1 "; + /*如果找不到人员所在分部,则只返回应用范围为总部的假期规则*/ + if (!resourceId.equals("")) { + if (recordSet.getDBType().equalsIgnoreCase("sqlserver")) { + sqlWhere += " and ( (scopeType=3 and ','+scopeValue+',' like '%," + resourceId + ",%') "; + } else if (recordSet.getDBType().equalsIgnoreCase("mysql")) { + sqlWhere += " and ( (scopeType=3 and concat(',',scopeValue,',') like '%," + resourceId + ",%') "; + } else { + sqlWhere += " and ( (scopeType=3 and ','||scopeValue||',' like '%," + resourceId + ",%') "; + } + } + if (!departmentId.equals("")) { + if (recordSet.getDBType().equalsIgnoreCase("sqlserver")) { + sqlWhere += " or (scopeType=2 and ','+scopeValue+',' like '%," + departmentId + ",%') "; + } else if (recordSet.getDBType().equalsIgnoreCase("mysql")) { + sqlWhere += " or (scopeType=2 and concat(',',scopeValue,',') like '%," + departmentId + ",%') "; + } else { + sqlWhere += " or (scopeType=2 and ','||scopeValue||',' like '%," + departmentId + ",%') "; + } + } + if (!subcompanyId.equals("")) { + if (recordSet.getDBType().equalsIgnoreCase("sqlserver")) { + sqlWhere += " or (scopeType=1 and ','+scopeValue+',' like '%," + subcompanyId + ",%') "; + } else if (recordSet.getDBType().equalsIgnoreCase("mysql")) { + sqlWhere += " or (scopeType=1 and concat(',',scopeValue,',') like '%," + subcompanyId + ",%') "; + } else { + sqlWhere += " or (scopeType=1 and ','||scopeValue||',' like '%," + subcompanyId + ",%') "; + } + } + + sqlWhere += " or scopeType=0 )"; + sql = sql + sqlWhere + " order by showOrder,id "; + scheLeaveids = ""; + List remleaveidsList = new ArrayList<>(); + recordSet.executeQuery(sql); + /*如果指定人员所在分部下面单独设置过假期规则,则取分部下面的假期规则*/ + while (recordSet.next()) { + String leaveid = recordSet.getString("id");//假期类型id + remleaveidsList.add(leaveid); + } + + for (String id : scheLeaveidsList) { + if (remleaveidsList.contains(id)) { + if (scheLeaveids.equals("")) { + scheLeaveids = id; + } else { + scheLeaveids += "," + id; + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + return scheLeaveids; + + } + /** + * 获取最小请假单位 + * 1-按天请假 + * 2-按半天请假 + * 3-按小时请假 + * 4-按整天请假 + * 其他:无效数据 + * + * @param ruleId 指定的假期规则ID + * @return + */ + public static int getMinimumUnit(String ruleId) { + int minimumUnit = -1;//最小请假单位 + KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo(); + minimumUnit = Util.getIntValue(kqLeaveRulesComInfo.getMinimumUnit(ruleId), -1); + return minimumUnit; + } + + /** + * 获取请假时长计算方式 + * 1-按照工作日计算请假时长 + * 2-按照自然日计算请假时长 + * 其他:无效数据 + * + * @param ruleId 指定的假期规则ID + * @return + */ + public static int getComputingMode(String ruleId) { + int computingMode = -1;//计算请假时长方式 + KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo(); + computingMode = Util.getIntValue(kqLeaveRulesComInfo.getComputingMode(ruleId), -1); + return computingMode; + } + + /** + * 按照自然日计算请假时长排除节假日、休息日 + * 0-不排除 + * 1-排除节假日 + * 2-排除休息日 + * 1,2-排除节假日和休息日 + * + * @param ruleId 指定的假期规则ID + * @return + */ + public static String getFilterHolidays(String ruleId) { + KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo(); + String filterHolidays = Util.null2s(kqLeaveRulesComInfo.getFilterHolidays(ruleId), "0"); + return filterHolidays; + } + + /** + * 获取日折算时长(多少小时算一天) + * + * @param ruleId 指定的假期规则ID + * @return + */ + public static String getHoursToDay(String ruleId) { + double hoursToDay = -1;//日折算时长 + int computingMode = -1;//计算请假时长方式 + int minimumUnit = -1;//最小请假单位 + KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo(); + hoursToDay = Util.getDoubleValue(kqLeaveRulesComInfo.getHoursToDay(ruleId), -1); + computingMode = Util.getIntValue(kqLeaveRulesComInfo.getComputingMode(ruleId), -1); + minimumUnit = Util.getIntValue(kqLeaveRulesComInfo.getMinimumUnit(ruleId), -1); + if (computingMode != 2) { + hoursToDay = -1; + } + return String.format("%.2f", hoursToDay); + } + + /** + * 1-按天请假 + * 2-按半天请假 + * 3-按小时请假 + * 4-按整天请假 + * + * @param minimumUnit + * @param lan + * @return + */ + public static String getMinimumUnitName(String minimumUnit, int lan) { + String minimumUnitName = ""; + switch (minimumUnit) { + case "1": + minimumUnitName = SystemEnv.getHtmlLabelName(1925, lan); + break; + case "2": + minimumUnitName = SystemEnv.getHtmlLabelName(1925, lan); + break; + case "3": + case "5": + case "6": + minimumUnitName = SystemEnv.getHtmlLabelName(391, lan); + break; + case "4": + minimumUnitName = SystemEnv.getHtmlLabelName(1925, lan); + break; + default: + break; + } + return minimumUnitName; + } + + /** + * 获取所有的假期规则 + * unitType:1-按天请假、2-按半天请假、3-按小时请假、4-按整天请假、-1:数据异常,无效数据 + * + * @return + */ + public static List> getAllLeaveRules() { + Map ruleMap = new HashMap(); + List> ruleList = new ArrayList>(); + + KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo(); + kqLeaveRulesComInfo.setTofirstRow(); + while (kqLeaveRulesComInfo.next()) { + if (kqLeaveRulesComInfo.getIsEnable().equals("1")) { + ruleMap = new HashMap(); + ruleMap.put("id", kqLeaveRulesComInfo.getId()); + ruleMap.put("name", kqLeaveRulesComInfo.getLeaveName()); + ruleMap.put("unitType", kqLeaveRulesComInfo.getMinimumUnit()); + ruleMap.put("proportion", kqLeaveRulesComInfo.getProportion()); + ruleMap.put("scopeType",kqLeaveRulesComInfo.getScopeType()); + ruleMap.put("scopeValue",kqLeaveRulesComInfo.getScopeValue()); + ruleList.add(ruleMap); + } + } + return ruleList; + } + + /** + * 根据人员ID获取其可见的所有假期类型 + * + * @param resourceId 指定人员ID + * @return + */ + public static String getAllLeaveRulesByUserId(String resourceId, String languageId) { + String resultStr = ""; + try { + ResourceComInfo resourceComInfo = new ResourceComInfo(); + String subcomId = resourceComInfo.getSubCompanyID(resourceId); + String deptId = resourceComInfo.getDepartmentID(resourceId); + + List tempList = new ArrayList(); + + Map itemMap = new HashMap(); + List itemList = new ArrayList(); + + String sql = "select * from kq_leaveRules where 1=1 and (isDelete is null or isDelete <>1) and isEnable=1"; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql); + while (recordSet.next()) { + String scopeType = recordSet.getString("scopeType"); + String scopeValue = recordSet.getString("scopeValue"); + String leaveName = recordSet.getString("leaveName"); + String id = recordSet.getString("id"); + + if (scopeType.equals("1")) { + tempList = Util.TokenizerString(scopeValue, ","); + if (!tempList.contains(subcomId)) { + continue; + } + } + + itemMap = new HashMap(); + itemMap.put("name", Util.formatMultiLang(leaveName, languageId)); + itemMap.put("id", id); + itemList.add(itemMap); + } + resultStr = JSONObject.toJSONString(itemList); + } catch (Exception e) { + e.printStackTrace(); + } + return resultStr; + } + public static boolean filterSubLeaveRule(KQLeaveRulesComInfo kqLeaveRulesComInfo, User user, String leaveId) { + return filterSubLeaveRule(Util.null2String(user.getUID()), kqLeaveRulesComInfo.getScopeType(leaveId), kqLeaveRulesComInfo.getScopeValue(leaveId), Util.null2String(user.getUserSubCompany1()),Util.null2String(user.getUserDepartment())); + } + public static boolean filterSubLeaveRule(String userId, String scopeType, String scopeValue, String subCompany, String deptId) { + boolean isAdmin = ServiceUtil.isAdmin(userId); + if (isAdmin) { + return false; + } + if ("1".equals(scopeType)) { + if (scopeValue.indexOf(",") > 0) { + String[] split = scopeValue.split(","); + for (String v : split) { + if (!StringUtil.isEmpty(v) && v.equals(subCompany)) { + return false; + } + } + return true; + } else { + return !scopeValue.equals(subCompany); + } + }else if("2".equals(scopeType)){ + if (scopeValue.indexOf(",") > 0) { + String[] split = scopeValue.split(","); + for (String v : split) { + if (!StringUtil.isEmpty(v) && v.equals(deptId)) { + return false; + } + } + return true; + } else { + return !scopeValue.equals(deptId); + } + }else if("3".equals(scopeType)){ + if (scopeValue.indexOf(",") > 0) { + String[] split = scopeValue.split(","); + for (String v : split) { + if (!StringUtil.isEmpty(v) && v.equals(userId)) { + return false; + } + } + return true; + } else { + return !scopeValue.equals(userId); + } + } + return false; + } + /** + * 初始化年假 + * + * @param ruleId + * @return + */ + public static boolean initAnnualLeave(int ruleId) { + boolean isInitSuccess = false; + try { + /*判断年假是否初始化过*/ + RecordSet recordSet = new RecordSet(); + String sql = "select * from kq_LeaveRules where (isDelete is null or isDelete<>1) and id=" + ruleId; + recordSet.executeQuery(sql); + boolean initialized = recordSet.getCounts() > 0; + + /*没有初始化过就新建,已经初始化过就更新*/ + if (initialized) { + String updateSql = "update kq_LeaveRules set leaveName='年假-初始化',scopeType=0,scopeValue='',minimumUnit=1,hoursToDay=8,computingMode=1,balanceEnable=1," + + "isDelete=0,isEnable=1,leaveCode='annualLeave' where id=" + ruleId; + isInitSuccess = recordSet.executeUpdate(updateSql); + if (!isInitSuccess) { + return false; + } + + String deleteDetailSql = "delete from kq_LeaveRulesDetail where scopeType=0 and ruleId=" + ruleId; + recordSet.executeUpdate(deleteDetailSql); + + String insertDetailSql = "insert into kq_LeaveRulesDetail(ruleName,ruleId,scopeType,scopeValue,distributionMode,annualAmount,priority,validityRule,expirationMonth,expirationDay,extensionEnable,extendedDays,releaseRule,calcMethod)" + + "values('年假-总部规则'," + ruleId + ",0,'',3,0,1,0,'','',0,0,0,0)"; + isInitSuccess = recordSet.executeUpdate(insertDetailSql); + if (!isInitSuccess) { + return false; + } + } else { + KQTransMethod kqTransMethod = new KQTransMethod(); + int nextId = kqTransMethod.getNextId(); + + String insertSql = "insert into kq_LeaveRules(id,leaveName,scopeType,scopeValue,minimumUnit,hoursToDay,computingMode,balanceEnable,isDelete,isEnable,leaveCode)" + + "values(" + nextId + ",'年假-初始化',0,'',1,8,1,1,0,1,'annualLeave')"; + isInitSuccess = recordSet.executeUpdate(insertSql); + if (!isInitSuccess) { + return false; + } + + String insertDetailSql = "insert into kq_LeaveRulesDetail(ruleName,ruleId,scopeType,scopeValue,distributionMode,annualAmount,priority,validityRule,expirationMonth,expirationDay,extensionEnable,extendedDays,releaseRule,calcMethod)" + + "values('年假-总部规则'," + nextId + ",0,'',3,0,1,0,'','',0,0,0,0)"; + isInitSuccess = recordSet.executeUpdate(insertDetailSql); + if (!isInitSuccess) { + return false; + } + + String historySql = "update kq_initHistory set annualLeave=" + nextId + " where id=1"; + isInitSuccess = recordSet.executeUpdate(historySql); + + ruleId = nextId; + } + + String detailId = ""; + sql = "select * from kq_LeaveRulesDetail where scopeType=0 and ruleId=" + ruleId; + recordSet.executeQuery(sql); + if (recordSet.next()) { + detailId = recordSet.getString("id"); + } + if (detailId.equals("")) { + return false; + } + + /*先删除原来的明细记录,在插入新的明细记录*/ + String detailSql = "delete from kq_WorkingAgeToLeave where leaveRulesId=" + detailId; + isInitSuccess = recordSet.executeUpdate(detailSql); + if (!isInitSuccess) { + sql = "delete from kq_LeaveRules where leaveRulesId=" + detailId; + recordSet.executeUpdate(sql); + return false; + } + + /*插入明细记录*/ + detailSql = "insert into kq_WorkingAgeToLeave(leaveRulesId,lowerLimit,upperLimit,amount) values(?,?,?,?)"; + isInitSuccess = recordSet.executeUpdate(detailSql, detailId, 0, 1, 0); + isInitSuccess = recordSet.executeUpdate(detailSql, detailId, 1, 10, 5); + isInitSuccess = recordSet.executeUpdate(detailSql, detailId, 10, 20, 10); + isInitSuccess = recordSet.executeUpdate(detailSql, detailId, 20, 9999, 15); + } catch (Exception e) { + logger.info(e.getMessage()); + } + return isInitSuccess; + } + + /** + * 初始化带薪事假 + * + * @param ruleId + * @return + */ + public static boolean initPaidCompassionateLeave(int ruleId) { + /*判断是否初始化过*/ + RecordSet recordSet = new RecordSet(); + RecordSet rs = new RecordSet(); + String sql = "select * from kq_LeaveRules where (isDelete is null or isDelete<>1) and id=" + ruleId; + recordSet.executeQuery(sql); + boolean initialized = recordSet.getCounts() > 0; + + /*没有初始化过就新建,已经初始化过就更新*/ + boolean isInitSuccess = false; + if (initialized) { + String updateSql = "update kq_LeaveRules set leaveName='带薪事假-初始化',scopeType=0,scopeValue='',minimumUnit=1,hoursToDay=8,computingMode=1,balanceEnable=0," + + "isDelete=0,isEnable=1,leaveCode='paidCompassionateLeave' where id=" + ruleId; + isInitSuccess = rs.executeUpdate(updateSql); + if (!isInitSuccess) { + return false; + } + } else { + KQTransMethod kqTransMethod = new KQTransMethod(); + int nextId = kqTransMethod.getNextId(); + + String insertSql = "insert into kq_LeaveRules(id,leaveName,scopeType,scopeValue,minimumUnit,hoursToDay,computingMode,balanceEnable,isDelete,isEnable,leaveCode)" + + "values(" + nextId + ",'带薪事假-初始化',0,'',1,8,1,0,0,1,'paidCompassionateLeave')"; + isInitSuccess = rs.executeUpdate(insertSql); + if (!isInitSuccess) { + return false; + } + + String historySql = "update kq_initHistory set paidCompassionateLeave=" + nextId + " where id=1"; + isInitSuccess = rs.executeUpdate(historySql); + } + return isInitSuccess; + } + + /** + * 初始化带薪病假 + * + * @param ruleId + * @return + */ + public static boolean initPaidSickLeave(int ruleId) { + /*判断是否初始化过*/ + RecordSet recordSet = new RecordSet(); + RecordSet rs = new RecordSet(); + String sql = "select * from kq_LeaveRules where (isDelete is null or isDelete<>1) and id=" + ruleId; + recordSet.executeQuery(sql); + boolean initialized = recordSet.getCounts() > 0; + + /*没有初始化过就新建,已经初始化过就更新*/ + boolean isInitSuccess = false; + if (initialized) { + String updateSql = "update kq_LeaveRules set leaveName='带薪病假-初始化',scopeType=0,scopeValue='',minimumUnit=1,hoursToDay=8,computingMode=1,balanceEnable=0," + + "isDelete=0,isEnable=1,leaveCode='paidSickLeave' where id=" + ruleId; + isInitSuccess = rs.executeUpdate(updateSql); + if (!isInitSuccess) { + return false; + } + } else { + KQTransMethod kqTransMethod = new KQTransMethod(); + int nextId = kqTransMethod.getNextId(); + + String insertSql = "insert into kq_LeaveRules(id,leaveName,scopeType,scopeValue,minimumUnit,hoursToDay,computingMode,balanceEnable,isDelete,isEnable,leaveCode)" + + "values(" + nextId + ",'带薪病假-初始化',0,'',1,8,1,0,0,1,'paidSickLeave')"; + isInitSuccess = rs.executeUpdate(insertSql); + if (!isInitSuccess) { + return false; + } + + String historySql = "update kq_initHistory set paidSickLeave=" + nextId + " where id=1"; + isInitSuccess = rs.executeUpdate(historySql); + } + return isInitSuccess; + } + + /** + * 初始化调休 + * + * @param ruleId + * @return + */ + public static boolean initVacationLeave(int ruleId) { + /*判断是否初始化过*/ + RecordSet recordSet = new RecordSet(); + RecordSet rs = new RecordSet(); + String sql = "select * from kq_LeaveRules where (isDelete is null or isDelete<>1) and id=" + ruleId; + recordSet.executeQuery(sql); + boolean initialized = recordSet.getCounts() > 0; + + /*没有初始化过就新建,已经初始化过就更新*/ + boolean isInitSuccess = false; + if (initialized) { + String updateSql = "update kq_LeaveRules set leaveName='调休-初始化',scopeType=0,scopeValue='',minimumUnit=1,hoursToDay=8,computingMode=1,balanceEnable=1," + + "isDelete=0,isEnable=1,leaveCode='vacationLeave' where id=" + ruleId; + isInitSuccess = rs.executeUpdate(updateSql); + if (!isInitSuccess) { + return false; + } + + String deleteDetailSql = "delete from kq_LeaveRulesDetail where scopeType=0 and ruleId=" + ruleId; + rs.executeUpdate(deleteDetailSql); + + String insertDetailSql = "insert into kq_LeaveRulesDetail(ruleName,ruleId,scopeType,scopeValue,distributionMode,annualAmount,priority,validityRule,expirationMonth,expirationDay,extensionEnable,extendedDays,releaseRule,calcMethod)" + + "values('调休-总部规则'," + ruleId + ",0,'',5,0,1,0,'','',0,0,0,0)"; + isInitSuccess = rs.executeUpdate(insertDetailSql); + if (!isInitSuccess) { + return false; + } + } else { + /*判断系统中是否已经存在调休了,如果已存在,则不允许新建新的调休假期*/ + sql = "select * from kq_LeaveRules where (isDelete is null or isDelete<>1) and id in (select ruleId from kq_LeaveRulesDetail where (isDelete is null or isDelete<>1) and distributionMode=5)"; + rs.executeQuery(sql); + if (rs.getCounts() > 0) { + return false; + } + + KQTransMethod kqTransMethod = new KQTransMethod(); + int nextId = kqTransMethod.getNextId(); + + String insertSql = "insert into kq_LeaveRules(id,leaveName,scopeType,scopeValue,minimumUnit,hoursToDay,computingMode,balanceEnable,isDelete,isEnable,leaveCode)" + + "values(" + nextId + ",'调休-初始化',0,'',1,8,1,1,0,1,'vacationLeave')"; + isInitSuccess = rs.executeUpdate(insertSql); + if (!isInitSuccess) { + return false; + } + + String insertDetailSql = "insert into kq_LeaveRulesDetail(ruleName,ruleId,scopeType,scopeValue,distributionMode,annualAmount,priority,validityRule,expirationMonth,expirationDay,extensionEnable,extendedDays,releaseRule,calcMethod)" + + "values('调休-总部规则'," + nextId + ",0,'',5,0,1,0,'','',0,0,0,0)"; + isInitSuccess = rs.executeUpdate(insertDetailSql); + if (!isInitSuccess) { + return false; + } + + String historySql = "update kq_initHistory set vacationLeave=" + nextId + " where id=1"; + isInitSuccess = rs.executeUpdate(historySql); + } + return isInitSuccess; + } + + /** + * 初始化事假 + * + * @param ruleId + * @return + */ + public static boolean initCompassionateLeave(int ruleId) { + /*判断是否初始化过*/ + RecordSet recordSet = new RecordSet(); + RecordSet rs = new RecordSet(); + String sql = "select * from kq_LeaveRules where (isDelete is null or isDelete<>1) and id=" + ruleId; + recordSet.executeQuery(sql); + boolean initialized = recordSet.getCounts() > 0; + + /*没有初始化过就新建,已经初始化过就更新*/ + boolean isInitSuccess = false; + if (initialized) { + String updateSql = "update kq_LeaveRules set leaveName='事假-初始化',scopeType=0,scopeValue='',minimumUnit=1,hoursToDay=8,computingMode=1,balanceEnable=0," + + "isDelete=0,isEnable=1,leaveCode='compassionateLeave' where id=" + ruleId; + isInitSuccess = rs.executeUpdate(updateSql); + if (!isInitSuccess) { + return false; + } + } else { + KQTransMethod kqTransMethod = new KQTransMethod(); + int nextId = kqTransMethod.getNextId(); + + String insertSql = "insert into kq_LeaveRules(id,leaveName,scopeType,scopeValue,minimumUnit,hoursToDay,computingMode,balanceEnable,isDelete,isEnable,leaveCode)" + + "values(" + nextId + ",'事假-初始化',0,'',1,8,1,0,0,1,'compassionateLeave')"; + isInitSuccess = rs.executeUpdate(insertSql); + if (!isInitSuccess) { + return false; + } + + String historySql = "update kq_initHistory set compassionateLeave=" + nextId + " where id=1"; + isInitSuccess = rs.executeUpdate(historySql); + } + return isInitSuccess; + } + + /** + * 初始化病假 + * + * @param ruleId + * @return + */ + public static boolean initSickLeave(int ruleId) { + /*判断是否初始化过*/ + RecordSet recordSet = new RecordSet(); + RecordSet rs = new RecordSet(); + String sql = "select * from kq_LeaveRules where (isDelete is null or isDelete<>1) and id=" + ruleId; + recordSet.executeQuery(sql); + boolean initialized = recordSet.getCounts() > 0; + + /*没有初始化过就新建,已经初始化过就更新*/ + boolean isInitSuccess = false; + if (initialized) { + String updateSql = "update kq_LeaveRules set leaveName='病假-初始化',scopeType=0,scopeValue='',minimumUnit=1,hoursToDay=8,computingMode=1,balanceEnable=0," + + "isDelete=0,isEnable=1,leaveCode='sickLeave' where id=" + ruleId; + isInitSuccess = rs.executeUpdate(updateSql); + if (!isInitSuccess) { + return false; + } + } else { + KQTransMethod kqTransMethod = new KQTransMethod(); + int nextId = kqTransMethod.getNextId(); + + String insertSql = "insert into kq_LeaveRules(id,leaveName,scopeType,scopeValue,minimumUnit,hoursToDay,computingMode,balanceEnable,isDelete,isEnable,leaveCode)" + + "values(" + nextId + ",'病假-初始化',0,'',1,8,1,0,0,1,'sickLeave')"; + isInitSuccess = rs.executeUpdate(insertSql); + if (!isInitSuccess) { + return false; + } + + String historySql = "update kq_initHistory set sickLeave=" + nextId + " where id=1"; + isInitSuccess = rs.executeUpdate(historySql); + } + return isInitSuccess; + } + + /** + * 初始化产假 + * + * @param ruleId + * @return + */ + public static boolean initMaternityLeave(int ruleId) { + /*判断是否初始化过*/ + RecordSet recordSet = new RecordSet(); + RecordSet rs = new RecordSet(); + String sql = "select * from kq_LeaveRules where (isDelete is null or isDelete<>1) and id=" + ruleId; + recordSet.executeQuery(sql); + boolean initialized = recordSet.getCounts() > 0; + + /*没有初始化过就新建,已经初始化过就更新*/ + boolean isInitSuccess = false; + if (initialized) { + String updateSql = "update kq_LeaveRules set leaveName='产假-初始化',scopeType=0,scopeValue='',minimumUnit=1,hoursToDay=8,computingMode=2,balanceEnable=0," + + "isDelete=0,isEnable=1,leaveCode='maternityLeave' where id=" + ruleId; + isInitSuccess = rs.executeUpdate(updateSql); + if (!isInitSuccess) { + return false; + } + } else { + KQTransMethod kqTransMethod = new KQTransMethod(); + int nextId = kqTransMethod.getNextId(); + + String insertSql = "insert into kq_LeaveRules(id,leaveName,scopeType,scopeValue,minimumUnit,hoursToDay,computingMode,balanceEnable,isDelete,isEnable,leaveCode)" + + "values(" + nextId + ",'产假-初始化',0,'',1,8,2,0,0,1,'maternityLeave')"; + isInitSuccess = rs.executeUpdate(insertSql); + if (!isInitSuccess) { + return false; + } + + String historySql = "update kq_initHistory set maternityLeave=" + nextId + " where id=1"; + isInitSuccess = rs.executeUpdate(historySql); + } + return isInitSuccess; + } + + /** + * 初始化陪产假 + * + * @param ruleId + * @return + */ + public static boolean initPaternityLeave(int ruleId) { + /*判断是否初始化过*/ + RecordSet recordSet = new RecordSet(); + RecordSet rs = new RecordSet(); + String sql = "select * from kq_LeaveRules where (isDelete is null or isDelete<>1) and id=" + ruleId; + recordSet.executeQuery(sql); + boolean initialized = recordSet.getCounts() > 0; + + /*没有初始化过就新建,已经初始化过就更新*/ + boolean isInitSuccess = false; + if (recordSet.next()) { + String updateSql = "update kq_LeaveRules set leaveName='陪产假-初始化',scopeType=0,scopeValue='',minimumUnit=1,hoursToDay=8,computingMode=2,balanceEnable=0," + + "isDelete=0,isEnable=1,leaveCode='paternityLeave' where id=" + ruleId; + isInitSuccess = rs.executeUpdate(updateSql); + if (!isInitSuccess) { + return false; + } + } else { + KQTransMethod kqTransMethod = new KQTransMethod(); + int nextId = kqTransMethod.getNextId(); + + String insertSql = "insert into kq_LeaveRules(id,leaveName,scopeType,scopeValue,minimumUnit,hoursToDay,computingMode,balanceEnable,isDelete,isEnable,leaveCode)" + + "values(" + nextId + ",'陪产假-初始化',0,'',1,8,2,0,0,1,'paternityLeave')"; + isInitSuccess = rs.executeUpdate(insertSql); + if (!isInitSuccess) { + return false; + } + + String historySql = "update kq_initHistory set paternityLeave=" + nextId + " where id=1"; + isInitSuccess = rs.executeUpdate(historySql); + } + return isInitSuccess; + } + + /** + * 初始化婚假 + * + * @param ruleId + * @return + */ + public static boolean initMarriageLeave(int ruleId) { + /*判断是否初始化过*/ + RecordSet recordSet = new RecordSet(); + RecordSet rs = new RecordSet(); + String sql = "select * from kq_LeaveRules where (isDelete is null or isDelete<>1) and id=" + ruleId; + recordSet.executeQuery(sql); + boolean initialized = recordSet.getCounts() > 0; + + /*没有初始化过就新建,已经初始化过就更新*/ + boolean isInitSuccess = false; + if (initialized) { + String updateSql = "update kq_LeaveRules set leaveName='婚假-初始化',scopeType=0,scopeValue='',minimumUnit=1,hoursToDay=8,computingMode=2,balanceEnable=0," + + "isDelete=0,isEnable=1,leaveCode='marriageLeave' where id=" + ruleId; + isInitSuccess = rs.executeUpdate(updateSql); + if (!isInitSuccess) { + return false; + } + } else { + KQTransMethod kqTransMethod = new KQTransMethod(); + int nextId = kqTransMethod.getNextId(); + + String insertSql = "insert into kq_LeaveRules(id,leaveName,scopeType,scopeValue,minimumUnit,hoursToDay,computingMode,balanceEnable,isDelete,isEnable,leaveCode)" + + "values(" + nextId + ",'婚假-初始化',0,'',1,8,2,0,0,1,'marriageLeave')"; + isInitSuccess = rs.executeUpdate(insertSql); + if (!isInitSuccess) { + return false; + } + + String historySql = "update kq_initHistory set marriageLeave=" + nextId + " where id=1"; + isInitSuccess = rs.executeUpdate(historySql); + } + return isInitSuccess; + } + + /** + * 初始化丧假 + * + * @param ruleId + * @return + */ + public static boolean initFuneralLeave(int ruleId) { + /*判断是否初始化过*/ + RecordSet recordSet = new RecordSet(); + RecordSet rs = new RecordSet(); + String sql = "select * from kq_LeaveRules where (isDelete is null or isDelete<>1) and id=" + ruleId; + recordSet.executeQuery(sql); + boolean initialized = recordSet.getCounts() > 0; + + /*没有初始化过就新建,已经初始化过就更新*/ + boolean isInitSuccess = false; + if (initialized) { + String updateSql = "update kq_LeaveRules set leaveName='丧假-初始化',scopeType=0,scopeValue='',minimumUnit=1,hoursToDay=8,computingMode=1,balanceEnable=0," + + "isDelete=0,isEnable=1,leaveCode='funeralLeave' where id=" + ruleId; + isInitSuccess = rs.executeUpdate(updateSql); + if (!isInitSuccess) { + return false; + } + } else { + KQTransMethod kqTransMethod = new KQTransMethod(); + int nextId = kqTransMethod.getNextId(); + + String insertSql = "insert into kq_LeaveRules(id,leaveName,scopeType,scopeValue,minimumUnit,hoursToDay,computingMode,balanceEnable,isDelete,isEnable,leaveCode)" + + "values(" + nextId + ",'丧假-初始化',0,'',1,8,1,0,0,1,'funeralLeave')"; + isInitSuccess = rs.executeUpdate(insertSql); + if (!isInitSuccess) { + return false; + } + + String historySql = "update kq_initHistory set funeralLeave=" + nextId + " where id=1"; + isInitSuccess = rs.executeUpdate(historySql); + } + return isInitSuccess; + } + + /** + * 初始化哺乳假 + * + * @param ruleId + * @return + */ + public static boolean initBreastfeedingLeave(int ruleId) { + /*判断是否初始化过*/ + RecordSet recordSet = new RecordSet(); + RecordSet rs = new RecordSet(); + String sql = "select * from kq_LeaveRules where (isDelete is null or isDelete<>1) and id=" + ruleId; + recordSet.executeQuery(sql); + boolean initialized = recordSet.getCounts() > 0; + + /*没有初始化过就新建,已经初始化过就更新*/ + boolean isInitSuccess = false; + if (initialized) { + String updateSql = "update kq_LeaveRules set leaveName='哺乳假-初始化',scopeType=0,scopeValue='',minimumUnit=1,hoursToDay=8,computingMode=1,balanceEnable=0," + + "isDelete=0,isEnable=1,leaveCode='breastfeedingLeave' where id=" + ruleId; + isInitSuccess = rs.executeUpdate(updateSql); + if (!isInitSuccess) { + return false; + } + } else { + KQTransMethod kqTransMethod = new KQTransMethod(); + int nextId = kqTransMethod.getNextId(); + + String insertSql = "insert into kq_LeaveRules(id,leaveName,scopeType,scopeValue,minimumUnit,hoursToDay,computingMode,balanceEnable,isDelete,isEnable,leaveCode)" + + "values(" + nextId + ",'哺乳假-初始化',0,'',1,8,1,0,0,1,'breastfeedingLeave')"; + isInitSuccess = rs.executeUpdate(insertSql); + if (!isInitSuccess) { + return false; + } + + String historySql = "update kq_initHistory set breastfeedingLeave=" + nextId + " where id=1"; + isInitSuccess = rs.executeUpdate(historySql); + } + return isInitSuccess; + } + + /** + * 根据人员ID以及名称获取对应的假期规则ID(主要对于对接小E) + * + * @param resourceId 人员ID + * @param leaveName 假期规则名称 + * @return + */ + public static List getLeaveRuleIdByName(String resourceId, String leaveName) { + List dataList = new ArrayList(); + try { + ResourceComInfo resourceComInfo = new ResourceComInfo(); + String subcomId = resourceComInfo.getSubCompanyID(resourceId); + + Map dataMap = new HashMap(); + + String sql = "select * from kq_LeaveRules where (isDelete is null or isDelete <>1) and isEnable=1 and leaveName like '%" + leaveName + "%'"; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql); + while (recordSet.next()) { + int scopeType = Util.getIntValue(recordSet.getString("scopeType"), 0); + String scopeValue = Util.null2String(recordSet.getString("scopeValue")); + + if (scopeType == 1) { + List tempList = Util.TokenizerString(scopeValue, ","); + if (!tempList.contains(subcomId)) { + continue; + } + } + + dataMap = new HashMap(); + dataMap.put("ruleId", recordSet.getString("id")); + dataMap.put("name", Util.formatMultiLang(recordSet.getString("leaveName"), "7")); + dataList.add(dataMap); + } + } catch (Exception e) { + e.printStackTrace(); + } + return dataList; + } + + /** + * 判断此请假类型是否是由 法定年假+福利年假 组合而成的混合模式 + * + * @param ruleId 指定的请假类型的id(对应于kq_LeaveRules表的主键ID) + * @return true--是混合模式、false--不是 + */ + public static boolean isMixMode(String ruleId) { + boolean flag = false; + try { + String sql = "select * from kq_LeaveRulesDetail where (isDelete is null or isDelete<>1) and distributionMode=6 and ruleId=?"; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql, ruleId); + if (recordSet.next()) { + flag = true; + } + } catch (Exception e) { + logger.info(e.getMessage()); + } + return flag; + } + + /** + * 获取请假类型的颜色(随机生成) + * + * @return + */ + public static String getColor() { + String color = ""; + try { + StringBuffer result = new StringBuffer(); + for (int i = 0; i < 6; i++) { + //随机生成0-15的数值并转换成16进制 + result.append(Integer.toHexString(new Random().nextInt(16))); + } + color = "#" + result.toString().toUpperCase(); + } catch (Exception e) { + System.out.println("获取16进制字符串异常,返回默认..."); + color = "#00CCCC"; + } + return color; + } + + public static String getChildName(String balanceofleaveid){ + String name = ""; + try { + String sql = "select childId from kq_balanceOfLeave where id=?"; + RecordSet recordSet = new RecordSet(); + KQChildrenComInfo kqChildrenComInfo = new KQChildrenComInfo(); + recordSet.executeQuery(sql, balanceofleaveid); + if (recordSet.next()) { + String chlid = Util.null2s(recordSet.getString("childId"), ""); + if(StringUtils.isNotBlank(chlid)){ + name= kqChildrenComInfo.getChildrenName(chlid); + } + } + } catch (Exception e) { + logger.info(e.getMessage()); + } + return name; + } + /** + * 是否是调休 + * @param ruleId + * @return + */ + public static boolean isTiaoXiu(String ruleId){ + boolean flag = false; + try { + String sql = "select * from kq_LeaveRulesDetail where (isDelete is null or isDelete<>1) and distributionMode=5 and ruleId=?"; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql, ruleId); + if (recordSet.next()) { + flag = true; + } + } catch (Exception e) { + logger.info(e.getMessage()); + } + return flag; + } + + public static boolean isTiaoXiu(String ruleId, String subCompanyId, String departmentId, String resourceId) { + boolean flag = false; + RecordSet recordSet = new RecordSet(); + try { + KQLeaveRulesDetailComInfo detailComInfo = new KQLeaveRulesDetailComInfo(); + recordSet.writeLog("isTiaoXiu>>1=" +ruleId+";2="+ subCompanyId+";3="+ departmentId+";4="+ resourceId ); + int distributionMode = Util.getIntValue(detailComInfo.getDistributionMode(ruleId, subCompanyId, departmentId, resourceId), 1); + if (distributionMode == 5) { + flag = true; + } + recordSet.writeLog("isTiaoXiu>>distributionMode=" +distributionMode); +// if (!flag) { + if (true) { + + String sql = "select * from kq_LeaveRulesDetail where (isDelete is null or isDelete<>1) " + + "and distributionMode=5 and ruleId=? "; + String sqlWhere = ""; + if (!resourceId.equals("")) { + if (recordSet.getDBType().equalsIgnoreCase("sqlserver")) { + sqlWhere = " and (scopeType=3 and ','+scopeValue+',' like '%," + resourceId + ",%') "; + } else if (recordSet.getDBType().equalsIgnoreCase("mysql")) { + sqlWhere = " and (scopeType=3 and concat(',',scopeValue,',') like '%," + resourceId + ",%') "; + } else { + sqlWhere = " and (scopeType=3 and ','||scopeValue||',' like '%," + resourceId + ",%') "; + } + recordSet.writeLog("isTiaoXiu>>sql1=" + sql + sqlWhere); + recordSet.executeQuery(sql + sqlWhere, ruleId); + if (recordSet.next()) { + return true; + } + } else if (!departmentId.equals("")) { + if (recordSet.getDBType().equalsIgnoreCase("sqlserver")) { + sqlWhere = " and (scopeType=2 and ','+scopeValue+',' like '%," + departmentId + ",%') "; + } else if (recordSet.getDBType().equalsIgnoreCase("mysql")) { + sqlWhere = " and (scopeType=2 and concat(',',scopeValue,',') like '%," + departmentId + ",%') "; + } else { + sqlWhere = " and (scopeType=2 and ','||scopeValue||',' like '%," + departmentId + ",%') "; + } + recordSet.writeLog("isTiaoXiu>>sql2=" + sql + sqlWhere); + recordSet.executeQuery(sql + sqlWhere, ruleId); + if (recordSet.next()) { + return true; + } + } else if (!subCompanyId.equals("")) { + if (recordSet.getDBType().equalsIgnoreCase("sqlserver")) { + sqlWhere = " and (scopeType=1 and ','+scopeValue+',' like '%," + subCompanyId + ",%') "; + } else if (recordSet.getDBType().equalsIgnoreCase("mysql")) { + sqlWhere = " and (scopeType=1 and concat(',',scopeValue,',') like '%," + subCompanyId + ",%') "; + } else { + sqlWhere = " and (scopeType=1 and ','||scopeValue||',' like '%," + subCompanyId + ",%') "; + } + recordSet.writeLog("isTiaoXiu>>sql3=" + sql + sqlWhere); + recordSet.executeQuery(sql + sqlWhere, ruleId); + if (recordSet.next()) { + return true; + } + } else { + sqlWhere = " and scopeType=0 "; + recordSet.writeLog("isTiaoXiu>>sql4=" + sql + sqlWhere); + recordSet.executeQuery(sql + sqlWhere, ruleId); + if (recordSet.next()) { + return true; + } + } + } + + recordSet.writeLog("isTiaoXiu>>flag=" + flag); + } catch (Exception e) { + recordSet.writeLog(e.getMessage()); + recordSet.writeLog(e); + } + return flag; + } + + public static int getTiaoXiu(String subCompanyId, String departmentId, String resourceId) { + int ruleid = 0; + RecordSet recordSet = new RecordSet(); + try { + + String sql = "select * from kq_LeaveRulesDetail where (isDelete is null or isDelete<>1) " + + "and distributionMode=5 "; + String sqlWhere = ""; + if (!resourceId.equals("")) { + if (recordSet.getDBType().equalsIgnoreCase("sqlserver")) { + sqlWhere = " and (scopeType=3 and ','+scopeValue+',' like '%," + resourceId + ",%') "; + } else if (recordSet.getDBType().equalsIgnoreCase("mysql")) { + sqlWhere = " and (scopeType=3 and concat(',',scopeValue,',') like '%," + resourceId + ",%') "; + } else { + sqlWhere = " and (scopeType=3 and ','||scopeValue||',' like '%," + resourceId + ",%') "; + } + + recordSet.executeQuery(sql + sqlWhere); + while (recordSet.next()) { + ruleid = recordSet.getInt("ruleId"); + return ruleid; + } + } + if (!departmentId.equals("")) { + if (recordSet.getDBType().equalsIgnoreCase("sqlserver")) { + sqlWhere = " and (scopeType=2 and ','+scopeValue+',' like '%," + departmentId + ",%') "; + } else if (recordSet.getDBType().equalsIgnoreCase("mysql")) { + sqlWhere = " and (scopeType=2 and concat(',',scopeValue,',') like '%," + departmentId + ",%') "; + } else { + sqlWhere = " and (scopeType=2 and ','||scopeValue||',' like '%," + departmentId + ",%') "; + } + + recordSet.executeQuery(sql + sqlWhere); + while (recordSet.next()) { + ruleid = recordSet.getInt("ruleId"); + return ruleid; + } + } + if (!subCompanyId.equals("")) { + if (recordSet.getDBType().equalsIgnoreCase("sqlserver")) { + sqlWhere = " and (scopeType=1 and ','+scopeValue+',' like '%," + subCompanyId + ",%') "; + } else if (recordSet.getDBType().equalsIgnoreCase("mysql")) { + sqlWhere = " and (scopeType=1 and concat(',',scopeValue,',') like '%," + subCompanyId + ",%') "; + } else { + sqlWhere = " and (scopeType=1 and ','||scopeValue||',' like '%," + subCompanyId + ",%') "; + } + + recordSet.executeQuery(sql + sqlWhere); + while (recordSet.next()) { + ruleid = recordSet.getInt("ruleId"); + return ruleid; + } + } + + sqlWhere = " and scopeType=0 "; + + recordSet.executeQuery(sql + sqlWhere); + while (recordSet.next()) { + ruleid = recordSet.getInt("ruleId"); + return ruleid; + } + + } catch (Exception e) { + recordSet.writeLog(e.getMessage()); + recordSet.writeLog(e); + } + return ruleid; + } + + public static Map isRepeat(String ruleid,int scopeType,String scopeValue,User user,String ruleDetailId){ + Map result = new HashMap<>(); + result.put("flag","0");//0=未重复,1=重复了不让保存 +// String sql = "select id,ruleid,scopetype,scopevalue,distributionmode from kq_LeaveRulesDetail where (isDelete is null or isDelete<>1) and distributionMode=5 "; + String sql = "select id,ruleid,scopetype,scopevalue,distributionmode from kq_LeaveRulesDetail where (isDelete is null or isDelete<>1) "; + RecordSet recordSet = new RecordSet(); + recordSet.writeLog("ruleid="+ruleid+",scopeType="+scopeType+",scopeValue="+scopeValue); + recordSet.executeQuery(sql); + while (recordSet.next()) { + String tmp_id = Util.null2String(recordSet.getString("id")); + String tmp_ruleid = Util.null2String(recordSet.getString("ruleid")); + String tmp_scopetype = Util.null2String(recordSet.getString("scopetype")); + String tmp_scopevalue = Util.null2String(recordSet.getString("scopevalue")); + String tmp_distributionmode = Util.null2String(recordSet.getString("distributionmode")); + recordSet.writeLog("tmp_id="+tmp_id+",tmp_ruleid="+tmp_ruleid+",tmp_scopetype="+tmp_scopetype+",tmp_scopevalue="+tmp_scopevalue); + if(tmp_ruleid.equals(ruleid) && ("".equals(ruleDetailId) || !tmp_id.equals(ruleDetailId))){ + //同一个假期类型,不能同时设置为【加班自动计入调休】和其他的规则,比如按工龄自动发放 + if(!tmp_distributionmode.equals("5")){ + result.put("flag","1"); + result.put("msg", SystemEnv.getHtmlLabelName(546798, user.getLanguage())); + return result; + } + } + + if(tmp_distributionmode.equals("5") && tmp_scopetype.equals(Util.null2String(scopeType)) && ("".equals(ruleDetailId) || !tmp_id.equals(ruleDetailId))){ + //总部级别的范围单独处理下,因为存在之前是分部级别,维护了分部id,这个时候即便是scopytype=0,但是scopevalue依然有值了,所以总部级别不用进行scopevalue的比对 + if("0".equals(tmp_scopetype)){ + result.put("flag","1"); + result.put("msg", SystemEnv.getHtmlLabelName(546797, user.getLanguage())); + return result; + } + if(null != scopeValue && scopeValue.indexOf(",")>-1){ + String[] values = scopeValue.split(","); + for (String value : values) { + if((","+tmp_scopevalue+",").indexOf(","+value+",")>-1){ + result.put("flag","1"); + result.put("msg", SystemEnv.getHtmlLabelName(546797, user.getLanguage())); + return result; + } + } + }else { + if((","+tmp_scopevalue+",").indexOf(","+scopeValue+",")>-1){ + result.put("flag","1"); + result.put("msg", SystemEnv.getHtmlLabelName(546797, user.getLanguage())); + return result; + } + } + } + } + + return result; + } + + /** + * 是否是育儿假,且不开启叠加 + * @param ruleId + * @return + */ + public static boolean isLeaveOfParental(String ruleId){ + boolean flag = false; + try { + String sql = "select * from kq_LeaveRulesDetail where (isDelete is null or isDelete<>1) and distributionMode=8 and ruleId=?"; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql, ruleId); + if (recordSet.next()) { + String severalChildren = Util.null2s(recordSet.getString("severalChildren"), "0"); + if(severalChildren.equals("0")){ + flag = true; + } + } + } catch (Exception e) { + logger.info(e.getMessage()); + } + return flag; + } + /** + * 是否是育儿假且开启了叠加 + * @param ruleId + * @return + */ + public static boolean isLeaveOfParentalNum(String ruleId){ + boolean flag = false; + try { + String sql = "select * from kq_LeaveRulesDetail where (isDelete is null or isDelete<>1) and distributionMode=8 and ruleId=?"; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql, ruleId); + if (recordSet.next()) { + String severalChildren = Util.null2s(recordSet.getString("severalChildren"), "0"); + if(severalChildren.equals("1")){ + flag = true; + } + } + } catch (Exception e) { + logger.info(e.getMessage()); + } + return flag; + } + + /** + * 半天单位 时间选择方式:1-下拉框选择 、2-具体时间 + * @param ruleId + * @return + */ + public static int getTimeselection(String ruleId) { + int timeselection = 1;//最小请假单位 + KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo(); + timeselection = Util.getIntValue(kqLeaveRulesComInfo.getTimeSelection(ruleId), 1); + return timeselection; + } + + public void updateChildLeaveDate(int scopeType,String scopeValue,int validityRule,String ruleId){ + RecordSet rs = new RecordSet(); + try { + // 查询当年育儿假数据 + String sql = "select * from kq_balanceOfLeave where (isDelete is null or isDelete<>1) and leaveRulesId = "+ruleId ; + + if (scopeType == 1 ) { + sql += " and resourceid in (select id from hrmresource where subCompanyId1 in (" + scopeValue + ") )"; + }else if (scopeType == 2 ) { + sql += " and resourceid in (select id from hrmresource where departmentId in (" + scopeValue + ") )"; + }else if (scopeType == 3) { + sql += " and (" + Tools.getOracleSQLIn(scopeValue, "resourceid") + ") "; + } + KQBalanceOfLeaveEntity balanceEntity = null; + ArrayList balanceEntities = new ArrayList<>(); + rs.executeQuery(sql); + while (rs.next()) { + int id = rs.getInt("id"); + String childId = Util.null2s(rs.getString("childId"), ""); + if(StringUtils.isNotBlank(childId)){ + String expirationDate = Util.null2s(rs.getString("expirationDate"), ""); + String effectiveDate = Util.null2s(rs.getString("effectiveDate"), ""); + balanceEntity = new KQBalanceOfLeaveEntity(); + balanceEntity.setId(id); + balanceEntity.setExpirationDate(expirationDate); + balanceEntity.setEffectiveDate(effectiveDate); + balanceEntities.add(balanceEntity); + } + } + sql = " update kq_balanceOfLeave set expirationDate =? where id= ? "; + for (int i = 0; balanceEntities != null && i < balanceEntities.size(); i++) { + KQBalanceOfLeaveEntity balance = balanceEntities.get(i); + String uid = Util.null2String(balance.getId()); + String effectiveDate = Util.null2String(balance.getEffectiveDate()); + String expirationDate = "2222-12-31"; + if (validityRule != 0) { + expirationDate = TimeUtil.dateAdd(TimeUtil.yearAdd(effectiveDate, 1), -1); + } + rs.executeUpdate(sql, expirationDate,uid); + } + + }catch (Exception e){ + e.printStackTrace(); + rs.writeLog(e); + } + } +} diff --git a/领悦二开new/src/com/engine/kq/biz/KQLeaveRulesComInfo.java b/领悦二开new/src/com/engine/kq/biz/KQLeaveRulesComInfo.java new file mode 100644 index 0000000..3790b34 --- /dev/null +++ b/领悦二开new/src/com/engine/kq/biz/KQLeaveRulesComInfo.java @@ -0,0 +1,319 @@ +package com.engine.kq.biz; + +import com.engine.kq.wfset.util.KQAttFlowCheckUtil; +import weaver.cache.CacheBase; +import weaver.cache.CacheColumn; +import weaver.cache.CacheColumnType; +import weaver.cache.PKColumn; +import weaver.general.Util; +import weaver.systeminfo.SystemEnv; + +/** + * 假期规则缓存类 + */ +public class KQLeaveRulesComInfo extends CacheBase { + + /** + * 数据来源 + */ + protected static String TABLE_NAME = "kq_leaveRules"; + /** + * sql中的where信息,不要以where开始 + */ + protected static String TABLE_WHERE = " (isDelete is null or isDelete !=1) "; + /** + * sql中的order by信息,不要以order by开始 + */ + protected static String TABLE_ORDER = " showOrder,id "; + + /** + * 主键 + */ + @PKColumn(type = CacheColumnType.NUMBER) + protected static String PK_NAME = "id"; + + /** + * 假期规则名称 + */ + @CacheColumn(name = "leaveName") + protected static int leaveName; + + @CacheColumn(name = "SchevacationON") + protected static int SchevacationON; + + @CacheColumn(name = "Schevacation") + protected static int Schevacation; + + /** + * 是否禁用:0-未禁用、1-已禁用 + */ + @CacheColumn(name = "isEnable") + protected static int isEnable; + + /** + * 应用范围:0-总部、1-分部 + */ + @CacheColumn(name = "scopeType") + protected static int scopeType; + + /** + * 分部ID(当应用范围为分部时选择的分部ID) + */ + @CacheColumn(name = "scopeValue") + protected static int scopeValue; + + /** + * 最小请假单位 + * 1-按天请假 + * 2-按半天请假 + * 3-按小时请假 + * 4-按整天请假 + * 其他:无效数据 + */ + @CacheColumn(name = "minimumUnit") + protected static int minimumUnit; + + /** + * 余额单位变更时的换算比例 + * XX小时=1天 + */ + @CacheColumn(name = "proportion") + protected static int proportion; + + /** + * 日折算时长(1天=XX小时) + */ + @CacheColumn(name = "hoursToDay") + protected static int hoursToDay; + + /** + * 按自然日计算请假时长,0-不排除,1-排除节假日,2-排除休息日,3-排除节假日和休息日 + */ + @CacheColumn(name = "filterHolidays") + protected static int filterHolidays; + + /** + * 计算请假时长方式: + * 1-按工作日计算请假时长 + * 2-按自然日计算请假时长 + */ + @CacheColumn(name = "computingMode") + protected static int computingMode; + + /** + * 启用假期余额: + * 0-不启用 + * 1-启用 + */ + @CacheColumn(name = "balanceEnable") + protected static int balanceEnable; + + /** + * 假期类型标识 + */ + @CacheColumn(name = "leaveCode") + protected static int leaveCode; + + /** + * 半天单位 时间选择方式:1-下拉框选择 、2-具体时间 + */ + @CacheColumn(name = "timeselection") + protected static int timeselection; + + /** + * 折算方式 1是四舍五入 2是向上取整 3是向下取整 + */ + @CacheColumn(name = "conversion") + protected static int conversion; + + /** + * 流程重复时段 1是重复 0是不重复,默认不重复 + */ + @CacheColumn(name = "repeat_time") + protected static int repeatTime; + + public String getId(){ + return (String)getRowValue(PK_INDEX); + } + + public String getLeaveName() { + return (String)getRowValue(leaveName); + } + + public String getLeaveName(String key){ + return (String) getValue(leaveName,key); + } + + public String getSchevacationON() { + return (String)getRowValue(SchevacationON); + } + + public String getSchevacationON(String key){ + return (String) getValue(SchevacationON,key); + } + + public String getSchevacation() { + return (String)getRowValue(Schevacation); + } + + public String getSchevacation(String key){ + return (String) getValue(Schevacation,key); + } + + public String getIsEnable() { + return (String)getRowValue(isEnable); + } + + public String getIsEnable(String key){ + return (String) getValue(isEnable,key); + } + + public String getScopeType() { + return (String)getRowValue(scopeType); + } + + public String getScopeType(String key){ + return (String) getValue(scopeType,key); + } + + public String getScopeValue() { + return (String)getRowValue(scopeValue); + } + + public String getScopeValue(String key){ + return (String) getValue(scopeValue,key); + } + + public String getMinimumUnit() { + return (String)getRowValue(minimumUnit); + } + + public String getMinimumUnit(String key){ + return (String)getValue(minimumUnit,key); + } + + public String getProportion() { + return (String)getRowValue(proportion); + } + + public String getProportion(String key){ + return (String)getValue(proportion,key); + } + + public String getHoursToDay() { + return (String)getRowValue(hoursToDay); + } + + public String getHoursToDay(String key){ + return (String)getValue(hoursToDay,key); + } + public String getFilterHolidays() { + return (String)getRowValue(filterHolidays); + } + + public String getFilterHolidays(String key){ + return (String)getValue(filterHolidays,key); + } + + public String getComputingMode() { + return (String)getRowValue(computingMode); + } + + public String getComputingMode(String key){ + return (String)getValue(computingMode,key); + } + + public String getBalanceEnable() { + return (String)getRowValue(balanceEnable); + } + + public String getBalanceEnable(String key){ + return (String)getValue(balanceEnable,key); + } + + public String getLeaveCode() { + return (String)getRowValue(leaveCode); + } + + public String getLeaveCode(String key){ + return (String)getValue(leaveCode,key); + } + + public String getTimeSelection() { + String value = (String) getRowValue(timeselection); + if (value == null || value.equals("")) { + value = "1"; + } + return value; + } + + public String getTimeSelection(String key) { + String value = (String) getValue(timeselection, key); + if (value == null || value.equals("")) { + value = "1"; + } + return value; + } + + public String getConversion() { + return (String)getRowValue(conversion); + } + + public String getConversion(String key){ + return (String)getValue(conversion,key); + } + + public String getRepeatTime() { + return (String)getRowValue(repeatTime); + } + + public String getRepeatTime(String key){ + return (String)getValue(repeatTime,key); + } + + public String getUnitName(int language){ + String unitName = "";//单位名称,天/小时 + int minimumUnit = Util.getIntValue(getMinimumUnit(),1); + if (minimumUnit == 1 || minimumUnit == 2 || minimumUnit == 4) { + unitName = SystemEnv.getHtmlLabelName(389325, language);//(天) + } else { + unitName = SystemEnv.getHtmlLabelName(389326, language);//(小时) + } + return unitName; + } + + public String getUnitName(String key,int language){ + String unitName = "";//单位名称,天/小时 + int minimumUnit = Util.getIntValue(getMinimumUnit(key),1); + if (minimumUnit == 1 || minimumUnit == 2 || minimumUnit == 4) { + unitName = SystemEnv.getHtmlLabelName(389325, language);//(天) + } else { + unitName = SystemEnv.getHtmlLabelName(389326, language);//(小时) + } + +// KQTransMethod method = new KQTransMethod(); +// unitName = "("+method.getMinimumUnitName4Browser(""+minimumUnit, ""+language)+")"; + return unitName; + } + + public String getUnitNameNew(String key,int language){ + String unitName = "";//单位名称,天/小时 + int minimumUnit = Util.getIntValue(getMinimumUnit(key),1); + if (minimumUnit == 1 || minimumUnit == 2 || minimumUnit == 4) { + unitName = SystemEnv.getHtmlLabelName(389325, language);//(天) + } else { + unitName = SystemEnv.getHtmlLabelName(389326, language);//(小时) + } + return unitName; + } + + + + @Override + public void removeCache() { + super.removeCache(); + KQAttFlowCheckUtil kqAttFlowCheckUtil = new KQAttFlowCheckUtil(); + kqAttFlowCheckUtil.initLeaveUnit(); + } + +} diff --git a/领悦二开new/src/com/engine/kq/biz/KQLeaveRulesDetailComInfo.java b/领悦二开new/src/com/engine/kq/biz/KQLeaveRulesDetailComInfo.java new file mode 100644 index 0000000..b7398ec --- /dev/null +++ b/领悦二开new/src/com/engine/kq/biz/KQLeaveRulesDetailComInfo.java @@ -0,0 +1,1329 @@ +package com.engine.kq.biz; + +import weaver.cache.*; +import weaver.common.StringUtil; +import weaver.conn.RecordSet; +import weaver.general.Util; + +/** + * @Auther: Administrator + * @Date: 2019-03-08 16:23 + * @Description: + */ +public class KQLeaveRulesDetailComInfo extends CacheBase { + + /** + * 数据来源 + */ + protected static String TABLE_NAME = "kq_leaveRulesDetail"; + /** + * sql中的where信息,不要以where开始 + */ + protected static String TABLE_WHERE = " (isDelete is null or isDelete !=1) "; + /** + * sql中的order by信息,不要以order by开始 + */ + protected static String TABLE_ORDER = "id"; + + /** + * 主键 + */ + @PKColumn(type = CacheColumnType.NUMBER) + protected static String PK_NAME = "id"; + + /** + * 假期规则的ID + */ + @CacheColumn(name = "id") + protected static int id; + + /** + * 假期类型的ID + */ + @CacheColumn(name = "ruleId") + protected static int ruleId; + + /** + * 假期规则名称 + */ + @CacheColumn(name = "ruleName") + protected static int ruleName; + + /** + * 应用范围:0-总部、1-分部 + */ + @CacheColumn(name = "scopeType") + protected static int scopeType; + + /** + * 分部ID(当应用范围为分部时选择的分部ID) + */ + @CacheColumn(name = "scopeValue") + protected static int scopeValue; + + /** + * 余额发放方式: + * 1-手动发放 + * 2-按司龄自动发放 + * 3-按工龄自动发放 + * 4-每年自动发放固定天数 + * 5-加班时长自动计入余额 + * 6-按司龄+工龄自动发放 + */ + @CacheColumn(name = "distributionMode") + protected static int distributionMode; + + /** + * 每人发放小时(天)数 + * 注:当余额发放方式为"4-每年自动发放固定天数"时有效 + */ + @CacheColumn(name = "annualAmount") + protected static int annualAmount; + + /** + * 法定年假的规则:(当【余额发放方式】选择【6-按司龄+工龄自动发放】才有效) + * 0-工龄(默认) + * 1-司龄 + * 2-司龄+工龄 + */ + @CacheColumn(name = "legalKey") + protected static int legalKey; + + /** + * 福利年假的规则:(当【余额发放方式】选择【6-按司龄+工龄自动发放】才有效) + * 0-工龄 + * 1-司龄(默认) + * 2-司龄+工龄 + */ + @CacheColumn(name = "welfareKey") + protected static int welfareKey; + + /** + * 扣减优先级:(当【余额发放方式】选择【6-按司龄+工龄自动发放】才有效) + * 1-法定年假 + * 2-福利年假 + */ + @CacheColumn(name = "priority") + protected static int priority; + + /** + * 计算方式 + */ + @CacheColumn(name = "calcMethod") + protected static int calcMethod; + + /** + * //假期基数的发放日期 + * //1--每年的1月1号 + * //2--入职日期 + * //3--参加工作日期 + */ + @CacheColumn(name = "baseAmountReleaseDate") + protected static int baseAmountReleaseDate; + + /** + * //假期基数的变动日期 + * //1--每年的1月1号 + * //2--入职日期 + * //3--参加工作日期 + */ + @CacheColumn(name = "baseAmountChangeDate") + protected static int baseAmountChangeDate; + + /** + * 假期基数折算方式 + * 0--不折算 + * 1--四舍五入 + * 2--向上取整 + * 3--向下取整 + * 4--向上取0.5的倍数 + * 5--向下取0.5的倍数 + */ + @CacheColumn(name = "convertMode") + protected static int convertMode; + + /** + * 折算后保留的小数点位数 + */ + @CacheColumn(name = "decimalDigit") + protected static int decimalDigit; + + /** + * 有效期规则 + * 0-永久有效 + * 1-按自然年(1月1日-12月31日) + * 2-按入职日期起12个月 + * 3-自定义次年失效日期 + * 4-按天数失效 + * 5-按季度失效 + * 6-按月数失效 + */ + @CacheColumn(name = "validityRule") + protected static int validityRule; + + /** + * 失效日期-月 + */ + @CacheColumn(name = "expirationMonth") + protected static int expirationMonth; + + /** + * 失效日期-日 + */ + @CacheColumn(name = "expirationDay") + protected static int expirationDay; + + /** + * 有效天数 + */ + @CacheColumn(name = "effectiveDays") + protected static int effectiveDays; + + /** + * 有效月数 + */ + @CacheColumn(name = "effectiveMonths") + protected static int effectiveMonths; + + /** + * 是否允许延长有效期 + * 0-不允许 + * 1-允许 + */ + @CacheColumn(name = "extensionEnable") + protected static int extensionEnable; + + /** + * 允许延长的有效期天数 + */ + @CacheColumn(name = "extendedDays") + protected static int extendedDays; + + /** + * 释放规则 + * 0-不限制 + * 1-按天释放 + * 2-按月释放 + */ + @CacheColumn(name = "releaseRule") + protected static int releaseRule; + + /** + * 假期类型 + */ + @CacheColumn(name = "leaveCode") + protected static int leaveCode; + + /** + * 是否需要排除次账号 + * 0--不排除,即次账号正常享受年假 + * 1--排除,即次账号不能享受年假 + */ + @CacheColumn(name = "excludeSubAccount") + protected static int excludeSubAccount; + + /** + * 转正之前是否允许发放假期余额 + * 0--不允许 + * 1--允许 + */ + @CacheColumn(name = "beforeFormal") + protected static int beforeFormal; + + /** + * 多孩叠加开关 + * 0--不 + * 1--开 + */ + @CacheColumn(name = "severalChildren") + protected static int severalChildren; + + /** + * 孩子多少周岁前发放。 + */ + @CacheColumn(name = "yearsOld") + protected static int yearsOld; + + /** + *是否按照省份发放育儿假。1否,2是 + */ + @CacheColumn(name = "isprovince") + protected static int isprovince; + + /** + *是否按照省份发放育儿假。1否,2是 + */ + @CacheColumn(name = "carryOver") + protected static int carryOver; + + private static final String[] SCOPE_TYPES = {"3", "2", "1"}; + @Override + public CacheMap initCache() throws Exception { + CacheMap localData = super.createCacheMap(); + RecordSet rs = new RecordSet(); + String sql = "select * from kq_leaveRulesDetail where (isDelete is null or isDelete<>1) order by id"; + rs.executeQuery(sql); + while (rs.next()) { + String _id = rs.getString("id"); + String _ruleId = rs.getString("ruleId");//假期类型的ID + String _ruleName = rs.getString("ruleName");//假期类型的ID + String _scopeType = rs.getString("scopeType");//假期类型的流程可见范围 + String _scopeValue = rs.getString("scopeValue");//流程可见范围为分部时勾选的分部ID + String _distributionMode = rs.getString("distributionMode"); + String _annualAmount = rs.getString("annualAmount"); + String _legalKey = rs.getString("legalKey"); + String _welfareKey = rs.getString("welfareKey"); + String _priority = rs.getString("priority"); + String _calcMethod = rs.getString("calcMethod"); + String _baseAmountReleaseDate = rs.getString("baseAmountReleaseDate"); + String _baseAmountChangeDate = rs.getString("baseAmountChangeDate"); + String _convertMode = rs.getString("convertMode"); + String _decimalDigit = rs.getString("decimalDigit"); + String _validityRule = rs.getString("validityRule"); + String _expirationMonth = rs.getString("expirationMonth"); + String _expirationDay = rs.getString("expirationDay"); + String _effectiveDays = rs.getString("effectiveDays"); + String _effectiveMonths = rs.getString("effectiveMonths"); + String _extensionEnable = rs.getString("extensionEnable"); + String _extendedDays = rs.getString("extendedDays"); + String _releaseRule = rs.getString("releaseRule"); + String _leaveCode = rs.getString("leaveCode"); + String _excludeSubAccount = rs.getString("excludeSubAccount"); + String _beforeFormal = rs.getString("beforeFormal"); + String _severalChildren = rs.getString("severalChildren"); + String _yearsOld = rs.getString("yearsOld"); + String _isprovince = rs.getString("isprovince"); + String _carryOver = rs.getString("carryOver"); + if (_scopeType.equals("1") || _scopeType.equals("2") || _scopeType.equals("3")) { + String[] scopeValueArr = _scopeValue.split(","); + for (int i = 0; i < scopeValueArr.length; i++) { + String PK = _ruleId + "|" + _scopeType + "|" + scopeValueArr[i]; + + + CacheItem row = createCacheItem(); + row.set(PK_INDEX, PK); + row.set(id, _id); + row.set(ruleId, _ruleId); + row.set(ruleName, _ruleName); + row.set(scopeType, _scopeType); + row.set(scopeValue, _scopeValue); + row.set(distributionMode, _distributionMode); + row.set(annualAmount, _annualAmount); + row.set(legalKey, _legalKey); + row.set(welfareKey, _welfareKey); + row.set(priority, _priority); + row.set(calcMethod, _calcMethod); + row.set(baseAmountReleaseDate, _baseAmountReleaseDate); + row.set(baseAmountChangeDate, _baseAmountChangeDate); + row.set(convertMode, _convertMode); + row.set(decimalDigit, _decimalDigit); + row.set(validityRule, _validityRule); + row.set(expirationMonth, _expirationMonth); + row.set(expirationDay, _expirationDay); + row.set(effectiveDays, _effectiveDays); + row.set(effectiveMonths, _effectiveMonths); + row.set(extensionEnable, _extensionEnable); + row.set(extendedDays, _extendedDays); + row.set(releaseRule, _releaseRule); + row.set(leaveCode, _leaveCode); + row.set(excludeSubAccount, _excludeSubAccount); + row.set(beforeFormal, _beforeFormal); + row.set(severalChildren, _severalChildren); + row.set(yearsOld, _yearsOld); + row.set(isprovince, _isprovince); + row.set(carryOver, _carryOver); + modifyCacheItem(PK, row); + localData.put(PK, row); + } + } else { + String PK = ruleId + "|" + scopeType; + + CacheItem row = createCacheItem(); + row.set(PK_INDEX, PK); + row.set(id, _id); + row.set(ruleId, _ruleId); + row.set(ruleName, _ruleName); + row.set(scopeType, _scopeType); + row.set(scopeValue, _scopeValue); + row.set(distributionMode, _distributionMode); + row.set(annualAmount, _annualAmount); + row.set(legalKey, _legalKey); + row.set(welfareKey, _welfareKey); + row.set(priority, _priority); + row.set(calcMethod, _calcMethod); + row.set(baseAmountReleaseDate, _baseAmountReleaseDate); + row.set(baseAmountChangeDate, _baseAmountChangeDate); + row.set(convertMode, _convertMode); + row.set(decimalDigit, _decimalDigit); + row.set(validityRule, _validityRule); + row.set(expirationMonth, _expirationMonth); + row.set(expirationDay, _expirationDay); + row.set(effectiveDays, _effectiveDays); + row.set(effectiveMonths, _effectiveMonths); + row.set(extensionEnable, _extensionEnable); + row.set(extendedDays, _extendedDays); + row.set(releaseRule, _releaseRule); + row.set(leaveCode, _leaveCode); + row.set(excludeSubAccount, _excludeSubAccount); + row.set(beforeFormal, _beforeFormal); + row.set(severalChildren, _severalChildren); + row.set(yearsOld, _yearsOld); + row.set(isprovince, _isprovince); + row.set(carryOver, _carryOver); + modifyCacheItem(PK, row); + localData.put(PK, row); + } + } + return localData; + } + + @Override + public CacheItem initCache(String key) { + if (key == null || "".equals(key.trim())) { + return null; + } + + String ruleIdTemp = "";//假期类型的ID + String scopeTypeTemp = "";//假期类型的流程可见范围 + String scopeValueTemp = "";//流程可见范围为分部时勾选的分部ID + String PK = ""; + + String[] keyArr = key.split("\\|"); + String sql = ""; + RecordSet rs = new RecordSet(); + if (keyArr.length == 2) { + ruleIdTemp = keyArr[0]; + scopeTypeTemp = keyArr[1]; + PK = ruleIdTemp + "|0"; + + sql = "select * from kq_leaveRulesDetail where (isDelete is null or isDelete<>1) and ruleId=" + ruleIdTemp + " and scopeType=" + scopeTypeTemp + " order by id"; + } + if (keyArr.length == 3) { + ruleIdTemp = keyArr[0]; + scopeTypeTemp = keyArr[1]; + scopeValueTemp = keyArr[2]; + PK = ruleIdTemp + "|1|" + scopeValueTemp; + + sql = "select * from kq_leaveRulesDetail where (isDelete is null or isDelete<>1) and ruleId=" + ruleIdTemp + " and scopeType=" + scopeTypeTemp; + if (rs.getDBType().equalsIgnoreCase("sqlserver")) { + sql += " and ','+scopeValue+',' like '%," + scopeValueTemp + ",%'"; + } else if (rs.getDBType().equalsIgnoreCase("mysql")) { + sql += " and concat(',',scopeValue,',') like '%," + scopeValueTemp + ",%'"; + } else { + sql += " and ','||scopeValue||',' like '%," + scopeValueTemp + ",%'"; + } + sql += " order by id "; + } + rs.executeQuery(sql); + if (rs.next()) { + String _id = rs.getString("id"); + String _ruleId = rs.getString("ruleId");//假期类型的ID + String _ruleName = rs.getString("ruleName");//假期类型的ID + String _scopeType = rs.getString("scopeType");//假期类型的流程可见范围 + String _scopeValue = rs.getString("scopeValue");//流程可见范围为分部时勾选的分部ID + String _distributionMode = rs.getString("distributionMode"); + String _annualAmount = rs.getString("annualAmount"); + String _legalKey = rs.getString("legalKey"); + String _welfareKey = rs.getString("welfareKey"); + String _priority = rs.getString("priority"); + String _calcMethod = rs.getString("calcMethod"); + String _baseAmountReleaseDate = rs.getString("baseAmountReleaseDate"); + String _baseAmountChangeDate = rs.getString("baseAmountChangeDate"); + String _convertMode = rs.getString("convertMode"); + String _decimalDigit = rs.getString("decimalDigit"); + String _validityRule = rs.getString("validityRule"); + String _expirationMonth = rs.getString("expirationMonth"); + String _expirationDay = rs.getString("expirationDay"); + String _effectiveDays = rs.getString("effectiveDays"); + String _effectiveMonths = rs.getString("effectiveMonths"); + String _extensionEnable = rs.getString("extensionEnable"); + String _extendedDays = rs.getString("extendedDays"); + String _releaseRule = rs.getString("releaseRule"); + String _leaveCode = rs.getString("leaveCode"); + String _excludeSubAccount = rs.getString("excludeSubAccount"); + String _beforeFormal = rs.getString("beforeFormal"); + String _severalChildren = rs.getString("severalChildren"); + String _yearsOld = rs.getString("yearsOld"); + String _isprovince = rs.getString("isprovince"); + String _carryOver = rs.getString("carryOver"); + + CacheItem row = createCacheItem(); + row.set(PK_INDEX, PK); + row.set(id, _id); + row.set(ruleId, _ruleId); + row.set(ruleName, _ruleName); + row.set(scopeType, _scopeType); + row.set(scopeValue, _scopeValue); + row.set(distributionMode, _distributionMode); + row.set(annualAmount, _annualAmount); + row.set(legalKey, _legalKey); + row.set(welfareKey, _welfareKey); + row.set(priority, _priority); + row.set(calcMethod, _calcMethod); + row.set(baseAmountReleaseDate, _baseAmountReleaseDate); + row.set(baseAmountChangeDate, _baseAmountChangeDate); + row.set(convertMode, _convertMode); + row.set(decimalDigit, _decimalDigit); + row.set(validityRule, _validityRule); + row.set(expirationMonth, _expirationMonth); + row.set(expirationDay, _expirationDay); + row.set(effectiveDays, _effectiveDays); + row.set(effectiveMonths, _effectiveMonths); + row.set(extensionEnable, _extensionEnable); + row.set(extendedDays, _extendedDays); + row.set(releaseRule, _releaseRule); + row.set(leaveCode, _leaveCode); + row.set(excludeSubAccount, _excludeSubAccount); + row.set(beforeFormal, _beforeFormal); + row.set(severalChildren, _severalChildren); + row.set(yearsOld, _yearsOld); + row.set(isprovince, _isprovince); + row.set(carryOver, _carryOver); + modifyCacheItem(key, row); + return row; + } else { + CacheItem row = createCacheItem(); + modifyCacheItem(key, row); + return row; + } + } + + private String getId(String key) { + return (String) getValue(id, key); + } + +// public String getId(String ruleId, String subcompanyId) { +// String PK = ruleId + "|1|" + subcompanyId; +// String id = getId(PK); +// if (id == null || id == "") { +// PK = ruleId + "|0"; +// id = getId(PK); +// } +// return id; +// } + + private String getRuleId(String key) { + return (String) getValue(ruleId, key); + } + + private String getRuleName(String key) { + return (String) getValue(ruleName, key); + } + +// public String getRuleName(String ruleId, String subcompanyId) { +// String PK = ruleId + "|1|" + subcompanyId; +// String ruleName = getRuleName(PK); +// if (ruleName == null || ruleName == "") { +// PK = ruleId + "|0"; +// ruleName = getRuleName(PK); +// } +// return ruleName; +// } + + private String getScopeType(String key) { + return (String) getValue(scopeType, key); + } + +// public String getScopeType(String ruleId, String subcompanyId) { +// String PK = ruleId + "|1|" + subcompanyId; +// String scopeType = getScopeType(PK); +// if (scopeType == null || scopeType == "") { +// PK = ruleId + "|0"; +// scopeType = getScopeType(PK); +// } +// return scopeType; +// } + + private String getScopeValue(String key) { + return (String) getValue(scopeValue, key); + } + +// public String getScopeValue(String ruleId, String subcompanyId) { +// String PK = ruleId + "|1|" + subcompanyId; +// String scopeValue = getScopeValue(PK); +// if (scopeValue == null || scopeValue == "") { +// PK = ruleId + "|0"; +// scopeValue = getScopeValue(PK); +// } +// return scopeValue; +// } + + private String getDistributionMode(String key) { + return (String) getValue(distributionMode, key); + } + +// public String getDistributionMode(String ruleId, String subcompanyId) { +// String PK = ruleId + "|1|" + subcompanyId; +// String distributionMode = getDistributionMode(PK); +// if (distributionMode == null || distributionMode == "") { +// PK = ruleId + "|0"; +// distributionMode = getDistributionMode(PK); +// } +// return distributionMode; +// } + + private String getAnnualAmount(String key) { + return (String) getValue(annualAmount, key); + } + +// public String getAnnualAmount(String ruleId, String subcompanyId) { +// String PK = ruleId + "|1|" + subcompanyId; +// String annualAmount = getAnnualAmount(PK); +// if (annualAmount == null || annualAmount == "") { +// PK = ruleId + "|0"; +// annualAmount = getAnnualAmount(PK); +// } +// return annualAmount; +// } + + private String getLegalKey(String key) { + return (String) getValue(legalKey, key); + } + +// public String getLegalKey(String ruleId, String subcompanyId) { +// String PK = ruleId + "|1|" + subcompanyId; +// String legalKey = getLegalKey(PK); +// if (legalKey == null || legalKey == "") { +// PK = ruleId + "|0"; +// legalKey = getLegalKey(PK); +// } +// return legalKey; +// } + + private String getWelfareKey(String key) { + return (String) getValue(welfareKey, key); + } + +// public String getWelfareKey(String ruleId, String subcompanyId) { +// String PK = ruleId + "|1|" + subcompanyId; +// String welfareKey = getWelfareKey(PK); +// if (welfareKey == null || welfareKey == "") { +// PK = ruleId + "|0"; +// welfareKey = getWelfareKey(PK); +// } +// return welfareKey; +// } + + private String getPriority(String key) { + return (String) getValue(priority, key); + } + +// public String getPriority(String ruleId, String subcompanyId) { +// String PK = ruleId + "|1|" + subcompanyId; +// String priority = getPriority(PK); +// if (priority == null || priority == "") { +// PK = ruleId + "|0"; +// priority = getPriority(PK); +// } +// return priority; +// } + + private String getValidityRule(String key) { + return (String) getValue(validityRule, key); + } + +// public String getValidityRule(String ruleId, String subcompanyId) { +// String PK = ruleId + "|1|" + subcompanyId; +// String validityRule = getValidityRule(PK); +// if (validityRule == null || validityRule == "") { +// PK = ruleId + "|0"; +// validityRule = getValidityRule(PK); +// } +// return validityRule; +// } + + private String getExpirationMonth(String key) { + return (String) getValue(expirationMonth, key); + } + +// public String getExpirationMonth(String ruleId, String subcompanyId) { +// String PK = ruleId + "|1|" + subcompanyId; +// String expirationMonth = getExpirationMonth(PK); +// if (expirationMonth == null || expirationMonth == "") { +// PK = ruleId + "|0"; +// expirationMonth = getExpirationMonth(PK); +// } +// if (expirationMonth.length() == 1) { +// expirationMonth = "0" + expirationMonth; +// } +// return expirationMonth; +// } + + private String getExpirationDay(String key) { + return (String) getValue(expirationDay, key); + } + +// public String getExpirationDay(String ruleId, String subcompanyId) { +// String PK = ruleId + "|1|" + subcompanyId; +// String expirationDay = getExpirationDay(PK); +// if (expirationDay == null || expirationDay == "") { +// PK = ruleId + "|0"; +// expirationDay = getExpirationDay(PK); +// } +// if (expirationDay.length() == 1) { +// expirationDay = "0" + expirationDay; +// } +// return expirationDay; +// } + + private String getEffectiveDays(String key) { + return (String) getValue(effectiveDays, key); + } + +// public String getEffectiveDays(String ruleId, String subcompanyId) { +// String PK = ruleId + "|1|" + subcompanyId; +// String effectiveDays = getEffectiveDays(PK); +// if (effectiveDays == null || effectiveDays == "") { +// PK = ruleId + "|0"; +// effectiveDays = getEffectiveDays(PK); +// } +// if (Util.getIntValue(effectiveDays, 0) < 1) { +// effectiveDays = "1"; +// } +// return effectiveDays; +// } + + private String getEffectiveMonths(String key) { + return (String) getValue(effectiveMonths, key); + } + +// public String getEffectiveMonths(String ruleId, String subcompanyId) { +// String PK = ruleId + "|1|" + subcompanyId; +// String effectiveMonths = getEffectiveMonths(PK); +// if (effectiveMonths == null || effectiveMonths == "") { +// PK = ruleId + "|0"; +// effectiveMonths = getEffectiveMonths(PK); +// } +// if (Util.getIntValue(effectiveMonths, 0) < 1) { +// effectiveMonths = "1"; +// } +// return effectiveMonths; +// } + + private String getExtensionEnable(String key) { + return (String) getValue(extensionEnable, key); + } + +// public String getExtensionEnable(String ruleId, String subcompanyId) { +// String PK = ruleId + "|1|" + subcompanyId; +// String extensionEnable = getExtensionEnable(PK); +// if (extensionEnable == null || extensionEnable == "") { +// PK = ruleId + "|0"; +// extensionEnable = getExtensionEnable(PK); +// } +// return extensionEnable; +// } + + private String getExtendedDays(String key) { + return (String) getValue(extendedDays, key); + } + +// public String getExtendedDays(String ruleId, String subcompanyId) { +// String PK = ruleId + "|1|" + subcompanyId; +// String extendedDays = getExtendedDays(PK); +// if (extendedDays == null || extendedDays == "") { +// PK = ruleId + "|0"; +// extendedDays = getExtendedDays(PK); +// } +// return extendedDays; +// } + + private String getReleaseRule(String key) { + return (String) getValue(releaseRule, key); + } + +// public String getReleaseRule(String ruleId, String subcompanyId) { +// String PK = ruleId + "|1|" + subcompanyId; +// String releaseRule = getReleaseRule(PK); +// if (releaseRule == null || releaseRule == "") { +// PK = ruleId + "|0"; +// releaseRule = getReleaseRule(PK); +// } +// return releaseRule; +// } + + private String getLeaveCode(String key) { + return (String) getValue(leaveCode, key); + } + +// public String getLeaveCode(String ruleId, String subcompanyId) { +// String PK = ruleId + "|1|" + subcompanyId; +// String leaveCode = getLeaveCode(PK); +// if (leaveCode == null || leaveCode == "") { +// PK = ruleId + "|0"; +// leaveCode = getLeaveCode(PK); +// } +// return leaveCode; +// } + + private String getCalcMethod(String key) { + return (String) getValue(calcMethod, key); + } + +// public String getCalcMethod(String ruleId, String subcompanyId) { +// String PK = ruleId + "|1|" + subcompanyId; +// String calcMethod = getCalcMethod(PK); +// if (calcMethod == null || calcMethod == "") { +// PK = ruleId + "|0"; +// calcMethod = getCalcMethod(PK); +// } +// return calcMethod; +// } + + private String getBaseAmountReleaseDate(String key) { + return (String) getValue(baseAmountReleaseDate, key); + } + +// public String getBaseAmountReleaseDate(String ruleId, String subcompanyId){ +// String PK = ruleId + "|1|" + subcompanyId; +// String baseAmountReleaseDate = getBaseAmountReleaseDate(PK); +// if (baseAmountReleaseDate == null || baseAmountReleaseDate == "") { +// PK = ruleId + "|0"; +// baseAmountReleaseDate = getBaseAmountReleaseDate(PK); +// } +// return baseAmountReleaseDate; +// } + + private String getBaseAmountChangeDate(String key) { + return (String) getValue(baseAmountChangeDate, key); + } + +// public String getBaseAmountChangeDate(String ruleId, String subcompanyId){ +// String PK = ruleId + "|1|" + subcompanyId; +// String baseAmountChangeDate = getBaseAmountChangeDate(PK); +// if (baseAmountChangeDate == null || baseAmountChangeDate == "") { +// PK = ruleId + "|0"; +// baseAmountChangeDate = getBaseAmountChangeDate(PK); +// } +// return baseAmountChangeDate; +// } + + private String getConvertMode(String key) { + return (String) getValue(convertMode, key); + } + +// public String getConvertMode(String ruleId, String subcompanyId){ +// String PK = ruleId + "|1|" + subcompanyId; +// String convertMode = getConvertMode(PK); +// if (convertMode == null || convertMode == "") { +// PK = ruleId + "|0"; +// convertMode = getConvertMode(PK); +// } +// if (convertMode == null || convertMode.equals("")) { +// convertMode = "1"; +// } +// return convertMode; +// } + + private String getDecimalDigit(String key) { + return (String) getValue(decimalDigit, key); + } + +// public String getDecimalDigit(String ruleId, String subcompanyId){ +// String PK = ruleId + "|1|" + subcompanyId; +// String decimalDigit = getDecimalDigit(PK); +// if (decimalDigit == null || decimalDigit == "") { +// PK = ruleId + "|0"; +// decimalDigit = getDecimalDigit(PK); +// } +// if (decimalDigit == null || decimalDigit == "" || Util.getIntValue(decimalDigit, 0) < 2) { +// decimalDigit = "2"; +// } +// return decimalDigit; +// } + + private String getExcludeSubAccount(String key) { + return (String) getValue(excludeSubAccount, key); + } + +// public String getExcludeSubAccount(String ruleId, String subcompanyId){ +// String PK = ruleId + "|1|" + subcompanyId; +// String excludeSubAccount = getExcludeSubAccount(PK); +// if (excludeSubAccount == null || excludeSubAccount == "") { +// PK = ruleId + "|0"; +// excludeSubAccount = getExcludeSubAccount(PK); +// } +// return excludeSubAccount; +// } + + private String getBeforeFormal(String key) { + return (String) getValue(beforeFormal, key); + } + +// public String getBeforeFormal(String ruleId, String subcompanyId){ +// String PK = ruleId + "|1|" + subcompanyId; +// String beforeFormal = getBeforeFormal(PK); +// if (beforeFormal == null || beforeFormal == "") { +// PK = ruleId + "|0"; +// beforeFormal = getBeforeFormal(PK); +// } +// return beforeFormal; +// } + private String getSeveralChildren(String key) { + return (String) getValue(severalChildren, key); + } + +// public String getSeveralChildren(String ruleId, String subcompanyId){ +// String PK = ruleId + "|1|" + subcompanyId; +// String severalChildren = getSeveralChildren(PK); +// if (severalChildren == null || severalChildren == "") { +// PK = ruleId + "|0"; +// severalChildren = getSeveralChildren(PK); +// } +// return severalChildren; +// } + + private String getYearsOld(String key) { + return (String) getValue(yearsOld, key); + } + +// public String getYearsOld(String ruleId, String subcompanyId){ +// String PK = ruleId + "|1|" + subcompanyId; +// String yearsOld = getYearsOld(PK); +// if (yearsOld == null || yearsOld == "") { +// PK = ruleId + "|0"; +// yearsOld = getYearsOld(PK); +// } +// return yearsOld; +// } + private String getIsProvince(String key) { + return (String) getValue(isprovince, key); + } + + private String getCarryOver(String key) { + return (String) getValue(carryOver, key); + } + +// public String getIsProvince(String ruleId, String subcompanyId){ +// String PK = ruleId + "|1|" + subcompanyId; +// String isprovince = getIsProvince(PK); +// if (isprovince == null || isprovince == "") { +// PK = ruleId + "|0"; +// isprovince = getIsProvince(PK); +// } +// return isprovince; +// } + + + + public String getId(String ruleId, String subcompanyId, String departmentId, String resourceId) { + String value = ""; + String[] scopeValue = {resourceId, departmentId, subcompanyId}; + for(int i=0; i fromList = new ArrayList(); + List toList = new ArrayList(); + for (int i = 0; i < restTimeLen3; i++) { + String startType = "0"; + String startTime = Util.getIntValues((String) params.get("startTime3_" + i)); + String endType = "0"; + String endTime = Util.getIntValues((String) params.get("endTime3_" + i)); + + String fromDateTime = (startType.equals("0") ? currentDate : tomorrowDate) + " " + startTime + ":00"; + String toDateTime = (endType.equals("0") ? currentDate : tomorrowDate) + " " + endTime + ":00"; + if (fromDateTime.compareTo(toDateTime) > 0) { + logger.info("结束时间必须大于开始时间,fromDateTime=" + fromDateTime + ",toDateTime=" + toDateTime); + return -1; + } + fromList.add(fromDateTime); + toList.add(toDateTime); + } + /*利用冒泡法对日期时间进行排序*/ + for (int i = 0; i < fromList.size(); i++) { + for (int j = 0; j < fromList.size() - i - 1; j++) { + if (fromList.get(j).compareTo(fromList.get(j + 1)) > 0) { + String str = fromList.get(j); + fromList.set(j, fromList.get(j + 1)); + fromList.set(j + 1, str); + + str = toList.get(j); + toList.set(j, toList.get(j + 1)); + toList.set(j + 1, str); + } + } + } + /*根据排序后的数据判断是否时间段有重叠*/ + for (int i = 0; i < fromList.size() - 1; i++) { + if (fromList.get(i + 1).compareTo(toList.get(i)) < 0) { + logger.info("休息时段不能交叉"); + return -1; + } + } + } + + /*校验休息日排除休息时间的设置是否正确*/ + if (hasRestTime1 == 1) { + int restTimeLen1 = Util.getIntValue((String) params.get("restTimeLen1"), 0); + + List fromList = new ArrayList(); + List toList = new ArrayList(); + for (int i = 0; i < restTimeLen1; i++) { + String startType = "0"; + String startTime = Util.getIntValues((String) params.get("startTime1_" + i)); + String endType = "0"; + String endTime = Util.getIntValues((String) params.get("endTime1_" + i)); + + String fromDateTime = (startType.equals("0") ? currentDate : tomorrowDate) + " " + startTime + ":00"; + String toDateTime = (endType.equals("0") ? currentDate : tomorrowDate) + " " + endTime + ":00"; + if (fromDateTime.compareTo(toDateTime) > 0) { + logger.info("结束时间必须大于开始时间:fromDateTime=" + fromDateTime + ",toDateTime=" + toDateTime); + return -1; + } + fromList.add(fromDateTime); + toList.add(toDateTime); + } + /*利用冒泡法对日期时间进行排序*/ + for (int i = 0; i < fromList.size(); i++) { + for (int j = 0; j < fromList.size() - i - 1; j++) { + if (fromList.get(j).compareTo(fromList.get(j + 1)) > 0) { + String str = fromList.get(j); + fromList.set(j, fromList.get(j + 1)); + fromList.set(j + 1, str); + + str = toList.get(j); + toList.set(j, toList.get(j + 1)); + toList.set(j + 1, str); + } + } + } + /*根据排序后的数据判断是否时间段有重叠*/ + for (int i = 0; i < fromList.size() - 1; i++) { + if (fromList.get(i + 1).compareTo(toList.get(i)) < 0) { + logger.info("休息时段不能交叉"); + return -1; + } + } + } + + String sql = "insert into kq_OvertimeRules(name,groupIds,isDelete) values(?,?,0)"; + RecordSet recordSet = new RecordSet(); + flag = recordSet.executeUpdate(sql, name, groupIds); + if (!flag) { + logger.info("加班规则保存失败");//保存失败 + return -1; + } + + sql = "select max(id) maxId from kq_OvertimeRules"; + recordSet.executeQuery(sql); + if (recordSet.next()) { + ruleId = recordSet.getInt("maxId"); + } + + if (ruleId != 0) { + sql = "insert into kq_OvertimeRulesDetail(ruleId,dayType,overtimeEnable,computingMode,startTime,minimumLen,maxmumLen,paidLeaveEnable,lenOfOvertime,lenOfLeave,hasRestTime,paidleaveenabletype,paidleaveenableflowtype) " + + "values(?,?,?,?,?,?,?,?,?,?,?,?)"; + /** + * 保存工作日加班规则 + */ + flag = recordSet.executeUpdate(sql, ruleId, 2, overtimeEnable2, computingMode2, startTime2, minimumLen2, maxmumLen2, paidLeaveEnable2, lenOfOvertime2, lenOfLeave2, 0,paidLeaveEnableType2,paidLeaveEnableFlowType2); + if (!flag) { + logger.info("工作日加班规则保存失败");//保存失败 + return -1; + } + /** + * 保存休息日加班规则 + */ + flag = recordSet.executeUpdate(sql, ruleId, 3, overtimeEnable3, computingMode3, 0, minimumLen3, maxmumLen3, paidLeaveEnable3, lenOfOvertime3, lenOfLeave3, hasRestTime3,paidLeaveEnableType3,paidLeaveEnableFlowType3); + if (!flag) { + logger.info("休息日加班规则保存失败");//保存失败 + return -1; + } + + if (hasRestTime3 == 1) { + int restTimeLen3 = Util.getIntValue((String) params.get("restTimeLen3"), 0); + + for (int i = 0; i < restTimeLen3; i++) { + String startType = "0"; + String startTime = Util.getIntValues((String) params.get("startTime3_" + i)); + String endType = "0"; + String endTime = Util.getIntValues((String) params.get("endTime3_" + i)); + + String restTimeSql = "insert into kq_OvertimeRestTime(ruleId,dayType,startType,startTime,endType,endTime) values(?,?,?,?,?,?)"; + flag = recordSet.executeUpdate(restTimeSql, ruleId, 3, startType, startTime, endType, endTime); + if (!flag) { + logger.info("休息日加班规则休息时段保存失败");//保存失败 + return -1; + } + } + } + /** + * 保存节假日加班规则 + */ + flag = recordSet.executeUpdate(sql, ruleId, 1, overtimeEnable1, computingMode1, 0, minimumLen1, maxmumLen1, paidLeaveEnable1, lenOfOvertime1, lenOfLeave1, hasRestTime1,paidLeaveEnableType1,paidLeaveEnableFlowType1); + if (!flag) { + logger.info("节假日加班规则保存失败"); + return -1; + } + + if (hasRestTime1 == 1) { + int restTimeLen1 = Util.getIntValue((String) params.get("restTimeLen1"), 0); + + for (int i = 0; i < restTimeLen1; i++) { + String startType = "0"; + String startTime = Util.getIntValues((String) params.get("startTime1_" + i)); + String endType = "0"; + String endTime = Util.getIntValues((String) params.get("endTime1_" + i)); + + String restTimeSql = "insert into kq_OvertimeRestTime(ruleId,dayType,startType,startTime,endType,endTime) values(?,?,?,?,?,?)"; + flag = recordSet.executeUpdate(restTimeSql, ruleId, 1, startType, startTime, endType, endTime); + if (!flag) { + logger.info("节假日加班规则休息时段保存失败"); + return -1; + } + } + } + } + } catch (Exception e) { + ruleId = -1; + } + return ruleId; + } + + /************************************************加班单位的相关接口************************************************/ + /** + * 获取最小加班单位 + * 1-按天加班 + * 2-按半天加班 + * 3-按小时加班 + * 4-按整天加班 + * 5-按半小时加班 + * 6-按整小时加班 + * @return -1:接口异常,返回的无效数据。 + */ + public static int getMinimumUnit() { + int minimumUnit = -1; + String sql = "select * from kq_OvertimeUnit where (isDelete is null or isDelete !=1) and id=1"; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql); + if (recordSet.next()) { + minimumUnit = recordSet.getInt("minimumUnit"); + } + return minimumUnit; + } + + /** + * 获取最小加班单位 + * 1-按天加班 + * 2-按半天加班 + * 3-按小时加班 + * 4-按整天加班 + * 5-按半小时加班 + * 6-按整小时加班 + * @return -1:接口异常,返回的无效数据。 + */ + public static Map getMinimumUnitAndConversion() { + Map map = Maps.newHashMap(); + int minimumUnit = -1; + int overtimeConversion = -1; + String sql = "select * from kq_OvertimeUnit where (isDelete is null or isDelete !=1) and id=1"; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql); + if (recordSet.next()) { + minimumUnit = recordSet.getInt("minimumUnit"); + overtimeConversion = recordSet.getInt("overtimeConversion"); + map.put("minimumUnit", ""+minimumUnit); + map.put("overtimeConversion", ""+overtimeConversion); + } + return map; + } + + + /** + * 获取加班单位的日折算时长 + * + * @return -1:接口异常,返回的无效数据。 + */ + public static double getHoursToDay() { + double hoursToDay = -1.00; + String sql = "select * from kq_OvertimeUnit where (isDelete is null or isDelete !=1) and id=1"; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql); + if (recordSet.next()) { + hoursToDay = recordSet.getDouble("hoursToDay"); + } + BigDecimal bigDecimal = new BigDecimal(hoursToDay); + return bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); + } + + /** + * 获取半天显示类型,是时间还是下拉框 + * 半天单位 时间选择方式:1-下拉框选择 、2-具体时间 + * @return + */ + public static String getTimeselection() { + int timeselection = 1; + String sql = "select * from kq_OvertimeUnit where (isDelete is null or isDelete !=1) and id=1"; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql); + if (recordSet.next()) { + timeselection = recordSet.getInt("timeselection"); + } + if(timeselection == 1 || timeselection == 2){ + return ""+timeselection; + }else{ + return "1"; + } + } + + /** + * 获取加班所有需要的数据 + * @param resourceId + * @param date + * @param changeTypeMap + * @return + */ + public static void getOverTimeData(String resourceId, String date, + Map changeTypeMap,Map overRulesDetailMap,Map> restTimeMap,Map computingModeMap) { + int changeType = -1; + + KQTimesArrayComInfo kqTimesArrayComInfo = new KQTimesArrayComInfo(); + /*获取考勤组的ID,因为考勤组有有效期,所以需要传入日期*/ + KQGroupMemberComInfo kqGroupMemberComInfo = new KQGroupMemberComInfo(); + String groupId = Util.null2s(kqGroupMemberComInfo.getKQGroupId(resourceId, date),""); + + /*该人员不存在于任意一个考勤组中,请为其设置考勤组*/ + if(groupId.length() == 0){ + logger.writeLog("该人员不存在于任意一个考勤组中,请为其设置考勤组。resourceId=" + resourceId + ",date=" + date); + return ; + } + KQGroupComInfo kqGroupComInfo = new KQGroupComInfo(); + String overtimeType = kqGroupComInfo.getOvertime_type(groupId); + + changeType = KQHolidaySetBiz.getChangeType(groupId, date); + if(KQHolidaySetBiz.getWorkDay(resourceId, date)){ + changeType = -1; + } + if (changeType != 1 && changeType != 2 && changeType != 3) { + KQWorkTime kqWorkTime = new KQWorkTime(); + changeType = kqWorkTime.isWorkDay(resourceId, date) ? 2 : 3; + } + String change_key = date+"_"+resourceId; + changeTypeMap.put(change_key, changeType); + + List restTimeList = new ArrayList(); + int overtimeRuleId = 0;//加班规则的ID + RecordSet recordSet = new RecordSet(); + RecordSet rs = new RecordSet(); + String sql = "select id from kq_OvertimeRules where (isDelete is null or isDelete !=1) "; + if (recordSet.getDBType().equalsIgnoreCase("sqlserver")) { + sql += " and ','+groupIds+',' like '%," + groupId + ",%'"; + } else if (recordSet.getDBType().equalsIgnoreCase("mysql")) { + sql += " and concat(',',groupIds,',') like '%," + groupId + ",%'"; + } else { + sql += " and ','||groupIds||',' like '%," + groupId + ",%'"; + } + if("1".equals(overtimeType)){ + //如果是按照班次的 + KQWorkTime kqWorkTime = new KQWorkTime(); + String serialId = kqWorkTime.getSerialIds(resourceId, date); + if(StringUtil.isNotNull(serialId)){ + String getShiftSql = "select * from kq_shiftmanagement where (isdelete is null or isdelete <> '1') and id="+serialId; + rs.executeQuery(getShiftSql); + if(rs.next()){ + String overtimeId = rs.getString("overtime_rule_id"); + if(StringUtil.isNotNull(overtimeId)){ + sql = "select id from kq_OvertimeRules where (isDelete is null or isDelete !=1) and id = "+overtimeId; + }else{ + logger.writeLog("该人员这一天班次的加班规则为空。resourceId=" + resourceId + ",date=" + date); + return ; + } + }else{ + logger.writeLog("该人员这一天没有查询到班次。resourceId=" + resourceId + ",date=" + date); + return ; + } + }else{ + logger.writeLog("该人员这一天没有设置班次。resourceId=" + resourceId + ",date=" + date); + return ; + } + } + recordSet.executeQuery(sql); + if (recordSet.next()) { + overtimeRuleId = recordSet.getInt("id"); + + sql = "select * from kq_OvertimeRulesDetail where ruleId=" + overtimeRuleId + " and dayType=" + changeType; + recordSet.executeQuery(sql); + if (recordSet.next()) { + int id = recordSet.getInt("id"); + int ruleId = recordSet.getInt("ruleId"); + int dayType = recordSet.getInt("dayType"); + int overtimeEnable = recordSet.getInt("overtimeEnable"); + int computingMode = recordSet.getInt("computingMode"); + int startTime = recordSet.getInt("startTime"); + int minimumLen = recordSet.getInt("minimumLen"); + int maxmumLen = Util.getIntValue(recordSet.getString("maxmumLen"), 2880); + int paidLeaveEnable = recordSet.getInt("paidLeaveEnable"); + double lenOfOvertime = Util.getDoubleValue(recordSet.getString("lenOfOvertime"), 1.00); + double lenOfLeave = Util.getDoubleValue(recordSet.getString("lenOfLeave"), 1.00); + int hasRestTime = Util.getIntValue(recordSet.getString("hasRestTime")); + int before_startTime = recordSet.getInt("before_startTime"); + int canmiddlerest = Util.getIntValue(recordSet.getString("canmiddlerest"), 0); + + int paidLeaveEnableType = recordSet.getInt("paidLeaveEnableType"); + int paidLeaveEnableDefaultType = recordSet.getInt("paidLeaveEnableDefaultType"); + int paidLeaveEnableFlowType = recordSet.getInt("paidLeaveEnableFlowType"); + int restTimeType = recordSet.getInt("restTimeType"); + int has_cut_point = Util.getIntValue(Util.null2s(recordSet.getString("has_cut_point"),"0"),0); + if(paidLeaveEnableType <= 0){ + paidLeaveEnableType = 1; + } + if(paidLeaveEnableDefaultType <= 0){ + paidLeaveEnableDefaultType = 1; + } + if(paidLeaveEnableFlowType <= 0){ + paidLeaveEnableFlowType = 1; + } + if(paidLeaveEnableType == 1 && paidLeaveEnable == 0){ + //如果就没有开启关联调休,那么默认的加班转调休方式就是第一种 + paidLeaveEnableDefaultType = 1; + } + if(restTimeType <= 0){ + restTimeType = 1; + } + String cut_point = Util.null2s(recordSet.getString("cut_point"),""); + String key = date+"_"+changeType; + + KQOvertimeRulesDetailEntity kqOvertimeRulesDetail = new KQOvertimeRulesDetailEntity(); + kqOvertimeRulesDetail.setRuleId(ruleId); + kqOvertimeRulesDetail.setDayType(dayType); + kqOvertimeRulesDetail.setOvertimeEnable(overtimeEnable); + kqOvertimeRulesDetail.setComputingMode(computingMode); + kqOvertimeRulesDetail.setStartTime(startTime); + kqOvertimeRulesDetail.setMinimumLen(minimumLen); + kqOvertimeRulesDetail.setMaxmumLen(maxmumLen); + kqOvertimeRulesDetail.setPaidLeaveEnable(paidLeaveEnable); + kqOvertimeRulesDetail.setLenOfOvertime(lenOfOvertime); + kqOvertimeRulesDetail.setLenOfLeave(lenOfLeave); + kqOvertimeRulesDetail.setHasRestTime(hasRestTime); + kqOvertimeRulesDetail.setBefore_startTime(before_startTime); + kqOvertimeRulesDetail.setCut_point(cut_point); + kqOvertimeRulesDetail.setHas_cut_point(has_cut_point); + kqOvertimeRulesDetail.setId(id); + kqOvertimeRulesDetail.setPaidLeaveEnableType(paidLeaveEnableType); + kqOvertimeRulesDetail.setPaidLeaveEnableDefaultType(paidLeaveEnableDefaultType); + kqOvertimeRulesDetail.setPaidLeaveEnableFlowType(paidLeaveEnableFlowType); + kqOvertimeRulesDetail.setRestTimeType(restTimeType); + kqOvertimeRulesDetail.setIsOvertimeCal(canmiddlerest); + overRulesDetailMap.put(key, kqOvertimeRulesDetail); + computingModeMap.put(key, computingMode); + + /** + * 因为休息时段可以设置次日的数据,所以获取某一天的休息时段的时候,需要先考虑上一个日期所设置的次日的休息时段 + */ + String lastDay = DateUtil.addDay(date, -1, "yyyy-MM-dd"); + KQOvertimeRulesDetailEntity pre_kqOvertimeRulesDetail = getOvertimeRulesDetail(resourceId, lastDay); + int pre_overtimeEnable = pre_kqOvertimeRulesDetail.getOvertimeEnable(); + int pre_hasRestTime = pre_kqOvertimeRulesDetail.getHasRestTime(); + if (pre_overtimeEnable == 1 && pre_hasRestTime == 1) { + int prehas_cut_point = pre_kqOvertimeRulesDetail.getHas_cut_point(); + String precut_point = pre_kqOvertimeRulesDetail.getCut_point(); + + int pre_dayType = pre_kqOvertimeRulesDetail.getDayType(); + int pre_ruleId = pre_kqOvertimeRulesDetail.getRuleId(); + + sql = "select * from kq_OvertimeRestTime where ruleId=" + pre_ruleId + " and dayType=" + pre_dayType; + RecordSet recordSet1 = new RecordSet(); + recordSet1.executeQuery(sql); + while (recordSet1.next()) { + String startType = recordSet1.getString("startType"); + String startTime1 = recordSet1.getString("startTime"); + String endType = recordSet1.getString("endType"); + String endTime = recordSet1.getString("endTime"); + if("1".equals(endType)){ + if(!"1".equals(startType)){ + startTime1 = "00:00"; + } + if(1 == prehas_cut_point){ + //如果昨日的加班规则开启了临界点 需要判断下是否是临界点之后的排除休息时间,是临界点之后的排除休息时间才会影响到第二天的 + if(StringUtil.isNotNull(precut_point)){ + //比如排除休息时间是23-次日1,归属点2点,那么次日0到次日1这部分可以划到第二天的排除休息时间里 + //比如排除休息时间是23-次日2,归属点1点,那么次日1到次日2这部分可以不可以划到第二天了的排除休息时间里 + //比如排除休息时间是次日2-次日4,归属点1点,那么次日2到次日4这部分可以不可以划到第二天了的排除休息时间里 + if(precut_point.compareTo(startTime1) < 0){ + //如果归属点小于开始时间了,则这个排除休息时间就没效果了 + continue; + }else{ + if(precut_point.compareTo(endTime) < 0){ + //如果归属点小于结束时间,大于排除休息开始时间,则排除休息时间就直接以归属点作为结束时间 + endTime = precut_point; + } + } + } + } + String[] str = new String[]{startTime1, endTime}; + restTimeList.add(str); + } + } + } + + overtimeEnable = kqOvertimeRulesDetail.getOvertimeEnable(); + hasRestTime = kqOvertimeRulesDetail.getHasRestTime(); + restTimeType = kqOvertimeRulesDetail.getRestTimeType(); + if (overtimeEnable == 1 && hasRestTime == 1) { + if(restTimeType == 1){ + sql = "select * from kq_OvertimeRestTime where ruleId=" + ruleId + " and dayType=" + dayType; + RecordSet recordSet1 = new RecordSet(); + recordSet1.executeQuery(sql); + while (recordSet1.next()) { + String startType = recordSet1.getString("startType"); + String startTime1 = recordSet1.getString("startTime"); + String endType = recordSet1.getString("endType"); + String endTime = recordSet1.getString("endTime"); + + if("1".equals(startType)){ + startTime1 = kqTimesArrayComInfo.turn24to48Time(startTime1); + } + if("1".equals(endType)){ + endTime = kqTimesArrayComInfo.turn24to48Time(endTime); + } + String[] str = new String[]{startTime1, endTime}; + restTimeList.add(str); + } + }else{ + sql = "select * from kq_OvertimeRestlength where ruleId=" + ruleId + " and dayType=" + dayType+" order by dsporder "; + RecordSet recordSet1 = new RecordSet(); + recordSet1.executeQuery(sql); + while (recordSet1.next()) { + String overlength = Util.null2String(recordSet1.getString("overlength")); + String cutlength = Util.null2String(recordSet1.getString("cutlength")); + if(overlength.length() > 0 && cutlength.length() > 0){ + String[] str = new String[]{overlength, cutlength}; + restTimeList.add(str); + } + } + } + } + restTimeMap.put(key, restTimeList); + } + + + } else { + logger.writeLog("该人员所属的考勤组没有设置过任何加班规则,请为其设置加班规则。resourceId=" + resourceId + ",date="+date+",changeType=" + changeType); + } + + return ; + } + + /** + * 按加班时长范围设置转调休时长 + * 按照加班时长从大到小排序 取到最大的满足了,那么调休就直接按照这个来转调休了 + */ + public Map> getBalanceLengthDetailMap(int ruleDetailid){ + Map> balanceLengthDetailMap = Maps.newHashMap(); + RecordSet recordSet = new RecordSet(); + List overtimelengthList = Lists.newArrayList(); + List balancelengthList = Lists.newArrayList(); + String sql = "select * from kq_OvertimeBalanceLengthDetail where rulesdetailid= ? order by overtimelength desc "; + recordSet.executeQuery(sql, ruleDetailid); + while (recordSet.next()){ + String overtimelength = recordSet.getString("overtimelength"); + String balancelength = recordSet.getString("balancelength"); + overtimelengthList.add(overtimelength); + balancelengthList.add(balancelength); + } + if(!overtimelengthList.isEmpty() && !balancelengthList.isEmpty()){ + balanceLengthDetailMap.put("overtimelengthList", overtimelengthList); + balanceLengthDetailMap.put("balancelengthList", balancelengthList); + return balanceLengthDetailMap; + } + return balanceLengthDetailMap; + } + + /** + * 按加班的时间段设置转调休时长 + */ + public Map> getBalanceTimeDetailMap(int ruleDetailid){ + Map> balanceTimethDetailMap = Maps.newHashMap(); + RecordSet recordSet = new RecordSet(); + List idList = Lists.newArrayList(); + List timepointList = Lists.newArrayList(); + List lenOfOvertimeList = Lists.newArrayList(); + List lenOfLeaveList = Lists.newArrayList(); + String sql = "select * from kq_OvertimeBalanceTimeDetail where rulesdetailid= ? order by dsporder "; + recordSet.executeQuery(sql, ruleDetailid); + while (recordSet.next()){ + String id = recordSet.getString("id"); + String timepoint = recordSet.getString("timepoint"); + String lenOfOvertime = recordSet.getString("lenOfOvertime"); + String lenOfLeave = recordSet.getString("lenOfLeave"); + idList.add(id); + timepointList.add(timepoint); + lenOfOvertimeList.add(lenOfOvertime); + lenOfLeaveList.add(lenOfLeave); + } + if(!timepointList.isEmpty() && !lenOfOvertimeList.isEmpty() && !lenOfLeaveList.isEmpty()){ + balanceTimethDetailMap.put("idList", idList); + balanceTimethDetailMap.put("timepointList", timepointList); + balanceTimethDetailMap.put("lenOfOvertimeList", lenOfOvertimeList); + balanceTimethDetailMap.put("lenOfLeaveList", lenOfLeaveList); + return balanceTimethDetailMap; + } + return balanceTimethDetailMap; + } +} diff --git a/领悦二开new/src/com/engine/kq/biz/KQReportBiz.java b/领悦二开new/src/com/engine/kq/biz/KQReportBiz.java new file mode 100644 index 0000000..7eaca25 --- /dev/null +++ b/领悦二开new/src/com/engine/kq/biz/KQReportBiz.java @@ -0,0 +1,3653 @@ +package com.engine.kq.biz; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.engine.kq.biz.chain.shiftinfo.ShiftInfoBean; +import com.engine.kq.cmd.attendanceButton.ButtonStatusEnum; +import com.engine.kq.enums.FlowReportTypeEnum; +import com.engine.kq.enums.KqSplitFlowTypeEnum; +import com.engine.kq.log.KQLog; +import com.engine.kq.util.KQDurationCalculatorUtil; + +import java.text.DecimalFormatSymbols; +import java.util.Map.Entry; + +import com.engine.kq.util.KQTransMethod; +import weaver.common.DateUtil; +import weaver.common.StringUtil; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.BaseBean; +import weaver.general.TimeUtil; +import weaver.general.Util; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; +import weaver.systeminfo.SystemEnv; + +import java.text.DecimalFormat; +import java.util.*; + +public class KQReportBiz extends BaseBean { + + private static DecimalFormat df = new DecimalFormat("0.00"); + + private DecimalFormatSymbols symbols = new DecimalFormatSymbols(); + + + public String format(double value) { +// DecimalFormatSymbols symbols = new DecimalFormatSymbols(); + symbols.setDecimalSeparator('.'); + df.setMaximumFractionDigits(5); + df.setDecimalFormatSymbols(symbols); + return df.format(value); + } + + + private KQLog kqLog = new KQLog(); + /** + * 初始化当天考勤数据 + */ + public void initKQReportData(){ + String date = DateUtil.getCurrentDate(); + RecordSet rs = new RecordSet(); + String sql = ""; + try{ + boolean hasInit = false; + sql = "select 1 from kq_report_check where check_date = ? "; + rs.executeQuery(sql,date); + if(rs.next()) { + hasInit = true; + } + + String beforeyesterday = DateUtil.addDate(date,-2); + String yesterday = DateUtil.addDate(date,-1); + if(!hasInit){ + //这里做过功能是每天都刷下考勤缓存 因为这个缓存也是异步的,一点都不稳定 + kqLog.info("begin do KQOneStopUp refreshCominfo invoke ..."); + new KQOneStopUp().refreshCominfo(); + kqLog.info("end do KQOneStopUp refreshCominfo invoke ..."); + + KQFormatBiz kqFormatBiz = new KQFormatBiz(); + kqFormatBiz.clearFormatPool(); + //格式化上上天数据 + kqFormatBiz.formatDateByKQDate(beforeyesterday); + //格式化上一天数据 + kqFormatBiz.formatDateByKQDate(yesterday); + //初始化今天数据 + kqFormatBiz.formatDateByKQDate(date); + + sql = " insert into kq_report_check(check_date) values (?)"; + rs.executeUpdate(sql,date); + + writeLog(date+"执行考勤报表数据格式化成功!"); + } + }catch (Exception e){ + writeLog(e); + } + } + + public Map getModel_ShiftRule(String i,String serialId) { + RecordSet rs = new RecordSet(); + HashMap sectionMap = new HashMap<>(); + String getStartWorkSections = "select * from kq_ShiftOnOffWorkSections where SERIALID=? and record=? "; + rs.executeQuery(getStartWorkSections,serialId,i); + while (rs.next()) { + String onoffworktype = Util.null2String(rs.getString("onoffworktype")); + String clockinnot = Util.null2s(Util.null2String(rs.getString("clockinnot")), "0"); + sectionMap.put(onoffworktype, clockinnot); + } + return sectionMap; + } + + /*** + * 获取考勤状态 + * @param resourceId + * @param fromdate + * @param todate + * @param isAll + * @return + */ + public List getKqDateInfo(String resourceId, String fromdate, String todate, boolean isAll) { + List kqdates = new ArrayList<>(); + RecordSet rs = new RecordSet(); + String sql = ""; + try { + Map kqdate = null; + List datas = null; + Map data = null; + sql = " select kqdate,serialid, workbegindate, workbegintime,workenddate, workendtime," + + " signintime,signouttime,beLateMins,graveBeLateMins,leaveEarlyMins,graveLeaveEarlyMins," + + " absenteeismMins, forgotCheckMins,forgotBeginWorkCheckMins,otherinfo,serialnumber "+ + " from kq_format_detail " + + " where resourceid=? and kqdate>=? and kqdate<=? "; + if(!isAll){ + if(rs.getDBType().equalsIgnoreCase("oracle") || Util.null2String(rs.getOrgindbtype()).equals("dm") || Util.null2String(rs.getOrgindbtype()).equals("st")) { + sql += " and nvl(beLateMins,0)+nvl(graveBeLateMins,0)+nvl(leaveEarlyMins,0)+nvl(graveLeaveEarlyMins,0)+nvl(absenteeismMins,0)+nvl(forgotCheckMins,0)+nvl(forgotBeginWorkCheckMins,0)>0 "; + }else if((rs.getDBType()).equalsIgnoreCase("mysql")){ + sql += " and ifnull(beLateMins,0)+ifnull(graveBeLateMins,0)+ifnull(leaveEarlyMins,0)+ifnull(graveLeaveEarlyMins,0)+ifnull(absenteeismMins,0)+ifnull(forgotCheckMins,0)+ifnull(forgotBeginWorkCheckMins,0)>0 "; + }else { + sql += " and isnull(beLateMins,0)+isnull(graveBeLateMins,0)+isnull(leaveEarlyMins,0)+isnull(graveLeaveEarlyMins,0)+isnull(absenteeismMins,0)+isnull(forgotCheckMins,0)+isnull(forgotBeginWorkCheckMins,0)>0 "; + } + } + sql += " order by kqdate,serialnumber "; + + rs.executeQuery(sql,resourceId,fromdate, todate); + while(rs.next()){ + String serialnumber = Util.null2String(rs.getString("serialnumber")); + String serialid = Util.null2String(rs.getString("serialid")); + String workbegindate = Util.null2String(rs.getString("workbegindate")); + String workbegintime = Util.null2String(rs.getString("workbegintime")); + String workenddate = Util.null2String(rs.getString("workenddate")); + String workendtime = Util.null2String(rs.getString("workendtime")); + String signintime = Util.null2String(rs.getString("signintime")); + String signouttime = Util.null2String(rs.getString("signouttime")); + int beLateMins = rs.getInt("beLateMins"); + int graveBeLateMins = rs.getInt("graveBeLateMins"); + int leaveEarlyMins = rs.getInt("leaveEarlyMins"); + int graveLeaveEarlyMins = rs.getInt("graveLeaveEarlyMins"); + int absenteeismMins = rs.getInt("absenteeismMins"); + int forgotCheckMins = rs.getInt("forgotCheckMins"); + int forgotBeginWorkCheckMins = rs.getInt("forgotBeginWorkCheckMins"); + String otherinfo = Util.null2String(rs.getString("otherinfo")); + + String shift_begindate = ""; + String shift_beginworktime = ""; + String shift_enddate = ""; + String shift_endworktime = ""; + if(otherinfo.length() > 0){ + JSONObject otherinfo_object = JSONObject.parseObject(otherinfo); + if(otherinfo_object != null && !otherinfo_object.isEmpty()){ + JSONObject shiftRule = (JSONObject) otherinfo_object.get("shiftRule"); + if(shiftRule != null && !shiftRule.isEmpty()){ + shift_begindate = Util.null2String(shiftRule.get("shift_begindate")); + shift_beginworktime = Util.null2String(shiftRule.get("shift_beginworktime")); + shift_enddate = Util.null2String(shiftRule.get("shift_enddate")); + shift_endworktime = Util.null2String(shiftRule.get("shift_endworktime")); + if(shift_begindate.length() > 0){ + workbegindate = shift_begindate; + } + if(shift_beginworktime.length() > 0){ + workbegintime = shift_beginworktime; + } + if(shift_enddate.length() > 0){ + workenddate = shift_enddate; + } + if(shift_endworktime.length() > 0){ + workendtime = shift_endworktime; + } + } + } + } + + kqdate = new HashMap<>(); + datas = new ArrayList<>(); + kqdate.put("kqdate",Util.null2String(rs.getString("kqdate"))); + if(workbegindate.length()>0){ + data = new HashMap<>(); + data.put("workbegindate",workbegindate); + data.put("workbegintime",workbegintime); + data.put("signintime",signintime); + + data.put("workenddate",workenddate); + data.put("workendtime",workendtime); + data.put("signouttime",signouttime); + String status = ""; + if(beLateMins>0||graveBeLateMins>0){ + status = ButtonStatusEnum.BELATE.getStatusCode(); + } + if(forgotBeginWorkCheckMins>0){ + if(status.length()>0)status+=","; + status += ButtonStatusEnum.NOSIGN_ON.getStatusCode(); + } + if(leaveEarlyMins>0||graveLeaveEarlyMins>0){ + if(status.length()>0)status+=","; + status += ButtonStatusEnum.LEAVEERALY.getStatusCode(); + } + if(absenteeismMins>0){ + int isondutyfreecheck =0; + int isoffdutyfreecheck =0; + Map model_ShiftRule = getModel_ShiftRule(serialnumber, serialid); + Iterator iter = model_ShiftRule.entrySet().iterator(); + while (iter.hasNext()) { + Entry entry = (Entry) iter.next(); + String key = Util.null2String(entry.getKey()); + String value = Util.null2String(entry.getValue()); + if(key.equals("start")&&value.equals("1")){ + isondutyfreecheck = 1; + } + if(key.equals("end")&&value.equals("1")){ + isoffdutyfreecheck = 1; + } + } + data.put("start",isondutyfreecheck); + data.put("end",isoffdutyfreecheck); + if(status.length()>0)status+=","; + status += ButtonStatusEnum.ABSENT.getStatusCode(); + } + if(forgotCheckMins>0){ + if(status.length()>0)status+=","; + status += ButtonStatusEnum.NOSIGN.getStatusCode(); + } + data.put("status",status); + datas.add(data); + } + + kqdate.put("checkInfo",datas); + kqdates.add(kqdate); + } + } catch (Exception e) { + writeLog(e); + } + return kqdates; + } + + /** + * 获取真实的开始日期和结束日期,没有权限的人最大只能查询本季 + * @param fromDate + * @param toDate + * @param user + * @return + */ + public Map realDate(String fromDate, String toDate, User user, String reportType) { + Map dateMap = new HashMap<>(); + dateMap.put("fromDate", fromDate); + dateMap.put("toDate", toDate); + boolean hasRight = false; + if("-100".equals(reportType)) { + RecordSet rs = new RecordSet(); + String departmentId = ""; + rs.executeQuery("select subcompanyid1, departmentId from hrmresource where id = ?", user.getUID()); + if (rs.next()) { + departmentId = StringUtil.vString(rs.getString("departmentId")); + } + hasRight = HrmUserVarify.checkUserRight("MobileSignInfo:Manage", user, departmentId); + } else { + hasRight = new KQReportBiz().hasReportRight(reportType,""+user.getUID()); + } + boolean kq_personal_reportsearch = KQSettingsBiz.showLeaveTypeSet("kq_personal_reportsearch"); + if(!hasRight && kq_personal_reportsearch) { // 开启开关,且没有权限的账号,最大查询只支持到本季 + String seasonFromDate = TimeUtil.getDateByOption("4","0"); + String seasonToDate = TimeUtil.getDateByOption("4","1"); + if(toDate.compareTo(seasonFromDate) < 0 || fromDate.compareTo(seasonToDate) > 0) { + dateMap.put("fromDate", "-1"); + dateMap.put("toDate", "-1"); + return dateMap; + } else if(fromDate.compareTo(seasonFromDate) < 0) { + fromDate = seasonFromDate; + if(toDate.compareTo(seasonToDate) > 0) { + toDate = seasonToDate; + } + } else if(fromDate.compareTo(seasonFromDate) >= 0) { + if(toDate.compareTo(seasonToDate) > 0) { + toDate = seasonToDate; + } + } + } + dateMap.put("fromDate", fromDate); + dateMap.put("toDate", toDate); + return dateMap; + } + + /** + * 是否有考勤报表相关权限 + * @param reportType 1:考勤汇总报表; 2:每日统计报表; 3:原始打卡记录; 4:员工假期余额 + * @param userId + * @return + */ + public boolean hasReportRight(String reportType, String userId){ + String sql = ""; + RecordSet rs = new RecordSet(); + sql = " select sharelevel,subcomid, deptid,userid,jobtitleid,foralluser from kq_reportshare where resourceid=? "; + if(reportType.length()>0 ){ + sql += " and (reportname =0 or reportname =" + reportType+")"; + } + rs.executeQuery(sql,userId); + if(rs.next()) { + return true; + } + return false; + } + + /** + * 将操作导出四大考勤报表的日志记录到数据库中,谁操作的导出,什么时间操作的导出,导出的条件都存储下来 + * @param params + * @param user + */ + public void insertKqReportExportLog(Map params, User user) { + RecordSet rs = new RecordSet(); + String exportParams = JSON.toJSONString(params); + String sql = "insert into kq_exportreport_log(operatorid,exportparams) values(?,?)"; + rs.executeUpdate(sql, user.getUID(), exportParams); + } + + /** + * 获取报表权限 + * @param reportType 报表类型 + * @param userId 用户id + * @param tableExt 别名 + * @return + */ + public String getReportRight(String reportType, String userId, String tableExt){ + String rightSql = ""; + String sql = ""; + RecordSet rs = new RecordSet(); + try{ + List userAllUserIds = new ArrayList<>(); + List userAllDeptIds = new ArrayList<>(); + List userAllSubCompanyIds = new ArrayList<>(); + List userAllJobtitleIds = new ArrayList<>(); + boolean forAllUser = false; + sql = " select sharelevel,subcomid, deptid,userid,jobtitleid,foralluser from kq_reportshare where resourceid=? "; + if(reportType.length()>0 ){ + sql += " and (reportname =0 or reportname =" + reportType+")"; + } + rs.executeQuery(sql,userId); + while(rs.next()){ + int sharelevel = rs.getInt("sharelevel"); + if(sharelevel==0){//分部 + if(Util.null2String(rs.getString("subcomid")).length()>0){ + userAllSubCompanyIds.add(rs.getString("subcomid")); + } + }else if(sharelevel==1){//部门 + if(Util.null2String(rs.getString("deptid")).length()>0) { + userAllDeptIds.add(rs.getString("deptid")); + } + }else if(sharelevel==2){//人员 + if(Util.null2String(rs.getString("userid")).length()>0) { + userAllUserIds.add(rs.getString("userid")); + } + }else if(sharelevel==3){//岗位 + if(Util.null2String(rs.getString("jobtitleid")).length()>0) { + userAllJobtitleIds.add(rs.getString("jobtitleid")); + } + }else if(sharelevel==4){//所有人 + forAllUser = true; + userAllUserIds.clear(); + userAllDeptIds.clear(); + userAllSubCompanyIds.clear(); + userAllJobtitleIds.clear(); + break; + } + } + + if(!forAllUser) { + for (int sharelevel = 0; sharelevel < 4; sharelevel++) { + if (sharelevel == 0) {//分部 + if (userAllSubCompanyIds.size() > 0) { + if(rightSql.length()>0)rightSql+= " or "; + rightSql += tableExt+".subcompanyid1 in(" + String.join(",", userAllSubCompanyIds) + ")"; + } + } else if (sharelevel == 1) {//部门 + if (userAllDeptIds.size() > 0) { + if(rightSql.length()>0)rightSql+= " or "; + rightSql += tableExt+".departmentid in(" + String.join(",", userAllDeptIds) + ")"; + } + } else if (sharelevel == 2) {//人员 + if (userAllUserIds.size() > 0) { + if(rightSql.length()>0)rightSql+= " or "; + rightSql += tableExt+".id in(" + String.join(",", userAllUserIds) + ")"; + } + } else if (sharelevel == 3) {//岗位 + if (userAllJobtitleIds.size() > 0) { + if(rightSql.length()>0)rightSql+= " or "; + rightSql += tableExt+".jobtitle in(" + String.join(",", userAllJobtitleIds) + ")"; + } + } + } + + //可以看自己和下属的考勤 + String selfSql = " ("+tableExt+".id = "+userId+" or "+tableExt+".managerstr like '%,"+userId+",%')"; + if(rightSql.length()>0){ + rightSql = " and ((" +rightSql+") or "+selfSql+" ) "; + }else{ + rightSql = " and "+selfSql; + } + + } + }catch (Exception e){ + writeLog(e); + } + return rightSql; + } + + public static String getUnitType(KQReportFieldComInfo kqReportFieldComInfo, User user){ + String unitTypeName = ""; + String unitType = Util.null2String(kqReportFieldComInfo.getUnittype()); + String parentid = Util.null2String( kqReportFieldComInfo.getParentid()); + String fieldName = Util.null2String(kqReportFieldComInfo.getFieldname()); + if(kqReportFieldComInfo.getIsLeaveType().equals("1")){ + if(fieldName.equals("businessLeave")){ + unitType = KQTravelRulesBiz.getMinimumUnit().equals("3")?"2":"1";//单位类型 + }else if(fieldName.equals("officialBusiness")){ + unitType = KQExitRulesBiz.getMinimumUnit().equals("3")?"2":"1";//单位类型 + }else if(parentid.equals("overtime") || parentid.equals("overtime_nonleave") || parentid.equals("overtime_4leave")){ + unitType = (KQOvertimeRulesBiz.getMinimumUnit()==3 || KQOvertimeRulesBiz.getMinimumUnit()==5 ||KQOvertimeRulesBiz.getMinimumUnit()==6)?"2":"1";//单位类型 + } + } + if(Util.null2String(unitType).length()>0){ + if(unitType.equals("1")){ + unitTypeName=SystemEnv.getHtmlLabelName(1925, user.getLanguage()); + }else if(unitType.equals("2")){ + unitTypeName=SystemEnv.getHtmlLabelName(391, user.getLanguage()); + }else if(unitType.equals("3")){ + unitTypeName=SystemEnv.getHtmlLabelName(18083, user.getLanguage()); + } + } + return unitTypeName; + } + + /** + * 为每日统计报表做流程数据查询 + * @param params + * @param user + * @return + */ + public Map getDailyFlowData(Map params, User user){ + Map datas = new HashMap<>();; + try{ + datas.putAll(getDailyFlowLeaveData(params,user)); + datas.putAll(getDailyFlowEvectionOutData(params,user)); + datas.putAll(getDailyFlowOverTimeData(params,user)); + datas.putAll(getDailyFlowLeaveBackData(params,user)); + + datas.putAll(getSignDetailInfoData(params,user)); + }catch (Exception e){ + writeLog(e); + } + return datas; + } + + public Map getFlowData(Map params, User user){ + Map datas = new HashMap<>();; + try{ + datas.putAll(getFlowLeaveData(params,user)); + datas.putAll(getFlowEvectionOutData(params,user)); + datas.putAll(getFlowOverTimeDataNew(params,user)); + datas.putAll(getFlowOtherData(params,user)); + datas.putAll(getFlowLeaveBackData(params,user)); + datas.putAll(getFlowProcessChangeData(params,user)); + + datas.putAll(getCardMap(params,user)); + datas.putAll(getOverTime(params,user)); + }catch (Exception e){ + writeLog(e); + } + return datas; + } + + /** + * 获取出差和公出数据 + * @param params + * @param user + * @return + */ + public Map getFlowEvectionOutData(Map params, User user){ + Map datas = new HashMap<>();; + RecordSet rs = new RecordSet(); + String sql = ""; + String sqlWhere = " "; + try{ + String[] tables = new String[]{KqSplitFlowTypeEnum.EVECTION.getTablename(),//出差 + KqSplitFlowTypeEnum.OUT.getTablename()};//公出 + + String minimumUnit = "";//单位类型 + double proportion = 0.00;//换算关系 + + JSONObject jsonObj = JSON.parseObject(Util.null2String(params.get("data"))); + String fromDate = Util.null2String(jsonObj.get("fromDate")); + String toDate = Util.null2String(jsonObj.get("toDate")); + String typeselect =Util.null2String(jsonObj.get("typeselect")); + if(typeselect.length()==0)typeselect = "3"; + if(!typeselect.equals("") && !typeselect.equals("0")&& !typeselect.equals("6")){ + if(typeselect.equals("1")){ + fromDate = TimeUtil.getCurrentDateString(); + toDate = TimeUtil.getCurrentDateString(); + }else{ + fromDate = TimeUtil.getDateByOption(typeselect,"0"); + toDate = TimeUtil.getDateByOption(typeselect,"1"); + } + } + String subCompanyId = Util.null2String(jsonObj.get("subCompanyId")); + String departmentId = Util.null2String(jsonObj.get("departmentId")); + String resourceId = Util.null2String(jsonObj.get("resourceId")); + String allLevel = Util.null2String(jsonObj.get("allLevel")); + String isNoAccount = Util.null2String(jsonObj.get("isNoAccount")); + String viewScope = Util.null2String(jsonObj.get("viewScope")); + if(subCompanyId.length()>0){ + sqlWhere +=" and a.subcompanyid1 in("+subCompanyId+") "; + } + + if(departmentId.length()>0){ + sqlWhere +=" and a.departmentid in("+departmentId+") "; + } + + if(resourceId.length()>0){ + sqlWhere +=" and b.resourceid in("+resourceId+") "; + } + + if(viewScope.equals("4")){//我的下属 + if(allLevel.equals("1")){//所有下属 + sqlWhere+=" and a.managerstr like '%,"+user.getUID()+",%'"; + }else{ + sqlWhere+=" and a.managerid="+user.getUID();//直接下属 + } + } + if (!"1".equals(isNoAccount)) { + sqlWhere += " and a.loginid is not null "+(rs.getDBType().equals("oracle")?"":" and a.loginid<>'' "); + } + + for(String table : tables){ + sql = " select resourceid, durationrule, sum(duration) as val from hrmresource a, "+table+" b "+ + " where a.id = b.resourceid and (b.status is null or b.status<>1) and belongdate >='"+fromDate+"' and belongdate <='"+toDate+"' "+sqlWhere+ + " group by resourceid, durationrule "; + rs.execute(sql); + while (rs.next()) { + String resourceid = rs.getString("resourceid"); + double value = rs.getDouble("val"); + String durationrule = rs.getString("durationrule"); + + String flowType = ""; + if(KqSplitFlowTypeEnum.EVECTION.getTablename().equals(table)){ + flowType = "businessLeave"; + minimumUnit = KQTravelRulesBiz.getMinimumUnit();//单位类型 + proportion = Util.getDoubleValue(KQTravelRulesBiz.getHoursToDay());//换算关系 + + }else if(KqSplitFlowTypeEnum.OUT.getTablename().equals(table)){ + flowType = "officialBusiness"; + minimumUnit = KQExitRulesBiz.getMinimumUnit();//单位类型 + proportion = Util.getDoubleValue(KQExitRulesBiz.getHoursToDay());//换算关系 + } + + if(KQUnitBiz.isLeaveHour(minimumUnit)){//按小时 + if(!KQUnitBiz.isLeaveHour(durationrule)){ + if(proportion>0) value = value*proportion; + } + }else{//按天 + if(KQUnitBiz.isLeaveHour(durationrule)){ + if(proportion>0) value = value/proportion; + } + } + + String key = resourceid+"|"+flowType; + if(datas.containsKey(key)){ + value += Util.getDoubleValue(Util.null2String(datas.get(key))); + } + //df.format 默认是不四舍五入的 0.125这样的就会直接变成0.12了 + df.setMaximumFractionDigits(5); + datas.put(key, format(value)); + } + } + }catch (Exception e){ + writeLog(e); + } + return datas; + } + + /** + * 获取每日的出差和公出数据 + * @param params + * @param user + * @return + */ + public Map getDailyFlowEvectionOutData(Map params, User user){ + Map datas = new HashMap<>();; + RecordSet rs = new RecordSet(); + String sql = ""; + String sqlWhere = " "; + try{ + String[] tables = new String[]{KqSplitFlowTypeEnum.EVECTION.getTablename(),//出差 + KqSplitFlowTypeEnum.OUT.getTablename()};//公出 + + String minimumUnit = "";//单位类型 + double proportion = 0.00;//换算关系 + + JSONObject jsonObj = JSON.parseObject(Util.null2String(params.get("data"))); + String fromDate = Util.null2String(jsonObj.get("fromDate")); + String toDate = Util.null2String(jsonObj.get("toDate")); + String typeselect =Util.null2String(jsonObj.get("typeselect")); + if(typeselect.length()==0)typeselect = "3"; + if(!typeselect.equals("") && !typeselect.equals("0")&& !typeselect.equals("6")){ + if(typeselect.equals("1")){ + fromDate = TimeUtil.getCurrentDateString(); + toDate = TimeUtil.getCurrentDateString(); + }else{ + fromDate = TimeUtil.getDateByOption(typeselect,"0"); + toDate = TimeUtil.getDateByOption(typeselect,"1"); + } + } + String subCompanyId = Util.null2String(jsonObj.get("subCompanyId")); + String departmentId = Util.null2String(jsonObj.get("departmentId")); + String resourceId = Util.null2String(jsonObj.get("resourceId")); + String allLevel = Util.null2String(jsonObj.get("allLevel")); + String isNoAccount = Util.null2String(jsonObj.get("isNoAccount")); + String viewScope = Util.null2String(jsonObj.get("viewScope")); + if(subCompanyId.length()>0){ + sqlWhere +=" and a.subcompanyid1 in("+subCompanyId+") "; + } + + if(departmentId.length()>0){ + sqlWhere +=" and a.departmentid in("+departmentId+") "; + } + + if(resourceId.length()>0){ + sqlWhere +=" and b.resourceid in("+resourceId+") "; + } + + if(viewScope.equals("4")){//我的下属 + if(allLevel.equals("1")){//所有下属 + sqlWhere+=" and a.managerstr like '%,"+user.getUID()+",%'"; + }else{ + sqlWhere+=" and a.managerid="+user.getUID();//直接下属 + } + } + if (!"1".equals(isNoAccount)) { + sqlWhere += " and a.loginid is not null "+(rs.getDBType().equals("oracle")?"":" and a.loginid<>'' "); + } + + for(String table : tables){ + sql = " select resourceid, durationrule, sum(duration) as val,belongdate from hrmresource a, "+table+" b "+ + " where a.id = b.resourceid and (b.status is null or b.status<>1) and belongdate >='"+fromDate+"' and belongdate <='"+toDate+"' "+sqlWhere+ + " group by resourceid, durationrule,belongdate "; + rs.execute(sql); + while (rs.next()) { + String resourceid = rs.getString("resourceid"); + String belongdate = rs.getString("belongdate"); + double value = rs.getDouble("val"); + String durationrule = rs.getString("durationrule"); + + String flowType = ""; + if(KqSplitFlowTypeEnum.EVECTION.getTablename().equals(table)){ + flowType = "businessLeave"; + minimumUnit = KQTravelRulesBiz.getMinimumUnit();//单位类型 + proportion = Util.getDoubleValue(KQTravelRulesBiz.getHoursToDay());//换算关系 + }else if(KqSplitFlowTypeEnum.OUT.getTablename().equals(table)){ + flowType = "officialBusiness"; + minimumUnit = KQExitRulesBiz.getMinimumUnit();//单位类型 + proportion = Util.getDoubleValue(KQExitRulesBiz.getHoursToDay());//换算关系 + } + + if(KQUnitBiz.isLeaveHour(minimumUnit)){//按小时 + if(!KQUnitBiz.isLeaveHour(durationrule)){ + if(proportion>0) value = value*proportion; + } + }else{//按天 + if(KQUnitBiz.isLeaveHour(durationrule)){ + if(proportion>0) value = value/proportion; + } + } + + String key = resourceid+"|"+belongdate+"|"+flowType; + if(datas.containsKey(key)){ + value += Util.getDoubleValue(Util.null2String(datas.get(key))); + } + //df.format 默认是不四舍五入的 0.125这样的就会直接变成0.12了 + df.setMaximumFractionDigits(5); + datas.put(key, format(value)); + } + } + }catch (Exception e){ + writeLog(e); + } + return datas; + } + + /** + * 获取请假数据 + * @param params + * @param user + * @return + */ + public Map getFlowLeaveData(Map params, User user){ + Map datas = new HashMap<>();; + RecordSet rs = new RecordSet(); + String sql = ""; + String sqlWhere = " "; + try{ + KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo(); + JSONObject jsonObj = JSON.parseObject(Util.null2String(params.get("data"))); + String fromDate = Util.null2String(jsonObj.get("fromDate")); + String toDate = Util.null2String(jsonObj.get("toDate")); + String typeselect =Util.null2String(jsonObj.get("typeselect")); + if(typeselect.length()==0)typeselect = "3"; + if(!typeselect.equals("") && !typeselect.equals("0")&& !typeselect.equals("6")){ + if(typeselect.equals("1")){ + fromDate = TimeUtil.getCurrentDateString(); + toDate = TimeUtil.getCurrentDateString(); + }else{ + fromDate = TimeUtil.getDateByOption(typeselect,"0"); + toDate = TimeUtil.getDateByOption(typeselect,"1"); + } + } + String subCompanyId = Util.null2String(jsonObj.get("subCompanyId")); + String departmentId = Util.null2String(jsonObj.get("departmentId")); + String resourceId = Util.null2String(jsonObj.get("resourceId")); + String allLevel = Util.null2String(jsonObj.get("allLevel")); + String isNoAccount = Util.null2String(jsonObj.get("isNoAccount")); + String viewScope = Util.null2String(jsonObj.get("viewScope")); + if(subCompanyId.length()>0){ + sqlWhere +=" and a.subcompanyid1 in("+subCompanyId+") "; + } + + if(departmentId.length()>0){ + sqlWhere +=" and a.departmentid in("+departmentId+") "; + } + + if(resourceId.length()>0){ + sqlWhere +=" and b.resourceid in("+resourceId+") "; + } + + if(viewScope.equals("4")){//我的下属 + if(allLevel.equals("1")){//所有下属 + sqlWhere+=" and a.managerstr like '%,"+user.getUID()+",%'"; + }else{ + sqlWhere+=" and a.managerid="+user.getUID();//直接下属 + } + } + if (!"1".equals(isNoAccount)) { + sqlWhere += " and a.loginid is not null "+(rs.getDBType().equals("oracle")?"":" and a.loginid<>'' "); + } + + sql = " select resourceid, newleavetype, durationrule, sum(duration) as val from hrmresource a, "+KqSplitFlowTypeEnum.LEAVE.getTablename()+" b "+ + " where a.id = b.resourceid and (b.status is null or b.status != 1) and belongdate >='"+fromDate+"' and belongdate <='"+toDate+"' " +sqlWhere + + " group by resourceid, newleavetype, durationrule "; + rs.execute(sql); + while (rs.next()) { + String resourceid = rs.getString("resourceid"); + String newleavetype = rs.getString("newleavetype"); + String durationrule = rs.getString("durationrule"); + double value = rs.getDouble("val")<0?0:rs.getDouble("val"); + + double proportion = Util.getDoubleValue(kqLeaveRulesComInfo.getProportion(newleavetype)); + if(KQUnitBiz.isLeaveHour(newleavetype, kqLeaveRulesComInfo)){//按小时 + if(!KQUnitBiz.isLeaveHour(durationrule)){ + if(proportion>0) value = value*proportion; + } + }else{//按天 + if(KQUnitBiz.isLeaveHour(durationrule)){ + if(proportion>0) value = value/proportion; + } + } + + String key = resourceid+"|leaveType_"+newleavetype; + if(datas.containsKey(key)){ + value += Util.getDoubleValue(Util.null2String(datas.get(key))); + } + //df.format 默认是不四舍五入的 0.125这样的就会直接变成0.12了 + df.setMaximumFractionDigits(5); + datas.put(key,format(value)); + } + }catch (Exception e){ + writeLog(e); + } + return datas; + } + + + //获取打卡数据用于判断外勤,补卡等信息=============================== + public Map getCardMap(Map params, User user){ + Map datas = new HashMap<>();; + RecordSet rs = new RecordSet(); + String sql = ""; + String sqlWhere = " "; + //rs.writeLog("getCardMap="+ JSONObject.toJSONString(params)); + try{ + String show_card_source = Util.null2String(params.get("show_card_source")); + if(!"1".equals(show_card_source)){//下面的日历都是实时拼接,这里还是控制下数据库的交互次数,虽然用起来没啥用-.- + return datas; + } + + KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo(); + KQTransMethod kqTransMethod = new KQTransMethod(); + JSONObject jsonObj = JSON.parseObject(Util.null2String(params.get("data"))); + rs.writeLog("jsonObj="+ jsonObj.toJSONString()); + String fromDate = Util.null2String(jsonObj.get("fromDate")); + String toDate = Util.null2String(jsonObj.get("toDate")); + String typeselect =Util.null2String(jsonObj.get("typeselect")); + if(typeselect.length()==0)typeselect = "3"; + if(!typeselect.equals("") && !typeselect.equals("0")&& !typeselect.equals("6")){ + if(typeselect.equals("1")){ + fromDate = TimeUtil.getCurrentDateString(); + toDate = TimeUtil.getCurrentDateString(); + }else{ + fromDate = TimeUtil.getDateByOption(typeselect,"0"); + toDate = TimeUtil.getDateByOption(typeselect,"1"); + } + } + String subCompanyId = Util.null2String(jsonObj.get("subCompanyId")); + String departmentId = Util.null2String(jsonObj.get("departmentId")); + String resourceId = Util.null2String(jsonObj.get("resourceId")); + String allLevel = Util.null2String(jsonObj.get("allLevel")); + String isNoAccount = Util.null2String(jsonObj.get("isNoAccount")); + String viewScope = Util.null2String(jsonObj.get("viewScope")); + if(subCompanyId.length()>0){ + sqlWhere +=" and a.subcompanyid1 in("+subCompanyId+") "; + } + + if(departmentId.length()>0){ + sqlWhere +=" and a.departmentid in("+departmentId+") "; + } + + if(resourceId.length()>0){ + sqlWhere +=" and a.id in("+resourceId+") "; + } + + if(viewScope.equals("4")){//我的下属 + if(allLevel.equals("1")){//所有下属 + sqlWhere+=" and a.managerstr like '%,"+user.getUID()+",%'"; + }else{ + sqlWhere+=" and a.managerid="+user.getUID();//直接下属 + } + } + if (!"1".equals(isNoAccount)) { + sqlWhere += " and a.loginid is not null "+(rs.getDBType().equals("oracle")?"":" and a.loginid<>'' "); + } + //em7外勤、云桥外勤数据同步、钉钉外勤打卡、微信外勤转考勤(补卡先留一个口子,以防客户要) +// sqlWhere += " and (signfrom like 'card%' or signfrom='e9_mobile_out' or signfrom='EMSyn_out' or signfrom='DingTalk_out' or signfrom='Wechat_out') "; + + sql = " select a.id,b.signdate,b.id as signid,b.signfrom from hrmresource a, hrmschedulesign b "+ + " where a.id = b.userid and b.signdate >='"+fromDate+"' and b.signdate <='"+toDate+"' " +sqlWhere + + " order by a.id,b.signdate "; + rs.execute(sql); +// kqLog.info("card.sql="+sql); + while (rs.next()) { + String resourceid = Util.null2String(rs.getString("id")); + String signdate = Util.null2String(rs.getString("signdate")); + String signid = Util.null2String(rs.getString("signid")); + String signfrom = Util.null2String(rs.getString("signfrom")); + String signFromShow = kqTransMethod.getSignFromShow(signfrom, ""+user.getLanguage()); + String key = resourceid+"|"+signdate; + + datas.put(signid,signFromShow); + } + }catch (Exception e){ + writeLog(e); + } + return datas; + } + +//获取打卡数据用于判断外勤,补卡等信息=============================== + + /** + * 获取销假数据 + * @param params + * @param user + * @return + */ + public Map getFlowLeaveBackData(Map params, User user){ + Map datas = new HashMap<>();; + RecordSet rs = new RecordSet(); + String sql = ""; + String sqlWhere = " "; + try{ + KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo(); + JSONObject jsonObj = JSON.parseObject(Util.null2String(params.get("data"))); + String fromDate = Util.null2String(jsonObj.get("fromDate")); + String toDate = Util.null2String(jsonObj.get("toDate")); + String typeselect =Util.null2String(jsonObj.get("typeselect")); + if(typeselect.length()==0)typeselect = "3"; + if(!typeselect.equals("") && !typeselect.equals("0")&& !typeselect.equals("6")){ + if(typeselect.equals("1")){ + fromDate = TimeUtil.getCurrentDateString(); + toDate = TimeUtil.getCurrentDateString(); + }else{ + fromDate = TimeUtil.getDateByOption(typeselect,"0"); + toDate = TimeUtil.getDateByOption(typeselect,"1"); + } + } + String subCompanyId = Util.null2String(jsonObj.get("subCompanyId")); + String departmentId = Util.null2String(jsonObj.get("departmentId")); + String resourceId = Util.null2String(jsonObj.get("resourceId")); + String allLevel = Util.null2String(jsonObj.get("allLevel")); + String isNoAccount = Util.null2String(jsonObj.get("isNoAccount")); + String viewScope = Util.null2String(jsonObj.get("viewScope")); + if(subCompanyId.length()>0){ + sqlWhere +=" and a.subcompanyid1 in("+subCompanyId+") "; + } + + if(departmentId.length()>0){ + sqlWhere +=" and a.departmentid in("+departmentId+") "; + } + + if(resourceId.length()>0){ + sqlWhere +=" and b.resourceid in("+resourceId+") "; + } + + if(viewScope.equals("4")){//我的下属 + if(allLevel.equals("1")){//所有下属 + sqlWhere+=" and a.managerstr like '%,"+user.getUID()+",%'"; + }else{ + sqlWhere+=" and a.managerid="+user.getUID();//直接下属 + } + } + if (!"1".equals(isNoAccount)) { + sqlWhere += " and a.loginid is not null "+(rs.getDBType().equals("oracle")?"":" and a.loginid<>'' "); + } + + sql = " select resourceid, newleavetype, durationrule, sum(duration) as val from hrmresource a, "+KqSplitFlowTypeEnum.LEAVEBACK.getTablename()+" b "+ + " where a.id = b.resourceid and belongdate >='"+fromDate+"' and belongdate <='"+toDate+"' " +sqlWhere + + " group by resourceid, newleavetype, durationrule "; + rs.execute(sql); + while (rs.next()) { + String resourceid = rs.getString("resourceid"); + String newleavetype = rs.getString("newleavetype"); + String durationrule = rs.getString("durationrule"); + double value = rs.getDouble("val")<0?0:rs.getDouble("val"); + + double proportion = Util.getDoubleValue(kqLeaveRulesComInfo.getProportion(newleavetype)); + if(KQUnitBiz.isLeaveHour(newleavetype,kqLeaveRulesComInfo)){//按小时 + if(!KQUnitBiz.isLeaveHour(durationrule)){ + if(proportion>0) value = value*proportion; + } + }else{//按天 + if(KQUnitBiz.isLeaveHour(durationrule)){ + if(proportion>0) value = value/proportion; + } + } + + String key = resourceid+"|leavebackType_"+newleavetype; + if(datas.containsKey(key)){ + value += Util.getDoubleValue(Util.null2String(datas.get(key))); + } + //df.format 默认是不四舍五入的 0.125这样的就会直接变成0.12了 + df.setMaximumFractionDigits(5); + datas.put(key,format(value)); + } + }catch (Exception e){ + writeLog(e); + } + return datas; + } + + /** + * 获取考勤变更流程数据 + * @param params + * @param user + * @return + */ + public Map getFlowProcessChangeData(Map params, User user){ + Map datas = new HashMap<>();; + RecordSet rs = new RecordSet(); + String sql = ""; + String sqlWhere = " "; + try{ + String minimumUnit = "";//单位类型 + double proportion = 0.00;//换算关系 + + JSONObject jsonObj = JSON.parseObject(Util.null2String(params.get("data"))); + String fromDate = Util.null2String(jsonObj.get("fromDate")); + String toDate = Util.null2String(jsonObj.get("toDate")); + String typeselect =Util.null2String(jsonObj.get("typeselect")); + if(typeselect.length()==0)typeselect = "3"; + if(!typeselect.equals("") && !typeselect.equals("0")&& !typeselect.equals("6")){ + if(typeselect.equals("1")){ + fromDate = TimeUtil.getCurrentDateString(); + toDate = TimeUtil.getCurrentDateString(); + }else{ + fromDate = TimeUtil.getDateByOption(typeselect,"0"); + toDate = TimeUtil.getDateByOption(typeselect,"1"); + } + } + String subCompanyId = Util.null2String(jsonObj.get("subCompanyId")); + String departmentId = Util.null2String(jsonObj.get("departmentId")); + String resourceId = Util.null2String(jsonObj.get("resourceId")); + String allLevel = Util.null2String(jsonObj.get("allLevel")); + String isNoAccount = Util.null2String(jsonObj.get("isNoAccount")); + String viewScope = Util.null2String(jsonObj.get("viewScope")); + if(subCompanyId.length()>0){ + sqlWhere +=" and a.subcompanyid1 in("+subCompanyId+") "; + } + + if(departmentId.length()>0){ + sqlWhere +=" and a.departmentid in("+departmentId+") "; + } + + if(resourceId.length()>0){ + sqlWhere +=" and b.resourceid in("+resourceId+") "; + } + + if(viewScope.equals("4")){//我的下属 + if(allLevel.equals("1")){//所有下属 + sqlWhere+=" and a.managerstr like '%,"+user.getUID()+",%'"; + }else{ + sqlWhere+=" and a.managerid="+user.getUID();//直接下属 + } + } + if (!"1".equals(isNoAccount)) { + sqlWhere += " and a.loginid is not null "+(rs.getDBType().equals("oracle")?"":" and a.loginid<>'' "); + } + + sql = " select resourceid, durationrule, changetype,sum(duration) as val from hrmresource a, "+KqSplitFlowTypeEnum.PROCESSCHANGE.getTablename()+" b "+ + " where a.id = b.resourceid and belongdate >='"+fromDate+"' and belongdate <='"+toDate+"' "+sqlWhere+ + " group by resourceid, durationrule,changetype "; + rs.execute(sql); + while (rs.next()) { + String resourceid = rs.getString("resourceid"); + int changetype = Util.getIntValue(rs.getString("changetype")); + + String flowType = ""; + if(KqSplitFlowTypeEnum.EVECTION.getFlowtype() == changetype){ + flowType = "businessLeave_back"; + proportion = Util.getDoubleValue(KQTravelRulesBiz.getHoursToDay());//换算关系 + minimumUnit = KQTravelRulesBiz.getMinimumUnit(); + }else if(KqSplitFlowTypeEnum.OUT.getFlowtype() == changetype){ + flowType = "officialBusiness_back"; + minimumUnit = KQExitRulesBiz.getMinimumUnit(); + proportion = Util.getDoubleValue(KQExitRulesBiz.getHoursToDay());//换算关系 + } + double value = rs.getDouble("val")<0?0:rs.getDouble("val"); + String durationrule = rs.getString("durationrule"); + + if(KQUnitBiz.isLeaveHour(minimumUnit)){//按小时 + if(!KQUnitBiz.isLeaveHour(durationrule)){ + if(proportion>0) value = value*proportion; + } + }else{//按天 + if(KQUnitBiz.isLeaveHour(durationrule)){ + if(proportion>0) value = value/proportion; + } + } + + String key = resourceid+"|"+flowType; + if(datas.containsKey(key)){ + value += Util.getDoubleValue(Util.null2String(datas.get(key))); + } + //df.format 默认是不四舍五入的 0.125这样的就会直接变成0.12了 + df.setMaximumFractionDigits(5); + datas.put(key, format(value)); + } + }catch (Exception e){ + writeLog(e); + } + return datas; + } + + /** + * 获取每日请假数据 + * @param params + * @param user + * @return + */ + public Map getDailyFlowLeaveData(Map params, User user){ + Map datas = new HashMap<>();; + RecordSet rs = new RecordSet(); + String sql = ""; + String sqlWhere = " "; + try{ + KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo(); + JSONObject jsonObj = JSON.parseObject(Util.null2String(params.get("data"))); + String fromDate = Util.null2String(jsonObj.get("fromDate")); + String toDate = Util.null2String(jsonObj.get("toDate")); + String typeselect =Util.null2String(jsonObj.get("typeselect")); + if(typeselect.length()==0)typeselect = "3"; + if(!typeselect.equals("") && !typeselect.equals("0")&& !typeselect.equals("6")){ + if(typeselect.equals("1")){ + fromDate = TimeUtil.getCurrentDateString(); + toDate = TimeUtil.getCurrentDateString(); + }else{ + fromDate = TimeUtil.getDateByOption(typeselect,"0"); + toDate = TimeUtil.getDateByOption(typeselect,"1"); + } + } + String subCompanyId = Util.null2String(jsonObj.get("subCompanyId")); + String departmentId = Util.null2String(jsonObj.get("departmentId")); + String resourceId = Util.null2String(jsonObj.get("resourceId")); + String allLevel = Util.null2String(jsonObj.get("allLevel")); + String isNoAccount = Util.null2String(jsonObj.get("isNoAccount")); + String viewScope = Util.null2String(jsonObj.get("viewScope")); + if(subCompanyId.length()>0){ + sqlWhere +=" and a.subcompanyid1 in("+subCompanyId+") "; + } + + if(departmentId.length()>0){ + sqlWhere +=" and a.departmentid in("+departmentId+") "; + } + + if(resourceId.length()>0){ + sqlWhere +=" and b.resourceid in("+resourceId+") "; + } + + if(viewScope.equals("4")){//我的下属 + if(allLevel.equals("1")){//所有下属 + sqlWhere+=" and a.managerstr like '%,"+user.getUID()+",%'"; + }else{ + sqlWhere+=" and a.managerid="+user.getUID();//直接下属 + } + } + if (!"1".equals(isNoAccount)) { + sqlWhere += " and a.loginid is not null "+(rs.getDBType().equals("oracle")?"":" and a.loginid<>'' "); + } + + sql = " select resourceid, newleavetype, durationrule, sum(duration) as val,belongdate from hrmresource a, "+KqSplitFlowTypeEnum.LEAVE.getTablename()+" b "+ + " where a.id = b.resourceid and belongdate >='"+fromDate+"' and belongdate <='"+toDate+"' " +sqlWhere + + " group by resourceid, newleavetype, durationrule,belongdate "; + rs.execute(sql); + while (rs.next()) { + String resourceid = rs.getString("resourceid"); + String belongdate = rs.getString("belongdate"); + String newleavetype = rs.getString("newleavetype"); + String durationrule = rs.getString("durationrule"); + double value = rs.getDouble("val")<0?0:rs.getDouble("val"); + + double proportion = Util.getDoubleValue(kqLeaveRulesComInfo.getProportion(newleavetype)); + if(KQUnitBiz.isLeaveHour(newleavetype,kqLeaveRulesComInfo)){//按小时 + if(!KQUnitBiz.isLeaveHour(durationrule)){ + if(proportion>0) value = value*proportion; + } + }else{//按天 + if(KQUnitBiz.isLeaveHour(durationrule)){ + if(proportion>0) value = value/proportion; + } + } + + String key = resourceid+"|"+belongdate+"|leaveType_"+newleavetype; + if(datas.containsKey(key)){ + value += Util.getDoubleValue(Util.null2String(datas.get(key))); + } + //df.format 默认是不四舍五入的 0.125这样的就会直接变成0.12了 + df.setMaximumFractionDigits(5); + datas.put(key,format(value)); + } + }catch (Exception e){ + writeLog(e); + } + return datas; + } + + + public Map getSignDetailInfoData(Map params, User user){ + Map data = new HashMap<>(); + RecordSet rs = new RecordSet(); + String sql = ""; + String sqlWhere = " "; + try{ + KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo(); + JSONObject jsonObj = JSON.parseObject(Util.null2String(params.get("data"))); + String fromDate = Util.null2String(jsonObj.get("fromDate")); + String toDate = Util.null2String(jsonObj.get("toDate")); + String typeselect =Util.null2String(jsonObj.get("typeselect")); + if(typeselect.length()==0)typeselect = "3"; + if(!typeselect.equals("") && !typeselect.equals("0")&& !typeselect.equals("6")){ + if(typeselect.equals("1")){ + fromDate = TimeUtil.getCurrentDateString(); + toDate = TimeUtil.getCurrentDateString(); + }else{ + fromDate = TimeUtil.getDateByOption(typeselect,"0"); + toDate = TimeUtil.getDateByOption(typeselect,"1"); + } + } + String isneedcal = Util.null2String(params.get("isneedcal")); + if("".equals(isneedcal)){ + isneedcal = KQSettingsBiz.getKqformatAccurate()?"1":"0"; + } + String subCompanyId = Util.null2String(jsonObj.get("subCompanyId")); + String departmentId = Util.null2String(jsonObj.get("departmentId")); + String resourceId = Util.null2String(jsonObj.get("resourceId")); + String allLevel = Util.null2String(jsonObj.get("allLevel")); + String isNoAccount = Util.null2String(jsonObj.get("isNoAccount")); + String viewScope = Util.null2String(jsonObj.get("viewScope")); + if(subCompanyId.length()>0){ + sqlWhere +=" and a.subcompanyid1 in("+subCompanyId+") "; + } + + if(departmentId.length()>0){ + sqlWhere +=" and a.departmentid in("+departmentId+") "; + } + + if(resourceId.length()>0){ + sqlWhere +=" and b.resourceid in("+resourceId+") "; + } + + if(viewScope.equals("4")){//我的下属 + if(allLevel.equals("1")){//所有下属 + sqlWhere+=" and a.managerstr like '%,"+user.getUID()+",%'"; + }else{ + sqlWhere+=" and a.managerid="+user.getUID();//直接下属 + } + } + if (!"1".equals(isNoAccount)) { + sqlWhere += " and a.loginid is not null "+(rs.getDBType().equals("oracle")?"":" and a.loginid<>'' "); + } + + //================================= +// Map data = new HashMap<>(); + Map signStatusInfo = null; + KQShiftManagementComInfo kqShiftManagementComInfo = new KQShiftManagementComInfo(); + KQTimesArrayComInfo kqTimesArrayComInfo = new KQTimesArrayComInfo(); + sql = " select kqdate,resourceid,day_type,serialid,serialnumber,workbegindate,workbegintime, " + + " workenddate,workendtime,workmins,signindate,signintime,signoutdate,signouttime, \n" + + " attendanceMins,belatemins,graveBeLateMins,leaveearlymins,graveLeaveEarlyMins,absenteeismmins,forgotcheckMins,forgotBeginWorkCheckMins," + + " leaveMins,leaveInfo,evectionMins,outMins,signinid,signoutid,flowinfo,on_absenteeismmins,off_absenteeismmins \n" + + " from hrmresource a,kq_format_detail b \n" + + " where a.id = b.resourceid " +sqlWhere+ + " and b.kqdate >='" + fromDate + "' and b.kqdate<='"+toDate+"' \n" + + " order by b.serialnumber \n"; + rs.execute(sql); + while (rs.next()) { + String resourceid = Util.null2String(rs.getString("resourceid")); + String kqdate = Util.null2String(rs.getString("kqdate")); + String serialid = Util.null2String(rs.getString("serialid")); + String day_type = Util.null2s(rs.getString("day_type"),""); + int workMins = rs.getInt("workMins"); + boolean isNonWork = false; + if(day_type.length() > 0){ + if("holiday".equals(day_type) || "playday".equals(day_type)){ + isNonWork = true; + } + if(serialid.length() == 0){ + //弹性班制,会存在dayType是work但是没有班次的情况 + isNonWork = true; + } + }else{ + if(workMins<=0){ + isNonWork = true; + }else{ + if(serialid.length() > 0){ + String isRest = Util.null2s(kqShiftManagementComInfo.getIsRest(serialid),""); + if("1".equals(isRest)){ + isNonWork = true; + } + } + } + } + int serialnumber = rs.getInt("serialnumber")+1; + String workbegindate = Util.null2String(rs.getString("workbegindate")).trim(); + String workbegintime = Util.null2String(rs.getString("workbegintime")).trim(); + String workenddate = Util.null2String(rs.getString("workenddate")).trim(); + String workendtime = Util.null2String(rs.getString("workendtime")).trim(); + String signintime = Util.null2String(rs.getString("signintime")).trim(); + String signouttime = Util.null2String(rs.getString("signouttime")).trim(); + int attendanceMins = rs.getInt("attendanceMins"); + String beLateMins = Util.null2String(rs.getString("beLateMins")).trim(); + String graveBeLateMins = Util.null2String(rs.getString("graveBeLateMins")).trim(); + String leaveEarlyMins= Util.null2String(rs.getString("leaveEarlyMins")).trim(); + String graveLeaveEarlyMins= Util.null2String(rs.getString("graveLeaveEarlyMins")).trim(); + String absenteeismMins= Util.null2String(rs.getString("absenteeismMins")).trim(); + String forgotCheckMins = Util.null2String(rs.getString("forgotcheckMins")).trim(); + String forgotBeginWorkCheckMins = Util.null2String(rs.getString("forgotBeginWorkCheckMins")).trim(); + String signinid = Util.null2String(rs.getString("signinid")).trim(); + String signoutid = Util.null2String(rs.getString("signoutid")).trim(); + int leaveMins = rs.getInt("leaveMins"); + String leaveInfo = Util.null2String(rs.getString("leaveInfo")); + int evectionMins = rs.getInt("evectionMins"); + int outMins = rs.getInt("outMins"); + String flowinfo = Util.null2String(rs.getString("flowinfo")); + String on_absenteeismmins = Util.null2String(rs.getString("on_absenteeismmins")); + String off_absenteeismmins = Util.null2String(rs.getString("off_absenteeismmins")); + + String tmpkey = resourceid+"|"+kqdate+"|"; + + + if(!isNonWork){ + if (workbegintime.length() > 0) { + signStatusInfo = new HashMap(); + signStatusInfo.put("resourceId",resourceid); + signStatusInfo.put("kqdate",kqdate); + signStatusInfo.put("workdate",workbegindate); + signStatusInfo.put("worktime",workbegintime); + signStatusInfo.put("beLateMins",beLateMins); + signStatusInfo.put("forgotBeginWorkCheckMins",forgotBeginWorkCheckMins); + signStatusInfo.put("graveBeLateMins",graveBeLateMins); + signStatusInfo.put("absenteeismMins",absenteeismMins); + signStatusInfo.put("leaveMins",leaveMins); + signStatusInfo.put("leaveInfo",leaveInfo); + signStatusInfo.put("evectionMins",evectionMins); + signStatusInfo.put("outMins",outMins); + signStatusInfo.put("isneedcal",isneedcal); + signStatusInfo.put("flowinfo",flowinfo); + signStatusInfo.put("on_absenteeismmins",on_absenteeismmins); + signStatusInfo.put("off_absenteeismmins",off_absenteeismmins); + + signStatusInfo.put("workbegintime",workbegintime); + signStatusInfo.put("workendtime",workendtime); + + data.put(tmpkey+"signintime"+serialnumber, signintime.length()==0?SystemEnv.getHtmlLabelName(25994, user.getLanguage()):signintime); + data.put(tmpkey+"signinstatus"+serialnumber, KQReportBiz.getSignStatus(signStatusInfo,user,"on")); + } + + if (workendtime.length() > 0) { + signStatusInfo = new HashMap(); + signStatusInfo.put("resourceId",resourceid); + signStatusInfo.put("kqdate",kqdate); + signStatusInfo.put("workdate",workenddate); + signStatusInfo.put("worktime",kqTimesArrayComInfo.turn48to24Time(workendtime)); + signStatusInfo.put("leaveEarlyMins",leaveEarlyMins); + signStatusInfo.put("graveLeaveEarlyMins",graveLeaveEarlyMins); + signStatusInfo.put("forgotCheckMins",forgotCheckMins); + signStatusInfo.put("forgotBeginWorkCheckMins",forgotBeginWorkCheckMins); + signStatusInfo.put("absenteeismMins",absenteeismMins); + signStatusInfo.put("leaveMins",leaveMins); + signStatusInfo.put("leaveInfo",leaveInfo); + signStatusInfo.put("evectionMins",evectionMins); + signStatusInfo.put("outMins",outMins); + signStatusInfo.put("isneedcal",isneedcal); + signStatusInfo.put("flowinfo",flowinfo); + signStatusInfo.put("on_absenteeismmins",on_absenteeismmins); + signStatusInfo.put("off_absenteeismmins",off_absenteeismmins); + + signStatusInfo.put("workbegintime",workbegintime); + signStatusInfo.put("workendtime",workendtime); + + data.put(tmpkey+"signouttime"+serialnumber, signouttime.length()==0?SystemEnv.getHtmlLabelName(25994, user.getLanguage()):signouttime); + data.put(tmpkey+"signoutstatus"+serialnumber, KQReportBiz.getSignStatus(signStatusInfo,user,"off")); + } + }else{ + if(workMins>0){ + //弹性工时打卡时间取自签到签退数据 + } + signStatusInfo = new HashMap(); + signStatusInfo.put("resourceId",resourceid); + signStatusInfo.put("kqdate",kqdate); + signStatusInfo.put("leaveMins",leaveMins); + signStatusInfo.put("leaveInfo",leaveInfo); + signStatusInfo.put("evectionMins",evectionMins); + signStatusInfo.put("outMins",outMins); + signStatusInfo.put("isneedcal",isneedcal); + signStatusInfo.put("flowinfo",flowinfo); + signStatusInfo.put("on_absenteeismmins",on_absenteeismmins); + signStatusInfo.put("off_absenteeismmins",off_absenteeismmins); + + signStatusInfo.put("workbegintime",workbegintime); + signStatusInfo.put("workendtime",workendtime); + + if(signinid.length() > 0){ + data.put(tmpkey+"signintime"+serialnumber, signintime.length()==0?SystemEnv.getHtmlLabelName(25994, user.getLanguage()):signintime); + data.put(tmpkey+"signinstatus"+serialnumber, KQReportBiz.getSignStatus(signStatusInfo,user,"on")); + if(signoutid.length() > 0){ + data.put(tmpkey+"signouttime"+serialnumber, signouttime.length()==0?SystemEnv.getHtmlLabelName(25994, user.getLanguage()):signouttime); + data.put(tmpkey+"signoutstatus"+serialnumber, KQReportBiz.getSignStatus(signStatusInfo,user,"off")); + } + }else if(signoutid.length() > 0){ + data.put(tmpkey+"signouttime"+serialnumber, signouttime.length()==0?SystemEnv.getHtmlLabelName(25994, user.getLanguage()):signouttime); + data.put(tmpkey+"signoutstatus"+serialnumber, KQReportBiz.getSignStatus(signStatusInfo,user,"off")); + }else{ + data.put(tmpkey+"signinstatus"+serialnumber, KQReportBiz.getSignStatus(signStatusInfo,user,"on")); + data.put(tmpkey+"signoutstatus"+serialnumber, KQReportBiz.getSignStatus(signStatusInfo,user,"off")); + } + } + } + }catch (Exception e){ + writeLog(e); + } + return data; + } + + /** + * 获取每日销假数据 + * @param params + * @param user + * @return + */ + public Map getDailyFlowLeaveBackData(Map params, User user){ + Map datas = new HashMap<>();; + RecordSet rs = new RecordSet(); + String sql = ""; + String sqlWhere = " "; + try{ + KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo(); + JSONObject jsonObj = JSON.parseObject(Util.null2String(params.get("data"))); + String fromDate = Util.null2String(jsonObj.get("fromDate")); + String toDate = Util.null2String(jsonObj.get("toDate")); + String typeselect =Util.null2String(jsonObj.get("typeselect")); + if(typeselect.length()==0)typeselect = "3"; + if(!typeselect.equals("") && !typeselect.equals("0")&& !typeselect.equals("6")){ + if(typeselect.equals("1")){ + fromDate = TimeUtil.getCurrentDateString(); + toDate = TimeUtil.getCurrentDateString(); + }else{ + fromDate = TimeUtil.getDateByOption(typeselect,"0"); + toDate = TimeUtil.getDateByOption(typeselect,"1"); + } + } + String subCompanyId = Util.null2String(jsonObj.get("subCompanyId")); + String departmentId = Util.null2String(jsonObj.get("departmentId")); + String resourceId = Util.null2String(jsonObj.get("resourceId")); + String allLevel = Util.null2String(jsonObj.get("allLevel")); + String isNoAccount = Util.null2String(jsonObj.get("isNoAccount")); + String viewScope = Util.null2String(jsonObj.get("viewScope")); + if(subCompanyId.length()>0){ + sqlWhere +=" and a.subcompanyid1 in("+subCompanyId+") "; + } + + if(departmentId.length()>0){ + sqlWhere +=" and a.departmentid in("+departmentId+") "; + } + + if(resourceId.length()>0){ + sqlWhere +=" and b.resourceid in("+resourceId+") "; + } + + if(viewScope.equals("4")){//我的下属 + if(allLevel.equals("1")){//所有下属 + sqlWhere+=" and a.managerstr like '%,"+user.getUID()+",%'"; + }else{ + sqlWhere+=" and a.managerid="+user.getUID();//直接下属 + } + } + if (!"1".equals(isNoAccount)) { + sqlWhere += " and a.loginid is not null "+(rs.getDBType().equals("oracle")?"":" and a.loginid<>'' "); + } + + sql = " select resourceid, newleavetype, durationrule, sum(duration) as val,belongdate from hrmresource a, "+KqSplitFlowTypeEnum.LEAVEBACK.getTablename()+" b "+ + " where a.id = b.resourceid and belongdate >='"+fromDate+"' and belongdate <='"+toDate+"' " +sqlWhere + + " group by resourceid, newleavetype, durationrule,belongdate "; + rs.execute(sql); + while (rs.next()) { + String resourceid = rs.getString("resourceid"); + String belongdate = rs.getString("belongdate"); + String newleavetype = rs.getString("newleavetype"); + String durationrule = rs.getString("durationrule"); + double value = rs.getDouble("val")<0?0:rs.getDouble("val"); + + double proportion = Util.getDoubleValue(kqLeaveRulesComInfo.getProportion(newleavetype)); + if(KQUnitBiz.isLeaveHour(newleavetype,kqLeaveRulesComInfo)){//按小时 + if(!KQUnitBiz.isLeaveHour(durationrule)){ + if(proportion>0) value = value*proportion; + } + }else{//按天 + if(KQUnitBiz.isLeaveHour(durationrule)){ + if(proportion>0) value = value/proportion; + } + } + + String key = resourceid+"|"+belongdate+"|leavebackType_"+newleavetype; + if(datas.containsKey(key)){ + value += Util.getDoubleValue(Util.null2String(datas.get(key))); + } + //df.format 默认是不四舍五入的 0.125这样的就会直接变成0.12了 + df.setMaximumFractionDigits(5); + datas.put(key,format(value)); + } + }catch (Exception e){ + writeLog(e); + } + return datas; + } + + /** + * 获取实际加班数据,包括流程,打卡生成的 + * @return + */ + public Map getFlowOverTimeDataNew(Map params, User user){ + Map datas = new HashMap<>();; + RecordSet rs = new RecordSet(); + String sql = ""; + String sqlWhere = " "; + try{ + KQOvertimeRulesBiz kqOvertimeRulesBiz = new KQOvertimeRulesBiz(); + JSONObject jsonObj = JSON.parseObject(Util.null2String(params.get("data"))); + String fromDate = Util.null2String(jsonObj.get("fromDate")); + String toDate = Util.null2String(jsonObj.get("toDate")); + String typeselect =Util.null2String(jsonObj.get("typeselect")); + if(typeselect.length()==0)typeselect = "3"; + if(!typeselect.equals("") && !typeselect.equals("0")&& !typeselect.equals("6")){ + if(typeselect.equals("1")){ + fromDate = TimeUtil.getCurrentDateString(); + toDate = TimeUtil.getCurrentDateString(); + }else{ + fromDate = TimeUtil.getDateByOption(typeselect,"0"); + toDate = TimeUtil.getDateByOption(typeselect,"1"); + } + } + String subCompanyId = Util.null2String(jsonObj.get("subCompanyId")); + String departmentId = Util.null2String(jsonObj.get("departmentId")); + String resourceId = Util.null2String(jsonObj.get("resourceId")); + String allLevel = Util.null2String(jsonObj.get("allLevel")); + String isNoAccount = Util.null2String(jsonObj.get("isNoAccount")); + String viewScope = Util.null2String(jsonObj.get("viewScope")); + if(subCompanyId.length()>0){ + sqlWhere +=" and a.subcompanyid1 in("+subCompanyId+") "; + } + + if(departmentId.length()>0){ + sqlWhere +=" and a.departmentid in("+departmentId+") "; + } + + if(resourceId.length()>0){ + sqlWhere +=" and a.id in("+resourceId+") "; + } + + if(viewScope.equals("4")){//我的下属 + if(allLevel.equals("1")){//所有下属 + sqlWhere+=" and a.managerstr like '%,"+user.getUID()+",%'"; + }else{ + sqlWhere+=" and a.managerid="+user.getUID();//直接下属 + } + } + if (!"1".equals(isNoAccount)) { + sqlWhere += " and a.loginid is not null "+(rs.getDBType().equals("oracle")?"":" and a.loginid<>'' "); + } + + int uintType = kqOvertimeRulesBiz.getMinimumUnit();//当前加班单位 + double hoursToDay = kqOvertimeRulesBiz.getHoursToDay();//当前天跟小时计算关系 + + String valueField = ""; + + sql = " select resourceid,changeType, sum(cast(duration_min as decimal(18,4))) as val,paidLeaveEnable "+ + " from hrmresource a, kq_flow_overtime b "+ + " where a.id = b.resourceid and belongdate >='"+fromDate+"' and belongdate <='"+toDate+"' " +sqlWhere+ + " group by resourceid,changeType,paidLeaveEnable "; + rs.execute(sql); + kqLog.info("getFlowOverTimeDataNew:sql:"+sql); + while (rs.next()) { + String resourceid = rs.getString("resourceid"); + String paidLeaveEnable = rs.getString("paidLeaveEnable"); + int changeType =rs.getInt("changeType");//1-节假日、2-工作日、3-休息日 + double value = rs.getDouble("val")<0?0:rs.getDouble("val"); + if(uintType==3 || uintType== 5 || uintType== 6){//按小时计算 + value = Util.getDoubleValue(KQDurationCalculatorUtil.getDurationRound(value/(60.0)+"")); + }else{//按天计算 + value = Util.getDoubleValue(KQDurationCalculatorUtil.getDurationRound(value/(60.0*hoursToDay)+"")); + } + String flowType = ""; + if(changeType==1){ + flowType = "holidayOvertime"; + }else if(changeType==2){ + flowType = "workingDayOvertime"; + }else if(changeType==3){ + flowType = "restDayOvertime"; + } + if("1".equalsIgnoreCase(paidLeaveEnable)){ + //1表示关联调休 + flowType += "_4leave"; + }else{ + //0表示不关联调休 + flowType += "_nonleave"; + } + String key = resourceid+"|"+flowType; + //df.format 默认是不四舍五入的 0.125这样的就会直接变成0.12了 + df.setMaximumFractionDigits(5); + if(datas.containsKey(key)){ + double tmpVal = Util.getDoubleValue(Util.null2String(datas.get(key)),0.0); + tmpVal += value; + datas.put(key,format(tmpVal)); + }else{ + datas.put(key,format(value)); + } + } + }catch (Exception e){ + writeLog(e); + } + return datas; + } + + + /** + * 获取加班数据 + * @return + */ + public Map getFlowOverTimeData(Map params, User user){ + Map datas = new HashMap<>();; + RecordSet rs = new RecordSet(); + String sql = ""; + String sqlWhere = " "; + try{ + KQOvertimeRulesBiz kqOvertimeRulesBiz = new KQOvertimeRulesBiz(); + JSONObject jsonObj = JSON.parseObject(Util.null2String(params.get("data"))); + String fromDate = Util.null2String(jsonObj.get("fromDate")); + String toDate = Util.null2String(jsonObj.get("toDate")); + String typeselect =Util.null2String(jsonObj.get("typeselect")); + if(typeselect.length()==0)typeselect = "3"; + if(!typeselect.equals("") && !typeselect.equals("0")&& !typeselect.equals("6")){ + if(typeselect.equals("1")){ + fromDate = TimeUtil.getCurrentDateString(); + toDate = TimeUtil.getCurrentDateString(); + }else{ + fromDate = TimeUtil.getDateByOption(typeselect,"0"); + toDate = TimeUtil.getDateByOption(typeselect,"1"); + } + } + String subCompanyId = Util.null2String(jsonObj.get("subCompanyId")); + String departmentId = Util.null2String(jsonObj.get("departmentId")); + String resourceId = Util.null2String(jsonObj.get("resourceId")); + String allLevel = Util.null2String(jsonObj.get("allLevel")); + String isNoAccount = Util.null2String(jsonObj.get("isNoAccount")); + String viewScope = Util.null2String(jsonObj.get("viewScope")); + if(subCompanyId.length()>0){ + sqlWhere +=" and b.subcompanyid in("+subCompanyId+") "; + } + + if(departmentId.length()>0){ + sqlWhere +=" and b.departmentid in("+departmentId+") "; + } + + if(resourceId.length()>0){ + sqlWhere +=" and b.resourceid in("+resourceId+") "; + } + + if(viewScope.equals("4")){//我的下属 + if(allLevel.equals("1")){//所有下属 + sqlWhere+=" and a.managerstr like '%,"+user.getUID()+",%'"; + }else{ + sqlWhere+=" and a.managerid="+user.getUID();//直接下属 + } + } + if (!"1".equals(isNoAccount)) { + sqlWhere += " and a.loginid is not null "+(rs.getDBType().equals("oracle")?"":" and a.loginid<>'' "); + } + + int uintType = kqOvertimeRulesBiz.getMinimumUnit();//当前加班单位 + double hoursToDay = kqOvertimeRulesBiz.getHoursToDay();//当前天跟小时计算关系 + + String valueField = ""; + if(uintType==3 || uintType== 5 || uintType== 6){//按小时计算 + valueField = "sum( case when durationrule='3' then duration else duration*"+hoursToDay+" end) as val"; + }else{//按天计算 + valueField = "sum( case when durationrule='3' then duration/"+hoursToDay+" else duration end) as val"; + } + + sql = " select resourceid,changeType, " +valueField+ + " from hrmresource a, "+KqSplitFlowTypeEnum.OVERTIME.getTablename()+" b "+ + " where a.id = b.resourceid and belongdate >='"+fromDate+"' and belongdate <='"+toDate+"' " +sqlWhere+ + " group by resourceid,changeType,durationrule "; + rs.execute(sql); + while (rs.next()) { + String resourceid = rs.getString("resourceid"); + int changeType =rs.getInt("changeType");//1-节假日、2-工作日、3-休息日 + double value = rs.getDouble("val")<0?0:rs.getDouble("val"); + String flowType = ""; + if(changeType==1){ + flowType = "holidayOvertime"; + }else if(changeType==2){ + flowType = "workingDayOvertime"; + }else if(changeType==3){ + flowType = "restDayOvertime"; + } + String key = resourceid+"|"+flowType; + //df.format 默认是不四舍五入的 0.125这样的就会直接变成0.12了 + df.setMaximumFractionDigits(5); + if(datas.containsKey(key)){ + double tmpVal = Util.getDoubleValue(Util.null2String(datas.get(key)),0.0); + tmpVal += value; + datas.put(key,format(tmpVal)); + }else{ + datas.put(key,format(value)); + } + } + }catch (Exception e){ + writeLog(e); + } + return datas; + } + + /** + * 获取每日加班数据 + * @return + */ + public Map getDailyFlowOverTimeData(Map params, User user){ + Map datas = new HashMap<>();; + RecordSet rs = new RecordSet(); + String sql = ""; + String sqlWhere = " "; + try{ + KQOvertimeRulesBiz kqOvertimeRulesBiz = new KQOvertimeRulesBiz(); + JSONObject jsonObj = JSON.parseObject(Util.null2String(params.get("data"))); + String fromDate = Util.null2String(jsonObj.get("fromDate")); + String toDate = Util.null2String(jsonObj.get("toDate")); + String typeselect =Util.null2String(jsonObj.get("typeselect")); + if(typeselect.length()==0)typeselect = "3"; + if(!typeselect.equals("") && !typeselect.equals("0")&& !typeselect.equals("6")){ + if(typeselect.equals("1")){ + fromDate = TimeUtil.getCurrentDateString(); + toDate = TimeUtil.getCurrentDateString(); + }else{ + fromDate = TimeUtil.getDateByOption(typeselect,"0"); + toDate = TimeUtil.getDateByOption(typeselect,"1"); + } + } + String subCompanyId = Util.null2String(jsonObj.get("subCompanyId")); + String departmentId = Util.null2String(jsonObj.get("departmentId")); + String resourceId = Util.null2String(jsonObj.get("resourceId")); + String allLevel = Util.null2String(jsonObj.get("allLevel")); + String isNoAccount = Util.null2String(jsonObj.get("isNoAccount")); + String viewScope = Util.null2String(jsonObj.get("viewScope")); + if(subCompanyId.length()>0){ + sqlWhere +=" and a.subcompanyid1 in("+subCompanyId+") "; + } + + if(departmentId.length()>0){ + sqlWhere +=" and a.departmentid in("+departmentId+") "; + } + + if(resourceId.length()>0){ + sqlWhere +=" and a.id in("+resourceId+") "; + } + + if(viewScope.equals("4")){//我的下属 + if(allLevel.equals("1")){//所有下属 + sqlWhere+=" and a.managerstr like '%,"+user.getUID()+",%'"; + }else{ + sqlWhere+=" and a.managerid="+user.getUID();//直接下属 + } + } + if (!"1".equals(isNoAccount)) { + sqlWhere += " and a.loginid is not null "+(rs.getDBType().equals("oracle")?"":" and a.loginid<>'' "); + } + + int uintType = kqOvertimeRulesBiz.getMinimumUnit();//当前加班单位 + double hoursToDay = kqOvertimeRulesBiz.getHoursToDay();//当前天跟小时计算关系 + + String valueField = ""; + if(uintType==3 || uintType== 5 || uintType== 6){//按小时计算 + valueField = "sum( case when durationrule='3' then duration else duration*"+hoursToDay+" end) as val"; + }else{//按天计算 + valueField = "sum( case when durationrule='3' then duration/"+hoursToDay+" else duration end) as val"; + } + + sql = " select resourceid,changeType,belongdate,paidLeaveEnable, sum(cast(duration_min as decimal(18,4))) as val "+ + " from hrmresource a, kq_flow_overtime b "+ + " where a.id = b.resourceid and belongdate >='"+fromDate+"' and belongdate <='"+toDate+"' " +sqlWhere+ + " group by resourceid,changeType,paidLeaveEnable,belongdate "; + rs.execute(sql); + while (rs.next()) { + String resourceid = rs.getString("resourceid"); + String belongdate = rs.getString("belongdate"); + String paidLeaveEnable = rs.getString("paidLeaveEnable"); + int changeType =rs.getInt("changeType");//1-节假日、2-工作日、3-休息日 + double value = rs.getDouble("val")<0?0:rs.getDouble("val"); + if(uintType==3 || uintType== 5 || uintType== 6){//按小时计算 + value = Util.getDoubleValue(KQDurationCalculatorUtil.getDurationRound(value/(60.0)+"")); + }else{//按天计算 + value = Util.getDoubleValue(KQDurationCalculatorUtil.getDurationRound(value/(60.0*hoursToDay)+"")); + } + String flowType = ""; + if(changeType==1){ + flowType = "holidayOvertime"; + }else if(changeType==2){ + flowType = "workingDayOvertime"; + }else if(changeType==3){ + flowType = "restDayOvertime"; + } + if("1".equalsIgnoreCase(paidLeaveEnable)){ + //1表示关联调休 + flowType += "_4leave"; + }else{ + //0表示不关联调休 + flowType += "_nonleave"; + } + //df.format 默认是不四舍五入的 0.125这样的就会直接变成0.12了 + df.setMaximumFractionDigits(5); + datas.put(resourceid+"|"+belongdate+"|"+flowType,format(value)); + } + }catch (Exception e){ + writeLog(e); + } + return datas; + } + + /** + * 异常冲抵 + * @return + */ + public Map getFlowOtherData(Map params, User user){ + Map datas = new HashMap<>();; + RecordSet rs = new RecordSet(); + String sql = ""; + String sqlWhere = " "; + try{ + String minimumUnit = "";//单位类型 + double proportion = 0.00;//换算关系 + + JSONObject jsonObj = JSON.parseObject(Util.null2String(params.get("data"))); + String fromDate = Util.null2String(jsonObj.get("fromDate")); + String toDate = Util.null2String(jsonObj.get("toDate")); + String typeselect =Util.null2String(jsonObj.get("typeselect")); + if(typeselect.length()==0)typeselect = "3"; + if(!typeselect.equals("") && !typeselect.equals("0")&& !typeselect.equals("6")){ + if(typeselect.equals("1")){ + fromDate = TimeUtil.getCurrentDateString(); + toDate = TimeUtil.getCurrentDateString(); + }else{ + fromDate = TimeUtil.getDateByOption(typeselect,"0"); + toDate = TimeUtil.getDateByOption(typeselect,"1"); + } + } + String subCompanyId = Util.null2String(jsonObj.get("subCompanyId")); + String departmentId = Util.null2String(jsonObj.get("departmentId")); + String resourceId = Util.null2String(jsonObj.get("resourceId")); + String allLevel = Util.null2String(jsonObj.get("allLevel")); + String isNoAccount = Util.null2String(jsonObj.get("isNoAccount")); + String viewScope = Util.null2String(jsonObj.get("viewScope")); + if(subCompanyId.length()>0){ + sqlWhere +=" and a.subcompanyid1 in("+subCompanyId+") "; + } + + if(departmentId.length()>0){ + sqlWhere +=" and a.departmentid in("+departmentId+") "; + } + + if(resourceId.length()>0){ + sqlWhere +=" and b.resourceid in("+resourceId+") "; + } + + if(viewScope.equals("4")){//我的下属 + if(allLevel.equals("1")){//所有下属 + sqlWhere+=" and a.managerstr like '%,"+user.getUID()+",%'"; + }else{ + sqlWhere+=" and a.managerid="+user.getUID();//直接下属 + } + } + if (!"1".equals(isNoAccount)) { + sqlWhere += " and a.loginid is not null "+(rs.getDBType().equals("oracle")?"":" and a.loginid<>'' "); + } + + sql = " select resourceid, durationrule, sum(duration) as val from hrmresource a, "+KqSplitFlowTypeEnum.OTHER.getTablename()+" b "+ + " where a.id = b.resourceid and belongdate >='"+fromDate+"' and belongdate <='"+toDate+"' "+sqlWhere+ + " group by resourceid, durationrule "; + rs.execute(sql); + while (rs.next()) { + String resourceid = rs.getString("resourceid"); + double value = rs.getDouble("val")<0?0:rs.getDouble("val"); + String durationrule = rs.getString("durationrule"); + + if(KQUnitBiz.isLeaveHour(minimumUnit)){//按小时 + if(!KQUnitBiz.isLeaveHour(durationrule)){ + if(proportion>0) value = value*proportion; + } + }else{//按天 + if(KQUnitBiz.isLeaveHour(durationrule)){ + if(proportion>0) value = value/proportion; + } + } + + String key = resourceid+"|leaveDeduction"; + if(datas.containsKey(key)){ + value += Util.getDoubleValue(Util.null2String(datas.get(key))); + } + //df.format 默认是不四舍五入的 0.125这样的就会直接变成0.12了 + df.setMaximumFractionDigits(5); + datas.put(key, format(value)); + } + }catch (Exception e){ + writeLog(e); + } + return datas; + } + + /** + *日报表数据 + * @param resourceId + * @param fromDate + * @param toDate + * @return + */ + public Map getDetialDatas(String resourceId,String fromDate, String toDate, User user){ + return getDetialDatas(resourceId,fromDate,toDate,user,new HashMap(),false,0,"0"); + } + + /** + * 考勤汇总报表上下午显示开关不开启 + * @param resourceId + * @param fromDate + * @param toDate + * @param user + * @param flowData + * @param isWrap + * @param uintType + * @param show_card_source + * @return + */ + public Map getDetialDatasHalfNotOpen(String resourceId,String fromDate, String toDate, User user, + Map flowData,boolean isWrap,int uintType,String show_card_source){ + KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo(); + KQShiftManagementComInfo kqShiftManagementComInfo = new KQShiftManagementComInfo(); + Map datas = new HashMap<>(); + Map data = null; + Map tmpdatas = new HashMap<>(); + Map tmpdatass = new HashMap<>(); + Map tmpdata = null; + Map tmpmap = null; + + Map tmpstatusdata = new HashMap<>(); + Map tmpstatus = null; + RecordSet rs = new RecordSet(); + String sql = ""; + + //add + String unit = "小时"; + if(uintType==1 || uintType== 2 || uintType== 4){//按天计算 + unit = "天"; + } + //kqLog.info("detail.flowdata="+JSONObject.toJSONString(flowData)); + + try { + sql = " select resourceid,day_type,serialid, kqdate, workMins,attendanceMins,signindate,signintime,signoutdate,signouttime,signinid,signoutid, belatemins, graveBeLateMins, leaveearlymins, graveLeaveEarlyMins, absenteeismmins, forgotcheckMins, forgotBeginWorkCheckMins, "+ + " leaveMins,leaveInfo,evectionMins,outMins " + + " from kq_format_detail " + + " where resourceid = ? and kqdate>=? and kqdate<=? "+ + " order by resourceid, kqdate, serialnumber "; + rs.executeQuery(sql,resourceId, fromDate,toDate); + while (rs.next()) { + String key = rs.getString("resourceid") + "|" + rs.getString("kqdate"); + int workMins = rs.getInt("workMins"); + + boolean isNonWork = false; + String serialid = Util.null2s(rs.getString("serialid"),""); + String dayType = Util.null2s(rs.getString("day_type"),""); + if(dayType.length() > 0){ + if("holiday".equals(dayType) || "playday".equals(dayType)){ + isNonWork = true; + } + }else{ + if(workMins<=0){ + isNonWork = true; + }else{ + if(serialid.length() > 0){ + String isRest = Util.null2s(kqShiftManagementComInfo.getIsRest(serialid),""); + if("1".equals(isRest)){ + isNonWork = true; + } + } + } + } + String attendanceMins = rs.getString("attendanceMins"); +// String chuqin = "出勤:"+KQDurationCalculatorUtil.getDurationRound(("" + (Util.getDoubleValue(attendanceMins) / 60.0)))+"小时"; + String overtimekey = key+"|overtime"; + String overtime = Util.null2String(flowData.get(overtimekey)); + boolean hasovertime = Util.getDoubleValue(overtime)>0; + overtime = hasovertime?(SystemEnv.getHtmlLabelName(6151, user.getLanguage())+":"+overtime+unit):"";//显示加班 + + String signinid = ""; + String signoutid = ""; + String signintime = ""; + String signouttime = ""; + if("1".equals(show_card_source)){ + String nosign = SystemEnv.getHtmlLabelName(25994, user.getLanguage());//未打卡 + signinid = Util.null2String(rs.getString("signinid")).trim(); + signintime = Util.null2String(rs.getString("signintime")).trim(); + String tmpin = SystemEnv.getHtmlLabelName(21974, user.getLanguage())+":"; + if(signinid.length()>0){ + String signinfrom = Util.null2String(flowData.get(signinid)); + signintime = tmpin+signintime+" "+signinfrom; + }else{ + signintime = tmpin+nosign; + } +// signintime = isWrap?"\r\n"+signintime:"
"+signintime; + + signoutid = Util.null2String(rs.getString("signoutid")).trim(); + signouttime = Util.null2String(rs.getString("signouttime")).trim(); + String tmpout = SystemEnv.getHtmlLabelName(21975, user.getLanguage())+":"; + if(signoutid.length()>0){ + String signoutfrom = Util.null2String(flowData.get(signoutid)); + signouttime = tmpout+signouttime+" "+signoutfrom; + }else{ + signouttime = tmpout+nosign; + } + signouttime = isWrap?"\r\n"+signouttime:"
"+signouttime; + } + + int beLateMins = rs.getInt("beLateMins"); + int leaveEarlyMins = rs.getInt("leaveEarlyMins"); + int graveBeLateMins = rs.getInt("graveBeLateMins"); + int absenteeismMins = rs.getInt("absenteeismMins"); + int graveLeaveEarlyMins = rs.getInt("graveLeaveEarlyMins"); + int forgotCheckMins = rs.getInt("forgotCheckMins"); + int forgotBeginWorkCheckMins = rs.getInt("forgotBeginWorkCheckMins"); + int leaveMins = rs.getInt("leaveMins"); + String leaveInfo = rs.getString("leaveInfo"); + int evectionMins = rs.getInt("evectionMins"); + int outMins = rs.getInt("outMins"); + String text = ""; + String tmptext =""; + String flag ="true"; + if(datas.get(key)==null){ + data = new HashMap<>(); + }else{ + data = (Map)datas.get(key); + tmptext = Util.null2String(data.get("text")); + } + tmpdata = new HashMap<>(); + if(tmpdatas.get(key)!=null){ + tmpmap = (Map)tmpdatas.get(key); + flag = Util.null2String(tmpmap.get("text")); + } + + String yichang =""; + if(tmpstatusdata.get(key)!=null){ + yichang = Util.null2String(tmpstatusdata.get(key)); + } + String sign =""; + String signkey = key+"|text"; + if(tmpstatusdata.get(signkey)!=null){ + sign = Util.null2String(tmpstatusdata.get(signkey)); + } + + if (isNonWork) { + if(text.length()>0) text +=" "; + if(sign.indexOf(SystemEnv.getHtmlLabelName(26593, user.getLanguage()))==-1){ + if(text.length()>0) { + text+= isWrap?"\r\n":"
"; + } + text += SystemEnv.getHtmlLabelName(26593, user.getLanguage()); + } + //休息日处理 + if(signinid.length()>0){ + text += (isWrap?"\r\n":"
")+signintime; + } + if(signoutid.length()>0){ + text += signouttime; + } + sign += text; + } else { + //处理打卡数据================== + if(text.length()>0) text+= isWrap?"\r\n":"
"; + text += signintime; + text += signouttime; + if(sign.length()>0) sign+= isWrap?"\r\n":"
"; + sign += text; + //处理打卡数据================== + + if (absenteeismMins > 0) {//旷工 + if(text.length()>0) text+=" "; + text += SystemEnv.getHtmlLabelName(20085, user.getLanguage()); +// text += ":"+KQDurationCalculatorUtil.getDurationRound(("" + (Util.getDoubleValue(""+absenteeismMins) / 60.0)))+"小时"; + if(yichang.indexOf(SystemEnv.getHtmlLabelName(20085, user.getLanguage()))==-1){ + if(yichang.length()>0) yichang+= isWrap?"\r\n":"
"; + yichang += SystemEnv.getHtmlLabelName(20085, user.getLanguage()); + } + }else { + if (beLateMins > 0) {//迟到 + if (text.length() > 0) text += " "; + text += SystemEnv.getHtmlLabelName(20081, user.getLanguage()); +// text += ":"+KQDurationCalculatorUtil.getDurationRound(("" + (Util.getDoubleValue(""+beLateMins) / 60.0)))+"小时"; + if(yichang.indexOf(SystemEnv.getHtmlLabelName(20081, user.getLanguage()))==-1) { + if (yichang.length() > 0) yichang += isWrap?"\r\n":"
"; + yichang += SystemEnv.getHtmlLabelName(20081, user.getLanguage()); + } + } + if (graveBeLateMins > 0) {//严重迟到 + if (text.length() > 0) text += " "; + text += SystemEnv.getHtmlLabelName(500546, user.getLanguage()); +// text += ":"+KQDurationCalculatorUtil.getDurationRound(("" + (Util.getDoubleValue(""+graveBeLateMins) / 60.0)))+"小时"; + if(yichang.indexOf(SystemEnv.getHtmlLabelName(500546, user.getLanguage()))==-1) { + if (yichang.length() > 0) yichang += isWrap?"\r\n":"
"; + yichang += SystemEnv.getHtmlLabelName(500546, user.getLanguage()); + } + } + if (leaveEarlyMins > 0) {//早退 + if (text.length() > 0) text += " "; + text += SystemEnv.getHtmlLabelName(20082, user.getLanguage()); +// text += ":"+KQDurationCalculatorUtil.getDurationRound(("" + (Util.getDoubleValue(""+leaveEarlyMins) / 60.0)))+"小时"; + if(yichang.indexOf(SystemEnv.getHtmlLabelName(20082, user.getLanguage()))==-1) { + if (yichang.length() > 0) yichang += isWrap?"\r\n":"
"; + yichang += SystemEnv.getHtmlLabelName(20082, user.getLanguage()); + } + } + if (graveLeaveEarlyMins > 0) {//严重早退 + if (text.length() > 0) text += " "; + text += SystemEnv.getHtmlLabelName(500547, user.getLanguage()); +// text += ":"+KQDurationCalculatorUtil.getDurationRound(("" + (Util.getDoubleValue(""+graveLeaveEarlyMins) / 60.0)))+"小时"; + if(yichang.indexOf(SystemEnv.getHtmlLabelName(500547, user.getLanguage()))==-1) { + if (yichang.length() > 0) yichang += isWrap?"\r\n":"
"; + yichang += SystemEnv.getHtmlLabelName(500547, user.getLanguage()); + } + } + if (forgotCheckMins > 0) {//漏签 + if (text.length() > 0) text += " "; + text += SystemEnv.getHtmlLabelName(20086, user.getLanguage()); + if(yichang.indexOf(SystemEnv.getHtmlLabelName(20086, user.getLanguage()))==-1) { + if (yichang.length() > 0) yichang += isWrap?"\r\n":"
"; + yichang += SystemEnv.getHtmlLabelName(20086, user.getLanguage()); + } + } + if (forgotBeginWorkCheckMins > 0) {//漏签 + if (text.length() > 0) text += " "; + text += SystemEnv.getHtmlLabelName(20086, user.getLanguage()); + if(yichang.indexOf(SystemEnv.getHtmlLabelName(20086, user.getLanguage()))==-1) { + if (yichang.length() > 0) yichang += isWrap?"\r\n":"
"; + yichang += SystemEnv.getHtmlLabelName(20086, user.getLanguage()); + } + } + } + } + if (leaveMins > 0) {//请假 + Map jsonObject = null; + if(leaveInfo.length()>0){ + jsonObject = JSON.parseObject(leaveInfo); + for (Entry entry : jsonObject.entrySet()) { + String newLeaveType = entry.getKey(); + String tmpLeaveMins = Util.null2String(entry.getValue()); + if(text.indexOf(kqLeaveRulesComInfo.getLeaveName(newLeaveType))==-1){ + if (text.length() > 0) text += " "; + //text += kqLeaveRulesComInfo.getLeaveName(newLeaveType)+tmpLeaveMins+SystemEnv.getHtmlLabelName(15049, user.getLanguage()); + text += Util.formatMultiLang( kqLeaveRulesComInfo.getLeaveName(newLeaveType),""+user.getLanguage()); +// text += ":"+KQDurationCalculatorUtil.getDurationRound(("" + (Util.getDoubleValue(""+leaveMins) / 60.0)))+"小时"; + if(yichang.length()>0) yichang+= isWrap?"\r\n":"
"; + yichang += Util.formatMultiLang( kqLeaveRulesComInfo.getLeaveName(newLeaveType),""+user.getLanguage()); + } + } + }else{ + if(text.indexOf(SystemEnv.getHtmlLabelName(670, user.getLanguage()))==-1) { + if (text.length() > 0) text += " "; + text += SystemEnv.getHtmlLabelName(670, user.getLanguage()); + } + } + } + if (evectionMins > 0) {//出差 + if(text.indexOf(SystemEnv.getHtmlLabelName(20084, user.getLanguage()))==-1) { + if (text.length() > 0) text += " "; + text += SystemEnv.getHtmlLabelName(20084, user.getLanguage()); +// text += ":"+KQDurationCalculatorUtil.getDurationRound(("" + (Util.getDoubleValue(""+evectionMins) / 60.0)))+"小时"; + if(yichang.length()>0) yichang+= isWrap?"\r\n":"
"; + yichang += SystemEnv.getHtmlLabelName(20084, user.getLanguage()); + } + } + if (outMins > 0) {//公出 + if(text.indexOf(SystemEnv.getHtmlLabelName(24058, user.getLanguage()))==-1) { + if (text.length() > 0) text += " "; + text += SystemEnv.getHtmlLabelName(24058, user.getLanguage()); +// text += ":"+KQDurationCalculatorUtil.getDurationRound(("" + (Util.getDoubleValue(""+outMins) / 60.0)))+"小时"; + if(yichang.length()>0) yichang+= isWrap?"\r\n":"
"; + yichang += SystemEnv.getHtmlLabelName(24058, user.getLanguage()); + } + } + + if(text.length()==0) { + text = "√"; + }else{ + flag = "false";//有其他的异常状态,则表示为false,不需要处理直接全部显示即可 + } + text += overtime; + + + //需要处理下打卡时间和异常状态显示的顺序--start + tmpstatusdata.put(key, yichang); + tmpstatusdata.put(signkey, sign); + boolean hasyichang = tmpstatusdata.get(key).length()>0; + if(tmptext.length()>0){ +// text = tmpstatusdata.get(signkey)+(isWrap?"\r\n":"
")+tmpstatusdata.get(key)+(isWrap?"\r\n":"
"+overtime); + text = tmpstatusdata.get(signkey); + if(hasyichang){ + if(text.length()>0){ + text += (isWrap?"\r\n":"
")+tmpstatusdata.get(key); + }else{ + text += tmpstatusdata.get(key); + } + } + if(hasovertime){ + text += (isWrap?"\r\n":"
")+overtime; + } + }else{ + text = tmpstatusdata.get(signkey); + if(hasyichang){ + if(text.length()>0){ + text += (isWrap?"\r\n":"
")+tmpstatusdata.get(key); + }else{ + text += tmpstatusdata.get(key); + } + } + if(hasovertime){ + text += (isWrap?"\r\n":"
")+overtime; + } + } + //需要处理下打卡时间和异常状态显示的顺序--end + tmpdatass.put(key, (isWrap?"\r\n":"
")+overtime); +// text = tmptext.length()>0?tmptext+" "+text:text;//显示所有的状态 + data.put("text", text); + datas.put(key, data); + + //add + tmpdata.put("text", flag); + tmpdatas.put(key, tmpdata); + //end + } + //全部搞一遍 + if(tmpdatas != null){ +// writeLog(n+">>>tmpdatas="+JSONObject.toJSONString(tmpdatas)); + Map data1 = null; + for(Entry entry : tmpdatas.entrySet()){ + String mapKey = Util.null2String(entry.getKey()); + Map mapValue = (Map)entry.getValue(); + String flag = Util.null2String(mapValue.get("text")); + if("true".equals(flag)){//需要加工的数据 + String overtime = String.valueOf(tmpdatass.get(mapKey)); + data1 = new HashMap<>(); + data1.put("text", "√"+overtime); + datas.put(mapKey, data1); + } + } +// writeLog("datas="+JSONObject.toJSONString(datas)); + } + }catch (Exception e){ + writeLog(e); + } + // 最后针对数据再处理一遍,不然出现2023-01-02: "休息" 形式的错误,导致页面记载报错,应该是2023-01-01: {text: "休息"}格式 + boolean isEnd = false; + for(String currentDate = fromDate; !isEnd;) { + if (currentDate.equals(toDate)) isEnd = true; + String dailyValue = Util.null2String(datas.get(currentDate)); + if(!"".equals(dailyValue) && !dailyValue.contains("text")) { + Map innerMap2 = new HashMap<>(); + innerMap2.put("text", dailyValue); + datas.put(currentDate, innerMap2); + } + currentDate = DateUtil.addDate(currentDate, 1); + } + return datas; + } + + /** + * 考勤汇总报表上下午显示开关开启 + * @param resourceId + * @param fromDate + * @param toDate + * @param user + * @param flowData + * @param isWrap + * @param uintType + * @param show_card_source + * @return + */ + public Map getDetialDatasHalfOpen(String resourceId,String fromDate, String toDate, User user, + Map flowData,boolean isWrap,int uintType,String show_card_source){ + KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo(); + KQTimesArrayComInfo kqTimesArrayComInfo = new KQTimesArrayComInfo(); + int split_time_index = kqTimesArrayComInfo.getArrayindexByTimes("13:00"); + KQShiftManagementComInfo kqShiftManagementComInfo = new KQShiftManagementComInfo(); + Map datas = new HashMap<>(); + Map data = null; + Map tmpdatas = new HashMap<>(); + Map tmpdatass = new HashMap<>(); + Map tmpdata = null; + Map tmpmap = null; + + Map tmpstatusdata = new HashMap<>(); + Map tmpstatus = null; + RecordSet rs = new RecordSet(); + String sql = ""; + + //add + String unit = "小时"; + if(uintType==1 || uintType== 2 || uintType== 4){//按天计算 + unit = "天"; + } + //kqLog.info("detail.flowdata="+JSONObject.toJSONString(flowData)); + + try { + sql = " select resourceid,day_type,serialid, kqdate, workMins, workbegintime, workendtime,attendanceMins,signindate,signintime,signoutdate,signouttime,signinid,signoutid, belatemins, graveBeLateMins, leaveearlymins, graveLeaveEarlyMins, absenteeismmins, forgotcheckMins, forgotBeginWorkCheckMins, "+ + " leaveMins,leaveInfo,evectionMins,outMins,flowinfo,on_absenteeismmins,off_absenteeismmins " + + " from kq_format_detail " + + " where resourceid = ? and kqdate>=? and kqdate<=? "+ + " order by resourceid, kqdate, serialnumber "; + rs.executeQuery(sql,resourceId, fromDate,toDate); + while (rs.next()) { + String kqDate = rs.getString("kqdate"); + String key = rs.getString("resourceid") + "|" + kqDate; + int workMins = rs.getInt("workMins"); + + String signinid = ""; + String signoutid = ""; + String signintime = ""; + String signouttime = ""; + if("1".equals(show_card_source)){ + String nosign = SystemEnv.getHtmlLabelName(25994, user.getLanguage());//未打卡 + signinid = Util.null2String(rs.getString("signinid")).trim(); + signintime = Util.null2String(rs.getString("signintime")).trim(); + String tmpin = SystemEnv.getHtmlLabelName(21974, user.getLanguage())+":"; + if(signinid.length()>0){ + String signinfrom = Util.null2String(flowData.get(signinid)); + signintime = tmpin+signintime+" "+signinfrom; + }else{ + signintime = tmpin+nosign; + } + signintime = isWrap?"\r\n"+signintime:"
"+signintime; +// signintime = isWrap?"\r\n"+signintime:"
"+signintime; + + signoutid = Util.null2String(rs.getString("signoutid")).trim(); + signouttime = Util.null2String(rs.getString("signouttime")).trim(); + String tmpout = SystemEnv.getHtmlLabelName(21975, user.getLanguage())+":"; + if(signoutid.length()>0){ + String signoutfrom = Util.null2String(flowData.get(signoutid)); + signouttime = tmpout+signouttime+" "+signoutfrom; + }else{ + signouttime = tmpout+nosign; + } + signouttime = isWrap?"\r\n"+signouttime:"
"+signouttime; + } + + String overtimekey = key+"|overtime"; + String overtime = Util.null2String(flowData.get(overtimekey)); + boolean hasovertime = Util.getDoubleValue(overtime)>0; + overtime = hasovertime? ((isWrap?"\r\n":"
")+(SystemEnv.getHtmlLabelName(6151, user.getLanguage())+":"+overtime+unit)):"";//显示加班 + + + String flowinfo = Util.null2String(rs.getString("flowinfo")); + ShiftInfoBean shiftInfoBean = KQDurationCalculatorUtil.getWorkTime(resourceId, kqDate, false); + boolean isNonWork = false; + String serialid = Util.null2s(rs.getString("serialid"),""); + String dayType = Util.null2s(rs.getString("day_type"),""); + if(dayType.length() > 0){ + if("holiday".equals(dayType) || "playday".equals(dayType)){ + isNonWork = true; + } + }else{ + if(workMins<=0){ + isNonWork = true; + }else{ + if(serialid.length() > 0){ + String isRest = Util.null2s(kqShiftManagementComInfo.getIsRest(serialid),""); + if("1".equals(isRest)){ + isNonWork = true; + } + } + } + } + if(shiftInfoBean == null || isNonWork) { + String textAM = SystemEnv.getHtmlLabelName(26593, user.getLanguage()); + String textPM = SystemEnv.getHtmlLabelName(26593, user.getLanguage()); + if(datas.get(key)==null){ + data = new HashMap<>(); + }else{ + data = (Map)datas.get(key); + } + if(shiftInfoBean != null) { + List halfWorkIndex = shiftInfoBean.getHalfWorkIndex(); + if (halfWorkIndex != null && !halfWorkIndex.isEmpty()) { + int[] halfWorkIndexs = halfWorkIndex.get(0); + split_time_index = halfWorkIndexs[1];//半天的时间 + } + } + if(flowinfo.length() > 0) { + Map jsonObject = JSON.parseObject(flowinfo); + for (Entry entry : jsonObject.entrySet()) { + String jsonKey = entry.getKey(); + String jsonValue = ""; + if (jsonKey.equalsIgnoreCase(FlowReportTypeEnum.LEAVE.getFlowType())) { + jsonValue = SystemEnv.getHtmlLabelName(670, user.getLanguage()); + } else if (jsonKey.equalsIgnoreCase(FlowReportTypeEnum.EVECTION.getFlowType())) { + jsonValue = SystemEnv.getHtmlLabelName(20084, user.getLanguage()); + } else if (jsonKey.equalsIgnoreCase(FlowReportTypeEnum.OUT.getFlowType())) { + jsonValue = SystemEnv.getHtmlLabelName(24058, user.getLanguage()); + } + JSONArray jsonArray = JSONArray.parseArray(Util.null2String(entry.getValue())); + if (jsonArray != null && !jsonArray.isEmpty()) { + //客户不存在多个重复流程的情况,只是显示第一个就行 + for (int i = 0; i < jsonArray.size(); i++) { + JSONObject jsonObject1 = (JSONObject) jsonArray.getJSONObject(i); + if (jsonObject1 != null && !jsonObject1.isEmpty()) { + String newLeaveType = Util.null2s(Util.null2String(jsonObject1.get("newLeaveType")), ""); + String begintime = Util.null2s(Util.null2String(jsonObject1.get("begintime")), ""); + String endtime = Util.null2s(Util.null2String(jsonObject1.get("endtime")), ""); + int beginIdx = kqTimesArrayComInfo.getArrayindexByTimes(begintime); + int endIdx = kqTimesArrayComInfo.getArrayindexByTimes(endtime); + if (jsonKey.equalsIgnoreCase(FlowReportTypeEnum.LEAVE.getFlowType())) { + if (newLeaveType.length() > 0) { + jsonValue = kqLeaveRulesComInfo.getLeaveName(newLeaveType); + } + } + if (beginIdx <= split_time_index && endIdx <= split_time_index) { + //上午 + textAM = jsonValue; + } else if (beginIdx >= split_time_index && endIdx >= split_time_index) { + //下午 + textPM = jsonValue; + } else { + //全天 + textAM = jsonValue; + textPM = jsonValue; + } + } + } + } + } + } + if(!"".equals(signintime)) { + textAM+=signintime; + } + if(!"".equals(signouttime)) { + textPM+=signouttime; + } + if(!"".equals(overtime)) { + textPM+=overtime; + } + data.put("text", textAM+""+textPM); + data.put("textAM", textAM); + data.put("textPM", textPM); + datas.put(key, data); + continue; + } + String attendanceMins = rs.getString("attendanceMins"); +// String chuqin = "出勤:"+KQDurationCalculatorUtil.getDurationRound(("" + (Util.getDoubleValue(attendanceMins) / 60.0)))+"小时"; + + + int beLateMins = rs.getInt("beLateMins"); + int leaveEarlyMins = rs.getInt("leaveEarlyMins"); + int graveBeLateMins = rs.getInt("graveBeLateMins"); + int absenteeismMins = rs.getInt("absenteeismMins"); + int graveLeaveEarlyMins = rs.getInt("graveLeaveEarlyMins"); + int forgotCheckMins = rs.getInt("forgotCheckMins"); + int forgotBeginWorkCheckMins = rs.getInt("forgotBeginWorkCheckMins"); + int leaveMins = rs.getInt("leaveMins"); + String leaveInfo = rs.getString("leaveInfo"); + int evectionMins = rs.getInt("evectionMins"); + int outMins = rs.getInt("outMins"); + + String workbeigintime = rs.getString("workbegintime"); + String workendtime = rs.getString("workendtime"); + + String halfPoint = shiftInfoBean.getHalfcalpoint(); //1440 + List halfWorkIndex = shiftInfoBean.getHalfWorkIndex(); + if (halfWorkIndex != null && !halfWorkIndex.isEmpty()) { + int[] halfWorkIndexs = halfWorkIndex.get(0); + split_time_index = halfWorkIndexs[1];//半天的时间 + } +// int halfPointIndex = split_time_index; //kqTimesArrayComInfo.getArrayindexByTimes(halfPoint); + + int on_absenteeismmins = Util.getIntValue(Util.null2String(rs.getString("on_absenteeismmins"))); + int off_absenteeismmins = Util.getIntValue(Util.null2String(rs.getString("off_absenteeismmins"))); + + String textAM = ""; + String textPM = ""; + if (workMins<=0) { + if("".equals(flowinfo)) { + textAM = SystemEnv.getHtmlLabelName(26593, user.getLanguage()); + textPM = SystemEnv.getHtmlLabelName(26593, user.getLanguage()); + } else { + Map jsonObject = JSON.parseObject(flowinfo); + for (Entry entry : jsonObject.entrySet()) { + String jsonKey = entry.getKey(); + String jsonValue = ""; + if (jsonKey.equalsIgnoreCase(FlowReportTypeEnum.LEAVE.getFlowType())) { + jsonValue = SystemEnv.getHtmlLabelName(670, user.getLanguage()); + } else if (jsonKey.equalsIgnoreCase(FlowReportTypeEnum.EVECTION.getFlowType())) { + jsonValue = SystemEnv.getHtmlLabelName(20084, user.getLanguage()); + } else if (jsonKey.equalsIgnoreCase(FlowReportTypeEnum.OUT.getFlowType())) { + jsonValue = SystemEnv.getHtmlLabelName(24058, user.getLanguage()); + } + JSONArray jsonArray = JSONArray.parseArray(Util.null2String(entry.getValue())); + if (jsonArray != null && !jsonArray.isEmpty()) { + //客户不存在多个重复流程的情况,只是显示第一个就行 + for (int i = 0; i < jsonArray.size(); i++) { + JSONObject jsonObject1 = (JSONObject) jsonArray.getJSONObject(i); + if (jsonObject1 != null && !jsonObject1.isEmpty()) { + String newLeaveType = Util.null2s(Util.null2String(jsonObject1.get("newLeaveType")), ""); + String begintime = Util.null2s(Util.null2String(jsonObject1.get("begintime")), ""); + String endtime = Util.null2s(Util.null2String(jsonObject1.get("endtime")), ""); + int beginIdx = kqTimesArrayComInfo.getArrayindexByTimes(begintime); + int endIdx = kqTimesArrayComInfo.getArrayindexByTimes(endtime); + if (jsonKey.equalsIgnoreCase(FlowReportTypeEnum.LEAVE.getFlowType())) { + if (newLeaveType.length() > 0) { + jsonValue = kqLeaveRulesComInfo.getLeaveName(newLeaveType); + } + } + if (beginIdx <= split_time_index && endIdx <= split_time_index) { + //上午 + textAM = jsonValue; + } else if (beginIdx >= split_time_index && endIdx >= split_time_index) { + //下午 + textPM = jsonValue; + } else { + //全天 + textAM = jsonValue; + textPM = jsonValue; + } + } + } + } + } + } + }else{ + textAM = "√"; + textPM = "√"; + if(on_absenteeismmins > 0) { + textAM = SystemEnv.getHtmlLabelName(20085, user.getLanguage()); + } + if(beLateMins > 0) { + //迟到 + textAM = SystemEnv.getHtmlLabelName(20081, user.getLanguage()); + } + if(graveBeLateMins > 0) { + //严重迟到 + textAM = SystemEnv.getHtmlLabelName(500546, user.getLanguage()); + } + if(forgotBeginWorkCheckMins > 0) { + // 漏签 + textAM = SystemEnv.getHtmlLabelName(20086, user.getLanguage()); + } + if(off_absenteeismmins > 0) { + // 下午旷工 + textPM = SystemEnv.getHtmlLabelName(20085, user.getLanguage()); + } + if (leaveEarlyMins > 0) { + // 早退 + textPM = SystemEnv.getHtmlLabelName(20082, user.getLanguage()); + } + if (graveLeaveEarlyMins > 0) { + // 严重早退 + textPM = SystemEnv.getHtmlLabelName(500547, user.getLanguage()); + } + if(forgotCheckMins > 0) { + // 下午漏签 + textPM = SystemEnv.getHtmlLabelName(20086, user.getLanguage()); + } + } + + if(workMins > 0 && flowinfo.length() > 0){ + Map jsonObject = JSON.parseObject(flowinfo); + for (Entry entry : jsonObject.entrySet()) { + + String jsonKey = entry.getKey(); + String jsonValue = ""; + if(jsonKey.equalsIgnoreCase(FlowReportTypeEnum.LEAVE.getFlowType())){ + jsonValue = SystemEnv.getHtmlLabelName(670, user.getLanguage()); + }else if(jsonKey.equalsIgnoreCase(FlowReportTypeEnum.EVECTION.getFlowType())){ + jsonValue = SystemEnv.getHtmlLabelName(20084, user.getLanguage()); + }else if(jsonKey.equalsIgnoreCase(FlowReportTypeEnum.OUT.getFlowType())){ + jsonValue = SystemEnv.getHtmlLabelName(24058, user.getLanguage()); + } + JSONArray jsonArray = JSONArray.parseArray(Util.null2String(entry.getValue())); + if(jsonArray != null && !jsonArray.isEmpty()){ + //客户不存在多个重复流程的情况,只是显示第一个就行 + for(int i = 0 ; i < jsonArray.size() ; i++){ + JSONObject jsonObject1 = (JSONObject) jsonArray.getJSONObject(i); + if(jsonObject1 != null && !jsonObject1.isEmpty()) { + String newLeaveType = Util.null2s(Util.null2String(jsonObject1.get("newLeaveType")), ""); + String begintime = Util.null2s(Util.null2String(jsonObject1.get("begintime")), ""); + String endtime = Util.null2s(Util.null2String(jsonObject1.get("endtime")), ""); + int beginIdx = kqTimesArrayComInfo.getArrayindexByTimes(begintime); + int endIdx = kqTimesArrayComInfo.getArrayindexByTimes(endtime); + if (jsonKey.equalsIgnoreCase(FlowReportTypeEnum.LEAVE.getFlowType())) { + if (newLeaveType.length() > 0) { + jsonValue = kqLeaveRulesComInfo.getLeaveName(newLeaveType); + } + } + if (begintime.equals(workbeigintime) && endIdx == split_time_index) { + textAM = jsonValue; + } else if (begintime.equals(workbeigintime) && endtime.equals(workendtime)) { + textAM = jsonValue; + textPM = jsonValue; + } else if (endIdx == split_time_index && endtime.equals(workendtime)) { + textPM = jsonValue; + } else { + if (beginIdx <= split_time_index && endIdx <= split_time_index) { + //上午 + textAM = jsonValue + (("".equals(textAM) || "√".equals(textAM)) ? "" : ", " + textAM); + } else if (beginIdx >= split_time_index && endIdx >= split_time_index) { + //下午 + textPM = jsonValue + (("".equals(textPM) || "√".equals(textPM)) ? "" : ", " + textPM); + } else { + //全天 + textAM = jsonValue + (("".equals(textAM) || "√".equals(textAM)) ? "" : ", " + textAM); + textPM = jsonValue + (("".equals(textPM) || "√".equals(textPM)) ? "" : ", " + textPM); + } + } + } + } + } + } + } + String text = ""; + String tmptext =""; + String flag ="true"; + if(datas.get(key)==null){ + data = new HashMap<>(); + }else{ + data = (Map)datas.get(key); + tmptext = Util.null2String(data.get("text")); + } + tmpdata = new HashMap<>(); + if(tmpdatas.get(key)!=null){ + tmpmap = (Map)tmpdatas.get(key); + flag = Util.null2String(tmpmap.get("text")); + } + + String yichang =""; + if(tmpstatusdata.get(key)!=null){ + yichang = Util.null2String(tmpstatusdata.get(key)); + } + String sign =""; + String signkey = key+"|text"; + if(tmpstatusdata.get(signkey)!=null){ + sign = Util.null2String(tmpstatusdata.get(signkey)); + } + + if (isNonWork) { + if(text.length()>0) text +=" "; + if(sign.indexOf(SystemEnv.getHtmlLabelName(26593, user.getLanguage()))==-1){ + if(text.length()>0) { + text+= isWrap?"\r\n":"
"; + } + text += SystemEnv.getHtmlLabelName(26593, user.getLanguage()); + } + //休息日处理 + if(signinid.length()>0){ + text += (isWrap?"\r\n":"
")+signintime; + } + if(signoutid.length()>0){ + text += signouttime; + } + sign += text; + } else { + //处理打卡数据================== + if(text.length()>0) text+= isWrap?"\r\n":"
"; + text += signintime; + text += signouttime; + if(sign.length()>0) sign+= isWrap?"\r\n":"
"; + sign += text; + //处理打卡数据================== + + if (absenteeismMins > 0) {//旷工 + if(text.length()>0) text+=" "; + text += SystemEnv.getHtmlLabelName(20085, user.getLanguage()); +// text += ":"+KQDurationCalculatorUtil.getDurationRound(("" + (Util.getDoubleValue(""+absenteeismMins) / 60.0)))+"小时"; + if(yichang.indexOf(SystemEnv.getHtmlLabelName(20085, user.getLanguage()))==-1){ + if(yichang.length()>0) yichang+= isWrap?"\r\n":"
"; + yichang += SystemEnv.getHtmlLabelName(20085, user.getLanguage()); + } + }else { + if (beLateMins > 0) {//迟到 + if (text.length() > 0) text += " "; + text += SystemEnv.getHtmlLabelName(20081, user.getLanguage()); +// text += ":"+KQDurationCalculatorUtil.getDurationRound(("" + (Util.getDoubleValue(""+beLateMins) / 60.0)))+"小时"; + if(yichang.indexOf(SystemEnv.getHtmlLabelName(20081, user.getLanguage()))==-1) { + if (yichang.length() > 0) yichang += isWrap?"\r\n":"
"; + yichang += SystemEnv.getHtmlLabelName(20081, user.getLanguage()); + } + } + if (graveBeLateMins > 0) {//严重迟到 + if (text.length() > 0) text += " "; + text += SystemEnv.getHtmlLabelName(500546, user.getLanguage()); +// text += ":"+KQDurationCalculatorUtil.getDurationRound(("" + (Util.getDoubleValue(""+graveBeLateMins) / 60.0)))+"小时"; + if(yichang.indexOf(SystemEnv.getHtmlLabelName(500546, user.getLanguage()))==-1) { + if (yichang.length() > 0) yichang += isWrap?"\r\n":"
"; + yichang += SystemEnv.getHtmlLabelName(500546, user.getLanguage()); + } + } + if (leaveEarlyMins > 0) {//早退 + if (text.length() > 0) text += " "; + text += SystemEnv.getHtmlLabelName(20082, user.getLanguage()); +// text += ":"+KQDurationCalculatorUtil.getDurationRound(("" + (Util.getDoubleValue(""+leaveEarlyMins) / 60.0)))+"小时"; + if(yichang.indexOf(SystemEnv.getHtmlLabelName(20082, user.getLanguage()))==-1) { + if (yichang.length() > 0) yichang += isWrap?"\r\n":"
"; + yichang += SystemEnv.getHtmlLabelName(20082, user.getLanguage()); + } + } + if (graveLeaveEarlyMins > 0) {//严重早退 + if (text.length() > 0) text += " "; + text += SystemEnv.getHtmlLabelName(500547, user.getLanguage()); +// text += ":"+KQDurationCalculatorUtil.getDurationRound(("" + (Util.getDoubleValue(""+graveLeaveEarlyMins) / 60.0)))+"小时"; + if(yichang.indexOf(SystemEnv.getHtmlLabelName(500547, user.getLanguage()))==-1) { + if (yichang.length() > 0) yichang += isWrap?"\r\n":"
"; + yichang += SystemEnv.getHtmlLabelName(500547, user.getLanguage()); + } + } + if (forgotCheckMins > 0) {//漏签 + if (text.length() > 0) text += " "; + text += SystemEnv.getHtmlLabelName(20086, user.getLanguage()); + if(yichang.indexOf(SystemEnv.getHtmlLabelName(20086, user.getLanguage()))==-1) { + if (yichang.length() > 0) yichang += isWrap?"\r\n":"
"; + yichang += SystemEnv.getHtmlLabelName(20086, user.getLanguage()); + } + } + if (forgotBeginWorkCheckMins > 0) {//漏签 + if (text.length() > 0) text += " "; + text += SystemEnv.getHtmlLabelName(20086, user.getLanguage()); + if(yichang.indexOf(SystemEnv.getHtmlLabelName(20086, user.getLanguage()))==-1) { + if (yichang.length() > 0) yichang += isWrap?"\r\n":"
"; + yichang += SystemEnv.getHtmlLabelName(20086, user.getLanguage()); + } + } + } + } +// if (leaveMins > 0) {//请假 +// Map jsonObject = null; +// if(leaveInfo.length()>0){ +// jsonObject = JSON.parseObject(leaveInfo); +// for (Entry entry : jsonObject.entrySet()) { +// String newLeaveType = entry.getKey(); +// String tmpLeaveMins = Util.null2String(entry.getValue()); +// if(text.indexOf(kqLeaveRulesComInfo.getLeaveName(newLeaveType))==-1){ +// if (text.length() > 0) text += " "; +// //text += kqLeaveRulesComInfo.getLeaveName(newLeaveType)+tmpLeaveMins+SystemEnv.getHtmlLabelName(15049, user.getLanguage()); +// text += Util.formatMultiLang( kqLeaveRulesComInfo.getLeaveName(newLeaveType),""+user.getLanguage()); +//// text += ":"+KQDurationCalculatorUtil.getDurationRound(("" + (Util.getDoubleValue(""+leaveMins) / 60.0)))+"小时"; +// if(yichang.length()>0) yichang+= isWrap?"\r\n":"
"; +// yichang += Util.formatMultiLang( kqLeaveRulesComInfo.getLeaveName(newLeaveType),""+user.getLanguage()); +// } +// } +// }else{ +// if(text.indexOf(SystemEnv.getHtmlLabelName(670, user.getLanguage()))==-1) { +// if (text.length() > 0) text += " "; +// text += SystemEnv.getHtmlLabelName(670, user.getLanguage()); +// } +// } +// } +// if (evectionMins > 0) {//出差 +// if(text.indexOf(SystemEnv.getHtmlLabelName(20084, user.getLanguage()))==-1) { +// if (text.length() > 0) text += " "; +// text += SystemEnv.getHtmlLabelName(20084, user.getLanguage()); +//// text += ":"+KQDurationCalculatorUtil.getDurationRound(("" + (Util.getDoubleValue(""+evectionMins) / 60.0)))+"小时"; +// if(yichang.length()>0) yichang+= isWrap?"\r\n":"
"; +// yichang += SystemEnv.getHtmlLabelName(20084, user.getLanguage()); +// } +// } +// if (outMins > 0) {//公出 +// if(text.indexOf(SystemEnv.getHtmlLabelName(24058, user.getLanguage()))==-1) { +// if (text.length() > 0) text += " "; +// text += SystemEnv.getHtmlLabelName(24058, user.getLanguage()); +//// text += ":"+KQDurationCalculatorUtil.getDurationRound(("" + (Util.getDoubleValue(""+outMins) / 60.0)))+"小时"; +// if(yichang.length()>0) yichang+= isWrap?"\r\n":"
"; +// yichang += SystemEnv.getHtmlLabelName(24058, user.getLanguage()); +// } +// } + + if(text.length()==0) { + text = "√"; + }else{ + flag = "false";//有其他的异常状态,则表示为false,不需要处理直接全部显示即可 + } + text += overtime; + + + //需要处理下打卡时间和异常状态显示的顺序--start + tmpstatusdata.put(key, yichang); + tmpstatusdata.put(signkey, sign); + boolean hasyichang = tmpstatusdata.get(key).length()>0; + if(tmptext.length()>0){ +// text = tmpstatusdata.get(signkey)+(isWrap?"\r\n":"
")+tmpstatusdata.get(key)+(isWrap?"\r\n":"
"+overtime); + text = tmpstatusdata.get(signkey); + if(hasyichang){ + if(text.length()>0){ + text += (isWrap?"\r\n":"
")+tmpstatusdata.get(key); + }else{ + text += tmpstatusdata.get(key); + } + } + if(hasovertime){ + text += (isWrap?"\r\n":"
")+overtime; + } + }else{ + text = tmpstatusdata.get(signkey); + if(hasyichang){ + if(text.length()>0){ + text += (isWrap?"\r\n":"
")+tmpstatusdata.get(key); + }else{ + text += tmpstatusdata.get(key); + } + } + if(hasovertime){ + text += (isWrap?"\r\n":"
")+overtime; + } + } + //需要处理下打卡时间和异常状态显示的顺序--end + tmpdatass.put(key, (isWrap?"\r\n":"
")+overtime); + if(!"".equals(signintime)) { + textAM+=signintime; + } + if(!"".equals(signouttime)) { + textPM+=signouttime; + } + if(!"".equals(overtime)) { + textPM+=overtime; + } + data.put("text", textAM+""+textPM); + data.put("textAM", textAM); + data.put("textPM", textPM); +// text = tmptext.length()>0?tmptext+" "+text:text;//显示所有的状态 +// data.put("text", text); + datas.put(key, data); + + //add + tmpdata.put("text", flag); + tmpdatas.put(key, tmpdata); + //end + } + //全部搞一遍 +// if(tmpdatas != null){ +//// writeLog(n+">>>tmpdatas="+JSONObject.toJSONString(tmpdatas)); +// Map data1 = null; +// for(Entry entry : tmpdatas.entrySet()){ +// String mapKey = Util.null2String(entry.getKey()); +// Map mapValue = (Map)entry.getValue(); +// String flag = Util.null2String(mapValue.get("text")); +// if("true".equals(flag)){//需要加工的数据 +// String overtime = String.valueOf(tmpdatass.get(mapKey)); +// data1 = new HashMap<>(); +// data1.put("text", "√"+overtime); +// datas.put(mapKey, data1); +// } +// } +//// writeLog("datas="+JSONObject.toJSONString(datas)); +// } + }catch (Exception e){ + writeLog(e); + } + // 最后针对数据再处理一遍,不然出现2023-01-02: "休息" 形式的错误,导致页面记载报错,应该是2023-01-01: {text: "休息"}格式 +// boolean isEnd = false; +// for(String currentDate = fromDate; !isEnd;) { +// if (currentDate.equals(toDate)) isEnd = true; +// String dailyValue = Util.null2String(datas.get(currentDate)); +// if(!"".equals(dailyValue) && !dailyValue.contains("text")) { +// Map innerMap2 = new HashMap<>(); +// innerMap2.put("text", dailyValue); +// datas.put(currentDate, innerMap2); +// } +// currentDate = DateUtil.addDate(currentDate, 1); +// } + return datas; + } + + public Map getDetialDatas(String resourceId,String fromDate, String toDate, User user, + Map flowData,boolean isWrap,int uintType,String show_card_source){ + boolean isKqReportHalfOpen = "1".equals(new KQSettingsComInfo().getMain_val("kq_report_half")); + if(isKqReportHalfOpen) { + return getDetialDatasHalfOpen(resourceId, fromDate, toDate, user, flowData, isWrap, uintType, show_card_source); + } + return getDetialDatasHalfNotOpen(resourceId, fromDate, toDate, user, flowData, isWrap, uintType, show_card_source); + } + +// public String getSignStatus(Map data, User user){ +// String result = ""; +// String signtype = Util.null2String(data.get("signtype"));//上班 下班 +// String worktime = Util.null2String(data.get("worktime"));//工作时间 +// String signtime = Util.null2String(data.get("signtime"));//签到时间 +// String abnormalMins = Util.null2String(data.get("abnormalMins"));//异常分钟数 +// String forgotCheck = Util.null2String(data.get("forgotCheck"));//漏签 +// if(worktime.length()>0){ +// if(signtime.length()>0){ +// if(Util.getDoubleValue(abnormalMins)>0){ +// result =SystemEnv.getHtmlLabelName(signtype.equals("1")?20081:20082, user.getLanguage())+abnormalMins+SystemEnv.getHtmlLabelName(15049, user.getLanguage());//迟到 早退 +// }else{ +// result =SystemEnv.getHtmlLabelName(225, user.getLanguage());//正常 +// } +// }else if(forgotCheck.equals("1")){ +// result =SystemEnv.getHtmlLabelName(20086, user.getLanguage());//漏签 +// } +// }else{ +// result = ""; +// } +// +// return result; +// } + + public int getSerialCount(String resourceId, String fromDate, String toDate, String serialId){ + RecordSet rs = new RecordSet(); + String sql = ""; + int serialCount = 0; + try{ + sql = "select count(1) from hrmresource a, kq_format_total b where a.id= b.resourceid and b.resourceid = ? and b.kqdate >=? and b.kqdate <=? and b.serialId = ? "; + rs.executeQuery(sql,resourceId,fromDate,toDate, serialId); + if(rs.next()){ + serialCount = rs.getInt(1); + } + }catch (Exception e){ + writeLog(e); + } + return serialCount; + } + + public static String getSignStatus(Map signInfo, User user){ + return getSignStatus(signInfo,user,""); + } + + public static String getSignStatusHalfNotOpen(Map signInfo, User user,String onOrOff){ + KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo(); + String text = ""; + String isneedcal = Util.null2String(signInfo.get("isneedcal")); + String workdate = Util.null2String(signInfo.get("workdate")); + String worktime = Util.null2String(signInfo.get("worktime")); + if(!new KQFormatBiz().needCal(workdate,worktime,isneedcal)) {//还未到时间无需计算 + return text; + } + int absenteeismMins = Util.getIntValue(Util.null2String(signInfo.get("absenteeismMins"))); + int beLateMins = Util.getIntValue(Util.null2String(signInfo.get("beLateMins"))); + int graveBeLateMins = Util.getIntValue(Util.null2String(signInfo.get("graveBeLateMins"))); + int leaveEarlyMins = Util.getIntValue(Util.null2String(signInfo.get("leaveEarlyMins"))); + int graveLeaveEarlyMins = Util.getIntValue(Util.null2String(signInfo.get("graveLeaveEarlyMins"))); + int forgotCheckMins = Util.getIntValue(Util.null2String(signInfo.get("forgotCheckMins"))); + int forgotBeginWorkCheckMins = Util.getIntValue(Util.null2String(signInfo.get("forgotBeginWorkCheckMins"))); + int leaveMins = Util.getIntValue(Util.null2String(signInfo.get("leaveMins"))); + String leaveInfo = Util.null2String(signInfo.get("leaveInfo")); + int evectionMins = Util.getIntValue(Util.null2String(signInfo.get("evectionMins"))); + int outMins = Util.getIntValue(Util.null2String(signInfo.get("outMins"))); + + if(worktime.length()>0){ + if (absenteeismMins > 0) {//旷工 + text = SystemEnv.getHtmlLabelName(20085, user.getLanguage())+absenteeismMins+SystemEnv.getHtmlLabelName(15049, user.getLanguage()); + }else { + if (beLateMins > 0) {//迟到 + text = SystemEnv.getHtmlLabelName(20081, user.getLanguage())+beLateMins+SystemEnv.getHtmlLabelName(15049, user.getLanguage()); + } + if (graveBeLateMins > 0) {//严重迟到 + text = SystemEnv.getHtmlLabelName( 500546, user.getLanguage())+graveBeLateMins+SystemEnv.getHtmlLabelName(15049, user.getLanguage()); + } + if (leaveEarlyMins > 0) {//早退 + text = SystemEnv.getHtmlLabelName(20082, user.getLanguage())+leaveEarlyMins+SystemEnv.getHtmlLabelName(15049, user.getLanguage()); + } + if (graveLeaveEarlyMins > 0) {//严重早退 + text = SystemEnv.getHtmlLabelName(500547, user.getLanguage())+graveLeaveEarlyMins+SystemEnv.getHtmlLabelName(15049, user.getLanguage()); + } + if (forgotCheckMins > 0) {//漏签 + text = SystemEnv.getHtmlLabelName(20086, user.getLanguage()); + } + if(onOrOff.length() > 0 && "on".equalsIgnoreCase(onOrOff)){ + if (forgotBeginWorkCheckMins > 0) {//漏签 + text = SystemEnv.getHtmlLabelName(20086, user.getLanguage()); + } + } + } + + if (leaveMins > 0) {//请假 + Map jsonObject = null; + if(leaveInfo.length()>0){ + jsonObject = JSON.parseObject(leaveInfo); + for (Entry entry : jsonObject.entrySet()) { + String newLeaveType = entry.getKey(); + String tmpLeaveMins = Util.null2String(entry.getValue()); + if(text.indexOf(kqLeaveRulesComInfo.getLeaveName(newLeaveType))==-1){ + if (text.length() > 0) text += " "; + //text += kqLeaveRulesComInfo.getLeaveName(newLeaveType)+tmpLeaveMins+SystemEnv.getHtmlLabelName(15049, user.getLanguage()); + text += Util.formatMultiLang(kqLeaveRulesComInfo.getLeaveName(newLeaveType),""+user.getLanguage()); + } + } + }else{ + if(text.indexOf(SystemEnv.getHtmlLabelName(670, user.getLanguage()))==-1) { + if (text.length() > 0) text += " "; + text += SystemEnv.getHtmlLabelName(670, user.getLanguage()); + } + } + } + if (evectionMins > 0) {//出差 + if(text.indexOf(SystemEnv.getHtmlLabelName(20084, user.getLanguage()))==-1) { + if (text.length() > 0) text += " "; + text += SystemEnv.getHtmlLabelName(20084, user.getLanguage()); + } + } + if (outMins > 0) {//公出 + if(text.indexOf(SystemEnv.getHtmlLabelName(24058, user.getLanguage()))==-1) { + if (text.length() > 0) text += " "; + text += SystemEnv.getHtmlLabelName(24058, user.getLanguage()); + } + } + if(text.equals("")){ + boolean needCal = new KQFormatBiz().needCal(workdate,worktime,isneedcal); + text = needCal?SystemEnv.getHtmlLabelName(225, user.getLanguage()):""; + } + }else{ + if (leaveMins > 0) {//请假 + Map jsonObject = null; + if(leaveInfo.length()>0){ + jsonObject = JSON.parseObject(leaveInfo); + for (Entry entry : jsonObject.entrySet()) { + String newLeaveType = entry.getKey(); + String tmpLeaveMins = Util.null2String(entry.getValue()); + if(text.indexOf(kqLeaveRulesComInfo.getLeaveName(newLeaveType))==-1){ + if (text.length() > 0) text += " "; + //text += kqLeaveRulesComInfo.getLeaveName(newLeaveType)+tmpLeaveMins+SystemEnv.getHtmlLabelName(15049, user.getLanguage()); + text += Util.formatMultiLang(kqLeaveRulesComInfo.getLeaveName(newLeaveType)); + } + } + }else{ + if(text.indexOf(SystemEnv.getHtmlLabelName(670, user.getLanguage()))==-1) { + if (text.length() > 0) text += " "; + text += SystemEnv.getHtmlLabelName(670, user.getLanguage()); + } + } + } + if (evectionMins > 0) {//出差 + if(text.indexOf(SystemEnv.getHtmlLabelName(20084, user.getLanguage()))==-1) { + if (text.length() > 0) text += " "; + text += SystemEnv.getHtmlLabelName(20084, user.getLanguage()); + } + } + if (outMins > 0) {//公出 + if(text.indexOf(SystemEnv.getHtmlLabelName(24058, user.getLanguage()))==-1) { + if (text.length() > 0) text += " "; + text += SystemEnv.getHtmlLabelName(24058, user.getLanguage()); + } + } + } + return text; + } + + /** + * 应用设置开启了考勤汇总报表半天开关方法 + * @param signInfo + * @param user + * @param onOrOff + * @return + */ + public static String getSignStatusHalfOpen(Map signInfo, User user,String onOrOff){ + KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo(); + KQTimesArrayComInfo kqTimesArrayComInfo = new KQTimesArrayComInfo(); + String split_time = Util.null2s(kqTimesArrayComInfo.getPropValue("qc1054152","split_time"),"13:00"); + int split_time_index = kqTimesArrayComInfo.getArrayindexByTimes(split_time); + String text = ""; + String isneedcal = Util.null2String(signInfo.get("isneedcal")); + String workdate = Util.null2String(signInfo.get("workdate")); + String worktime = Util.null2String(signInfo.get("worktime")); + String flowinfo = Util.null2String(signInfo.get("flowinfo")); + boolean isNonWork = Util.str2bool(Util.null2String(signInfo.get("isNonWork"))); + if(!new KQFormatBiz().needCal(workdate,worktime,isneedcal)) {//还未到时间无需计算 + return text; + } + String resourceId = Util.null2String(signInfo.get("resourceId")); + String kqDate = Util.null2String(signInfo.get("kqdate")); + ShiftInfoBean shiftInfoBean = KQDurationCalculatorUtil.getWorkTime(resourceId, kqDate, false); + if(shiftInfoBean == null || isNonWork) { + text = SystemEnv.getHtmlLabelName(26593, user.getLanguage()); + if(shiftInfoBean != null) { + List halfWorkIndex = shiftInfoBean.getHalfWorkIndex(); + if (halfWorkIndex != null && !halfWorkIndex.isEmpty()) { + int[] halfWorkIndexs = halfWorkIndex.get(0); + split_time_index = halfWorkIndexs[1];//半天的时间 + } + } + if(flowinfo.length() > 0) { + Map jsonObject = JSON.parseObject(flowinfo); + for (Entry entry : jsonObject.entrySet()) { + String jsonKey = entry.getKey(); + String jsonValue = ""; + if (jsonObject.containsKey(FlowReportTypeEnum.LEAVE.getFlowType())) { + jsonValue = SystemEnv.getHtmlLabelName(670, user.getLanguage()); + } else if (jsonObject.containsKey(FlowReportTypeEnum.EVECTION.getFlowType())) { + jsonValue = SystemEnv.getHtmlLabelName(20084, user.getLanguage()); + } else if (jsonObject.containsKey(FlowReportTypeEnum.OUT.getFlowType())) { + jsonValue = SystemEnv.getHtmlLabelName(24058, user.getLanguage()); + } + if (jsonKey.length() > 0) { + JSONArray jsonArray = JSONArray.parseArray(Util.null2String(entry.getValue())); + if (jsonArray != null && !jsonArray.isEmpty()) { + //客户不存在多个重复流程的情况,只是显示第一个就行 + for (int i = 0; i < jsonArray.size(); i++) { + JSONObject jsonObject1 = (JSONObject) jsonArray.getJSONObject(i); + if (jsonObject1 != null && !jsonObject1.isEmpty()) { + String newLeaveType = Util.null2s(Util.null2String(jsonObject1.get("newLeaveType")), ""); + String begintime = Util.null2s(Util.null2String(jsonObject1.get("begintime")), ""); + String endtime = Util.null2s(Util.null2String(jsonObject1.get("endtime")), ""); + int beginIdx = kqTimesArrayComInfo.getArrayindexByTimes(begintime); + int endIdx = kqTimesArrayComInfo.getArrayindexByTimes(endtime); + if (jsonKey.equalsIgnoreCase(FlowReportTypeEnum.LEAVE.getFlowType())) { + if (newLeaveType.length() > 0) { + jsonValue = kqLeaveRulesComInfo.getLeaveName(newLeaveType); + } + } + if (beginIdx <= split_time_index && endIdx <= split_time_index) { + //上午 + if ("on".equalsIgnoreCase(onOrOff)) { + text = jsonValue; + } + } else if (beginIdx >= split_time_index && endIdx >= split_time_index) { + //下午 + if ("off".equalsIgnoreCase(onOrOff)) { + text = jsonValue; + } + } else { + //全天 + text = jsonValue; + } + } + } + } + } + } + } + return text; + } + List halfWorkIndex = shiftInfoBean.getHalfWorkIndex(); + if(halfWorkIndex != null && !halfWorkIndex.isEmpty()) { + int[] halfWorkIndexs = halfWorkIndex.get(0); + split_time_index = halfWorkIndexs[1];//半天的时间 + } + int absenteeismMins = Util.getIntValue(Util.null2String(signInfo.get("absenteeismMins"))); + int beLateMins = Util.getIntValue(Util.null2String(signInfo.get("beLateMins"))); + int graveBeLateMins = Util.getIntValue(Util.null2String(signInfo.get("graveBeLateMins"))); + int leaveEarlyMins = Util.getIntValue(Util.null2String(signInfo.get("leaveEarlyMins"))); + int graveLeaveEarlyMins = Util.getIntValue(Util.null2String(signInfo.get("graveLeaveEarlyMins"))); + int forgotCheckMins = Util.getIntValue(Util.null2String(signInfo.get("forgotCheckMins"))); + int forgotBeginWorkCheckMins = Util.getIntValue(Util.null2String(signInfo.get("forgotBeginWorkCheckMins"))); + int leaveMins = Util.getIntValue(Util.null2String(signInfo.get("leaveMins"))); + String leaveInfo = Util.null2String(signInfo.get("leaveInfo")); + int evectionMins = Util.getIntValue(Util.null2String(signInfo.get("evectionMins"))); + int outMins = Util.getIntValue(Util.null2String(signInfo.get("outMins"))); + + int on_absenteeismmins = Util.getIntValue(Util.null2String(signInfo.get("on_absenteeismmins"))); + int off_absenteeismmins = Util.getIntValue(Util.null2String(signInfo.get("off_absenteeismmins"))); + + String workbeigintime = Util.null2String(signInfo.get("workbegintime")); + String workendtime = Util.null2String(signInfo.get("workendtime")); + String halfPoint = shiftInfoBean.getHalfcalpoint(); + int halfPointIndex = kqTimesArrayComInfo.getArrayindexByTimes(halfPoint); + + if(worktime.length()>0){ +// if (on_absenteeismmins > 0) {//上午旷工 +// text = SystemEnv.getHtmlLabelName(20085, user.getLanguage())+absenteeismMins+SystemEnv.getHtmlLabelName(15049, user.getLanguage()); +// }else { +// if (beLateMins > 0) {//迟到 +// text = SystemEnv.getHtmlLabelName(20081, user.getLanguage())+beLateMins+SystemEnv.getHtmlLabelName(15049, user.getLanguage()); +// } +// if (graveBeLateMins > 0) {//严重迟到 +// text = SystemEnv.getHtmlLabelName( 500546, user.getLanguage())+graveBeLateMins+SystemEnv.getHtmlLabelName(15049, user.getLanguage()); +// } +// if (leaveEarlyMins > 0) {//早退 +// text = SystemEnv.getHtmlLabelName(20082, user.getLanguage())+leaveEarlyMins+SystemEnv.getHtmlLabelName(15049, user.getLanguage()); +// } +// if (graveLeaveEarlyMins > 0) {//严重早退 +// text = SystemEnv.getHtmlLabelName(500547, user.getLanguage())+graveLeaveEarlyMins+SystemEnv.getHtmlLabelName(15049, user.getLanguage()); +// } +// if (forgotCheckMins > 0) {//漏签 +// text = SystemEnv.getHtmlLabelName(20086, user.getLanguage()); +// } +// if(onOrOff.length() > 0 && "on".equalsIgnoreCase(onOrOff)){ +// if (forgotBeginWorkCheckMins > 0) {//漏签 +// text = SystemEnv.getHtmlLabelName(20086, user.getLanguage()); +// } +// } +// } + + if("on".equalsIgnoreCase(onOrOff)) { + if (on_absenteeismmins > 0) { + text = SystemEnv.getHtmlLabelName(20085, user.getLanguage()); + } + if (beLateMins > 0) {//迟到 + if (text.length() > 0) { + text += " "; + } + text += SystemEnv.getHtmlLabelName(20081, user.getLanguage()) + beLateMins + SystemEnv.getHtmlLabelName(15049, user.getLanguage()); + } + if (graveBeLateMins > 0) {//严重迟到 + if (text.length() > 0) { + text += " "; + } + text += SystemEnv.getHtmlLabelName(500546, user.getLanguage()) + graveBeLateMins + SystemEnv.getHtmlLabelName(15049, user.getLanguage()); + } + if (forgotBeginWorkCheckMins > 0) {//漏签 + if (text.length() > 0) { + text += " "; + } + text += SystemEnv.getHtmlLabelName(20086, user.getLanguage()); + } + } + if("off".equalsIgnoreCase(onOrOff)){ + if(off_absenteeismmins > 0) { + text = SystemEnv.getHtmlLabelName(20085, user.getLanguage()); + } + if (leaveEarlyMins > 0) {//早退 + if (text.length() > 0) { + text += " "; + } + text += SystemEnv.getHtmlLabelName(20082, user.getLanguage())+leaveEarlyMins+SystemEnv.getHtmlLabelName(15049, user.getLanguage()); + } + if (graveLeaveEarlyMins > 0) {//严重早退 + if (text.length() > 0) { + text += " "; + } + text += SystemEnv.getHtmlLabelName(500547, user.getLanguage())+graveLeaveEarlyMins+SystemEnv.getHtmlLabelName(15049, user.getLanguage()); + } + if (forgotCheckMins > 0) {//漏签 + if (text.length() > 0) { + text += " "; + } + text += SystemEnv.getHtmlLabelName(20086, user.getLanguage()); + } + } + + if(flowinfo.length() > 0){ + Map jsonObject = JSON.parseObject(flowinfo); + for (Entry entry : jsonObject.entrySet()) { + String jsonKey = entry.getKey(); + String jsonValue = ""; + if(jsonKey.equalsIgnoreCase(FlowReportTypeEnum.LEAVE.getFlowType())){ + jsonValue = SystemEnv.getHtmlLabelName(670, user.getLanguage()); + }else if(jsonKey.equalsIgnoreCase(FlowReportTypeEnum.EVECTION.getFlowType())){ + jsonValue = SystemEnv.getHtmlLabelName(20084, user.getLanguage()); + }else if(jsonKey.equalsIgnoreCase(FlowReportTypeEnum.OUT.getFlowType())){ + jsonValue = SystemEnv.getHtmlLabelName(24058, user.getLanguage()); + } + if(jsonKey.length() > 0){ + JSONArray jsonArray = JSONArray.parseArray(Util.null2String(entry.getValue())); + if(jsonArray != null && !jsonArray.isEmpty()){ + //客户不存在多个重复流程的情况,只是显示第一个就行 + for(int i = 0 ; i < jsonArray.size() ; i++){ + JSONObject jsonObject1 = (JSONObject) jsonArray.getJSONObject(i); + if(jsonObject1 != null && !jsonObject1.isEmpty()){ + String newLeaveType = Util.null2s(Util.null2String(jsonObject1.get("newLeaveType")),""); + String begintime = Util.null2s(Util.null2String(jsonObject1.get("begintime")),""); + String endtime = Util.null2s(Util.null2String(jsonObject1.get("endtime")),""); + int beginIdx = kqTimesArrayComInfo.getArrayindexByTimes(begintime); + int endIdx = kqTimesArrayComInfo.getArrayindexByTimes(endtime); + + if(jsonKey.equalsIgnoreCase(FlowReportTypeEnum.LEAVE.getFlowType())){ + if(newLeaveType.length() > 0){ + jsonValue = kqLeaveRulesComInfo.getLeaveName(newLeaveType); + } + } + if(beginIdx <= split_time_index && endIdx <= split_time_index){ + //上午 + if("on".equalsIgnoreCase(onOrOff)){ + if(begintime.equals(workbeigintime) && endIdx == halfPointIndex) { + text = ""; + } else if(begintime.equals(workbeigintime) && endtime.equals(workendtime)) { + text = ""; + } + text = jsonValue+("".equals(text) ? "":", "+text); + } + }else if(beginIdx >= split_time_index && endIdx >= split_time_index){ + //下午 + if("off".equalsIgnoreCase(onOrOff)){ + if(endIdx == halfPointIndex && endtime.equals(workendtime)) { + text = ""; + } else if(begintime.equals(workbeigintime) && endtime.equals(workendtime)) { + text = ""; + } + text = jsonValue+("".equals(text) ? "":", "+text); + } + }else { + //全天 + if(begintime.equals(workbeigintime) && endtime.equals(workendtime)) { + text = ""; + } + text = jsonValue+("".equals(text) ? "":", "+text); + } + } + if(text.length() > 0){ + break; + } + } + } + } + } + } + + if(text.equals("")){ + boolean needCal = new KQFormatBiz().needCal(workdate,worktime); + text = needCal? SystemEnv.getHtmlLabelName(225, user.getLanguage()):""; + } + }else{ + text = SystemEnv.getHtmlLabelName(225, user.getLanguage()); + if("on".equalsIgnoreCase(onOrOff)){ + if(on_absenteeismmins > 0) { + text = SystemEnv.getHtmlLabelName(20085, user.getLanguage()); + } + } + if("off".equalsIgnoreCase(onOrOff)){ + if(off_absenteeismmins > 0) { + text = SystemEnv.getHtmlLabelName(20085, user.getLanguage()); + } + } + if(flowinfo.length() > 0) { + Map jsonObject = JSON.parseObject(flowinfo); + for (Entry entry : jsonObject.entrySet()) { + String jsonKey = entry.getKey(); + String jsonValue = ""; + if (jsonObject.containsKey(FlowReportTypeEnum.LEAVE.getFlowType())) { + jsonValue = SystemEnv.getHtmlLabelName(670, user.getLanguage()); + } else if (jsonObject.containsKey(FlowReportTypeEnum.EVECTION.getFlowType())) { + jsonValue = SystemEnv.getHtmlLabelName(20084, user.getLanguage()); + } else if (jsonObject.containsKey(FlowReportTypeEnum.OUT.getFlowType())) { + jsonValue = SystemEnv.getHtmlLabelName(24058, user.getLanguage()); + } + if (jsonKey.length() > 0) { + JSONArray jsonArray = JSONArray.parseArray(Util.null2String(entry.getValue())); + if (jsonArray != null && !jsonArray.isEmpty()) { + //客户不存在多个重复流程的情况,只是显示第一个就行 + for (int i = 0; i < jsonArray.size(); i++) { + JSONObject jsonObject1 = (JSONObject) jsonArray.getJSONObject(i); + if (jsonObject1 != null && !jsonObject1.isEmpty()) { + String newLeaveType = Util.null2s(Util.null2String(jsonObject1.get("newLeaveType")), ""); + String begintime = Util.null2s(Util.null2String(jsonObject1.get("begintime")), ""); + String endtime = Util.null2s(Util.null2String(jsonObject1.get("endtime")), ""); + int beginIdx = kqTimesArrayComInfo.getArrayindexByTimes(begintime); + int endIdx = kqTimesArrayComInfo.getArrayindexByTimes(endtime); + if (jsonKey.equalsIgnoreCase(FlowReportTypeEnum.LEAVE.getFlowType())) { + if (newLeaveType.length() > 0) { + jsonValue = kqLeaveRulesComInfo.getLeaveName(newLeaveType); + } + } + if (beginIdx <= split_time_index && endIdx <= split_time_index) { + //上午 + if ("on".equalsIgnoreCase(onOrOff)) { + text = jsonValue; + } + } else if (beginIdx >= split_time_index && endIdx >= split_time_index) { + //下午 + if ("off".equalsIgnoreCase(onOrOff)) { + text = jsonValue; + } + } else { + //全天 + text = jsonValue; + } + } + } + } + } + } + } + if(text.length() == 0){ + text = SystemEnv.getHtmlLabelName(26593, user.getLanguage()); + } + } + return text; + } + + public static String getSignStatus(Map signInfo, User user,String onOrOff){ + boolean isKqReportHalfOpen = "1".equals(new KQSettingsComInfo().getMain_val("kq_report_half")); + if(isKqReportHalfOpen) { + return getSignStatusHalfOpen(signInfo, user, onOrOff); + } + return getSignStatusHalfNotOpen(signInfo, user, onOrOff); + } + + /** + * 获取打卡状态(不包含具体分钟数) + * @param signInfo + * @param user + * @param onOrOff + * @return + */ + public static String getSignStatus2(Map signInfo, User user, String onOrOff) { + KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo(); + String text = ""; + String worktime = Util.null2String(signInfo.get("worktime")); + int absenteeismMins = Util.getIntValue(Util.null2String(signInfo.get("absenteeismMins"))); + int beLateMins = Util.getIntValue(Util.null2String(signInfo.get("beLateMins"))); + int graveBeLateMins = Util.getIntValue(Util.null2String(signInfo.get("graveBeLateMins"))); + int leaveEarlyMins = Util.getIntValue(Util.null2String(signInfo.get("leaveEarlyMins"))); + int graveLeaveEarlyMins = Util.getIntValue(Util.null2String(signInfo.get("graveLeaveEarlyMins"))); + int forgotCheckMins = Util.getIntValue(Util.null2String(signInfo.get("forgotCheckMins"))); + int forgotBeginWorkCheckMins = Util.getIntValue(Util.null2String(signInfo.get("forgotBeginWorkCheckMins"))); + int leaveMins = Util.getIntValue(Util.null2String(signInfo.get("leaveMins"))); + String leaveInfo = Util.null2String(signInfo.get("leaveInfo")); + int evectionMins = Util.getIntValue(Util.null2String(signInfo.get("evectionMins"))); + int outMins = Util.getIntValue(Util.null2String(signInfo.get("outMins"))); + Boolean isNonWork = (Boolean) signInfo.get("isNonWork"); + + if (!isNonWork) { + if (absenteeismMins > 0) {//旷工 + text = SystemEnv.getHtmlLabelName(20085, user.getLanguage()); + } else { + if (beLateMins > 0) {//迟到 + text = SystemEnv.getHtmlLabelName(20081, user.getLanguage()); + } + if (graveBeLateMins > 0) {//严重迟到 + text = SystemEnv.getHtmlLabelName(500546, user.getLanguage()); + } + if (leaveEarlyMins > 0) {//早退 + text = SystemEnv.getHtmlLabelName(20082, user.getLanguage()); + } + if (graveLeaveEarlyMins > 0) {//严重早退 + text = SystemEnv.getHtmlLabelName(500547, user.getLanguage()); + } + if (forgotCheckMins > 0) {//漏签 + text = SystemEnv.getHtmlLabelName(20086, user.getLanguage()); + } + if (onOrOff.length() > 0 && "on".equalsIgnoreCase(onOrOff)) { + if (forgotBeginWorkCheckMins > 0) {//漏签 + text = SystemEnv.getHtmlLabelName(20086, user.getLanguage()); + } + } + } + if (text.equals("") && leaveMins <= 0 && evectionMins <= 0 && outMins <= 0) { + text = SystemEnv.getHtmlLabelName(225, user.getLanguage()); + } + } + return text; + } + + public static boolean getShowFlowText(String leaveInfo,String onOrOff){ + Map jsonObject = null; + jsonObject = JSON.parseObject(leaveInfo); + String flow_signtype = ""; + for (Entry entry : jsonObject.entrySet()) { + String tmpSignType = Util.null2String(entry.getValue()); + flow_signtype += ","+tmpSignType; + } + if(flow_signtype.length() == 0){ + return true; + } + return isShowFlowText(flow_signtype,onOrOff); + } + + public static boolean isShowFlowText(String flow_signtype,String onOrOff){ + boolean showFlowText = true; + + if(flow_signtype.length() > 0){ + flow_signtype = flow_signtype.substring(1); + if("on".equalsIgnoreCase(onOrOff)){ + if((","+flow_signtype+",").indexOf(",1,") > -1){ + //抵扣了上班卡 + }else{ + //上班状态,但是没有上班抵扣流程 + showFlowText = false; + } + } + if("off".equalsIgnoreCase(onOrOff)){ + if((","+flow_signtype+",").indexOf(",2,") > -1){ + //抵扣了下班卡 + }else{ + //下班状态,但是没有下班抵扣流程 + showFlowText = false; + } + } + } + return showFlowText; + } + + public static int getPageSize(String pageSize, String pageUid, int userid){ + String sql = ""; + RecordSet rs = new RecordSet(); + int iPageSize= Util.getIntValue(pageSize,10); + if(iPageSize<10)iPageSize=10; + try{ + if(pageSize.length()>0){ + boolean flag = false; + sql = "select count(1) from ecology_pagesize where pageid = '"+pageUid+"' and userid ="+userid; + rs.executeQuery(sql); + if(rs.next()){ + if(rs.getInt(1)>0){ + flag = true; + } + } + if(flag){ + sql = "update ecology_pagesize set pagesize ="+pageSize+" where pageid = '"+pageUid+"' and userid ="+userid; + rs.executeUpdate(sql); + }else{ + sql = "insert into ecology_pagesize (pageid,pagesize,userid) values ('"+pageUid+"',"+pageSize+","+userid+")"; + rs.executeUpdate(sql); + } + }else{ + sql = "select pageSize from ecology_pagesize where pageid = '"+pageUid+"' and userid ="+userid; + rs.executeQuery(sql); + if(rs.next()){ + iPageSize = rs.getInt("pageSize"); + } + } + }catch (Exception e){ + new BaseBean().writeLog("KQReportBiz.getPageSize"+e); + } + + return iPageSize; + } + + //经常遇到申请变更流程或销假流程提示未归档,不胜其烦,所以搞一下 + public void reflow(String requestid){ + try { + requestid = Util.null2String(requestid); + String workflowid = ""; + String currentnodetype = ""; + if(requestid.length() == 0){ + return; + } + RecordSet rs2 = new RecordSet(); + String sql = "select requestid,workflowid,currentnodetype from workflow_requestbase where requestid = '"+requestid+"'"; + rs2.executeQuery(sql); + if(rs2.next()){ + workflowid = Util.null2String(rs2.getString("workflowid")); + currentnodetype = Util.null2String(rs2.getString("currentnodetype")); + } + + boolean isForce1 = false; + boolean isUpgrade1 = false; + if(requestid.length() == 0){ + return ; + } + if(workflowid.length() == 0){ + return ; + } + if(!"3".equals(currentnodetype)){ + return ; + } + long start = System.currentTimeMillis(); + + KQFlowActiontBiz kqFlowActiontBiz = new KQFlowActiontBiz(); + RecordSet rs = new RecordSet(); + RecordSet rs1 = new RecordSet(); + String proc_set_sql = "select * from kq_att_proc_set where field001 = ? "; + rs.executeQuery(proc_set_sql, workflowid); + if(rs.next()){ + String proc_set_id = rs.getString("id"); + //得到这个考勤流程设置是否使用明细 + String usedetails = rs.getString("usedetail"); + + int kqtype = Util.getIntValue(rs.getString("field006")); + + Map map = new HashMap(); + if(Util.getIntValue(requestid) > 0){ + map.put("requestId", "and t.requestId = " + requestid); + } + String tablename = ""; + if(kqtype == KqSplitFlowTypeEnum.LEAVE.getFlowtype()){ + tablename = KqSplitFlowTypeEnum.LEAVE.getTablename(); + }else if(kqtype == KqSplitFlowTypeEnum.EVECTION.getFlowtype()){ + tablename = KqSplitFlowTypeEnum.EVECTION.getTablename(); + }else if(kqtype == KqSplitFlowTypeEnum.OUT.getFlowtype()){ + tablename = KqSplitFlowTypeEnum.OUT.getTablename();; + }else if(kqtype == KqSplitFlowTypeEnum.OVERTIME.getFlowtype()){ + tablename = KqSplitFlowTypeEnum.OVERTIME.getTablename(); + return; + }else if(kqtype == KqSplitFlowTypeEnum.SHIFT.getFlowtype()){ + tablename = KqSplitFlowTypeEnum.SHIFT.getTablename();; + }else if(kqtype == KqSplitFlowTypeEnum.OTHER.getFlowtype()){ + tablename = KqSplitFlowTypeEnum.OTHER.getTablename();; + }else if(kqtype == KqSplitFlowTypeEnum.CARD.getFlowtype()){ + tablename = KqSplitFlowTypeEnum.CARD.getTablename();; + return; + }else if(kqtype == KqSplitFlowTypeEnum.LEAVEBACK.getFlowtype()){ + tablename = KqSplitFlowTypeEnum.LEAVEBACK.getTablename();; + }else{ + return; + } + if(null != tablename && tablename.length() > 0){ + String tmpsql = "select * from "+tablename+" where requestId="+requestid; + rs1.executeQuery(tmpsql); + if(rs1.next()){ + return;//表示已经产生了拆分数据 + } + } + + //先根据requestid删除中间表里的数据,再做啥插入操作 + if(kqtype == KqSplitFlowTypeEnum.OVERTIME.getFlowtype()) { + return;//加班就不搞了,有遇到用户销假选择错误流程,选择了加班流程导致这里reflow一次,多余生成了调休 + }else{ + String delSql = "delete from "+tablename+" where requestid = "+requestid; + rs1.executeUpdate(delSql); + Map result = kqFlowActiontBiz.handleKQFlowAction(proc_set_id, usedetails, Util.getIntValue(requestid), kqtype, Util.getIntValue(workflowid), isForce1,isUpgrade1,map); + } + + } + long end = System.currentTimeMillis(); + }catch (Exception e){ + e.printStackTrace();; + } + } + + + //add + public Map getOverTime(Map params, User user){ + Map datas = new HashMap<>();; + RecordSet rs = new RecordSet(); + String sql = ""; + String sqlWhere = " "; + try{ + KQOvertimeRulesBiz kqOvertimeRulesBiz = new KQOvertimeRulesBiz(); + JSONObject jsonObj = JSON.parseObject(Util.null2String(params.get("data"))); + String fromDate = Util.null2String(jsonObj.get("fromDate")); + String toDate = Util.null2String(jsonObj.get("toDate")); + String typeselect =Util.null2String(jsonObj.get("typeselect")); + if(typeselect.length()==0)typeselect = "3"; + if(!typeselect.equals("") && !typeselect.equals("0")&& !typeselect.equals("6")){ + if(typeselect.equals("1")){ + fromDate = TimeUtil.getCurrentDateString(); + toDate = TimeUtil.getCurrentDateString(); + }else{ + fromDate = TimeUtil.getDateByOption(typeselect,"0"); + toDate = TimeUtil.getDateByOption(typeselect,"1"); + } + } + String subCompanyId = Util.null2String(jsonObj.get("subCompanyId")); + String departmentId = Util.null2String(jsonObj.get("departmentId")); + String resourceId = Util.null2String(jsonObj.get("resourceId")); + String allLevel = Util.null2String(jsonObj.get("allLevel")); + String isNoAccount = Util.null2String(jsonObj.get("isNoAccount")); + String viewScope = Util.null2String(jsonObj.get("viewScope")); + if(subCompanyId.length()>0){ + sqlWhere +=" and a.subcompanyid1 in("+subCompanyId+") "; + } + + if(departmentId.length()>0){ + sqlWhere +=" and a.departmentid in("+departmentId+") "; + } + + if(resourceId.length()>0){ + sqlWhere +=" and a.id in("+resourceId+") "; + } + + if(viewScope.equals("4")){//我的下属 + if(allLevel.equals("1")){//所有下属 + sqlWhere+=" and a.managerstr like '%,"+user.getUID()+",%'"; + }else{ + sqlWhere+=" and a.managerid="+user.getUID();//直接下属 + } + } + if (!"1".equals(isNoAccount)) { + sqlWhere += " and a.loginid is not null "+(rs.getDBType().equals("oracle")?"":" and a.loginid<>'' "); + } + + int uintType = Util.getIntValue(Util.null2String(params.get("uintType")));//当前加班单位 + double hoursToDay = Util.getDoubleValue(Util.null2String(params.get("hoursToDay")));//当前天跟小时计算关系 + + String valueField = ""; + + sql = " select resourceid,belongdate,paidLeaveEnable,duration_min "+ + " from hrmresource a, kq_flow_overtime b "+ + " where a.id = b.resourceid and belongdate >='"+fromDate+"' and belongdate <='"+toDate+"' " +sqlWhere+ + " order by resourceid,belongdate "; + rs.execute(sql); +// kqLog.info("getOverTime:sql:"+sql); + while (rs.next()) { + String resourceid = rs.getString("resourceid"); + String belongdate = rs.getString("belongdate"); + String paidLeaveEnable = rs.getString("paidLeaveEnable"); +// int changeType =rs.getInt("changeType");//1-节假日、2-工作日、3-休息日 + double value = rs.getDouble("duration_min")<0?0:rs.getDouble("duration_min"); + if(uintType==3 || uintType== 5 || uintType== 6){//按小时计算 + value = Util.getDoubleValue(KQDurationCalculatorUtil.getDurationRound(value/(60.0)+"")); + }else{//按天计算 + value = Util.getDoubleValue(KQDurationCalculatorUtil.getDurationRound(value/(60.0*hoursToDay)+"")); + } + String key = resourceid+"|"+belongdate+"|overtime"; + if(value>0){ + df.setMaximumFractionDigits(5); + if(datas.containsKey(key)){ + double tmpVal = Util.getDoubleValue(Util.null2String(datas.get(key)),0.0); + tmpVal += value; + datas.put(key,format(tmpVal)); + }else{ + datas.put(key,format(value)); + } + +// if(datas.containsKey(key)){ +// datas.put(key,"加班"); +//// datas.put(key,SystemEnv.getHtmlLabelName(6151, user.getLanguage())); +// }else{ +// datas.put(key,"加班"); +// } + } + } + }catch (Exception e){ + writeLog(e); + } + return datas; + } +} diff --git a/领悦二开new/src/com/engine/kq/biz/KQScheduleSignImport.java b/领悦二开new/src/com/engine/kq/biz/KQScheduleSignImport.java new file mode 100644 index 0000000..645566a --- /dev/null +++ b/领悦二开new/src/com/engine/kq/biz/KQScheduleSignImport.java @@ -0,0 +1,877 @@ +package com.engine.kq.biz; + +import com.alibaba.fastjson.JSONObject; +import com.engine.kq.bean.ImportSetting; +import com.engine.kq.entity.KQScheduleSignEntity; +import com.engine.kq.timer.KQQueue; +import com.engine.kq.timer.KQTaskBean; +import com.engine.kq.util.KQDurationCalculatorUtil; +import com.engine.kq.wfset.util.SplitActionUtil; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import org.apache.poi.hssf.usermodel.*; +import org.apache.poi.poifs.filesystem.POIFSFileSystem; +import weaver.common.DateUtil; +import weaver.common.StringUtil; +import weaver.conn.BatchRecordSet; +import weaver.conn.RecordSet; +import weaver.conn.RecordSetDataSource; +import weaver.file.ImageFileManager; +import weaver.general.BaseBean; +import weaver.general.TimeUtil; +import weaver.general.Util; +import weaver.hrm.User; +import weaver.hrm.common.Tools; +import weaver.systeminfo.SystemEnv; + +import java.sql.Timestamp; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.*; + + +public class KQScheduleSignImport extends BaseBean { + private List errorInfo = new ArrayList(); + private String fileName = ""; + private String keyField = ""; + private int userlanguage = 7; //登录语言 + + public KQScheduleSignImport() { + } + + public KQScheduleSignImport(Map params) { + this.keyField = Util.null2String(params.get("keyField")); + if (this.keyField.length() == 0) this.keyField = "workcode"; + this.fileName = Util.null2String(params.get("excelfile")); + } + + /** + * 私有方法,获取Excel表格对应表格中的数据 + * + * @param cell Excel表格的行 + * @param row Excel表格的列 + * @return Excel表格对应表格中的数据 + */ + private String getCellValue(HSSFCell cell, HSSFRow row) { + if (cell == null) return ""; + String cellValue = ""; + switch (cell.getCellType()) { + + case NUMERIC: + if (HSSFDateUtil.isCellDateFormatted(cell)) { + SimpleDateFormat sdf = null; + if (cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("h:mm:ss")) { + sdf = new SimpleDateFormat("HH:mm:ss"); + } else {// 日期 + sdf = new SimpleDateFormat("yyyy-MM-dd"); + } + Date date = cell.getDateCellValue(); + cellValue = sdf.format(date); + } else { + cellValue = new java.text.DecimalFormat("0").format(cell.getNumericCellValue()); + } + break; + case STRING: + cellValue = cell.getStringCellValue(); + break; + case FORMULA: + cellValue = (DateFormat.getDateInstance().format((cell.getDateCellValue()))).toString(); + + break; + default: + + break; + } + return cellValue; + } + + /** + * 将Excel表格中的数据导入数据库 + */ + public synchronized void ExcelToDB() { + String sql = ""; + BatchRecordSet bRs = new BatchRecordSet(); + List> lsParams = new ArrayList<>(); + List params = null; + List> lsDelParams = new ArrayList<>(); + List delParams = null; + + List lsFormatData = new ArrayList<>(); + List> lsFormatParams = new ArrayList<>(); + List formatParams = null; + Map lsmap = new HashMap<>(); + + try { + ImageFileManager manager = new ImageFileManager(); + manager.getImageFileInfoById(Util.getIntValue(this.fileName)); + HSSFWorkbook workbook = new HSSFWorkbook(new POIFSFileSystem(manager.getInputStream())); + HSSFSheet sheet = workbook.getSheetAt(0); + HSSFRow row = null; + + Map> users = getUsers(this.userlanguage); + Map loginidMap = users.get("loginidMap"); + Map lastnameMap = users.get("lastnameMap"); + Map workcodeMap = users.get("workcodeMap"); + + int rowsNum = sheet.getLastRowNum(); + for (int i = 1; i < rowsNum + 1; i++) { + row = sheet.getRow(i); + if (row == null || !ScanRow(row)) continue; + int tmpUserId = 0; + String tmpLoginid = ""; + String tmpWorkcode = ""; + String tmpLastname = ""; + String tmpSigndate = ""; + String tmpSigntime = ""; + String tmpClientaddress = ""; + int tmpIsincom = 1; + String tmpLongitude = ""; + String tmpLatitude = ""; + String tmpAddr = ""; + for (int j = 0; j < row.getLastCellNum(); j++) { + if (j == 0) { + tmpLoginid = Util.null2String(this.getCellValue(row.getCell((short) j), row)).trim(); + } else if (j == 1) { + tmpWorkcode = Util.null2String(this.getCellValue(row.getCell((short) j), row)).trim(); + } else if (j == 2) { + tmpLastname = Util.null2String(this.getCellValue(row.getCell((short) j), row)).trim(); + } else if (j == 3) { + tmpSigndate = Util.null2String(this.getCellValue(row.getCell((short) j), row)); + if (tmpSigndate.length() == 0) continue; + SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(SDF.parse(tmpSigndate + " 00:00:00")); + tmpSigndate = TimeUtil.getFormartString(calendar, "yyyy-MM-dd"); + } else if (j == 4) { + tmpSigntime = Util.null2String(this.getCellValue(row.getCell((short) j), row)).trim(); + if (tmpSigntime.length() == 0) continue; + if (tmpSigntime.length() > 0) { + String[] a = tmpSigntime.split(":"); + if (a != null && a.length < 3) { + tmpSigntime += ":00"; + } + } + SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(SDF.parse("1999-01-01 " + tmpSigntime)); + tmpSigntime = TimeUtil.getFormartString(calendar, "HH:mm:ss"); + } else if (j == 5) { + tmpClientaddress = Util.null2String(this.getCellValue(row.getCell((short) j), row)); + } + } + if (tmpLoginid.length() == 0 && tmpWorkcode.length() == 0 && tmpLastname.length() == 0) continue; + if (this.keyField.equals("loginid")) { +// tmpUserId = getUserId(tmpLoginid); + tmpUserId = StringUtil.parseToInt(loginidMap.get(tmpLoginid), 0); + } else if (this.keyField.equals("workcode")) { +// tmpUserId = getUserId(tmpWorkcode); + tmpUserId = StringUtil.parseToInt(workcodeMap.get(tmpWorkcode), 0); + } else if (this.keyField.equals("lastname")) { +// tmpUserId = getUserId(tmpLastname); + tmpUserId = StringUtil.parseToInt(lastnameMap.get(tmpLastname), 0); + } + + if (tmpUserId <= 0) continue; + params = new ArrayList<>(); + params.add(tmpUserId); + params.add(1); + params.add(tmpSigndate); + params.add(tmpSigntime); + params.add(tmpClientaddress); + params.add(tmpIsincom); + params.add(1); + params.add("importExcel"); + params.add(tmpLongitude); + params.add(tmpLatitude); + params.add(tmpAddr); + lsParams.add(params); + + String belongDate = getBelongDate(new User(tmpUserId), tmpSigndate, tmpSigntime); + + String formatData = tmpUserId + "|" + tmpSigndate+ "|" + belongDate; + //Arraylist的底层源码采用的indexOf接口有性能问题,单独搞下 +// if (!lsFormatData.contains(formatData)) { +// lsFormatData.add(formatData); +// } + + //替换为hashmap,性能会高很多 + if(!lsmap.containsKey(formatData)){ + lsmap.put(formatData,formatData); + } + } + Map> overtimeMap = Maps.newHashMap(); + List overtimeList = Lists.newArrayList(); + //刷新报表数据 + if(null != lsmap){ + for(Map.Entry entry : lsmap.entrySet()){ + String mapKey = Util.null2String(entry.getKey()); + String mapValue = entry.getValue(); + formatParams = new ArrayList<>(); + String[] formatData = Util.splitString(mapValue, "|"); + +// for (int i = 0; lsFormatData != null && i < lsFormatData.size(); i++) { +// formatParams = new ArrayList<>(); +// String[] formatData = Util.splitString(lsFormatData.get(i), "|"); + + String date_1 = DateUtil.addDate(formatData[1], -1); + formatParams.add(formatData[0]); + formatParams.add(date_1); + lsFormatParams.add(formatParams); + + formatParams = new ArrayList<>(); + formatParams.add(formatData[0]); + formatParams.add(formatData[1]); + lsFormatParams.add(formatParams); + + delParams = new ArrayList<>(); + delParams.add(formatData[0]); + delParams.add(formatData[1]); + lsDelParams.add(delParams); + + String resourceId = formatData[0]; + String kqdate = formatData[1]; + String belongDate = formatData[2]; + if (overtimeMap.containsKey(resourceId)) { + List tmp_overtimeList = overtimeMap.get(resourceId); + if (!tmp_overtimeList.contains(kqdate)) { + tmp_overtimeList.add(kqdate); + if(!kqdate.equals(belongDate)) { + tmp_overtimeList.add(belongDate); + } + } + } else { + if (!overtimeList.contains(kqdate)) { + overtimeList.add(kqdate); + if(!kqdate.equals(belongDate)) { + overtimeList.add(belongDate); + } + } + overtimeMap.put(resourceId, overtimeList); + } + } + } + + + //删除本次同步数据 + sql = " delete from hrmschedulesign where signfrom='importExcel' and userid =? and signdate = ? "; + bRs.executeBatchSql(sql, lsDelParams); + + sql = " insert into HrmScheduleSign (userid, usertype, signdate, signtime, clientaddress, isincom, isimport, signfrom, longitude, latitude, addr) " + + " values(?,?,?,?,?,?,?,?,?,?,?)"; + bRs.executeBatchSql(sql, lsParams); + + new KQFormatBiz().format(lsFormatParams, 15); + //处理加班生成 + List tasks = new ArrayList<>(); + for (Map.Entry> mme : overtimeMap.entrySet()) { + String resid = mme.getKey(); + List overList = mme.getValue(); + for (String date : overList) { + SplitActionUtil.pushOverTimeTasks(date, date, resid, tasks); + } + } + if (!tasks.isEmpty()) { + KQQueue.writeTasks(tasks); + } + } catch (Exception e) { + writeLog(e); + } + + } + + /** + * 验证数据的合法性 + */ + public boolean ScanRow(HSSFRow row) { + boolean canImport = true; + try { + int userid = 0; + String loginid = "", workcode = "", lastname = ""; + for (int j = 0; j < row.getLastCellNum(); j++) { + if (j == 0) { + //验证loginid + loginid = this.getCellValue(row.getCell((short) j), row); + } else if (j == 1) { + //验证workcode + workcode = this.getCellValue(row.getCell((short) j), row); + } else if (j == 2) { + //验证用户名 + lastname = this.getCellValue(row.getCell((short) j), row); + } else if (j == 3) { + //验证考勤时间 + String signdate = Util.null2String(this.getCellValue(row.getCell((short) j), row)); + String signtime = Util.null2String(this.getCellValue(row.getCell((short) (j + 1)), row)).trim(); + if (signdate.length() == 0) { + canImport = false; + } + if (signtime.length() == 0) { + canImport = false; + } + if (signtime.length() > 0) { + String[] a = signtime.split(":"); + if (a != null && a.length < 3) { + signtime += ":00"; + } + } + + String signdatetime = signdate + " " + signtime; + if (signdate.length() > 0 && signtime.length() > 0 && checkData(signdatetime, "datetime")) + canImport = false; + } + } + if (this.keyField.equals("loginid")) { + if (loginid.length() == 0) canImport = false; + userid = getUserId(loginid); + } else if (this.keyField.equals("workcode")) { + if (workcode.length() == 0) canImport = false; + userid = getUserId(workcode); + } else if (this.keyField.equals("lastname")) { + if (lastname.length() == 0) canImport = false; + userid = getUserId(lastname); + } + if (userid == 0) { + canImport = false; + } + } catch (Exception e) { + writeLog(e); + } + return canImport; + } + + /** + * 验证数据的合法性 + */ + public List ScanFile() { + try { + ImageFileManager manager = new ImageFileManager(); + manager.getImageFileInfoById(Util.getIntValue(this.fileName)); + HSSFWorkbook workbook = new HSSFWorkbook(new POIFSFileSystem(manager.getInputStream())); + HSSFSheet sheet = workbook.getSheetAt(0); + + HSSFRow row = null; + + int number = 0; + int rowsNum = sheet.getLastRowNum(); + for (int i = 1; i < rowsNum + 1; i++) { + row = sheet.getRow(i); + if (row == null) continue; + number = i+1; + int userid = 0; + String loginid = "", workcode = "", lastname = ""; + for (int j = 0; j < row.getLastCellNum(); j++) { + if (j == 0) { + //验证loginid + loginid = Util.null2String(this.getCellValue(row.getCell((short) j), row)).trim(); + } else if (j == 1) { + //验证workcode + workcode = Util.null2String(this.getCellValue(row.getCell((short) j), row)).trim(); + } else if (j == 2) { + //验证用户名 + lastname = Util.null2String(this.getCellValue(row.getCell((short) j), row)).trim(); + } else if (j == 3) { + //验证考勤时间 + HSSFCell cell3 = row.getCell((short) j); + String signdate = Util.null2String(this.getCellValue(cell3, row)); + HSSFCell cell4 = row.getCell((short) (j + 1)); + String signtime = Util.null2String(this.getCellValue(cell4, row)).trim(); + + if (signtime.length() > 0) { + String[] a = signtime.split(":"); + if (a != null && a.length < 3) { + signtime += ":00"; + } + } + + if (this.keyField.equals("loginid")) { + if (loginid.length() == 0) { + errorInfo.add(SystemEnv.getHtmlLabelName(15323, userlanguage) + " " + number + " " + SystemEnv.getHtmlLabelName(503585, userlanguage)); + } else { + userid = getUserId(loginid); + if (userid == 0) { + errorInfo.add(SystemEnv.getHtmlLabelName(15323, userlanguage) + " " + number + " " + SystemEnv.getHtmlLabelName(503586, userlanguage)); + } + } + } else if (this.keyField.equals("workcode")) { + if (workcode.length() == 0) { + errorInfo.add(SystemEnv.getHtmlLabelName(15323, userlanguage) + " " + number + " " + SystemEnv.getHtmlLabelName(83770, userlanguage)); + } else { + userid = getUserId(workcode); + if (userid == 0) { + errorInfo.add(SystemEnv.getHtmlLabelName(15323, userlanguage) + " " + number + " " + SystemEnv.getHtmlLabelName(83772, userlanguage)); + } + } + } else if (this.keyField.equals("lastname")) { + if (lastname.length() == 0) { + errorInfo.add(SystemEnv.getHtmlLabelName(15323, userlanguage) + " " + number + " " + SystemEnv.getHtmlLabelName(83774, userlanguage)); + } else { + userid = getUserId(lastname); + if (userid == 0) { + errorInfo.add(SystemEnv.getHtmlLabelName(15323, userlanguage) + " " + number + " " + SystemEnv.getHtmlLabelName(83777, userlanguage)); + } + } + } + + if (signdate.length() == 0) { + errorInfo.add(SystemEnv.getHtmlLabelName(15323, userlanguage) + " " + number + " " + SystemEnv.getHtmlLabelName(83762, userlanguage)); + } + if (signtime.length() == 0) { + errorInfo.add(SystemEnv.getHtmlLabelName(15323, userlanguage) + " " + number + " " + SystemEnv.getHtmlLabelName(83763, userlanguage)); + } + String signdatetime = signdate + " " + signtime; + if (signdate.length() > 0 && signtime.length() > 0 && checkData(signdatetime, "datetime")) + errorInfo.add(SystemEnv.getHtmlLabelName(15323, userlanguage) + " " + number + " " + SystemEnv.getHtmlLabelName(83768, userlanguage)); + } + } + } + } catch (Exception e) { + writeLog(e); + errorInfo.add(SystemEnv.getHtmlLabelName(83779, userlanguage)); + } + return errorInfo; + } + + /** + * 判断数据类型 + * + * @param value + * @param type + * @return + */ + public static boolean checkData(String value, String type) { + boolean boo = false; + + if (type.equals("int")) { + try { + Integer.parseInt(value); + } catch (Exception e) { + boo = true; + } + } else if (type.equals("float")) { + try { + Float.parseFloat(value); + } catch (Exception e) { + boo = true; + } + } else if (type.equals("datetime")) { + try { + SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(SDF.parse(value)); + + } catch (ParseException e) { + boo = true; + } + } + return boo; + } + + public int getUserId(String val) { + int userid = 0; + RecordSet rs = new RecordSet(); + String sql = ""; + if (Util.isEnableMultiLang()) { + if (rs.getDBType().equalsIgnoreCase("sqlserver")) { + sql = "select id from hrmresource where ltrim(rtrim(dbo.convToMultiLang(ltrim(rtrim(" + keyField + "))," + userlanguage + ")))='" + Util.null2String(val).trim() + "'"; + } else { + sql = "select id from hrmresource where ltrim(rtrim(convToMultiLang(ltrim(rtrim(" + keyField + "))," + userlanguage + ")))='" + Util.null2String(val).trim() + "'"; + } + } else { + sql = "select id from hrmresource where ltrim(rtrim( " + keyField + "))='" + Util.null2String(val).trim() + "'"; + } + rs.execute(sql); + if (rs.next()) { + userid = rs.getInt("id"); + } + return userid; + } + + public static int getUserId(String val, String keyField, int userlanguage) { + int userid = 0; + RecordSet rs = new RecordSet(); + String sql = ""; + if (Util.isEnableMultiLang()) { + if (rs.getDBType().equalsIgnoreCase("sqlserver")) { + sql = "select id from hrmresource where ltrim(rtrim(dbo.convToMultiLang(ltrim(rtrim(" + keyField + "))," + userlanguage + ")))='" + Util.null2String(val).trim() + "'"; + } else { + sql = "select id from hrmresource where ltrim(rtrim(convToMultiLang(ltrim(rtrim(" + keyField + "))," + userlanguage + ")))='" + Util.null2String(val).trim() + "'"; + } + } else { + sql = "select id from hrmresource where ltrim(rtrim(" + keyField + "))='" + Util.null2String(val).trim() + "'"; + } + rs.execute(sql); + if (rs.next()) { + userid = rs.getInt("id"); + } + return userid; + } + + public void importData(String beginDate, String endDate, boolean isSyn) throws Exception { + writeLog("考勤机同步:importData:开始>>>>>>beginDate>>"+beginDate+">>>>>endDate>>>>"+endDate+">>>>>>"+DateUtil.getFullDate()); + RecordSet rs = new RecordSet(); + RecordSet delrs = new RecordSet(); + String sql = ""; + endDate = Tools.getDate(endDate, 1); + BatchRecordSet bRs = new BatchRecordSet(); + List> lsParams = new ArrayList<>(); + List params = null; + + List> lsDelParams = new ArrayList<>(); + List delParams = null; + + List lsFormatData = new ArrayList<>(); + List> lsFormatParams = new ArrayList<>(); + List formatParams = null; + + Map> users = getUsers(this.userlanguage); + Map loginidMap = users.get("loginidMap"); + Map lastnameMap = users.get("lastnameMap"); + Map workcodeMap = users.get("workcodeMap"); + List keymap = new ArrayList<>(); + + + List lsImportSetting = new ArrayList<>(); + ImportSetting importSetting = null; + sql = " select datasourceid, loginid, workcode, lastname, signdate, signtime, tablename, clientaddress,longitude,latitude,addr,memo " + + " from HrmScheduleSignSet "; + rs.execute(sql); + while (rs.next()) { + importSetting = new ImportSetting(); + importSetting.setDatasourceid(Util.null2String(rs.getString("datasourceid")).trim()); + importSetting.setLoginid(Util.null2String(rs.getString("loginid")).trim()); + importSetting.setWorkcode(Util.null2String(rs.getString("workcode")).trim()); + importSetting.setLastname(Util.null2String(rs.getString("lastname")).trim()); + importSetting.setSigndate(Util.null2String(rs.getString("signdate")).trim()); + importSetting.setSigntime(Util.null2String(rs.getString("signtime")).trim()); + importSetting.setTablename(Util.null2String(rs.getString("tablename")).trim()); + importSetting.setClientaddress(Util.null2String(rs.getString("clientaddress")).trim()); + importSetting.setLongitude(Util.null2String(rs.getString("longitude")).trim()); + importSetting.setLatitude(Util.null2String(rs.getString("latitude")).trim()); + importSetting.setAddr(Util.null2String(rs.getString("addr")).trim()); + importSetting.setMemo(Util.null2String(rs.getString("memo")).trim()); + lsImportSetting.add(importSetting); + } + List lsKQScheduleSignData = new ArrayList<>(); + KQScheduleSignEntity kqScheduleSignData = null; + for (int i = 0; lsImportSetting != null && i < lsImportSetting.size(); i++) { +// DataSource ds = null; +// Connection conn = null; + try { + importSetting = lsImportSetting.get(i); + String datasourceid = importSetting.getDatasourceid(); + String loginid = importSetting.getLoginid(); + String workcode = importSetting.getWorkcode(); + String lastname = importSetting.getLastname(); + String signdate = importSetting.getSigndate(); + String signtime = importSetting.getSigntime(); + String tablename = importSetting.getTablename(); + String clientaddress = importSetting.getClientaddress(); + String longitude = importSetting.getLongitude(); + String latitude = importSetting.getLatitude(); + String addr = importSetting.getAddr(); + String memo = importSetting.getMemo(); + +// ds = (DataSource) StaticObj.getServiceByFullname(("datasource." + datasourceid), DataSource.class); +// if (ds == null) continue; +// conn = ds.getConnection(); +// conn.setAutoCommit(true); +// PreparedStatement pstmt = null; +// ResultSet resultSet = null; + + DateFormat df = new SimpleDateFormat("HH:mm:ss"); + +// sql = "select * from " + tablename + " where " + signdate + " >= '" + beginDate + "' and " + signdate + " < '" + endDate + "' order by " + signdate + (signtime.length() == 0 || signtime.equalsIgnoreCase(signdate) ? "" : (", " + signtime)); + sql = " select * from " + tablename + " where modedatacreatedate >= '" + beginDate + "' and modedatacreatedate < '" + endDate + "' order by modedatacreatedate,modedatacreatetime "; + + //有遇到外部同步,上面的【conn = ds.getConnection();】这个阻塞住,导致下面的同步不执行,下面的用法和集成领导确认 + RecordSetDataSource rsds = new RecordSetDataSource(datasourceid); + +// pstmt = conn.prepareStatement(sql); +// resultSet = pstmt.executeQuery(); + + rsds.execute(sql); + + List noRepertSynData = new ArrayList<>(); + while (rsds.next()) { + String tmpLoginid = ""; + String tmpWorkcode = ""; + String tmpLastname = ""; + String tmpSigndate = ""; + String tmpSigntime = ""; + String tmpClientaddress = ""; + String tmpLongitude = ""; + String tmpLatitude = ""; + String tmpAddr = ""; + String tmpMemo = ""; + String tmpCreatedate = ""; + + if (loginid.length() > 0) tmpLoginid = Util.null2String(rsds.getString(loginid)).trim(); + if (workcode.length() > 0) tmpWorkcode = Util.null2String(rsds.getString(workcode)).trim(); + if (lastname.length() > 0) tmpLastname = Util.null2String(rsds.getString(lastname)).trim(); + if (signdate.length() > 0) tmpSigndate = Util.null2String(rsds.getString(signdate)).trim(); + if (clientaddress.length() > 0) + tmpClientaddress = Util.null2String(rsds.getString(clientaddress)); + if (longitude.length() > 0) tmpLongitude = Util.null2String(rsds.getString(longitude)).trim(); + if (latitude.length() > 0) tmpLatitude = Util.null2String(rsds.getString(latitude)).trim(); + if (addr.length() > 0) tmpAddr = Util.null2String(rsds.getString(addr)).trim(); + if (memo.length() > 0) tmpMemo = Util.null2String(rsds.getString(memo)).trim(); + tmpCreatedate = Util.null2String(rsds.getString("modedatacreatedate")).trim(); + + if (signtime.length() > 0) { + tmpSigntime = Util.null2String(rsds.getString(signtime)).trim(); + //判断tmpSigntime格式 08:21:11 如果为长格式需要格式化 + if (tmpSigntime.length() > 8) { + if(tmpSigntime.length()<16){//有遇到signtime格式为hh:mm:ss.0000的格式导致同步不成功 + tmpSigntime = tmpSigntime.substring(0,8); + }else{//比如上yyyy-mm-dd hh:mm的格式走原逻辑 + tmpSigntime = df.format(Timestamp.valueOf(tmpSigntime)); + } + } else if (tmpSigntime.length() < 8) { + //不带秒的情况 自动补齐 + tmpSigntime += ":00"; + } + } else { + tmpSigntime = ""; + } + + if (tmpSigndate.length() > 10) { + //如果时间为长格式,从signdate字段中格式化时间 + if (tmpSigndate.length() == 16) { + //不带秒的情况 自动补齐 + tmpSigndate += ":00"; + } + if (tmpSigntime.length() == 0) {//以signtime字段为有限 + tmpSigndate = tmpSigndate.length()>19?tmpSigndate.substring(0,19):tmpSigndate; + tmpSigntime = df.format(Timestamp.valueOf(tmpSigndate)); + } + tmpSigndate = Tools.formatDate(tmpSigndate, "yyyy-MM-dd"); + } + + //如果时间格式不带秒补齐 + if (tmpSigntime.length() <= 5) { + tmpSigntime += ":00"; + } + + kqScheduleSignData = new KQScheduleSignEntity(); + kqScheduleSignData.setLoginid(tmpLoginid); + kqScheduleSignData.setWorkcode(tmpWorkcode); + kqScheduleSignData.setLastname(tmpLastname); + kqScheduleSignData.setSigndate(tmpSigndate); + kqScheduleSignData.setSigntime(tmpSigntime); + kqScheduleSignData.setClientaddress(tmpClientaddress); + kqScheduleSignData.setLongitude(tmpLongitude); + kqScheduleSignData.setLatitude(tmpLatitude); + kqScheduleSignData.setAddr(tmpAddr); + kqScheduleSignData.setMemo(tmpMemo); + kqScheduleSignData.setCreatedate(tmpCreatedate); + lsKQScheduleSignData.add(kqScheduleSignData); + } +// resultSet.close(); +// pstmt.close(); + } catch (Exception e) { + writeLog(e); + } +// finally { +// if (conn != null) conn.close(); +// } + } + List noRepertSynData = new ArrayList<>(); + for (int i = 0; lsKQScheduleSignData != null && i < lsKQScheduleSignData.size(); i++) { + kqScheduleSignData = lsKQScheduleSignData.get(i); + String tmpLoginid = kqScheduleSignData.getLoginid(); + String tmpWorkcode = kqScheduleSignData.getWorkcode(); + String tmpLastname = kqScheduleSignData.getLastname(); + String tmpSigndate = kqScheduleSignData.getSigndate(); + String tmpSigntime = kqScheduleSignData.getSigntime(); + String tmpClientaddress = kqScheduleSignData.getClientaddress(); + String tmpLongitude = kqScheduleSignData.getLongitude(); + String tmpLatitude = kqScheduleSignData.getLatitude(); + String tmpAddr = kqScheduleSignData.getAddr(); + String tmpMemo = kqScheduleSignData.getMemo(); + String tmpCreatedate = kqScheduleSignData.getCreatedate(); + int userid = 0; + if (Util.null2String(tmpLoginid).length() > 0) { + userid = StringUtil.parseToInt(loginidMap.get(tmpLoginid), 0); +// userid = getUserId(tmpLoginid, "loginid", this.userlanguage); + } + if (userid == 0 && Util.null2String(tmpWorkcode).length() > 0) { + userid = StringUtil.parseToInt(workcodeMap.get(tmpWorkcode), 0); +// userid = getUserId(tmpWorkcode, "workcode", this.userlanguage); + } + if (userid == 0 && Util.null2String(tmpLastname).length() > 0) { + userid = StringUtil.parseToInt(lastnameMap.get(tmpLastname), 0); +// userid = getUserId(tmpLastname, "lastname", this.userlanguage); + } + + if (userid <= 0) { + writeLog("人员id未找到>>>>>>>>>>" + JSONObject.toJSONString(kqScheduleSignData)); + continue; + } + String dkParamData = userid + "#" + tmpCreatedate + "#" + tmpSigntime; + if (noRepertSynData.contains(dkParamData)) { + continue; + } + noRepertSynData.add(dkParamData); + params = new ArrayList<>(); + params.add(userid); + params.add(1); + params.add(tmpSigndate); + params.add(tmpSigntime); + params.add(tmpClientaddress); + params.add(1); + params.add(1); + params.add("OutDataSourceSyn"); + params.add(tmpLongitude); + params.add(tmpLatitude); + params.add(tmpAddr); + params.add(tmpMemo); + params.add(tmpCreatedate); + lsParams.add(params); + + String belongDate = getBelongDate(new User(userid), tmpCreatedate, tmpSigntime); + + String formatData = userid + "|" + tmpCreatedate+ "|" + belongDate; + if (!lsFormatData.contains(formatData)) { + lsFormatData.add(formatData); + } + } + + Map> overtimeMap = Maps.newHashMap(); + List overtimeList = Lists.newArrayList(); + //刷新报表数据 + for (int i = 0; lsFormatData != null && i < lsFormatData.size(); i++) { + formatParams = new ArrayList<>(); + String key = lsFormatData.get(i);//String formatData = userid + "|" + tmpSigndate; + String[] formatData = Util.splitString(lsFormatData.get(i), "|"); + String date_1 = DateUtil.addDate(formatData[1], -1); + formatParams.add(formatData[0]); + formatParams.add(date_1); + lsFormatParams.add(formatParams); + + formatParams = new ArrayList<>(); + formatParams.add(formatData[0]); + formatParams.add(formatData[1]); + lsFormatParams.add(formatParams); + + if (!keymap.contains(key)) { + keymap.add(key); + delParams = new ArrayList<>(); + delParams.add(formatData[0]); + delParams.add(formatData[1]); + lsDelParams.add(delParams); + } + + String resourceId = formatData[0]; + String kqdate = formatData[1]; + String belongDate = formatData[2]; + if (overtimeMap.containsKey(resourceId)) { + List tmp_overtimeList = overtimeMap.get(resourceId); + if (!tmp_overtimeList.contains(kqdate)) { + tmp_overtimeList.add(kqdate); + if(!kqdate.equals(belongDate)) { + tmp_overtimeList.add(belongDate); + } + } + } else { + if (!overtimeList.contains(kqdate)) { + overtimeList.add(kqdate); + if(!kqdate.equals(belongDate)) { + overtimeList.add(belongDate); + } + } + overtimeMap.put(resourceId, overtimeList); + } + } + + writeLog("同步之前删除数据:"+ JSONObject.toJSONString(lsDelParams)); + writeLog("同步插入数据:"+ JSONObject.toJSONString(lsParams)); + + //删除本次同步数据 + sql = " delete from hrmschedulesign where signfrom='OutDataSourceSyn' and userid =? and createdate = ? "; + bRs.executeBatchSql(sql, lsDelParams); + + + sql = " insert into HrmScheduleSign (userid, usertype, signdate, signtime, clientaddress, isincom, isimport, signfrom, longitude, latitude, addr,memo,createdate) " + + " values(?,?,?,?,?,?,?,?,?,?,?,?,?)"; + bRs.executeBatchSql(sql, lsParams); + + new KQFormatBiz().format(lsFormatParams, 12); + + //处理加班生成 + List tasks = new ArrayList<>(); + for (Map.Entry> mme : overtimeMap.entrySet()) { + String resid = mme.getKey(); + List overList = mme.getValue(); + for (String date : overList) { + SplitActionUtil.pushOverTimeTasks(date, date, resid, tasks); + } + } + if (!tasks.isEmpty()) { + KQQueue.writeTasks(tasks); + } + } + + public Map> getUsers(int language) { + RecordSet rs = new RecordSet(); + String sql = "select id,loginid,lastname,workcode from hrmresource where status in(0,1,2,3,5)"; + if (Util.isEnableMultiLang()) { + if (rs.getDBType().equalsIgnoreCase("sqlserver")) { + sql = "select id,loginid,ltrim(rtrim(dbo.convToMultiLang(ltrim(rtrim(lastname)),"+language+"))) as lastname,workcode from hrmresource where status in(0,1,2,3,5)"; + } else { + sql = "select id,loginid,ltrim(rtrim(convToMultiLang(ltrim(rtrim(lastname)),"+language+"))) as lastname,workcode from hrmresource where status in(0,1,2,3,5)"; + } + } + + Map> users = new HashMap>(); + rs.execute(sql); + Map loginidMap = new HashMap(); + Map lastnameMap = new HashMap(); + Map workcodeMap = new HashMap(); + String resourceId = "", loginid = "",lastname = "", workcode = ""; + while (rs.next()) { + if (StringUtil.isNull(resourceId = StringUtil.vString(rs.getString("id")))) continue; + loginid = StringUtil.vString(rs.getString("loginid")); + if (StringUtil.isNull(loginid)){ +// continue;//以防离职人员账号被清空的直接跳过,如果没有被清空,那么也支持离职人员的同步 + }else{ + loginidMap.put(loginid, resourceId); + } +// if (StringUtil.isNotNull(loginid = StringUtil.vString(rs.getString("loginid")))) loginidMap.put(loginid, resourceId); + if (StringUtil.isNotNull(lastname = StringUtil.vString(rs.getString("lastname")))) lastnameMap.put(lastname, resourceId); + if (StringUtil.isNotNull(workcode = StringUtil.vString(rs.getString("workcode")))) workcodeMap.put(workcode, resourceId); + } + users.put("loginidMap", loginidMap); + users.put("lastnameMap", lastnameMap); + users.put("workcodeMap", workcodeMap); + return users; + } + + public int getUserlanguage() { + return userlanguage; + } + + public void setUserlanguage(int userlanguage) { + this.userlanguage = userlanguage; + } + + private String getBelongDate(User user, String curDate, String signDateTime) { + String belongDate = curDate; + Map todayLineMap = KQDurationCalculatorUtil.getWorkButton(user, curDate,true); + if(todayLineMap != null) { + List> preInfo = (ArrayList>)todayLineMap.get("pre_signTime"); + if(preInfo != null) { + for(Map entry : preInfo) { + String pre_endtime_across = entry.get("endtime_across"); + String pre_endtime = entry.get("endtime"); + String signEndInfo = "1".equals(pre_endtime_across) ? (curDate+" "+pre_endtime+":00") : (DateUtil.addDate(curDate,-1)+" "+pre_endtime+":00"); + String signOutDateTime = signDateTime; + if(signOutDateTime.compareTo(signEndInfo) < 0) { + belongDate = DateUtil.addDate(curDate, -1); + } + } + } + } + return belongDate; + } + +} diff --git a/领悦二开new/src/com/engine/kq/biz/KQScheduleSignImportJob.java b/领悦二开new/src/com/engine/kq/biz/KQScheduleSignImportJob.java new file mode 100644 index 0000000..0d1f260 --- /dev/null +++ b/领悦二开new/src/com/engine/kq/biz/KQScheduleSignImportJob.java @@ -0,0 +1,30 @@ +package com.engine.kq.biz; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.Util; +import weaver.hrm.common.Tools; +import weaver.interfaces.schedule.BaseCronJob; + +public class KQScheduleSignImportJob extends BaseCronJob{ + public void execute() { + RecordSet rs = new RecordSet(); + try{ + + rs.writeLog("begin do KQScheduleSignImportJob invoke ..."); + + KQScheduleSignImport kqScheduleSignImport = new KQScheduleSignImport(); + //导入策略 每天导入前一天和当天数据 + int kqScheduleSignImportDay = Util.getIntValue(Prop.getInstance().getPropValue("QC637173", "KQScheduleSignImportDay"),1);//考勤自动同步同步几天前的数据,默认一天 + String date_from = Tools.getDate(Tools.getToday(),-kqScheduleSignImportDay); + String date_to = Tools.getDate(Tools.getToday()); + + rs.writeLog("do KQScheduleSignImportJob invoke..["+date_from+";"+date_to+"]"); + + kqScheduleSignImport.importData(date_from,date_to,false); + + rs.writeLog("end do KQScheduleSignImportJob invoke ..."); + }catch (Exception e) { + rs.writeLog(e) ; + } + } +} diff --git a/领悦二开new/src/com/engine/kq/biz/KQShiftManagementComInfo.java b/领悦二开new/src/com/engine/kq/biz/KQShiftManagementComInfo.java new file mode 100644 index 0000000..176f4f0 --- /dev/null +++ b/领悦二开new/src/com/engine/kq/biz/KQShiftManagementComInfo.java @@ -0,0 +1,814 @@ +package com.engine.kq.biz; + +import com.alibaba.fastjson.JSON; +import com.engine.kq.biz.chain.cominfo.HalfShiftComIndex; +import com.engine.kq.biz.chain.cominfo.RestShiftComIndex; +import com.engine.kq.biz.chain.cominfo.ShiftComIndex; +import com.engine.kq.biz.chain.cominfo.ShiftInfoCominfoBean; +import com.engine.kq.biz.chain.cominfo.WorkShiftComIndex; +import com.engine.kq.biz.chain.shiftinfo.ShiftInfoBean; +import com.engine.kq.cmd.shiftmanagement.toolkit.ShiftManagementToolKit; +import com.engine.kq.entity.TimeScopeEntity; +import com.engine.kq.log.KQLog; +import java.io.PrintWriter; +import java.io.Serializable; +import java.io.StringWriter; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.concurrent.ConcurrentHashMap; +import java.util.stream.Collectors; +import org.apache.commons.lang.math.NumberUtils; +import weaver.cache.CacheBase; +import weaver.cache.CacheColumn; +import weaver.cache.CacheColumnType; +import weaver.cache.CacheItem; +import weaver.cache.CacheMap; +import weaver.cache.PKColumn; +import weaver.conn.RecordSet; +import weaver.general.Util; + +/** + * 班次管理缓存类 + */ +public class KQShiftManagementComInfo extends CacheBase implements Serializable { + /* + * 需要关注 : 如果完全在 initCache 自己定义数据初始化, 这个字段可以不定义 + */ + protected static String TABLE_NAME = ""; + + /* + * 需要关注 : 如果完全在 initCache 自己定义数据初始化,或者不需要指定固定的条件, 这个字段可以不定义 + * sql中的where信息,不要以where开始 + */ + protected static String TABLE_WHERE = null; + + /* + * 需要关注 : 如果完全在 initCache 自己定义数据初始化,或者不需要指定顺序, 这个字段可以不定义 sql中的order + * by信息,不要以order by开始 + * + */ + protected static String TABLE_ORDER = null; + + @PKColumn(type = CacheColumnType.NUMBER) + protected static String PK_NAME = "id"; + + @CacheColumn + protected static int shiftbean; + + @CacheColumn + protected static int color; + + @CacheColumn + protected static int isoffdutyfreecheck; + + @CacheColumn + protected static int shiftonoffworkcount; + + @CacheColumn + protected static int serial; + + @CacheColumn + protected static int isresttimeopen; + + @CacheColumn + protected static int worktime; + + @CacheColumn + protected static int punchsetting; + + @CacheColumn + protected static int cardRemind; + + @CacheColumn + protected static int cardRemOfSignIn; + + @CacheColumn + protected static int minsBeforeSignIn; + + @CacheColumn + protected static int cardRemOfSignOut; + + @CacheColumn + protected static int minsAfterSignOut; + + @CacheColumn + protected static int remindMode; + + @CacheColumn + protected static int remindOnPC; + + @CacheColumn + protected static int signoutOnlyoff; + + @CacheColumn + protected static int isRest; + + @CacheColumn + protected static int overtimeRuleId; + + private KQLog kqLog = new KQLog(); + + private boolean isFormat = false; + + @Override + public CacheItem initCache(String key) { + if (key == null || "".equals(key.trim())) { + return null; + } + CacheMap localData = createCacheMap(); + String sql = ""; + kqLog = new KQLog(); + ConcurrentHashMap resourceKQGroups = new ConcurrentHashMap<>(); + //考勤组优先级 + try { + + ConcurrentHashMap shiftInfoBeanMap = new ConcurrentHashMap<>(); + ConcurrentHashMap idMap = new ConcurrentHashMap<>(); + ConcurrentHashMap colorsMap = new ConcurrentHashMap<>(); + ConcurrentHashMap isoffdutyfreechecksMap = new ConcurrentHashMap<>(); + ConcurrentHashMap shiftonoffworkcountsMap = new ConcurrentHashMap<>(); + ConcurrentHashMap serialsMap = new ConcurrentHashMap<>(); + ConcurrentHashMap isresttimeopensMap = new ConcurrentHashMap<>(); + ConcurrentHashMap worktimesMap = new ConcurrentHashMap<>(); + ConcurrentHashMap punchsettingsMap = new ConcurrentHashMap<>(); + ConcurrentHashMap cardRemindMap = new ConcurrentHashMap<>(); + ConcurrentHashMap cardRemOfSignInMap = new ConcurrentHashMap<>(); + ConcurrentHashMap minsBeforeSignInMap = new ConcurrentHashMap<>(); + ConcurrentHashMap cardRemOfSignOutMap = new ConcurrentHashMap<>(); + ConcurrentHashMap minsAfterSignOutMap = new ConcurrentHashMap<>(); + ConcurrentHashMap remindModeMap = new ConcurrentHashMap<>(); + ConcurrentHashMap remindOnPCMap = new ConcurrentHashMap<>(); + ConcurrentHashMap signoutOnlyoffMap = new ConcurrentHashMap<>(); + ConcurrentHashMap isResetMap = new ConcurrentHashMap<>(); + ConcurrentHashMap overtimeruleMap = new ConcurrentHashMap<>(); + RecordSet rs = new RecordSet(); + String getShiftInfo = "select * from kq_ShiftManagement where 1=1 and id="+key+" order by id "; + rs.execute(getShiftInfo); + while(rs.next()){ + String serialid = rs.getString("id"); + String isresttimeopen = rs.getString("isresttimeopen"); + String color = rs.getString("color"); + String shiftonoffworkcount = rs.getString("shiftonoffworkcount"); + String worktime = rs.getString("worktime"); + String serial = rs.getString("serial"); + String punchsetting = "1"; + String isoffdutyfreecheck = rs.getString("isoffdutyfreecheck"); + String cardRemind = rs.getString("cardRemind"); + String cardRemOfSignIn = rs.getString("cardRemOfSignIn"); + String minsBeforeSignIn = rs.getString("minsBeforeSignIn"); + String cardRemOfSignOut = rs.getString("cardRemOfSignOut"); + String minsAfterSignOut = rs.getString("minsAfterSignOut"); + String remindMode = rs.getString("remindMode"); + String remindOnPC = rs.getString("remindOnPC"); + String halfcalrule = rs.getString("halfcalrule"); + halfcalrule = Util.null2String(halfcalrule).length() == 0 ? "0" : halfcalrule; + String halfcalpoint = rs.getString("halfcalpoint"); + String halfcalpoint2cross = rs.getString("halfcalpoint2cross"); + String overtimeRuleId = rs.getString("overtime_rule_id"); + String signoutOnlyoff = rs.getString("signoutOnlyoff"); + String isRest = rs.getString("is_rest"); + + getShiftInfoBean(serialid,isresttimeopen,worktime,punchsetting,shiftInfoBeanMap,halfcalrule,halfcalpoint,halfcalpoint2cross,signoutOnlyoff); + + idMap.put(serialid, serialid); + colorsMap.put(serialid, color); + isoffdutyfreechecksMap.put(serialid, isoffdutyfreecheck); + shiftonoffworkcountsMap.put(serialid, shiftonoffworkcount); + serialsMap.put(serialid, serial); + isresttimeopensMap.put(serialid, isresttimeopen); + worktimesMap.put(serialid, worktime); + punchsettingsMap.put(serialid, punchsetting); + cardRemindMap.put(serialid,cardRemind); + cardRemOfSignInMap.put(serialid,cardRemOfSignIn); + minsBeforeSignInMap.put(serialid,minsBeforeSignIn); + cardRemOfSignOutMap.put(serialid,cardRemOfSignOut); + minsAfterSignOutMap.put(serialid,minsAfterSignOut); + remindModeMap.put(serialid,remindMode); + remindOnPCMap.put(serialid,remindOnPC); + signoutOnlyoffMap.put(serialid,signoutOnlyoff); + isResetMap.put(serialid,isRest); + overtimeruleMap.put(serialid,overtimeRuleId); + } + + + if(shiftInfoBeanMap.size()>0){ + CacheItem cacheItem = createCacheItem(); + Iterator> iterator = shiftInfoBeanMap.entrySet().iterator(); + while (iterator.hasNext()) { + Entry entry = iterator.next(); + String id = entry.getKey(); + Object value = entry.getValue(); + cacheItem.set(PK_INDEX, id); + cacheItem.set(shiftbean, value); + cacheItem.set(isoffdutyfreecheck, isoffdutyfreechecksMap.get(id)); + cacheItem.set(shiftonoffworkcount, shiftonoffworkcountsMap.get(id)); + cacheItem.set(serial, serialsMap.get(id)); + cacheItem.set(isresttimeopen, isresttimeopensMap.get(id)); + cacheItem.set(worktime, worktimesMap.get(id)); + cacheItem.set(punchsetting, punchsettingsMap.get(id)); + cacheItem.set(cardRemind,cardRemindMap.get(id)); + cacheItem.set(cardRemOfSignIn,cardRemOfSignInMap.get(id)); + cacheItem.set(minsBeforeSignIn,minsBeforeSignInMap.get(id)); + cacheItem.set(cardRemOfSignOut,cardRemOfSignOutMap.get(id)); + cacheItem.set(minsAfterSignOut,minsAfterSignOutMap.get(id)); + cacheItem.set(remindMode,remindModeMap.get(id)); + cacheItem.set(remindOnPC,remindOnPCMap.get(id)); + cacheItem.set(signoutOnlyoff,signoutOnlyoffMap.get(id)); + cacheItem.set(isRest,isResetMap.get(id)); + cacheItem.set(overtimeRuleId,overtimeruleMap.get(id)); + modifyCacheItem(id, cacheItem); + } + return cacheItem; + } + } catch (Exception e) { + kqLog.info(e); + } + return null; + } + + @Override + public CacheMap initCache() { + CacheMap localData = createCacheMap(); + String sql = ""; + kqLog = new KQLog(); + ConcurrentHashMap resourceKQGroups = new ConcurrentHashMap<>(); + //考勤组优先级 + try { + + ConcurrentHashMap shiftInfoBeanMap = new ConcurrentHashMap<>(); + ConcurrentHashMap idMap = new ConcurrentHashMap<>(); + ConcurrentHashMap colorsMap = new ConcurrentHashMap<>(); + ConcurrentHashMap isoffdutyfreechecksMap = new ConcurrentHashMap<>(); + ConcurrentHashMap shiftonoffworkcountsMap = new ConcurrentHashMap<>(); + ConcurrentHashMap serialsMap = new ConcurrentHashMap<>(); + ConcurrentHashMap isresttimeopensMap = new ConcurrentHashMap<>(); + ConcurrentHashMap worktimesMap = new ConcurrentHashMap<>(); + ConcurrentHashMap punchsettingsMap = new ConcurrentHashMap<>(); + ConcurrentHashMap cardRemindMap = new ConcurrentHashMap<>(); + ConcurrentHashMap cardRemOfSignInMap = new ConcurrentHashMap<>(); + ConcurrentHashMap minsBeforeSignInMap = new ConcurrentHashMap<>(); + ConcurrentHashMap cardRemOfSignOutMap = new ConcurrentHashMap<>(); + ConcurrentHashMap minsAfterSignOutMap = new ConcurrentHashMap<>(); + ConcurrentHashMap remindModeMap = new ConcurrentHashMap<>(); + ConcurrentHashMap remindOnPCMap = new ConcurrentHashMap<>(); + ConcurrentHashMap signoutOnlyoffMap = new ConcurrentHashMap<>(); + ConcurrentHashMap isResetMap = new ConcurrentHashMap<>(); + ConcurrentHashMap overtimeruleMap = new ConcurrentHashMap<>(); + RecordSet rs = new RecordSet(); + String getShiftInfo = "select * from kq_ShiftManagement where 1=1 order by id "; + rs.execute(getShiftInfo); + while(rs.next()){ + String serialid = rs.getString("id"); + String isresttimeopen = rs.getString("isresttimeopen"); + String color = rs.getString("color"); + String shiftonoffworkcount = rs.getString("shiftonoffworkcount"); + String worktime = rs.getString("worktime"); + String serial = rs.getString("serial"); + String punchsetting = "1"; + String isoffdutyfreecheck = rs.getString("isoffdutyfreecheck"); + String cardRemind = rs.getString("cardRemind"); + String cardRemOfSignIn = rs.getString("cardRemOfSignIn"); + String minsBeforeSignIn = rs.getString("minsBeforeSignIn"); + String cardRemOfSignOut = rs.getString("cardRemOfSignOut"); + String minsAfterSignOut = rs.getString("minsAfterSignOut"); + String remindMode = rs.getString("remindMode"); + String remindOnPC = rs.getString("remindOnPC"); + String halfcalrule = rs.getString("halfcalrule"); + halfcalrule = Util.null2String(halfcalrule).length() == 0 ? "0" : halfcalrule; + String halfcalpoint = rs.getString("halfcalpoint"); + String halfcalpoint2cross = rs.getString("halfcalpoint2cross"); + String signoutOnlyoff = rs.getString("signoutOnlyoff"); + String overtimeRuleId = rs.getString("overtime_rule_id"); + String isRest = rs.getString("is_rest"); + + getShiftInfoBean(serialid,isresttimeopen,worktime,punchsetting,shiftInfoBeanMap,halfcalrule,halfcalpoint,halfcalpoint2cross,signoutOnlyoff); + + idMap.put(serialid, serialid); + colorsMap.put(serialid, color); + isoffdutyfreechecksMap.put(serialid, isoffdutyfreecheck); + shiftonoffworkcountsMap.put(serialid, shiftonoffworkcount); + serialsMap.put(serialid, serial); + isresttimeopensMap.put(serialid, isresttimeopen); + worktimesMap.put(serialid, worktime); + punchsettingsMap.put(serialid, punchsetting); + cardRemindMap.put(serialid,cardRemind); + cardRemOfSignInMap.put(serialid,cardRemOfSignIn); + minsBeforeSignInMap.put(serialid,minsBeforeSignIn); + cardRemOfSignOutMap.put(serialid,cardRemOfSignOut); + minsAfterSignOutMap.put(serialid,minsAfterSignOut); + remindModeMap.put(serialid,remindMode); + remindOnPCMap.put(serialid,remindOnPC); + signoutOnlyoffMap.put(serialid,signoutOnlyoff); + isResetMap.put(serialid,isRest); + overtimeruleMap.put(serialid,overtimeRuleId); + } + + + if(shiftInfoBeanMap.size()>0){ + Iterator> iterator = shiftInfoBeanMap.entrySet().iterator(); + while (iterator.hasNext()) { + Entry entry = iterator.next(); + String id = entry.getKey(); + Object value = entry.getValue(); + CacheItem cacheItem = createCacheItem(); + cacheItem.set(PK_INDEX, id); + cacheItem.set(shiftbean, value); + cacheItem.set(isoffdutyfreecheck, isoffdutyfreechecksMap.get(id)); + cacheItem.set(shiftonoffworkcount, shiftonoffworkcountsMap.get(id)); + cacheItem.set(serial, serialsMap.get(id)); + cacheItem.set(isresttimeopen, isresttimeopensMap.get(id)); + cacheItem.set(worktime, worktimesMap.get(id)); + cacheItem.set(punchsetting, punchsettingsMap.get(id)); + cacheItem.set(cardRemind,cardRemindMap.get(id)); + cacheItem.set(cardRemOfSignIn,cardRemOfSignInMap.get(id)); + cacheItem.set(minsBeforeSignIn,minsBeforeSignInMap.get(id)); + cacheItem.set(cardRemOfSignOut,cardRemOfSignOutMap.get(id)); + cacheItem.set(minsAfterSignOut,minsAfterSignOutMap.get(id)); + cacheItem.set(remindMode,remindModeMap.get(id)); + cacheItem.set(remindOnPC,remindOnPCMap.get(id)); + cacheItem.set(signoutOnlyoff,signoutOnlyoffMap.get(id)); + cacheItem.set(isRest,isResetMap.get(id)); + cacheItem.set(overtimeRuleId,overtimeruleMap.get(id)); + modifyCacheItem(id, cacheItem); + localData.put(id, cacheItem); + } + } + } catch (Exception e) { + StringWriter errorsWriter = new StringWriter(); + e.printStackTrace(new PrintWriter(errorsWriter)); + kqLog.info(errorsWriter.toString()); + } + return localData; + } + + public String getId(){ + return (String)getRowValue(PK_INDEX); + } + + public String getColor() { return (String)getRowValue(color); } + + public String getColor(String key) + { + return (String)getValue(color,key); + } + + public String getIsoffdutyfreecheck() { return (String)getRowValue(isoffdutyfreecheck); } + + public String getIsoffdutyfreecheck(String key) + { + return (String)getValue(isoffdutyfreecheck,key); + } + + public String getShiftonoffworkcounts() { return (String)getRowValue(shiftonoffworkcount); } + + public String getShiftonoffworkcounts(String key) + { + return (String)getValue(shiftonoffworkcount,key); + } + + public String getSerial() { return (String)getRowValue(serial); } + + public String getSerial(String key) + { + return (String)getValue(serial,key); + } + + public String getIsresttimeopen() { return (String)getRowValue(isresttimeopen); } + + public String getIsresttimeopen(String key) + { + return (String)getValue(isresttimeopen,key); + } + + public String getWorktime() { return (String)getRowValue(worktime); } + + public String getWorktime(String key) + { + return (String)getValue(worktime,key); + } + + public String getPunchsetting() { + return (String) getRowValue(punchsetting); + } + + public String getPunchsetting(String key) { + return (String) getValue(punchsetting, key); + } + + public String getCardRemind() { + return (String) getRowValue(cardRemind); + } + + public String getCardRemind(String key) { + return (String) getValue(cardRemind,key); + } + + public String getCardRemOfSignIn() { + return (String) getRowValue(cardRemOfSignIn); + } + + public String getCardRemOfSignIn(String key) { + return (String) getValue(cardRemOfSignIn, key); + } + + public String getMinsBeforeSignIn() { + return (String) getRowValue(minsBeforeSignIn); + } + + public String getMinsBeforeSignIn(String key) { + return (String) getValue(minsBeforeSignIn, key); + } + + public String getCardRemOfSignOut() { + return (String) getRowValue(cardRemOfSignOut); + } + + public String getCardRemOfSignOut(String key) { + return (String) getValue(cardRemOfSignOut, key); + } + + public String getMinsAfterSignOut() { + return (String) getRowValue(minsAfterSignOut); + } + + public String getMinsAfterSignOut(String key) { + return (String) getValue(minsAfterSignOut, key); + } + + public String getRemindMode() { + return (String) getRowValue(remindMode); + } + + public String getRemindMode(String key) { + return (String) getValue(remindMode, key); + } + + public String getRemindOnPC() { + return (String) getRowValue(remindOnPC); + } + + public String getRemindOnPC(String key) { + return (String) getValue(remindOnPC, key); + } + + public String getSignoutOnlyoff() { + return (String) getRowValue(signoutOnlyoff); + } + + public String getSignoutOnlyoff(String key) { + return (String) getValue(signoutOnlyoff, key); + } + + public String getIsRest() { + return (String) getRowValue(isRest); + } + + public String getIsRest(String key) { + return (String) getValue(isRest, key); + } + + public String getOvertimeRuleId() { + return (String) getRowValue(overtimeRuleId); + } + + public String getOvertimeRuleId(String key) { + return (String) getValue(overtimeRuleId, key); + } + + private void getShiftInfoBean(String serialid, String isresttimeopen, String worktime, + String punchsettings, + ConcurrentHashMap serialMap, + String halfcalrule,String halfcalpoint,String halfcalpoint2cross, String tmp_signoutOnlyoff) throws Exception { + + Map workTimeMap = new HashMap<>(); + int workmins = 0; + List workTimes = Collections.synchronizedList(new ArrayList<>()); + List restTimes = Collections.synchronizedList(new ArrayList<>()); + KQShiftOnOffWorkSectionComInfo kqShiftOnOffWorkSectionComInfo = new KQShiftOnOffWorkSectionComInfo(); + KQShiftRestTimeSectionComInfo kqShiftRestTimeSectionComInfo = new KQShiftRestTimeSectionComInfo(); + + workTimes = kqShiftOnOffWorkSectionComInfo.getWorkSectionTimes(serialid); + if(workTimes != null && !workTimes.isEmpty()){ + if("1".equalsIgnoreCase(isresttimeopen)) { + //如果开启了才去判断 + restTimes = kqShiftRestTimeSectionComInfo.getRestSectionTimes(serialid); + } + if(NumberUtils.isNumber(worktime)){ + if(worktime.indexOf('.') == -1){ + workmins = Util.getIntValue(worktime,0); + }else { + worktime = worktime.substring(0,worktime.indexOf('.')); + workmins = Util.getIntValue(worktime,0); + } + + }else{ + workmins = 0; + kqLog.info("班次有问题,serialid:"+serialid+"工作时长为:"+worktime); + } + workTimeMap.put("workTime", workTimes); + workTimeMap.put("restTime", restTimes); + workTimeMap.put("serialid", serialid); + //工作时长分钟数 + workTimeMap.put("workmins", workmins+""); + workTimeMap.put("punchsettings", punchsettings); + workTimeMap.put("isresttimeopen", isresttimeopen); + workTimeMap.put("halfcalrule", halfcalrule); + workTimeMap.put("halfcalpoint", halfcalpoint); + workTimeMap.put("halfcalpoint2cross", halfcalpoint2cross); + workTimeMap.put("signoutOnlyoff", tmp_signoutOnlyoff.equals("1") ? "1" : "0"); + + ShiftInfoCominfoBean shiftInfoCominfoBean = setShiftInfoBean(workTimeMap); + serialMap.put(serialid, shiftInfoCominfoBean); + } + + } + + private ShiftInfoCominfoBean setShiftInfoBean(Map workTimeMap) throws Exception { + + ShiftComIndex workComIndex = new WorkShiftComIndex(""+weaver.systeminfo.SystemEnv.getHtmlLabelName(10005306,weaver.general.ThreadVarLanguage.getLang())+"",workTimeMap); + ShiftComIndex restComIndex = new RestShiftComIndex(""+weaver.systeminfo.SystemEnv.getHtmlLabelName(10005307,weaver.general.ThreadVarLanguage.getLang())+"",workTimeMap); + ShiftComIndex halfComIndex = new HalfShiftComIndex(""+weaver.systeminfo.SystemEnv.getHtmlLabelName(10005308,weaver.general.ThreadVarLanguage.getLang())+"",workTimeMap); + //创建执行链 + //前一天的都执行完了,去获取当天工作时段,再执行半天的规则 + workComIndex.setDuration(restComIndex); + //执行完了半天的规则,再最后判断休息的时段 + restComIndex.setDuration(halfComIndex); + + ShiftInfoCominfoBean shiftInfoCominfoBean = new ShiftInfoCominfoBean(); + + workComIndex.handleDuration(shiftInfoCominfoBean); + return shiftInfoCominfoBean; + } + + /** + * 考勤按钮 + * @param workdate + * @param serialidInfo + * @param containYesterday + * @return + */ + public Map getWorkButton(String workdate,Map serialidInfo, boolean containYesterday){ + Map shiftMap = new HashMap<>(); + + //考勤按钮还是走缓存 + KQShiftManagementRedis kqShiftManagementRedis = new KQShiftManagementRedis(); + DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + if(serialidInfo != null && !serialidInfo.isEmpty()){ + LocalDate preLocalDate = LocalDate.parse(workdate); + String preSplitDate = ""; + preLocalDate = preLocalDate.minusDays(1); + preSplitDate = preLocalDate.format(dateFormatter); + String serialid = Util.null2String(serialidInfo.get(workdate)); + String preSerialid = Util.null2String(serialidInfo.get(preSplitDate)); + if(containYesterday){ + if(Util.getIntValue(preSerialid) > 0){ + ShiftInfoCominfoBean pre_shiftInfoCominfoBean = kqShiftManagementRedis.getShiftInfoBean(preSerialid); + List timelineList = pre_shiftInfoCominfoBean.getTimelineList(); + if(timelineList!=null && !timelineList.isEmpty()){ + shiftMap.put("pre_timelineList", timelineList); + } + shiftMap.put("pre_isAcross", pre_shiftInfoCominfoBean.getIsAcross()); + shiftMap.put("pre_allWorkTime", pre_shiftInfoCominfoBean.getAllWorkTime()); + shiftMap.put("pre_allAcrossWorkTime", pre_shiftInfoCominfoBean.getAllAcrossWorkTime()); + shiftMap.put("pre_signTime", pre_shiftInfoCominfoBean.getSignWorkTime()); + shiftMap.put("pre_restTime", pre_shiftInfoCominfoBean.getRestAcrossLongTime()); + } + } + if(Util.getIntValue(serialid) > 0){ + ShiftInfoCominfoBean cur_shiftInfoCominfoBean = kqShiftManagementRedis.getShiftInfoBean(serialid); + Map shiftRuleMap = ShiftManagementToolKit.getShiftRuleInfo(serialid,false); + List timelineList = cur_shiftInfoCominfoBean.getTimelineList(); + if(timelineList!=null && !timelineList.isEmpty()){ + shiftMap.put("timelineList", timelineList); + } + shiftMap.put("isAcross", cur_shiftInfoCominfoBean.getIsAcross()); + shiftMap.put("allWorkTime", cur_shiftInfoCominfoBean.getAllWorkTime()); + shiftMap.put("allAcrossWorkTime", cur_shiftInfoCominfoBean.getAllAcrossWorkTime()); + shiftMap.put("signTime", cur_shiftInfoCominfoBean.getSignWorkTime()); + shiftMap.put("restTime", cur_shiftInfoCominfoBean.getRestAcrossLongTime()); + if(shiftRuleMap != null && !shiftRuleMap.isEmpty()){ + shiftMap.put("shiftRuleMap", shiftRuleMap); + } + } + } + + return shiftMap; + } + + /** + * 流程计算用的 + * @param workdate + * @param serialidInfo + * @param containYesterday + * @return + * shiftInfoBean 每一天内含有的班次都拆分出来,包含昨天班次在今天的时段0-24小时制的 + * shiftLongInfoBean 当天的班次数据,0-48小时制度的 + */ + public Map getWorkDuration(String workdate,Map serialidInfo,boolean containYesterday){ + + KQWorkTime kqWorkTime = new KQWorkTime(); + DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + Map dateWorkTimeMap = new HashMap<>(); + LocalDate preLocalDate = LocalDate.parse(workdate); + String preSplitDate = ""; + preLocalDate = preLocalDate.minusDays(1); + preSplitDate = preLocalDate.format(dateFormatter); + if(serialidInfo != null && !serialidInfo.isEmpty()){ + String preSerialid = Util.null2String(serialidInfo.get(preSplitDate)); + String serialid = Util.null2String(serialidInfo.get(workdate)); + Boolean isNonWork = kqWorkTime.isNonWork(serialidInfo); + ShiftInfoBean shiftInfoBean = new ShiftInfoBean(); + shiftInfoBean.setPreSplitDate(preSplitDate); + shiftInfoBean.setSplitDate(workdate); + shiftInfoBean.setD_Mins(0.0); + shiftInfoBean.setPreSerialid(preSerialid); + shiftInfoBean.setSerialid(serialid); + shiftInfoBean.setRestShift(isNonWork?1:0); + if(containYesterday){ + if(Util.getIntValue(serialid) > 0 || Util.getIntValue(preSerialid) > 0){ + fillShiftInfoBean(shiftInfoBean, preSerialid, serialid); + dateWorkTimeMap.put("shiftInfoBean", shiftInfoBean); + } + }else{ + if(Util.getIntValue(serialid) > 0){ + fillShiftInfoBean(shiftInfoBean, preSerialid, serialid); + dateWorkTimeMap.put("shiftInfoBean", shiftInfoBean); + } + } + } + + return dateWorkTimeMap; + } + + /** + * 根据班次id获取对应日期的上下班时间+休息时间 + * @param workdate + * @param serialidInfo + * @return + */ + public Map getWorkTimeMap(String workdate,Map serialidInfo){ + + DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + Map dateWorkTimeMap = new HashMap<>(); + LocalDate preLocalDate = LocalDate.parse(workdate); + String preSplitDate = ""; + preLocalDate = preLocalDate.minusDays(1); + preSplitDate = preLocalDate.format(dateFormatter); + if(serialidInfo != null && !serialidInfo.isEmpty()){ + String preSerialid = Util.null2String(serialidInfo.get(preSplitDate)); + String serialid = Util.null2String(serialidInfo.get(workdate)); + getShiftInfoBeanMap(dateWorkTimeMap,preSerialid, serialid); + } + + return dateWorkTimeMap; + } + + /** + * 根据考勤报表需要的 返回相应格式的数据 + * @param dateWorkTimeMap + * @param preSerialid + * @param serialid + */ + private void getShiftInfoBeanMap(Map dateWorkTimeMap,String preSerialid, String serialid) { + ShiftInfoCominfoBean cur_shiftInfoCominfoBean = getShiftInfoCominfoBean(serialid); + + if(cur_shiftInfoCominfoBean != null){ + dateWorkTimeMap.put("restTime",cur_shiftInfoCominfoBean.getRestAcrossLongTime()); + dateWorkTimeMap.put("workTime",cur_shiftInfoCominfoBean.getWorkAcrossLongTime()); + dateWorkTimeMap.put("workMins",cur_shiftInfoCominfoBean.getWorkmins()); + dateWorkTimeMap.put("isAcross",cur_shiftInfoCominfoBean.getIsAcross()); + dateWorkTimeMap.put("signTime", cur_shiftInfoCominfoBean.getSignWorkTime()); + dateWorkTimeMap.put("halfWorkTime", cur_shiftInfoCominfoBean.getHalfWorkTime()); + dateWorkTimeMap.put("halfWorkIndex", cur_shiftInfoCominfoBean.getHalfWorkIndex()); + dateWorkTimeMap.put("convertAttendDay", cur_shiftInfoCominfoBean.getConvertAttendDay()); + } + } + + /** + * 每次获取的话都需要获取昨天和今天的班次数据 + * @param shiftInfoBean + * @param preSerialid 昨天的班次 + * @param serialid 今天的班次 + */ + private void fillShiftInfoBean(ShiftInfoBean shiftInfoBean,String preSerialid,String serialid){ + ShiftInfoCominfoBean pre_shiftInfoCominfoBean = getShiftInfoCominfoBean(preSerialid); + ShiftInfoCominfoBean cur_shiftInfoCominfoBean = getShiftInfoCominfoBean(serialid); + Map pre_shiftRuleMap = ShiftManagementToolKit.getShiftRuleInfo(preSerialid,false); + Map shiftRuleMap = ShiftManagementToolKit.getShiftRuleInfo(serialid,false); + + //把前一个班次的填充好 + if(pre_shiftInfoCominfoBean != null){ + shiftInfoBean.setPreWorkIndex(pre_shiftInfoCominfoBean.getPreWorkTimeIndex()); + shiftInfoBean.setPreWorkAcrossIndex(pre_shiftInfoCominfoBean.getWorkAcrossTimeIndex()); + shiftInfoBean.setPreWorkMinsAcrossIndex(pre_shiftInfoCominfoBean.getWorkPunchMins()); + shiftInfoBean.setPreRestIndex(pre_shiftInfoCominfoBean.getPreRestTimeIndex()); + shiftInfoBean.setPreHalfWorkIndex(pre_shiftInfoCominfoBean.getHalfWorkIndex()); + shiftInfoBean.setPreWorkmins(pre_shiftInfoCominfoBean.getWorkmins()); + shiftInfoBean.setPreAllWorkTime(pre_shiftInfoCominfoBean.getAllWorkTime()); + shiftInfoBean.setPreAllAcrossWorkTime(pre_shiftInfoCominfoBean.getAllAcrossWorkTime()); + shiftInfoBean.setPreAllRestTime(pre_shiftInfoCominfoBean.getAllRestTime()); + shiftInfoBean.setPreAllAcrossRestTime(pre_shiftInfoCominfoBean.getAllAcrossRestTime()); + shiftInfoBean.setPreSerialid(preSerialid); + shiftInfoBean.setIsPreAcross(pre_shiftInfoCominfoBean.getIsAcross()); + shiftInfoBean.setShiftRuleMap(pre_shiftRuleMap); + shiftInfoBean.setPreConvertAttendDay(pre_shiftInfoCominfoBean.getConvertAttendDay()); + } + + //把当前班次的填充好 + if(cur_shiftInfoCominfoBean != null){ + shiftInfoBean.setWorkIndex(cur_shiftInfoCominfoBean.getWorkTimeIndex()); + shiftInfoBean.setWorkAcrossIndex(cur_shiftInfoCominfoBean.getWorkAcrossTimeIndex()); + shiftInfoBean.setWorkMinsAcrossIndex(cur_shiftInfoCominfoBean.getWorkPunchMins()); + shiftInfoBean.setRestIndex(cur_shiftInfoCominfoBean.getRestTimeIndex()); + shiftInfoBean.setHalfWorkIndex(cur_shiftInfoCominfoBean.getHalfWorkIndex()); + shiftInfoBean.setWorkmins(cur_shiftInfoCominfoBean.getWorkmins()); + shiftInfoBean.setAllWorkTime(cur_shiftInfoCominfoBean.getAllWorkTime()); + shiftInfoBean.setAllAcrossWorkTime(cur_shiftInfoCominfoBean.getAllAcrossWorkTime()); + shiftInfoBean.setAllRestTime(cur_shiftInfoCominfoBean.getAllRestTime()); + shiftInfoBean.setAllAcrossRestTime(cur_shiftInfoCominfoBean.getAllAcrossRestTime()); + shiftInfoBean.setAllLongWorkTime(cur_shiftInfoCominfoBean.getAllLongWorkTime()); + shiftInfoBean.setRestLongTimeIndex(cur_shiftInfoCominfoBean.getRestLongTimeIndex()); + shiftInfoBean.setWorkLongTimeIndex(cur_shiftInfoCominfoBean.getWorkLongTimeIndex()); + shiftInfoBean.setIsAcross(cur_shiftInfoCominfoBean.getIsAcross()); + shiftInfoBean.setSerialid(serialid); + shiftInfoBean.setShiftRuleMap(shiftRuleMap); + + if(cur_shiftInfoCominfoBean.getWorkAcrossLongTime() != null){ + List workTime1 = cur_shiftInfoCominfoBean.getWorkAcrossLongTime().stream().collect(Collectors.toList()); + List lsWorkTime = new KQWorkTime().formatTimeScope(workTime1, false); + shiftInfoBean.setWorkTime(lsWorkTime); + } + if(cur_shiftInfoCominfoBean.getSignWorkTime() != null){ + List signTime1 = cur_shiftInfoCominfoBean.getSignWorkTime().stream().collect(Collectors.toList()); + List lsSignTime = new KQWorkTime().formatTimeScope(signTime1, true); + shiftInfoBean.setSignTime(lsSignTime); + } + shiftInfoBean.setHalfcalrule(cur_shiftInfoCominfoBean.getHalfcalrule()); + shiftInfoBean.setHalfcalpoint(cur_shiftInfoCominfoBean.getHalfcalpoint()); + shiftInfoBean.setHalfcalpoint2cross(cur_shiftInfoCominfoBean.getHalfcalpoint2cross()); + shiftInfoBean.setWorkAcrossTime(cur_shiftInfoCominfoBean.getWorkAcrossTime()); + shiftInfoBean.setEachWorkMins(cur_shiftInfoCominfoBean.getEachWorkMins()); + shiftInfoBean.setConvertAttendDay(cur_shiftInfoCominfoBean.getConvertAttendDay()); + } + } + + public void removeShiftManagementCache(){ + KQShiftRestTimeSectionComInfo kqShiftRestTimeSectionComInfo = new KQShiftRestTimeSectionComInfo(); + KQShiftOnOffWorkSectionComInfo kqShiftOnOffWorkSectionComInfo = new KQShiftOnOffWorkSectionComInfo(); + kqShiftRestTimeSectionComInfo.removeShiftRestTimeSectionCache(); + kqShiftOnOffWorkSectionComInfo.removeShiftWorkSectionCache(); + super.removeCache(); + //改用redis和staticobj的方式 + KQShiftManagementRedis kqShiftManagementRedis = new KQShiftManagementRedis(); + kqShiftManagementRedis.resetShiftValWithRedis(); + } + + /** + * 根据班次获取shiftInfoCominfoBean + * @param serialid + * @return + */ + public ShiftInfoCominfoBean getShiftInfoCominfoBean(String serialid){ +// Object object = getObjValue(shiftbean, serialid); +// if(object != null){ +// return (ShiftInfoCominfoBean) object; +// }else{ +// return null; +// } + //改用redis和staticobj的方式 + KQShiftManagementRedis kqShiftManagementRedis = new KQShiftManagementRedis(); + return kqShiftManagementRedis.getShiftInfoBeanMapBySql(serialid); + } + + /** + * 根据人员和日期获取shiftInfoCominfoBean + * @param workdate + * @param serialidInfo + * @return + */ + public ShiftInfoCominfoBean getShiftInfoCominfoBean(String workdate,Map serialidInfo){ + ShiftInfoCominfoBean shiftInfoCominfoBean = null; + if(serialidInfo != null && !serialidInfo.isEmpty()){ + String serialid = Util.null2String(serialidInfo.get(workdate)); + if(Util.getIntValue(serialid) > 0){ + shiftInfoCominfoBean = getShiftInfoCominfoBean(serialid); + } + } + return shiftInfoCominfoBean; + } + + public boolean isFormat() { + return isFormat; + } + + public void setFormat(boolean format) { + isFormat = format; + } +} diff --git a/领悦二开new/src/com/engine/kq/biz/KQShiftScheduleComInfo.java b/领悦二开new/src/com/engine/kq/biz/KQShiftScheduleComInfo.java new file mode 100644 index 0000000..6842658 --- /dev/null +++ b/领悦二开new/src/com/engine/kq/biz/KQShiftScheduleComInfo.java @@ -0,0 +1,179 @@ +package com.engine.kq.biz; + +import com.alibaba.fastjson.JSON; +import weaver.cache.*; +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.Util; + +public class KQShiftScheduleComInfo extends CacheBase{ + + protected static String TABLE_NAME = "kq_shiftschedule"; + /** sql中的where信息,不要以where开始 */ + protected static String TABLE_WHERE = "where (isdelete is null or isdelete <> '1'or (isdelete='1' and (wfidstatus='1' or wfidstatus='2'))) ";//默认加载今天之前一个月数据 + /** sql中的order by信息,不要以order by开始 */ + protected static String TABLE_ORDER = "id"; + + @PKColumn(type = CacheColumnType.NUMBER) + protected static String PK_NAME = "id"; + + @CacheColumn(name = "serialid") + protected static int serialid; + + @CacheColumn(name = "groupid") + protected static int groupid; + + + private boolean isFormat = false; + private int shiftGroupId = -1; + + @Override + public CacheMap initCache() throws Exception { + CacheMap localData = super.createCacheMap(); + RecordSet rs = new RecordSet(); + String sql = ""; + if ("mysql".equals(rs.getDBType())) { + sql += " select CONCAT(resourceid,'|',kqdate) as id, serialid,groupid from kq_shiftschedule "+TABLE_WHERE + " and kqdate>='"+DateUtil.getFirstDayOfMonth(DateUtil.getCurrentDate())+"' and kqdate<='"+ DateUtil.getCurrentDate()+"'"; + }else if("sqlserver".equals(rs.getDBType())){ + sql += " select CONVERT(varchar,resourceid)+'|'+kqdate as id, serialid,groupid from kq_shiftschedule "+TABLE_WHERE + " and kqdate>='"+DateUtil.getFirstDayOfMonth(DateUtil.getCurrentDate())+"' and kqdate<='"+ DateUtil.getCurrentDate()+"'"; + } else { + sql = "select resourceid||'|'||kqdate as id, serialid,groupid from kq_shiftschedule "+TABLE_WHERE + " and kqdate>='"+DateUtil.getFirstDayOfMonth(DateUtil.getCurrentDate())+"' and kqdate<='"+ DateUtil.getCurrentDate()+"'"; + } + + //这里还是要保留删除但是没有生效的数据 + sql += " and (isdelete is null or isdelete <> '1' or (isdelete='1' and (wfidstatus='1' or wfidstatus='2')))"; + //zj + sql += " and (wfidstatus is null or wfidstatus = '3'or (isdelete='1' and (wfidstatus='1' or wfidstatus='2')))"; + rs.executeQuery(sql); + while (rs.next()) { + String id = Util.null2String(rs.getString(PK_NAME)); + CacheItem row = createCacheItem(); + parseResultSetToCacheItem(rs, row); + + // 这里需要记得调用这个 转化方法, 否则 这些自己加载的数据就不能正确转化,当然你也可以直接在转化逻辑写在这里,不过这样先让代码重复了 + modifyCacheItem(id, row); + localData.put(id, row); + } + return localData; + } + +// /** +// * 性能原因取消后续加载 +// * @return +// */ +// protected boolean autoInitIfNotFound() { +// return false; +// } + + @Override + public CacheItem initCache(String key) { + if (key == null || "".equals(key.trim())) { + return null; + } + + String[] keys = Util.splitString(key,"|"); + String resourceid = keys[0]; + String kqdate = keys[1]; + RecordSet rs = new RecordSet(); + String sql = ""; + if ("mysql".equals(rs.getDBType())) { + sql += " select CONCAT(resourceid,'|',kqdate) as id, serialid,groupid from kq_shiftschedule "+TABLE_WHERE+ " and resourceid ='"+resourceid+"' and kqdate='"+kqdate+"'"; + }else if("sqlserver".equals(rs.getDBType())){ + sql += " select CONVERT(varchar,resourceid)+'|'+kqdate as id, serialid,groupid from kq_shiftschedule "+TABLE_WHERE+ " and resourceid ='"+resourceid+"' and kqdate='"+kqdate+"'"; + } else { + sql = "select resourceid||'|'||kqdate as id, serialid,groupid from kq_shiftschedule "+TABLE_WHERE+ " and resourceid ='"+resourceid+"' and kqdate='"+kqdate+"'"; + } + + sql += " and (isdelete is null or isdelete <> '1'or (isdelete='1' and (wfidstatus='1' or wfidstatus='2')))"; + //zj + sql += " and (wfidstatus is null or wfidstatus = '3'or (isdelete='1' and (wfidstatus='1' or wfidstatus='2')))"; + + rs.executeQuery(sql); + if (rs.next()) { + CacheItem cacheItem = createCacheItem(); + parseResultSetToCacheItem(rs, cacheItem); + modifyCacheItem(key, cacheItem); + return cacheItem; + } + return null; + } + + private String getId() { + return (String) getRowValue(PK_INDEX); + } + + private String getSerialId() { + return (String) getRowValue(serialid); + } + + private String getSerialId(String key) { + if(!this.isFormat){ + return (String) getValue(serialid, key); + } + return getSerialidBySql(key); + } + + private String getSerialidBySql(String key) { + + String sql_serialid = ""; + if (key == null || "".equals(key.trim())) { + return null; + } + String[] keys = Util.splitString(key,"|"); + String resourceid = keys[0]; + String kqdate = keys[1]; + RecordSet rs = new RecordSet(); + String sql = ""; + if ("mysql".equals(rs.getDBType())) { + sql += " select CONCAT(resourceid,'|',kqdate) as id, serialid,groupid from kq_shiftschedule where (isdelete is null or isdelete <> '1' or (isdelete='1' and (wfidstatus='1' or wfidstatus='2'))) and resourceid ='"+resourceid+"' and kqdate='"+kqdate+"'"; + }else if("sqlserver".equals(rs.getDBType())){ + sql += " select CONVERT(varchar,resourceid)+'|'+kqdate as id, serialid,groupid from kq_shiftschedule where (isdelete is null or isdelete <> '1' or (isdelete='1' and (wfidstatus='1' or wfidstatus='2'))) and resourceid ='"+resourceid+"' and kqdate='"+kqdate+"'"; + } else { + sql = "select resourceid||'|'||kqdate as id, serialid,groupid from kq_shiftschedule where (isdelete is null or isdelete <> '1' or (isdelete='1' and (wfidstatus='1' or wfidstatus='2'))) and resourceid ='"+resourceid+"' and kqdate='"+kqdate+"'"; + } + + if(shiftGroupId > 0) { + sql += " and groupid = "+shiftGroupId; + } + sql += " and (isdelete is null or isdelete <> '1' or (isdelete='1' and (wfidstatus='1' or wfidstatus='2')))"; + //zj + sql += " and (wfidstatus is null or wfidstatus = '3' or (isdelete='1' and (wfidstatus='1' or wfidstatus='2')))"; + + rs.executeQuery(sql); + if (rs.next()) { + sql_serialid = rs.getString("serialid"); + } + return sql_serialid; + } + + private String getGroupId(String key) { + return (String) getValue(groupid, key); + } + + public String getSerialId(String resourceid, String kqdate) { + if(Util.null2String(resourceid).length()==0||Util.null2String(kqdate).length()==0)return ""; + return this.getSerialId(resourceid+"|"+kqdate); + } + + public String getGroupId(String resourceid, String kqdate) { + if(Util.null2String(resourceid).length()==0||Util.null2String(kqdate).length()==0)return ""; + return this.getGroupId(resourceid+"|"+kqdate); + } + + public boolean isFormat() { + return isFormat; + } + + public void setFormat(boolean format) { + isFormat = format; + } + + public int getShiftGroupId() { + return shiftGroupId; + } + + public void setShiftGroupId(int shiftGroupId) { + this.shiftGroupId = shiftGroupId; + } +} \ No newline at end of file diff --git a/领悦二开new/src/com/engine/kq/biz/KQWorkTime.java b/领悦二开new/src/com/engine/kq/biz/KQWorkTime.java new file mode 100644 index 0000000..790d29e --- /dev/null +++ b/领悦二开new/src/com/engine/kq/biz/KQWorkTime.java @@ -0,0 +1,471 @@ +package com.engine.kq.biz; + +import com.alibaba.fastjson.JSON; +import com.engine.kq.biz.chain.cominfo.ShiftInfoCominfoBean; +import com.engine.kq.cmd.shiftmanagement.toolkit.ShiftManagementToolKit; +import com.engine.kq.entity.KQGroupEntity; +import com.engine.kq.entity.TimeScopeEntity; +import com.engine.kq.entity.TimeSignScopeEntity; +import com.engine.kq.entity.WorkTimeEntity; +import com.engine.kq.log.KQLog; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import weaver.common.DateUtil; +import weaver.common.StringUtil; +import weaver.general.BaseBean; +import weaver.general.Util; +import weaver.hrm.resource.ResourceComInfo; + +public class KQWorkTime extends BaseBean { + private KQLog kqLog = new KQLog(); + private boolean isFormat = false; + + public WorkTimeEntity getWorkTime(String userId) { + return getWorkTime(userId, null); + } + + /** + * 判断是否是工作日 + * @param userId + * @param workdate + * @return + */ + public boolean isWorkDay(String userId, String workdate) { + boolean isWorkDay = false; + if(!KQHolidaySetBiz.isHoliday(userId,workdate)) {//不是节假日,且有班次 + Map serialInfo = getSerialInfo( userId, workdate, false); + if(!serialInfo.isEmpty()){ + if(Util.null2String(serialInfo.get("kqType")).equals("3")){ + Map result = (Map) serialInfo.get(workdate); + if(result!=null && result.size()>0 && Util.null2String(result.get("signStart")).length()>0 && Util.null2String(result.get("workMins")).length()>0){ + isWorkDay = true; + } + }else{ + boolean isRest = isNonWork(serialInfo); + if(isRest){ + return isWorkDay; + } + isWorkDay = Util.getIntValue(Util.null2String(serialInfo.get(workdate)))>0; + } + } + } + return isWorkDay; + } + + public boolean isNonWork(Map serialInfo){ + boolean isR = false; + if(serialInfo.containsKey("isRest")){ + Boolean isRest = (Boolean) serialInfo.get("isRest"); + if(isRest){ + isR = true; + } + } + if(serialInfo.containsKey("isHoliday")){ + Boolean isHoliday = (Boolean) serialInfo.get("isHoliday"); + if(isHoliday){ + isR = true; + } + } + return isR; + } + + public Map getWorkButton(String userId, String workdate, boolean containYesterday) { + Map result = new HashMap<>(); + try { + KQShiftManagementComInfo kQShiftManagementComInfo = new KQShiftManagementComInfo(); + Map serialInfo = getSerialInfo(userId, workdate, containYesterday); + kqLog.info("考勤组获取成员所在的班次 getWorkButton:serialInfo:"+ serialInfo); + String kqType = Util.null2String(serialInfo.get("kqType")); + if(serialInfo!=null&&serialInfo.size()>0){ + if("3".equalsIgnoreCase(kqType)){ + //自由班制的单独处理 + result = (Map) serialInfo.get(workdate); + if(result != null && !result.isEmpty()){ + result.put("isfree", "1"); + }else{ + result = new HashMap<>(); + } + }else{ + result = kQShiftManagementComInfo.getWorkButton(workdate,serialInfo,containYesterday); + kqLog.info("考勤组获取成员所在的班次 getWorkButton:result:"+ JSON.toJSONString(result)); + } + } + } catch (Exception e) { + writeLog(e); + } + return result; + } + + /** + * + * 获取今天所含班次的考勤时间(包含今天和昨天的) + * @param userId + * @param workdate + * @param containYesterday + * @param isLog 是否记录日志 + * @return + */ + public Map getWorkDuration(String userId, String workdate,boolean containYesterday,boolean isLog) { + Map result = new HashMap<>(); + try { + Map workTimeMap = null; + KQShiftManagementComInfo kQShiftManagementComInfo = new KQShiftManagementComInfo(); + Map serialInfo = getSerialInfo(userId, workdate, true); + if(isLog){ + //kqLog.info("考勤组获取成员所在的班次 getWorkDuration:"+serialInfo); + } + if(serialInfo!=null&&serialInfo.size()>0){ + String kqType = Util.null2String(serialInfo.get("kqType")); + if("3".equalsIgnoreCase(kqType)){ + //自由班制的单独处理 + result = (Map) serialInfo.get(workdate); + if(result != null && !result.isEmpty()){ + result.put("isfree", "1"); + }else{ + result = new HashMap<>(); + } + }else{ + workTimeMap = kQShiftManagementComInfo.getWorkDuration(workdate,serialInfo,containYesterday); + if(workTimeMap!=null){ + if(isLog) { + //kqLog.info( + // "考勤组获取成员所在的班次 getWorkDuration:workTimeMap:" + JSON.toJSONString(workTimeMap)); + } + result.put("shiftInfoBean",workTimeMap.get("shiftInfoBean")); + } + } + } + } catch (Exception e) { + writeLog(e); + } + return result; + } + + /** + * 获取今天所含班次的考勤时间(包含今天和昨天的) + * @param userId + * @param workdate + * @param containYesterday + * @return + */ + public Map getWorkDuration(String userId, String workdate,boolean containYesterday) { + return getWorkDuration(userId,workdate,containYesterday,true); + } + + /** + * 获取今天所含班次的考勤时间(今天的) + * @param userId + * @param workdate + * @return + */ + public ShiftInfoCominfoBean getShiftInfoCominfoBean(String userId, String workdate) { + ShiftInfoCominfoBean shiftInfoCominfoBean = null; + try { + Map workTimeMap = null; + KQShiftManagementComInfo kQShiftManagementComInfo = new KQShiftManagementComInfo(); + Map serialInfo = getSerialInfo(userId, workdate, false); + + if(serialInfo!=null&&serialInfo.size()>0){ + shiftInfoCominfoBean = kQShiftManagementComInfo.getShiftInfoCominfoBean(workdate,serialInfo); + } + } catch (Exception e) { + writeLog(e); + } + return shiftInfoCominfoBean; + } + + /** + * 获取考勤时间 + * @param userId + * @param workdate + * @return + */ + public WorkTimeEntity getWorkTime(String userId, String workdate) { + WorkTimeEntity workTimeEntity = new WorkTimeEntity(); + try { + KQShiftManagementComInfo kQShiftManagementComInfo = new KQShiftManagementComInfo(); + Map serialInfo = getSerialInfo(userId, workdate, false); + workTimeEntity.setIsExclude(Util.null2String(serialInfo.get("isExclude")).equals("1")); + workTimeEntity.setGroupId(Util.null2String(serialInfo.get("groupId"))); + if(serialInfo!=null&&serialInfo.size()>0) { + String kqType = Util.null2String(serialInfo.get("kqType")); + Boolean isNonWork = isNonWork(serialInfo); + String dayType = "work"; + if(serialInfo.containsKey("isRest")){ + Boolean isRest1 = (Boolean) serialInfo.get("isRest"); + if(isRest1){ + dayType = "playday"; + } + } + if(serialInfo.containsKey("isHoliday")){ + Boolean isHoliday1 = (Boolean) serialInfo.get("isHoliday"); + if(isHoliday1){ + dayType = "holiday"; + } + } + if(kqType.equals("3")){ + Map map = (Map)serialInfo.get(workdate); + workTimeEntity.setGroupId(Util.null2String(serialInfo.get("groupId"))); + workTimeEntity.setGroupName(Util.null2String(serialInfo.get("groupName"))); + workTimeEntity.setKQType(Util.null2String(kqType)); + workTimeEntity.setIsExclude(Util.null2String(serialInfo.get("isExclude")).equals("1")); + if(map!=null) { + workTimeEntity.setSignStart(Util.null2String(map.get("signStart"))); + workTimeEntity.setWorkMins(Util.getIntValue(Util.null2String(map.get("workMins")))); + workTimeEntity.setCalmethod(Util.null2String(map.get("calmethod"))); + }else{ + dayType = "playday"; + } + workTimeEntity.setNonWorkShift(0); + }else{ + int serialid = Util.getIntValue(Util.null2String(serialInfo.get(workdate)), 0); + + int signouOnlyoff = StringUtil.parseToInt(kQShiftManagementComInfo.getSignoutOnlyoff(String.valueOf(serialid)), 0); + workTimeEntity.setSignoutOnlyoff(signouOnlyoff); + + if (serialid > 0){ + workTimeEntity.setNonWorkShift(isNonWork?1:0); + + Map dateWorkTimeMap = kQShiftManagementComInfo.getWorkTimeMap(workdate, serialInfo); + workTimeEntity.setGroupId(Util.null2String(serialInfo.get("groupId"))); + workTimeEntity.setGroupName(Util.null2String(serialInfo.get("groupName"))); + workTimeEntity.setKQType(kqType); + workTimeEntity.setSerialId(""+serialid); + workTimeEntity.setShiftRuleInfo(ShiftManagementToolKit.getShiftRuleInfo(""+serialid,true)); + workTimeEntity.setSignTime(formatTimeScope((List)dateWorkTimeMap.get("signTime"),false)); + workTimeEntity.setWorkTime(formatTimeScope((List)dateWorkTimeMap.get("workTime"),true)); + workTimeEntity.setRestTime(formatTimeScope((List)dateWorkTimeMap.get("restTime"),false)); + workTimeEntity.setWorkMins(Util.getIntValue(Util.null2String(dateWorkTimeMap.get("workMins")))); + workTimeEntity.setIsAcross(Util.null2String(dateWorkTimeMap.get("isAcross"))); + workTimeEntity.setConvertAttendDay(Util.null2s(Util.null2String(dateWorkTimeMap.get("convertAttendDay")), "1.0")); + workTimeEntity.setHalfWorkTime((List)dateWorkTimeMap.get("halfWorkTime")); + workTimeEntity.setHalfWorkIndex((List)dateWorkTimeMap.get("halfWorkIndex")); + }else{ + dayType = "playday"; + } + } + workTimeEntity.setDayType(dayType); + } + } catch (Exception e) { + writeLog(e); + } + return workTimeEntity; + } + + public List formatTimeScope(List timeScope, boolean needWorkMins){ + List timeScopes = new ArrayList<>(); + KQTimesArrayComInfo kqTimesArrayComInfo = new KQTimesArrayComInfo(); + TimeScopeEntity timeScopeEntity = null; + for(int i=0;timeScope!=null && i obj = (Map)timeScope.get(i); + String bengintime_end = Util.null2String(obj.get("bengintime_end")); + String bengintime_end_across = Util.null2String(obj.get("bengintime_end_across")); + String endtime_start = Util.null2String(obj.get("endtime_start")); + String endtime_start_across = Util.null2String(obj.get("endtime_start_across")); + String bengintime_pre_across = Util.null2String(obj.get("bengintime_pre_across")); + timeScopeEntity = new TimeScopeEntity(); + timeScopeEntity.setBeginTime(Util.null2String(obj.get("bengintime"))); + timeScopeEntity.setBeginTimeAcross(Util.null2String(obj.get("bengintime_across")).equals("1"));//标记是否跨天 + timeScopeEntity.setEndTime(Util.null2String(obj.get("endtime"))); + timeScopeEntity.setEndTimeAcross(Util.null2String(obj.get("endtime_across")).equals("1"));//标记是否跨天 + timeScopeEntity.setBeginTimePreAcross("1".equalsIgnoreCase(bengintime_pre_across)); + + if(needWorkMins) { + int workBeginIdx = kqTimesArrayComInfo.getArrayindexByTimes(timeScopeEntity.getBeginTime()); + int workEndIdx = kqTimesArrayComInfo.getArrayindexByTimes(timeScopeEntity.getEndTime()); + timeScopeEntity.setWorkMins(workEndIdx - workBeginIdx); + } + if((bengintime_end != null && bengintime_end.length() >0) || (endtime_start != null && endtime_start.length() > 0)){ + TimeSignScopeEntity timeSignScopeEntity = new TimeSignScopeEntity(); + timeSignScopeEntity.setBeginTimeEnd(bengintime_end); + timeSignScopeEntity.setBeginTimeEndAcross("1".equalsIgnoreCase(bengintime_end_across)); + timeSignScopeEntity.setEndTimeStart(endtime_start); + timeSignScopeEntity.setEndTimeStartAcross("1".equalsIgnoreCase(endtime_start_across)); + timeSignScopeEntity.setBeginTimePreAcross("1".equalsIgnoreCase(bengintime_pre_across)); + timeScopeEntity.setTimeSignScopeEntity(timeSignScopeEntity); + } + timeScopes.add(timeScopeEntity); + } + return timeScopes; + } + + /** + * 获取当天班次 + * @param userId + * @param workdate + * @return + */ + public String getSerialIds(String userId, String workdate) { + Map serialInfo = getSerialInfo( userId, workdate, false); + return serialInfo!=null?Util.null2String(serialInfo.get(workdate)):""; + } + + /** + * 获取班次信息 获取顺序 工作日调整、排班、固定班和周期班 + * @param userId + * @param workdate + * @param containYesterday + * @return + */ + public Map getSerialInfo(String userId, String workdate, boolean containYesterday) { + Map serialInfo = new HashMap<>(); + String preworkdate = ""; + try { + KQGroupMemberComInfo groupMemberComInfo = new KQGroupMemberComInfo(); + groupMemberComInfo.setIsFormat(this.isFormat); + KQFixedSchedulceComInfo kqFixedSchedulceComInfo = new KQFixedSchedulceComInfo(); + kqFixedSchedulceComInfo.setFormat(this.isFormat); + KQShiftScheduleComInfo kqShiftScheduleComInfo = new KQShiftScheduleComInfo(); + kqShiftScheduleComInfo.setFormat(this.isFormat); + KQShiftManagementComInfo kqShiftManagementComInfo = new KQShiftManagementComInfo(); + kqShiftManagementComInfo.setFormat(this.isFormat); + KQGroupEntity kqGroupEntity = groupMemberComInfo.getUserKQGroupInfo(userId,workdate); + ResourceComInfo resourceComInfo = new ResourceComInfo(); + + preworkdate = DateUtil.addDate(workdate,-1); + if(containYesterday){ + Map pre_serialInfo = getSerialInfo(userId, preworkdate, false); + if(pre_serialInfo != null && !pre_serialInfo.isEmpty()){ + if(pre_serialInfo.containsKey(preworkdate)){ + serialInfo.put(preworkdate,pre_serialInfo.get(preworkdate));//获取前一天的班次 + } + } + } + + if(kqGroupEntity==null){//不在考勤组内 + serialInfo.put("isRest",true); + return serialInfo; + } + + + //无需考勤人员需要计算考勤时间,但不计算异常状态 +// if (("," + kqGroupEntity.getExcludeid() + ",").indexOf("," + userId + ",")>-1) {//排除人员无需计算考勤时间 +// return serialInfo; +// } + + if (("," + kqGroupEntity.getExcludeid() + ",").indexOf("," + userId + ",")>-1) {//排除人员无需计算考勤时间 + serialInfo.put("isExclude","1"); + } + + String begindate = Util.null2String(resourceComInfo.getCreatedate(userId)).trim(); + String companyStartDate = Util.null2String(resourceComInfo.getCompanyStartDate(userId)).trim(); + if(companyStartDate.length()!=10){ + companyStartDate = ""; + } + if(companyStartDate.length()>0 && companyStartDate.indexOf("-")>0){ + begindate=companyStartDate; + } + if(begindate.length()>0 && DateUtil.compDate(begindate,workdate)<0 ){//人员入职日期前无需计算考勤,如果没有入职日期,已创建日期为准 +// kqLog.writeLog("getSerialInfo 入职日期不满足条件:userId:"+userId+":workdate:"+workdate+":companyStartDate:"+companyStartDate+":begindate:"+begindate+":DateUtil.compDate(begindate,workdate):"+DateUtil.compDate(begindate,workdate)); + serialInfo.put("isRest",true); + return serialInfo; + } + + String endDate = Util.null2String(resourceComInfo.getEndDate(userId)); + + String status = Util.null2String(resourceComInfo.getStatus(userId)); + if(status.equals("0")||status.equals("1")||status.equals("2")||status.equals("3")){ + //在职 + }else{ + //其他状态 + if(endDate.length()>0 && DateUtil.compDate(endDate,workdate)>0){//人员合同结束日期无需计算考勤 +// kqLog.writeLog("getSerialInfo 人员合同结束日期不满足条件:userId:"+userId+":workdate:"+workdate+":endDate:"+endDate+":status:"+status+":DateUtil.compDate(endDate,workdate):"+DateUtil.compDate(endDate,workdate)); + serialInfo.put("isRest",true); + return serialInfo; + } + } + + String groupid = kqGroupEntity.getId(); + String groupname = kqGroupEntity.getGroupname(); + String kqtype = kqGroupEntity.getKqtype(); + int dayOfweek = DateUtil.getWeek(workdate)-1; + int preDayOfweek = DateUtil.getWeek(preworkdate)-1; + boolean preDayIsHoliday = KQHolidaySetBiz.isHoliday(userId,preworkdate); + boolean isHoliday = KQHolidaySetBiz.isHoliday(userId,workdate); + serialInfo.put("isHoliday",isHoliday); + KQSettingsComInfo kqSettingsComInfo = new KQSettingsComInfo(); + boolean needSkipHoliday = isHoliday; + //节假日或者调配休息日,是否需要返回当天的班次 + String holidayRestShift = Util.null2String(kqSettingsComInfo.getMain_val("holiday_rest_shift"),"0"); + if("1".equals(holidayRestShift)){ + //如果需要返回班次,那么isHoliday的判断就不需要了 + needSkipHoliday = false; + } + String serialid = ""; + + if(!kqtype.equals("2")){//处理调配工作日(除排班外) + if(KQHolidaySetBiz.getChangeType(groupid,preworkdate)==2){ + preDayOfweek = KQHolidaySetBiz.getRelatedDay(userId,preworkdate); + } + + if(KQHolidaySetBiz.getChangeType(groupid,workdate)==2){ + dayOfweek = KQHolidaySetBiz.getRelatedDay(userId,workdate); + } + } + serialInfo.put("groupId",groupid); + serialInfo.put("groupName",groupname); + serialInfo.put("kqType",kqtype); + if (kqtype.equals("1")) {//固定班 +// if(containYesterday && !serialInfo.containsKey(preworkdate)) { +// serialid = Util.null2String(kqFixedSchedulceComInfo.getSerialid(groupid,preDayOfweek)); +// if(!preDayIsHoliday&&serialid.length()>0 && Util.getIntValue(serialid) > 0){ +// serialInfo.put(preworkdate,serialid);//获取前一天的班次 +// } +// } + if(!serialInfo.containsKey(workdate)){ + serialid = Util.null2String(kqFixedSchedulceComInfo.getSerialid(groupid,dayOfweek)); + if( !needSkipHoliday&&serialid.length()>0 && Util.getIntValue(serialid) > 0){ + serialInfo.put(workdate, serialid);//获取当天的班次 + } + } + } else if (kqtype.equals("2")) {//排班 + //先取排班设置里的班次 +// serialid = Util.null2String(kqShiftScheduleComInfo.getSerialId(userId,preworkdate)); +// if(containYesterday && serialid.length()>0 && !preDayIsHoliday && Util.getIntValue(serialid) > 0){ +// serialInfo.put(preworkdate,Util.null2String(kqShiftScheduleComInfo.getSerialId(userId,preworkdate)));//获取前一天的班次 +// } + kqShiftScheduleComInfo.setShiftGroupId(Util.getIntValue(groupid)); + serialid = Util.null2String(kqShiftScheduleComInfo.getSerialId(userId,workdate)); + if(serialid.length()>0 && !needSkipHoliday && Util.getIntValue(serialid) > 0){ + serialInfo.put(workdate,Util.null2String(kqShiftScheduleComInfo.getSerialId(userId,workdate)));//获取当天的班次 + } + } else if (kqtype.equals("3")) {//自由班 + List weekDay = Util.splitString2List(kqGroupEntity.getWeekday(), ","); + String signStart = Util.null2String(kqGroupEntity.getSignstart());//签到开始时间 + int workMins = Util.getIntValue(Util.getIntValues(""+Util.getDoubleValue(Util.null2String(kqGroupEntity.getWorkhour()))*60));//工作时长 + if(signStart.length()>0 && workMins>0) { + String calmethod = Util.null2s(kqGroupEntity.getCalmethod(),"1"); + Map map = null; + if (weekDay.contains(""+preDayOfweek) && !preDayIsHoliday) {//前一天 + map = new HashMap<>(); + map.put("signStart", signStart); + map.put("workMins", workMins); + map.put("calmethod", calmethod); + serialInfo.put(preworkdate, map); + } + if (weekDay.contains(""+dayOfweek) && !isHoliday) {//当前天 + map = new HashMap<>(); + map.put("signStart", signStart); + map.put("workMins", workMins); + map.put("calmethod", calmethod); + serialInfo.put(workdate, map); + } + } + } + if(StringUtil.isNotNull(serialid)){ + String isRest = Util.null2s(kqShiftManagementComInfo.getIsRest(serialid),""); + serialInfo.put("isRest","1".equals(isRest)); + } + } catch (Exception e) { + writeLog(e); + } + return serialInfo; + } + + + public void setIsFormat(boolean isFormat){ + this.isFormat = isFormat; + } +} \ No newline at end of file diff --git a/领悦二开new/src/com/engine/kq/biz/chain/cominfo/ShiftInfoCominfoBean.java b/领悦二开new/src/com/engine/kq/biz/chain/cominfo/ShiftInfoCominfoBean.java new file mode 100644 index 0000000..12ee6bb --- /dev/null +++ b/领悦二开new/src/com/engine/kq/biz/chain/cominfo/ShiftInfoCominfoBean.java @@ -0,0 +1,521 @@ +package com.engine.kq.biz.chain.cominfo; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +/** + */ +public class ShiftInfoCominfoBean implements Serializable { + + + private static final long serialVersionUID = -1735765502081116461L; + + /** + * 当前班次如果是作为前一个班次存在,跨到次日的工作时段 + */ + private List preWorkTime; + + /** + * 当前班次作为当前班次存在,在0-24小时内的工作时段 + */ + private List workTime; + + /** + * 当前班次作为当前班次存在,如果存在跨天的话,包含跨天的工作时段,显示成0-24小时的 + */ + private List workAcrossTime; + + + /** + * 当前班次如果是作为前一个班次存在,跨到次日的工作时段 + */ + private List preWorkTimeIndex; + + /** + * 当前班次作为当前班次存在,在0-24小时内的工作时段 + */ + private List workTimeIndex; + + /** + * 当前班次作为当前班次存在,在0-48小时内的工作时段下标 + */ + private List workLongTimeIndex; + + /** + * 当前班次作为当前班次存在,在0-48小时内的工作时段下标 + */ + private List restLongTimeIndex; + + /** + * 存储所有的工作时间 48小时制休息时段 + */ + private List allLongWorkTime; + + /** + * 当前班次作为当前班次存在,如果存在跨天的话,包含跨天的工作时段,显示成0-24小时的 + */ + private List workAcrossTimeIndex; + + /** + * 考勤报表用的 48小时制工作时段 + */ + private List> workAcrossLongTime; + + /** + * 当天打卡时段时间:多少分钟可以开始签到签退的 + */ + private List workPunchMins; + + /** + * 当前班次如果是作为前一个班次存在,跨到次日的休息时段 + */ + private List preRestTime; + + /** + * 当前班次作为当前班次存在,在0-24小时内的休息时段 + */ + private List restTime; + + /** + * 当前班次作为当前班次存在,如果存在跨r天的话,包含跨天的休息时段,显示成0-24小时的 + */ + private List restAcrossTime; + /** + * 当前班次如果是作为前一个班次存在,跨到次日的休息时段 + */ + private List preRestTimeIndex; + + /** + * 当前班次作为当前班次存在,在0-24小时内的休息时段 + */ + private List restTimeIndex; + + /** + * 当前班次作为当前班次存在,如果存在跨r天的话,包含跨天的休息时段,显示成0-24小时的 + */ + private List restAcrossTimeIndex; + + /** + * 考勤报表用的 48小时制休息时段 + */ + private List> restAcrossLongTime; + + /** + * 要返回的半天规则时间区间对应的数组下标 + * 这里有值的话是三个,最早的开始时间 中间时间 最晚的下班时间 + */ + private List halfWorkTime; + + /** + * 要返回的半天规则时间区间对应的数组下标 + * 这里有值的话是三个,最早的开始时间 中间时间 最晚的下班时间 + */ + private List halfWorkIndex; + + /** + * 存储所有的工作时间 + */ + private List allWorkTime; + + /** + * 存储所有的跨天时间 + */ + private List allAcrossWorkTime; + /** + * 存储所有的休息时间 + */ + private List allRestTime; + + /** + * 存储所有的休息时间 + */ + private List allAcrossRestTime; + + /** + * 存储每一段工作时段内的工作时长 + */ + private List eachWorkMins; + + /** + * 工作时长 + */ + private int workmins; + + /** + * 当前日期的班次 + */ + private String serialid; + + /** + * 判断当前班次是否存在跨天 + */ + private String isAcross; + + /** + * 半天计算规则 + */ + private String halfcalrule; + + /** + * 自定义 半天计算规则 时间点 + */ + private String halfcalpoint; + + private String halfcalpoint2cross; + + private List timelineList; + + /** + * 允许签到签退的时段范围 + */ + private List> signWorkTime; + + /** + * 存储所有的工作时间是否跨天 和allWorkTime对应 + */ + private List allWorkTimeisAcross; + + private String uuid = ""; + + /** + * 应出勤折算天数 + */ + private String convertAttendDay = ""; + + public ShiftInfoCominfoBean() { + + this.preWorkTime = new ArrayList<>(); + this.workTime = new ArrayList<>(); + this.workAcrossTime = new ArrayList<>(); + this.preWorkTimeIndex = new ArrayList<>(); + this.workTimeIndex = new ArrayList<>(); + this.workAcrossTimeIndex = new ArrayList<>(); + this.workAcrossLongTime = new ArrayList<>(); + this.workPunchMins = new ArrayList<>(); + this.preRestTime = new ArrayList<>(); + this.restTime = new ArrayList<>(); + this.restAcrossTime = new ArrayList<>(); + this.preRestTimeIndex = new ArrayList<>(); + this.restTimeIndex = new ArrayList<>(); + this.restAcrossTimeIndex = new ArrayList<>(); + this.restAcrossLongTime = new ArrayList<>(); + this.halfWorkTime = new ArrayList<>(); + this.allWorkTime = new ArrayList<>(); + this.allAcrossWorkTime = new ArrayList<>(); + this.allRestTime = new ArrayList<>(); + this.allAcrossRestTime = new ArrayList<>(); + this.eachWorkMins = new ArrayList<>(); + this.workmins = 0; + this.serialid = ""; + this.isAcross = "0"; + this.halfcalrule = "0"; + this.halfWorkIndex = new ArrayList<>(); + + this.timelineList = new ArrayList<>(); + + this.workLongTimeIndex = new ArrayList<>(); + this.restLongTimeIndex = new ArrayList<>(); + this.allLongWorkTime = new ArrayList<>(); + this.signWorkTime = new ArrayList<>(); + this.allWorkTimeisAcross = new ArrayList<>(); + this.uuid = UUID.randomUUID().toString(); + this.halfcalpoint = "0"; + this.halfcalpoint2cross = "0"; + } + + public List getPreWorkTime() { + return preWorkTime; + } + + public void setPreWorkTime(List preWorkTime) { + this.preWorkTime = preWorkTime; + } + + public List getWorkTime() { + return workTime; + } + + public void setWorkTime(List workTime) { + this.workTime = workTime; + } + + public List getWorkAcrossTime() { + return workAcrossTime; + } + + public void setWorkAcrossTime(List workAcrossTime) { + this.workAcrossTime = workAcrossTime; + } + + public List> getWorkAcrossLongTime() { + return workAcrossLongTime; + } + + public void setWorkAcrossLongTime( + List> workAcrossLongTime) { + this.workAcrossLongTime = workAcrossLongTime; + } + + public List getWorkPunchMins() { + return workPunchMins; + } + + public void setWorkPunchMins(List workPunchMins) { + this.workPunchMins = workPunchMins; + } + + public List getHalfWorkTime() { + return halfWorkTime; + } + + public void setHalfWorkTime(List halfWorkTime) { + this.halfWorkTime = halfWorkTime; + } + + public int getWorkmins() { + return workmins; + } + + public void setWorkmins(int workmins) { + this.workmins = workmins; + } + + public String getSerialid() { + return serialid; + } + + public void setSerialid(String serialid) { + this.serialid = serialid; + } + + public List getAllWorkTime() { + return allWorkTime; + } + + public void setAllWorkTime(List allWorkTime) { + this.allWorkTime = allWorkTime; + } + + public List getAllAcrossWorkTime() { + return allAcrossWorkTime; + } + + public void setAllAcrossWorkTime(List allAcrossWorkTime) { + this.allAcrossWorkTime = allAcrossWorkTime; + } + + public List getRestTime() { + return restTime; + } + + public void setRestTime(List restTime) { + this.restTime = restTime; + } + + public String getIsAcross() { + return isAcross; + } + + public void setIsAcross(String isAcross) { + this.isAcross = isAcross; + } + + public List getPreRestTime() { + return preRestTime; + } + + public void setPreRestTime(List preRestTime) { + this.preRestTime = preRestTime; + } + + public List getRestAcrossTime() { + return restAcrossTime; + } + + public void setRestAcrossTime(List restAcrossTime) { + this.restAcrossTime = restAcrossTime; + } + + public List> getRestAcrossLongTime() { + return restAcrossLongTime; + } + + public void setRestAcrossLongTime( + List> restAcrossLongTime) { + this.restAcrossLongTime = restAcrossLongTime; + } + + public List getAllRestTime() { + return allRestTime; + } + + public void setAllRestTime(List allRestTime) { + this.allRestTime = allRestTime; + } + + public List getAllAcrossRestTime() { + return allAcrossRestTime; + } + + public void setAllAcrossRestTime(List allAcrossRestTime) { + this.allAcrossRestTime = allAcrossRestTime; + } + + public List getEachWorkMins() { + return eachWorkMins; + } + + public void setEachWorkMins(List eachWorkMins) { + this.eachWorkMins = eachWorkMins; + } + + public List getPreWorkTimeIndex() { + return preWorkTimeIndex; + } + + public void setPreWorkTimeIndex(List preWorkTimeIndex) { + this.preWorkTimeIndex = preWorkTimeIndex; + } + + public List getWorkTimeIndex() { + return workTimeIndex; + } + + public void setWorkTimeIndex(List workTimeIndex) { + this.workTimeIndex = workTimeIndex; + } + + public List getWorkAcrossTimeIndex() { + return workAcrossTimeIndex; + } + + public void setWorkAcrossTimeIndex(List workAcrossTimeIndex) { + this.workAcrossTimeIndex = workAcrossTimeIndex; + } + + public List getPreRestTimeIndex() { + return preRestTimeIndex; + } + + public void setPreRestTimeIndex(List preRestTimeIndex) { + this.preRestTimeIndex = preRestTimeIndex; + } + + public List getRestTimeIndex() { + return restTimeIndex; + } + + public void setRestTimeIndex(List restTimeIndex) { + this.restTimeIndex = restTimeIndex; + } + + public List getRestAcrossTimeIndex() { + return restAcrossTimeIndex; + } + + public void setRestAcrossTimeIndex(List restAcrossTimeIndex) { + this.restAcrossTimeIndex = restAcrossTimeIndex; + } + + public List getHalfWorkIndex() { + return halfWorkIndex; + } + + public void setHalfWorkIndex(List halfWorkIndex) { + this.halfWorkIndex = halfWorkIndex; + } + + public List getTimelineList() { + return timelineList; + } + + public void setTimelineList(List timelineList) { + this.timelineList = timelineList; + } + + public List getWorkLongTimeIndex() { + return workLongTimeIndex; + } + + public void setWorkLongTimeIndex(List workLongTimeIndex) { + this.workLongTimeIndex = workLongTimeIndex; + } + + public List getRestLongTimeIndex() { + return restLongTimeIndex; + } + + public void setRestLongTimeIndex(List restLongTimeIndex) { + this.restLongTimeIndex = restLongTimeIndex; + } + + public List getAllLongWorkTime() { + return allLongWorkTime; + } + + public void setAllLongWorkTime(List allLongWorkTime) { + this.allLongWorkTime = allLongWorkTime; + } + + public List> getSignWorkTime() { + return signWorkTime; + } + + public void setSignWorkTime( + List> signWorkTime) { + this.signWorkTime = signWorkTime; + } + + public List getAllWorkTimeisAcross() { + return allWorkTimeisAcross; + } + + public void setAllWorkTimeisAcross(List allWorkTimeisAcross) { + this.allWorkTimeisAcross = allWorkTimeisAcross; + } + + public String getHalfcalrule() { + return halfcalrule; + } + + public void setHalfcalrule(String halfcalrule) { + this.halfcalrule = halfcalrule; + } + + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public String getHalfcalpoint() { + return halfcalpoint; + } + + public void setHalfcalpoint(String halfcalpoint) { + this.halfcalpoint = halfcalpoint; + } + + public String getHalfcalpoint2cross() { + return halfcalpoint2cross; + } + + public void setHalfcalpoint2cross(String halfcalpoint2cross) { + this.halfcalpoint2cross = halfcalpoint2cross; + } + + public String getConvertAttendDay() { + return convertAttendDay; + } + + public void setConvertAttendDay(String convertAttendDay) { + this.convertAttendDay = convertAttendDay; + } +} + diff --git a/领悦二开new/src/com/engine/kq/biz/chain/shiftinfo/ShiftInfoBean.java b/领悦二开new/src/com/engine/kq/biz/chain/shiftinfo/ShiftInfoBean.java new file mode 100644 index 0000000..85311c0 --- /dev/null +++ b/领悦二开new/src/com/engine/kq/biz/chain/shiftinfo/ShiftInfoBean.java @@ -0,0 +1,804 @@ +package com.engine.kq.biz.chain.shiftinfo; + +import com.engine.kq.entity.TimeScopeEntity; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 1、首先有个KQTimesArrayComInfo缓存类,这个类把00:00-23:59的时间点都转换成了0-1439的数值 + * 我把这个数值视作下标index + * + * 2、假如班次设置的工作时段是 + * 8:00-12:00 + * 13:00-18:00 + * 22:00-次日4:00 + * + * 3、... + * + * 4、那么restTimes表示的就是休息时段15:00-16:00对应的数组下标{[100,200]},举个栗子而已 + * + * 5、那么workIndex表示的就是休息时段8:00-12:00...对应的数组下标{[50,80],[90,180],[250,280]},workIndexTime存的就是时间点举个栗子而已 + * + * 6、那么halfWorkIndex表示的就是半天规则情况下需要用到的数组下标 + * 上面的例子里的工作时长的15个小时,所以半天的话,需要从8:00-16:30,只要是满足小于这个范围段内的都是半天,大于的就是1天了 + * halfWorkIndex对应的数组下标就是{[50,70]},halfWorkIndexTime存的就是时间点举个栗子而已 + * + * 7、那么wholeWorkIndex表示的就是整天规则情况下需要用到的数组下标,我只需要知道workIndex就可以了。wholeWorkIndexTime存的就是时间点 + * + */ +public class ShiftInfoBean { + /** + * 指定开始时间 + */ + private String splitFromTime; + /** + * 指定结束时间 + */ + private String splitToTime; + + /** + * 指定日期 因为流程时段区间已经被拆分成一天一条了 + */ + private String splitDate; + /** + * 要返回当天的工作时间区间对应的数组下标 这个是不包含跨天的 + */ + private List workIndex; + + /** + * 要返回当天的工作时间区间对应的数组下标 这个是包含跨天的 + */ + private List workAcrossIndex; + + /** + * 要返回当天的工作时间区间对应的时间 这个是包含跨天的 + */ + private List workAcrossTime; + + /** + * 当天打卡时段时间:多少分钟可以开始签到签退的 + */ + private List workMinsAcrossIndex; + /** + * 要返回的休息时间区间对应的数组下标 不包含跨天 + */ + private List restIndex; + /** + * 要返回的休息时间区间对应的数组下标 包含跨天的 + */ + private List restAcrossIndex; + /** + * 要返回的半天规则时间区间对应的数组下标 + * 这里有值的话是三个,最早的开始时间 中间时间 最晚的下班时间 + */ + private List halfWorkIndex; + + /** + * 工作时长 + */ + private int workmins; + + private int signoutOnlyoff; + + /** + * 加班用的前日期是何种类型 + */ + private int changeType; + + /** + * 当前日期的班次 + */ + private String serialid; + + /** + * 指定日期的前一天,因为存在跨天,昨天数据可能也需要在今天统计 + */ + private String preSplitDate; + + /** + * 这个返回的是前一天的班次存在跨天,跨到今天的工作时段区间 + */ + private List preWorkIndex; + + /** + * 要返回前一天天的工作时间区间对应的数组下标 这个是包含跨天的 + */ + private List preWorkAcrossIndex; + + /** + * 要返回前一天打卡时段信息:多少分钟可以开始签到签退的 + */ + private List preWorkMinsAcrossIndex; + + /** + * 映射前一天的跨天和时间区间下标 + */ + private Map preWorktimeAcrossMap; + /** + * 要返回前一天的休息时间区间对应的数组下标 + */ + private List preRestIndex; + /** + * 要返回的前一天的半天规则时间区间对应的数组下标 + * 这里有值的话是三个,开始时间 中间时间 下班时间 + */ + private List preHalfWorkIndex; + + /** + * 前一天的工作时长 + */ + private int preWorkmins; + + /** + * 前一个日期的班次 + */ + private String preSerialid; + + /** + * 得到实际时长分钟数 + */ + private double D_Mins; + + /** + * 流程判断的各种规则 + * 半天小时的 + */ + private String minimumUnit; + + /** + * 流程用的时候存的值 + */ + private String duration; + + /** + * 针对时段跨天 流程跨天的情况,23:59-24:00差一分钟的处理 + */ + private String oneMoreMinute; + + /** + * 当前时间段 + */ + private int[] curMins; + + /** + * 当前时间段 + */ + private int[] preMins; + + /** + * 存储所有的工作时间 + */ + private List allWorkTime; + + /** + * 存储所有的跨天时间 + */ + private List allAcrossWorkTime; + /** + * 存储所有的休息时间 + */ + private List allRestTime; + + /** + * 存储所有的休息时间 + */ + private List allAcrossRestTime; + + + + /** + * 存储所有的工作时间 + */ + private List preAllWorkTime; + + /** + * 存储所有的跨天时间 + */ + private List preAllAcrossWorkTime; + /** + * 存储所有的休息时间 + */ + private List preAllRestTime; + + /** + * 存储所有的休息时间 + */ + private List preAllAcrossRestTime; + + /** + * 是否是自由班製 + */ + private boolean isfree; + /** + * 自由班制签到开始时间 + */ + private String freeSignStart; + /** + * 自由班制工作时长 + */ + private String freeWorkMins; + /** + * 自由班制应该签退时间 + */ + private String freeSignEnd; + /** + * 自由班制 半天中间点 + */ + private String freeSignMiddle; + + + /** + * 当前班次作为当前班次存在,在0-48小时内的工作时段下标 + */ + private List workLongTimeIndex; + + /** + * 当前班次作为当前班次存在,在0-48小时内的工作时段下标 + */ + private List restLongTimeIndex; + + /** + * 存储所有的工作时间 48小时制休息时段 + */ + private List allLongWorkTime; + + /** + * 判断当前班次是否存在跨天 + */ + private String isAcross; + + /** + * 判断前一天班次是否存在跨天 + */ + private String isPreAcross; + + private Map shiftRuleMap; + + /** + * 和kqformdate里的workTimeEntity用到的保持一致 + */ + private List signTime;//允许打卡时间 + /** + * 和kqformdate里的workTimeEntity用到的保持一致 + */ + private List workTime;//工作时间 + + /** + * 半天计算规则 + */ + private String halfcalrule; + + /** + * 自定义 半天计算规则 时间点 + */ + private String halfcalpoint; + + private String halfcalpoint2cross; + + /** + * 存储每一段工作时段内的工作时长 + */ + private List eachWorkMins; + /** + * 是否是非工作日 1表示是非工作日班次 + */ + private int restShift; + + /** + * 昨天应出勤折算天数 + */ + private String preConvertAttendDay = ""; + + /** + * 应出勤折算天数 + */ + private String convertAttendDay = ""; + + public ShiftInfoBean() { + this.splitFromTime = ""; + this.splitToTime = ""; + this.splitDate = ""; + this.workIndex = new ArrayList<>(); + this.workAcrossIndex = new ArrayList<>(); + this.restIndex = new ArrayList<>(); + this.restAcrossIndex = new ArrayList<>(); + this.halfWorkIndex = new ArrayList<>(); + this.workmins = 0; + this.signoutOnlyoff = 0; + this.preSplitDate = ""; + this.preWorkIndex = new ArrayList<>(); + this.preWorkAcrossIndex = new ArrayList<>(); + this.preWorktimeAcrossMap = new HashMap<>(); + this.preRestIndex = new ArrayList<>(); + this.preHalfWorkIndex = new ArrayList<>(); + this.preWorkmins = 0; + this.D_Mins = 0.0; + this.minimumUnit = ""; + this.duration = ""; + this.oneMoreMinute = ""; + this.preWorkMinsAcrossIndex = new ArrayList<>(); + this.workMinsAcrossIndex = new ArrayList<>(); + this.preSerialid = ""; + this.serialid = ""; + this.workAcrossTime = new ArrayList<>(); + this.isfree = false; + this.freeSignStart = ""; + this.freeWorkMins = ""; + this.freeSignEnd = ""; + this.freeSignMiddle = ""; + + this.workLongTimeIndex = new ArrayList<>(); + this.restLongTimeIndex = new ArrayList<>(); + this.allLongWorkTime = new ArrayList<>(); + this.isAcross = ""; + this.isPreAcross = ""; + this.shiftRuleMap = Maps.newHashMap(); + this.workTime = Lists.newArrayList(); + this.signTime = Lists.newArrayList(); + this.halfcalrule = ""; + this.halfcalpoint = ""; + this.halfcalpoint2cross = ""; + this.eachWorkMins = new ArrayList<>(); + } + + public String getSplitDate() { + return splitDate; + } + + public void setSplitDate(String splitDate) { + this.splitDate = splitDate; + } + + public String getSplitFromTime() { + return splitFromTime; + } + + public void setSplitFromTime(String splitFromTime) { + this.splitFromTime = splitFromTime; + } + + public String getSplitToTime() { + return splitToTime; + } + + public void setSplitToTime(String splitToTime) { + this.splitToTime = splitToTime; + } + + public List getWorkIndex() { + return workIndex; + } + + public void setWorkIndex(List workIndex) { + this.workIndex = workIndex; + } + + public List getRestIndex() { + return restIndex; + } + + public void setRestIndex(List restIndex) { + this.restIndex = restIndex; + } + + public List getHalfWorkIndex() { + return halfWorkIndex; + } + + public void setHalfWorkIndex(List halfWorkIndex) { + this.halfWorkIndex = halfWorkIndex; + } + + public double getD_Mins() { + return D_Mins; + } + + public void setD_Mins(double d_Mins) { + D_Mins = d_Mins; + } + + public String getPreSplitDate() { + return preSplitDate; + } + + public void setPreSplitDate(String preSplitDate) { + this.preSplitDate = preSplitDate; + } + + public List getPreWorkIndex() { + return preWorkIndex; + } + + public void setPreWorkIndex(List preWorkIndex) { + this.preWorkIndex = preWorkIndex; + } + + public List getWorkAcrossIndex() { + return workAcrossIndex; + } + + public void setWorkAcrossIndex(List workAcrossIndex) { + this.workAcrossIndex = workAcrossIndex; + } + + public int getWorkmins() { + return workmins; + } + + public void setWorkmins(int workmins) { + this.workmins = workmins; + } + + public int getSignoutOnlyoff() { + return signoutOnlyoff; + } + + public void setSignoutOnlyoff(int signoutOnlyoff) { + this.signoutOnlyoff = signoutOnlyoff; + } + + public String getMinimumUnit() { + return minimumUnit; + } + + public void setMinimumUnit(String minimumUnit) { + this.minimumUnit = minimumUnit; + } + + public List getPreHalfWorkIndex() { + return preHalfWorkIndex; + } + + public void setPreHalfWorkIndex(List preHalfWorkIndex) { + this.preHalfWorkIndex = preHalfWorkIndex; + } + + public List getPreWorkAcrossIndex() { + return preWorkAcrossIndex; + } + + public void setPreWorkAcrossIndex(List preWorkAcrossIndex) { + this.preWorkAcrossIndex = preWorkAcrossIndex; + } + + public Map getPreWorktimeAcrossMap() { + return preWorktimeAcrossMap; + } + + public void setPreWorktimeAcrossMap( + Map preWorktimeAcrossMap) { + this.preWorktimeAcrossMap = preWorktimeAcrossMap; + } + + public List getPreRestIndex() { + return preRestIndex; + } + + public void setPreRestIndex(List preRestIndex) { + this.preRestIndex = preRestIndex; + } + + public int getPreWorkmins() { + return preWorkmins; + } + + public void setPreWorkmins(int preWorkmins) { + this.preWorkmins = preWorkmins; + } + + public List getRestAcrossIndex() { + return restAcrossIndex; + } + + public void setRestAcrossIndex(List restAcrossIndex) { + this.restAcrossIndex = restAcrossIndex; + } + + public String getDuration() { + return duration; + } + + public void setDuration(String duration) { + this.duration = duration; + } + + public String getOneMoreMinute() { + return oneMoreMinute; + } + + public void setOneMoreMinute(String oneMoreMinute) { + this.oneMoreMinute = oneMoreMinute; + } + + public List getWorkMinsAcrossIndex() { + return workMinsAcrossIndex; + } + + public void setWorkMinsAcrossIndex(List workMinsAcrossIndex) { + this.workMinsAcrossIndex = workMinsAcrossIndex; + } + + public List getPreWorkMinsAcrossIndex() { + return preWorkMinsAcrossIndex; + } + + public void setPreWorkMinsAcrossIndex(List preWorkMinsAcrossIndex) { + this.preWorkMinsAcrossIndex = preWorkMinsAcrossIndex; + } + + public String getSerialid() { + return serialid; + } + + public void setSerialid(String serialid) { + this.serialid = serialid; + } + + public String getPreSerialid() { + return preSerialid; + } + + public void setPreSerialid(String preSerialid) { + this.preSerialid = preSerialid; + } + + public int[] getCurMins() { + return curMins; + } + + public void setCurMins(int[] curMins) { + this.curMins = curMins; + } + + public int[] getPreMins() { + return preMins; + } + + public void setPreMins(int[] preMins) { + this.preMins = preMins; + } + + public List getWorkAcrossTime() { + return workAcrossTime; + } + + public void setWorkAcrossTime(List workAcrossTime) { + this.workAcrossTime = workAcrossTime; + } + + public int getChangeType() { + return changeType; + } + + public void setChangeType(int changeType) { + this.changeType = changeType; + } + + public List getAllWorkTime() { + return allWorkTime; + } + + public void setAllWorkTime(List allWorkTime) { + this.allWorkTime = allWorkTime; + } + + public List getAllAcrossWorkTime() { + return allAcrossWorkTime; + } + + public void setAllAcrossWorkTime(List allAcrossWorkTime) { + this.allAcrossWorkTime = allAcrossWorkTime; + } + + public List getAllRestTime() { + return allRestTime; + } + + public void setAllRestTime(List allRestTime) { + this.allRestTime = allRestTime; + } + + public List getAllAcrossRestTime() { + return allAcrossRestTime; + } + + public void setAllAcrossRestTime(List allAcrossRestTime) { + this.allAcrossRestTime = allAcrossRestTime; + } + + public List getPreAllWorkTime() { + return preAllWorkTime; + } + + public void setPreAllWorkTime(List preAllWorkTime) { + this.preAllWorkTime = preAllWorkTime; + } + + public List getPreAllAcrossWorkTime() { + return preAllAcrossWorkTime; + } + + public void setPreAllAcrossWorkTime(List preAllAcrossWorkTime) { + this.preAllAcrossWorkTime = preAllAcrossWorkTime; + } + + public List getPreAllRestTime() { + return preAllRestTime; + } + + public void setPreAllRestTime(List preAllRestTime) { + this.preAllRestTime = preAllRestTime; + } + + public List getPreAllAcrossRestTime() { + return preAllAcrossRestTime; + } + + public void setPreAllAcrossRestTime(List preAllAcrossRestTime) { + this.preAllAcrossRestTime = preAllAcrossRestTime; + } + + public boolean isIsfree() { + return isfree; + } + + public void setIsfree(boolean isfree) { + this.isfree = isfree; + } + + public String getFreeSignStart() { + return freeSignStart; + } + + public void setFreeSignStart(String freeSignStart) { + this.freeSignStart = freeSignStart; + } + + public String getFreeWorkMins() { + return freeWorkMins; + } + + public void setFreeWorkMins(String freeWorkMins) { + this.freeWorkMins = freeWorkMins; + } + + public String getFreeSignEnd() { + return freeSignEnd; + } + + public void setFreeSignEnd(String freeSignEnd) { + this.freeSignEnd = freeSignEnd; + } + + public String getFreeSignMiddle() { + return freeSignMiddle; + } + + public void setFreeSignMiddle(String freeSignMiddle) { + this.freeSignMiddle = freeSignMiddle; + } + + public List getWorkLongTimeIndex() { + return workLongTimeIndex; + } + + public void setWorkLongTimeIndex(List workLongTimeIndex) { + this.workLongTimeIndex = workLongTimeIndex; + } + + public List getRestLongTimeIndex() { + return restLongTimeIndex; + } + + public void setRestLongTimeIndex(List restLongTimeIndex) { + this.restLongTimeIndex = restLongTimeIndex; + } + + public List getAllLongWorkTime() { + return allLongWorkTime; + } + + public void setAllLongWorkTime(List allLongWorkTime) { + this.allLongWorkTime = allLongWorkTime; + } + + public String getIsAcross() { + return isAcross; + } + + public void setIsAcross(String isAcross) { + this.isAcross = isAcross; + } + + public String getIsPreAcross() { + return isPreAcross; + } + + public void setIsPreAcross(String isPreAcross) { + this.isPreAcross = isPreAcross; + } + + public Map getShiftRuleMap() { + return shiftRuleMap; + } + + public void setShiftRuleMap(Map shiftRuleMap) { + this.shiftRuleMap = shiftRuleMap; + } + + public List getSignTime() { + return signTime; + } + + public void setSignTime(List signTime) { + this.signTime = signTime; + } + + public List getWorkTime() { + return workTime; + } + + public void setWorkTime(List workTime) { + this.workTime = workTime; + } + + public String getHalfcalrule() { + return halfcalrule; + } + + public void setHalfcalrule(String halfcalrule) { + this.halfcalrule = halfcalrule; + } + + public List getEachWorkMins() { + return eachWorkMins; + } + + public void setEachWorkMins(List eachWorkMins) { + this.eachWorkMins = eachWorkMins; + } + + public String getHalfcalpoint() { + return halfcalpoint; + } + + public void setHalfcalpoint(String halfcalpoint) { + this.halfcalpoint = halfcalpoint; + } + + public String getHalfcalpoint2cross() { + return halfcalpoint2cross; + } + + public void setHalfcalpoint2cross(String halfcalpoint2cross) { + this.halfcalpoint2cross = halfcalpoint2cross; + } + + public int getRestShift() { + return restShift; + } + + public void setRestShift(int restShift) { + this.restShift = restShift; + } + + public String getConvertAttendDay() { + return convertAttendDay; + } + + public void setConvertAttendDay(String convertAttendDay) { + this.convertAttendDay = convertAttendDay; + } + + public String getPreConvertAttendDay() { + return preConvertAttendDay; + } + + public void setPreConvertAttendDay(String preConvertAttendDay) { + this.preConvertAttendDay = preConvertAttendDay; + } +} diff --git a/领悦二开new/src/com/engine/kq/cmd/report/ExportExcelCmd.java b/领悦二开new/src/com/engine/kq/cmd/report/ExportExcelCmd.java new file mode 100644 index 0000000..461dc27 --- /dev/null +++ b/领悦二开new/src/com/engine/kq/cmd/report/ExportExcelCmd.java @@ -0,0 +1,954 @@ +package com.engine.kq.cmd.report; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.engine.common.biz.AbstractCommonCommand; +import com.engine.common.entity.BizLogContext; +import com.engine.core.interceptor.CommandContext; +import com.engine.kq.biz.*; +import com.engine.kq.util.ExcelUtil; +import com.engine.kq.util.KQDurationCalculatorUtil; +import com.engine.kq.util.UtilKQ; +import com.engine.lingyue.util.KqUtil; +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.general.TimeUtil; +import weaver.general.Util; +import weaver.hrm.User; +import weaver.hrm.company.DepartmentComInfo; +import weaver.hrm.company.SubCompanyComInfo; +import weaver.hrm.job.JobTitlesComInfo; +import weaver.hrm.resource.ResourceComInfo; +import weaver.systeminfo.SystemEnv; +import com.google.common.collect.Lists; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.math.BigDecimal; +import java.util.*; + +public class ExportExcelCmd extends AbstractCommonCommand> { + + private HttpServletRequest request; + private HttpServletResponse response; + private List lsFieldDataKey; + + private boolean isKqReportHalfOpen = "1".equals(new KQSettingsComInfo().getMain_val("kq_report_half")); + + public ExportExcelCmd(Map params, HttpServletRequest request, HttpServletResponse response, User user) { + this.user = user; + this.params = params; + this.request = request; + this.response = response; + this.lsFieldDataKey = new ArrayList<>(); + } + + @Override + public Map execute(CommandContext commandContext) { + Map retmap = new HashMap(); + RecordSet rs = new RecordSet(); + String sql = ""; + try { + SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo(); + DepartmentComInfo departmentComInfo = new DepartmentComInfo(); + ResourceComInfo resourceComInfo = new ResourceComInfo(); + JobTitlesComInfo jobTitlesComInfo = new JobTitlesComInfo(); + KQLeaveRulesBiz kqLeaveRulesBiz = new KQLeaveRulesBiz(); + KQSettingsComInfo kqSettingsComInfo = new KQSettingsComInfo(); + String leavetype_is_on = Util.null2String(kqSettingsComInfo.getMain_val("leavetype_is_on"),"0"); + + KQReportBiz kqReportBiz = new KQReportBiz(); + new KQReportBiz().insertKqReportExportLog(params, user); + JSONObject jsonObj = JSON.parseObject(Util.null2String(params.get("data"))); + String attendanceSerial = Util.null2String(jsonObj.get("attendanceSerial")); + String fromDate = Util.null2String(jsonObj.get("fromDate")); + String toDate = Util.null2String(jsonObj.get("toDate")); + String typeselect = Util.null2String(jsonObj.get("typeselect")); + if (typeselect.length() == 0) typeselect = "3"; + if (!typeselect.equals("") && !typeselect.equals("0") && !typeselect.equals("6")) { + if (typeselect.equals("1")) { + fromDate = TimeUtil.getCurrentDateString(); + toDate = TimeUtil.getCurrentDateString(); + } else { + fromDate = TimeUtil.getDateByOption(typeselect, "0"); + toDate = TimeUtil.getDateByOption(typeselect, "1"); + } + } + //人员状态 + String status = Util.null2String(jsonObj.get("status")); + String subCompanyId = Util.null2String(jsonObj.get("subCompanyId")); + String departmentId = Util.null2String(jsonObj.get("departmentId")); + String resourceId = Util.null2String(jsonObj.get("resourceId")); + String allLevel = Util.null2String(jsonObj.get("allLevel")); + String isNoAccount = Util.null2String(jsonObj.get("isNoAccount")); + String viewScope = Util.null2String(jsonObj.get("viewScope")); + List showColumns = Util.splitString2List(Util.null2String(jsonObj.get("showColumns")), ","); + showColumns.add("lastname"); + showColumns.removeIf(showColumn->showColumn.trim().equals("")); + + List tmpShowColumns = new ArrayList<>(); + for(String showColumn:showColumns){ + tmpShowColumns.add(showColumn); + String cascadekey = ""; + if(showColumn.equals("beLate")){ + cascadekey = "beLateMins"; + }else if(showColumn.equals("leaveEearly")){ + cascadekey = "leaveEarlyMins"; + }else if(showColumn.equals("graveBeLate")){ + cascadekey = "graveBeLateMins"; + }else if(showColumn.equals("graveLeaveEarly")){ + cascadekey = "graveLeaveEarlyMins"; + }else if(showColumn.equals("absenteeism")){ + cascadekey = "absenteeismMins"; + }else if(showColumn.equals("overtime")){ + tmpShowColumns.add("overtime_4leave"); + tmpShowColumns.add("overtime_nonleave"); + tmpShowColumns.add("workingDayOvertime_nonleave"); + tmpShowColumns.add("workingDayOvertime_4leave"); + tmpShowColumns.add("restDayOvertime_nonleave"); + tmpShowColumns.add("restDayOvertime_4leave"); + tmpShowColumns.add("holidayOvertime_4leave"); + tmpShowColumns.add("holidayOvertime_nonleave"); + } + if(cascadekey.length()>0){ + tmpShowColumns.add(cascadekey); + } + } + showColumns = tmpShowColumns; + + String rightSql = new KQReportBiz().getReportRight("1", "" + user.getUID(), "a"); + + LinkedHashMap workbook = new LinkedHashMap<>(); + List lsSheet = new ArrayList<>(); + Map sheet = null; + List titleList = new ArrayList<>(); + Map title = null; + List> dataList = new ArrayList<>(); + List data = null; + List> constraintList = null; + + sheet = new HashMap<>(); + sheet.put("sheetName", SystemEnv.getHtmlLabelName(390351, user.getLanguage())); + sheet.put("sheetTitle", SystemEnv.getHtmlLabelName(390351, user.getLanguage())); + boolean isEnd = false; + Calendar cal = DateUtil.getCalendar(); + + List> leaveRules = kqLeaveRulesBiz.getAllLeaveRules(); + Map mapChildColumnInfo = null; + List childColumns = null; + KQReportFieldComInfo kqReportFieldComInfo = new KQReportFieldComInfo(); + while (kqReportFieldComInfo.next()) { + if (Util.null2String(kqReportFieldComInfo.getParentid()).length() > 0) continue; + if(kqReportFieldComInfo.getFieldname().equals("kqCalendar"))continue; + if(KQReportFieldComInfo.cascadekey2fieldname.keySet().contains(kqReportFieldComInfo.getFieldname()))continue; + if (!kqReportFieldComInfo.getReportType().equals("all") && !kqReportFieldComInfo.getReportType().equals("month")) + continue; + if (!showColumns.contains(kqReportFieldComInfo.getFieldname())&&!showColumns.contains(kqReportFieldComInfo.getParentid())) continue; + if("leave".equalsIgnoreCase(kqReportFieldComInfo.getFieldname())&&leaveRules.size()==0){ + continue; + } + title = new HashMap<>(); + String unitType = KQReportBiz.getUnitType(kqReportFieldComInfo, user); + if(unitType.length()>0){ + title.put("title", SystemEnv.getHtmlLabelNames(kqReportFieldComInfo.getFieldlabel(), user.getLanguage())+ "(" + unitType + ")"); + }else{ + title.put("title", SystemEnv.getHtmlLabelNames(kqReportFieldComInfo.getFieldlabel(), user.getLanguage())); + } + title.put("width", 30 * 256); + this.lsFieldDataKey.add(kqReportFieldComInfo.getFieldname()); + mapChildColumnInfo = this.getChildColumnsInfo(kqReportFieldComInfo.getFieldname(), user); + childColumns = (List) mapChildColumnInfo.get("childColumns"); + if (childColumns.size() > 0) {//跨列width取子列的width + title.put("children", childColumns); + title.put("colSpan", childColumns.size()); + } else { + title.put("rowSpan", 3); + } + titleList.add(title); + + titleList.addAll(this.getCascadeKeyColumnsInfo(kqReportFieldComInfo.getCascadekey(),user)); + } + + String today = DateUtil.getCurrentDate(); +// if (DateUtil.compDate(today, toDate) > 0) {//结束如期不大于今天 +// toDate = today; +// } + + if(showColumns.contains("kqCalendar")) { + childColumns = new ArrayList<>(); + for (String date = fromDate; !isEnd; ) { + if (date.equals(toDate)) isEnd = true; + title = new HashMap<>(); + title.put("title", UtilKQ.getWeekDayShort(DateUtil.getWeek(date)-1,user.getLanguage()) +"\r\n"+ DateUtil.geDayOfMonth(date)); + title.put("width", 30 * 256); + childColumns.add(title); + cal.setTime(DateUtil.parseToDate(date)); + date = DateUtil.getDate(cal.getTime(), 1); + } + + title = new HashMap(); + title.put("title", SystemEnv.getHtmlLabelName(386476, user.getLanguage())); + if (childColumns.size() > 0) {//跨列width取子列的width + title.put("children", childColumns); + title.put("colSpan", childColumns.size()); + } + titleList.add(title); + } + sheet.put("titleList", titleList); + + // 没有权限的人最大只支持查询本季 + Map getRealDate = new KQReportBiz().realDate(fromDate, toDate, user, "1"); + fromDate = getRealDate.get("fromDate"); + toDate = getRealDate.get("toDate"); + if("-1".equals(fromDate) || "-1".equals(toDate)) { + retmap.put("status", "1"); + return retmap; + } + + String forgotBeginWorkCheck_field = " sum(b.forgotBeginWorkCheck) "; + + if(rs.getDBType().equalsIgnoreCase("oracle")) { + forgotBeginWorkCheck_field = " sum(nvl(b.forgotBeginWorkCheck,0)) "; + }else if((rs.getDBType()).equalsIgnoreCase("mysql")){ + forgotBeginWorkCheck_field = " sum(ifnull(b.forgotBeginWorkCheck,0)) "; + }else { + forgotBeginWorkCheck_field = " sum(isnull(b.forgotBeginWorkCheck,0)) "; + } + + Map definedFieldInfo = new KQFormatBiz().getDefinedField(); + String definedFieldSum = Util.null2String(definedFieldInfo.get("definedFieldSum")); + String backFields = " (select sum(fdjbtians) as jbts from uf_kqgshsj u where u.xm = a.id and u.rq>='"+fromDate+"' and u.rq<= '"+toDate+"') as jbts,(select sum(gcyjzbts) as gzts from uf_kqgshsj u where u.xm = a.id and u.rq>='"+fromDate+"' and u.rq<= '"+toDate+"') as gzts,a.id,a.lastname,a.workcode,a.dsporder,b.resourceid,a.subcompanyid1 as subcompanyid,a.departmentid,a.jobtitle," + + " sum(b.workdays) as workdays,sum(b.workMins) as workMins,sum(b.attendancedays) as attendancedays," + + " sum(b.attendanceMins) as attendanceMins,sum(b.beLate) as beLate,sum(b.beLateMins) as beLateMins, " + + " sum(b.graveBeLate) as graveBeLate, sum(b.graveBeLateMins) as graveBeLateMins,sum(b.leaveEearly) as leaveEearly," + + " sum(b.leaveEarlyMins) as leaveEarlyMins, sum(b.graveLeaveEarly) as graveLeaveEarly, " + + " sum(b.graveLeaveEarlyMins) as graveLeaveEarlyMins,sum(b.absenteeism) as absenteeism, " + + " sum(b.signdays) as signdays,sum(b.signmins) as signmins, "+ + " sum(b.absenteeismMins) as absenteeismMins, sum(b.forgotCheck)+"+forgotBeginWorkCheck_field+" as forgotCheck "+(definedFieldSum.length()>0?","+definedFieldSum+"":""); + if(rs.getDBType().equals("oracle")){ + backFields = "/*+ index(kq_format_total IDX_KQ_FORMAT_TOTAL_KQDATE) */ "+backFields; + } + String sqlFrom = " from hrmresource a, kq_format_total b where a.id= b.resourceid and b.kqdate >='" + fromDate + "' and b.kqdate <='" + toDate + "'"; + String sqlWhere = rightSql; + String groupBy = " group by a.id,a.lastname,a.workcode,a.dsporder,b.resourceid,a.subcompanyid1,a.departmentid,a.jobtitle "; + if (subCompanyId.length() > 0) { + sqlWhere += " and a.subcompanyid1 in(" + subCompanyId + ") "; + } + + if (departmentId.length() > 0) { + sqlWhere += " and a.departmentid in(" + departmentId + ") "; + } + + if (resourceId.length() > 0) { + sqlWhere += " and a.id in(" + resourceId + ") "; + } + + if (viewScope.equals("4")) {//我的下属 + if (allLevel.equals("1")) {//所有下属 + sqlWhere += " and a.managerstr like '%," + user.getUID() + ",%'"; + } else { + sqlWhere += " and a.managerid=" + user.getUID();//直接下属 + } + } + if (!"1".equals(isNoAccount)) { + sqlWhere += " and a.loginid is not null " + (rs.getDBType().equals("oracle") ? "" : " and a.loginid<>'' "); + } + + if(status.length()>0){ + if (!status.equals("8") && !status.equals("9")) { + sqlWhere += " and a.status = "+status+ ""; + }else if (status.equals("8")) { + sqlWhere += " and (a.status = 0 or a.status = 1 or a.status = 2 or a.status = 3) "; + } + } + + String orderBy = " order by a.dsporder asc, a.lastname asc "; + String descOrderBy = " order by a.dsporder desc, a.lastname desc "; + sql = "select " + backFields + sqlFrom + sqlWhere + groupBy + orderBy; + + //System.out.println("start" + DateUtil.getFullDate()); + + + String show_card_source = Util.null2String(kqSettingsComInfo.getMain_val("show_card_source"),"0");//是否显示打卡数据,以及打卡数据来源 + params.put("show_card_source",show_card_source); + KQOvertimeRulesBiz kqOvertimeRulesBiz = new KQOvertimeRulesBiz(); + int uintType = kqOvertimeRulesBiz.getMinimumUnit();//当前加班单位 + double hoursToDay = kqOvertimeRulesBiz.getHoursToDay();//当前天跟小时计算关系 + params.put("uintType",uintType); + params.put("hoursToDay",hoursToDay); + Map flowData = new KQReportBiz().getFlowData(params, user); + //System.out.println("end" + DateUtil.getFullDate()); + + // #1475814-概述:满足考勤报分部部门显示及导出时显示全路径 + String fullPathMainKey = "show_full_path"; + String isShowFullPath = Util.null2String(kqSettingsComInfo.getMain_val(fullPathMainKey),"0"); + + //事假 + int leaveabsencetype = Util.getIntValue(rs.getPropValue("hrm_kqreport","leaveabsencetype")); + //病假 + int sickleavetype = Util.getIntValue(rs.getPropValue("hrm_kqreport","sickleavetype")); + //年假 + int annualleavetype = Util.getIntValue(rs.getPropValue("hrm_kqreport","annualleavetype")); + //陪产假 + int paternityleavetype = Util.getIntValue(rs.getPropValue("hrm_kqreport","paternityleavetype")); + //婚假 + int marriageleavetype = Util.getIntValue(rs.getPropValue("hrm_kqreport","marriageleavetype")); + //丧假 + int bereavementleavetype = Util.getIntValue(rs.getPropValue("hrm_kqreport","bereavementleavetype")); + //探亲假 + int homeleavetype = Util.getIntValue(rs.getPropValue("hrm_kqreport","homeleavetype")); + //哺乳假 + int breastfeedleavetype = Util.getIntValue(rs.getPropValue("hrm_kqreport","breastfeed_leave_id")); + + rs.execute(sql); + int calIndex = -1; + while (rs.next()) { + data = new ArrayList<>(); + String id = rs.getString("id"); + for (int fieldDataKeyIdx =0;fieldDataKeyIdx serialIds = null; + if (Util.null2String(jsonObj.get("attendanceSerial")).length() > 0) { + serialIds = Util.splitString2List(Util.null2String(jsonObj.get("attendanceSerial")), ","); + for(int i=0;serialIds!=null&&i> allLeaveRules = kqLeaveRulesBiz.getAllLeaveRules(); + if (("1").equals(leavetype_is_on)) { + KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo(); + for (int i = allLeaveRules.size() - 1; i >= 0; i--) { + Map leaveRule = allLeaveRules.get(i); + String leaveId = Util.null2String(leaveRule.get("id")); + boolean flag = kqLeaveRulesBiz.filterSubLeaveRule(kqLeaveRulesComInfo, user, leaveId); + if (flag) { + allLeaveRules.remove(i); + } + } + } + Map leaveRule = null; + for (int i = 0; allLeaveRules != null && i < allLeaveRules.size(); i++) { + leaveRule = allLeaveRules.get(i); + String flowType = Util.null2String("leaveType_" + leaveRule.get("id")); + String leaveData = Util.null2String(flowData.get(id + "|" + flowType)); + String flowLeaveBackType = Util.null2String("leavebackType_" + leaveRule.get("id")); + String leavebackData = Util.null2s(Util.null2String(flowData.get(id + "|" + flowLeaveBackType)), "0.0"); + String b_flowLeaveData = ""; + String flowLeaveData = ""; + try { + //以防止出现精度问题 + if (leaveData.length() == 0) { + leaveData = "0.0"; + } + if (leavebackData.length() == 0) { + leavebackData = "0.0"; + } + BigDecimal b_leaveData = new BigDecimal(leaveData); + BigDecimal b_leavebackData = new BigDecimal(leavebackData); + b_flowLeaveData = b_leaveData.subtract(b_leavebackData).toString(); + if(Util.getDoubleValue(b_flowLeaveData, -1) < 0){ + b_flowLeaveData = "0.0"; + } + } catch (Exception e) { + writeLog("GetKQReportCmd:leaveData" + leaveData + ":leavebackData:" + leavebackData + ":" + e); + } + + if (b_flowLeaveData.length() > 0) { + flowLeaveData = KQDurationCalculatorUtil.getDurationRound(b_flowLeaveData); + } else { + flowLeaveData = KQDurationCalculatorUtil.getDurationRound(Util.null2String(Util.getDoubleValue(leaveData, 0.0) - Util.getDoubleValue(leavebackData, 0.0))); + } + data.add(flowLeaveData); + } + continue; + }else if(fieldName.equals("overtime")){ + fieldValue = KQDurationCalculatorUtil.getDurationRound(Util.null2String(flowData.get(id + "|workingDayOvertime_nonleave"))); + data.add(getFieldValueByUnitType(fieldValue,kqReportFieldComInfo.getUnittype(KQReportFieldComInfo.field2Id.get("workingDayOvertime_nonleave")))); + + fieldValue = KQDurationCalculatorUtil.getDurationRound(Util.null2String(flowData.get(id + "|restDayOvertime_nonleave"))); + data.add(getFieldValueByUnitType(fieldValue,kqReportFieldComInfo.getUnittype(KQReportFieldComInfo.field2Id.get("restDayOvertime_nonleave")))); + + fieldValue = KQDurationCalculatorUtil.getDurationRound(Util.null2String(flowData.get(id + "|holidayOvertime_nonleave"))); + data.add(getFieldValueByUnitType(fieldValue,kqReportFieldComInfo.getUnittype(KQReportFieldComInfo.field2Id.get("holidayOvertime_nonleave")))); + + fieldValue = KQDurationCalculatorUtil.getDurationRound(Util.null2String(flowData.get(id + "|workingDayOvertime_4leave"))); + data.add(getFieldValueByUnitType(fieldValue,kqReportFieldComInfo.getUnittype(KQReportFieldComInfo.field2Id.get("workingDayOvertime_4leave")))); + + fieldValue = KQDurationCalculatorUtil.getDurationRound(Util.null2String(flowData.get(id + "|restDayOvertime_4leave"))); + data.add(getFieldValueByUnitType(fieldValue,kqReportFieldComInfo.getUnittype(KQReportFieldComInfo.field2Id.get("restDayOvertime_4leave")))); + + fieldValue = KQDurationCalculatorUtil.getDurationRound(Util.null2String(flowData.get(id + "|holidayOvertime_4leave"))); + data.add(getFieldValueByUnitType(fieldValue,kqReportFieldComInfo.getUnittype(KQReportFieldComInfo.field2Id.get("holidayOvertime_4leave")))); + + double workingDayOvertime_4leave = Util.getDoubleValue(Util.null2String(flowData.get(id+"|workingDayOvertime_4leave"))); + workingDayOvertime_4leave = workingDayOvertime_4leave<0?0:workingDayOvertime_4leave; + double restDayOvertime_4leave = Util.getDoubleValue(Util.null2String(flowData.get(id+"|restDayOvertime_4leave"))); + restDayOvertime_4leave = restDayOvertime_4leave<0?0:restDayOvertime_4leave; + double holidayOvertime_4leave = Util.getDoubleValue(Util.null2String(flowData.get(id+"|holidayOvertime_4leave"))); + holidayOvertime_4leave = holidayOvertime_4leave<0?0:holidayOvertime_4leave; + + double workingDayOvertime_nonleave = Util.getDoubleValue(Util.null2String(flowData.get(id+"|workingDayOvertime_nonleave"))); + workingDayOvertime_nonleave = workingDayOvertime_nonleave<0?0:workingDayOvertime_nonleave; + double restDayOvertime_nonleave = Util.getDoubleValue(Util.null2String(flowData.get(id+"|restDayOvertime_nonleave"))); + restDayOvertime_nonleave = restDayOvertime_nonleave<0?0:restDayOvertime_nonleave; + double holidayOvertime_nonleave = Util.getDoubleValue(Util.null2String(flowData.get(id+"|holidayOvertime_nonleave"))); + holidayOvertime_nonleave = holidayOvertime_nonleave<0?0:holidayOvertime_nonleave; + fieldValue = KQDurationCalculatorUtil.getDurationRound(String.valueOf(workingDayOvertime_4leave+restDayOvertime_4leave+holidayOvertime_4leave+ + workingDayOvertime_nonleave+restDayOvertime_nonleave+holidayOvertime_nonleave)); + data.add(getFieldValueByUnitType(fieldValue,kqReportFieldComInfo.getUnittype(KQReportFieldComInfo.field2Id.get("overtimeTotal")))); + continue; + }else if(fieldName.equals("businessLeave") || fieldName.equals("officialBusiness")){ + String businessLeaveData = Util.null2s(Util.null2String(flowData.get(id+"|"+fieldName)),"0.0"); + String backType = fieldName+"_back"; + String businessLeavebackData = Util.null2s(Util.null2String(flowData.get(id+"|"+backType)),"0.0"); + String businessLeave = ""; + try{ + //以防止出现精度问题 + if(businessLeaveData.length() == 0){ + businessLeaveData = "0.0"; + } + if(businessLeavebackData.length() == 0){ + businessLeavebackData = "0.0"; + } + BigDecimal b_businessLeaveData = new BigDecimal(businessLeaveData); + BigDecimal b_businessLeavebackData = new BigDecimal(businessLeavebackData); + businessLeave = b_businessLeaveData.subtract(b_businessLeavebackData).toString(); + if(Util.getDoubleValue(businessLeave, -1) < 0){ + businessLeave = "0.0"; + } + }catch (Exception e){ + } + fieldValue = KQDurationCalculatorUtil.getDurationRound(businessLeave); + } else if(Util.null2String(kqReportFieldComInfo.getCascadekey(fieldid)).length()>0){ + fieldValue = Util.formatMultiLang(Util.null2String(rs.getString(fieldName)),""+user.getLanguage()); + data.add(fieldValue); + + List lsCascadekey = Util.splitString2List(kqReportFieldComInfo.getCascadekey(fieldid),","); + for(int i=0;i0){ + fieldid = KQReportFieldComInfo.field2Id.get(lsCascadekey.get(i)); + fieldValue = getFieldValueByUnitType(rs.getString(lsCascadekey.get(i)),kqReportFieldComInfo.getUnittype(fieldid)); + }else{ + fieldValue = "0"; + } + data.add(fieldValue); + } + continue; + }else { + fieldValue = Util.formatMultiLang(Util.null2String(rs.getString(fieldName)),""+user.getLanguage()); + fieldValue = getFieldValueByUnitType(fieldValue,kqReportFieldComInfo.getUnittype(fieldid)); + } + fieldValue = Util.formatMultiLang(fieldValue,""+user.getLanguage()); + data.add(fieldValue); + } + + List amData = Lists.newArrayList(); + List pmData = Lists.newArrayList(); + if(isKqReportHalfOpen) { + amData.addAll(data); + pmData.addAll(data); + calIndex = data.size(); + } + + if(showColumns.contains("kqCalendar")) { + rs.writeLog("=============== ExportExcelCmd detialDatas showColumns kqCalendar================= "); +// Map detialDatas = kqReportBiz.getDetialDatas(id, fromDate, toDate, user,flowData,true); + Map detialDatas = kqReportBiz.getDetialDatas(id, fromDate, toDate, user,flowData,true,uintType,show_card_source); + rs.writeLog("=============== ExportExcelCmd detialDatas ================= "+ detialDatas); + String user_endDate = Util.null2String(resourceComInfo.getEndDate(id)); + String user_status = Util.null2String(resourceComInfo.getStatus(id)); + String begindate = Util.null2String(resourceComInfo.getCreatedate(id)).trim(); + String companyStartDate = Util.null2String(resourceComInfo.getCompanyStartDate(id)).trim(); + if(companyStartDate.length()!=10){ + companyStartDate = ""; + } + if(companyStartDate.length()>0 && companyStartDate.indexOf("-")>0){ + begindate=companyStartDate; + } + isEnd = false; + for (String date = fromDate; !isEnd; ) { + if (date.equals(toDate)) isEnd = true; + String dismissDate = resourceComInfo.getEndDate(id); + if(!"".equals(dismissDate) && DateUtil.compDate(dismissDate, date)>0) { + if(isKqReportHalfOpen) { + amData.add(""); + pmData.add(""); + } else { + data.add(""); + } + } else if (DateUtil.compDate(today, date) > 0) { + if(isKqReportHalfOpen) { + amData.add(""); + pmData.add(""); + } else { + data.add(""); + } + } else { + if(!(user_status.equals("0")||user_status.equals("1")||user_status.equals("2")||user_status.equals("3"))){ + //其他状态 + if(user_endDate.length()>0 && date.compareTo(user_endDate)>0){//人员合同结束日期之后 + if(isKqReportHalfOpen) { + amData.add(""); + pmData.add(""); + } else { + data.add(""); + } + cal.setTime(DateUtil.parseToDate(date)); + date = DateUtil.getDate(cal.getTime(), 1); + continue; + } + } + if(begindate.length()>0 && date.compareTo(begindate)<0 ){//人员入职日期前无需计算考勤,如果没有入职日期,已创建日期为准 + if(isKqReportHalfOpen) { + amData.add(""); + pmData.add(""); + } else { + data.add(""); + } + cal.setTime(DateUtil.parseToDate(date)); + date = DateUtil.getDate(cal.getTime(), 1); + continue; + } + if (detialDatas.get(id + "|" + date) != null) { + if(isKqReportHalfOpen) { + amData.add(((Map) detialDatas.get(id + "|" + date)).get("textAM")); + pmData.add(((Map) detialDatas.get(id + "|" + date)).get("textPM")); + } else { + data.add(((Map) detialDatas.get(id + "|" + date)).get("text")); + } + } else { + if(isKqReportHalfOpen) { + amData.add(SystemEnv.getHtmlLabelName(26593, user.getLanguage())); + pmData.add(SystemEnv.getHtmlLabelName(26593, user.getLanguage())); + } else { + data.add(SystemEnv.getHtmlLabelName(26593, user.getLanguage())); + } + } + } + cal.setTime(DateUtil.parseToDate(date)); + date = DateUtil.getDate(cal.getTime(), 1); + } + } + if(isKqReportHalfOpen) { + dataList.add(amData); + dataList.add(pmData); + } else { + dataList.add(data); + } + } + sheet.put("dataList", dataList); + if(isKqReportHalfOpen) { + sheet.put("calIndex", calIndex); + } + sheet.put("constraintList", constraintList); + sheet.put("createFile", "1"); + lsSheet.add(sheet); + + workbook.put("sheet", lsSheet); + String fileName = SystemEnv.getHtmlLabelName(390351, user.getLanguage())+" "+fromDate+" "+toDate; + workbook.put("fileName", fileName); + ExcelUtil ExcelUtil = new ExcelUtil(); + Map exportMap = ExcelUtil.export(workbook, request, response,true); + retmap.putAll(exportMap); + retmap.put("status", "1"); + } catch (Exception e) { + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(382661, user.getLanguage())); + writeLog(e); + } + return retmap; + } + + private Map getChildColumnsInfo(String parentid, User user) { + Map returnMap = new HashMap<>(); + List titleList = new ArrayList<>(); + Map title = null; + KQSettingsComInfo kqSettingsComInfo = new KQSettingsComInfo(); + String leavetype_is_on = Util.null2String(kqSettingsComInfo.getMain_val("leavetype_is_on"),"0"); + if (parentid.equals("attendanceSerial")) {//考勤班次 + KQShiftManagementComInfo kqShiftManagementComInfo = new KQShiftManagementComInfo(); + JSONObject jsonObj = JSON.parseObject(Util.null2String(params.get("data"))); + List serialIds = null; + if (Util.null2String(jsonObj.get("attendanceSerial")).length() > 0) { + serialIds = Util.splitString2List(Util.null2String(jsonObj.get("attendanceSerial")), ","); + } + for (int i = 0; serialIds != null && i < serialIds.size(); i++) { + title = new HashMap<>(); + title.put("title", Util.formatMultiLang(kqShiftManagementComInfo.getSerial(serialIds.get(i)),""+user.getLanguage())); + title.put("width", 30 * 256); + titleList.add(title); + } + } else if (parentid.equals("leave")) { + KQLeaveRulesBiz kqLeaveRulesBiz = new KQLeaveRulesBiz(); + List> leaveRules = kqLeaveRulesBiz.getAllLeaveRules(); + if (("1").equals(leavetype_is_on)) { + KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo(); + for (int i = leaveRules.size() - 1; i >= 0; i--) { + Map leaveRule = leaveRules.get(i); + String leaveId = Util.null2String(leaveRule.get("id")); + boolean flag = kqLeaveRulesBiz.filterSubLeaveRule(kqLeaveRulesComInfo, user, leaveId); + if (flag) { + leaveRules.remove(i); + } + } + } + for (int i = 0; leaveRules != null && i < leaveRules.size(); i++) { + Map leaveRule = leaveRules.get(i); + String name = Util.formatMultiLang(Util.null2String(leaveRule.get("name")),""+user.getLanguage()); + String unitType = Util.null2String(leaveRule.get("unitType")); + String unitName = (KQUnitBiz.isLeaveHour(unitType)) ? SystemEnv.getHtmlLabelName(391, user.getLanguage()) : SystemEnv.getHtmlLabelName(1925, user.getLanguage()); + title = new HashMap<>(); + title.put("title", name + "(" + unitName + ")"); + title.put("width", 30 * 256); + titleList.add(title); + } + }else if(parentid.equals("overtime")){ + String[] overtimeChild = {"overtime_nonleave","overtime_4leave","overtimeTotal"}; + for(int i=0;i0){ + if(unitType.equals("1")){ + unitTypeName=SystemEnv.getHtmlLabelName(1925, user.getLanguage()); + }else if(unitType.equals("2")){ + unitTypeName=SystemEnv.getHtmlLabelName(391, user.getLanguage()); + }else if(unitType.equals("3")){ + unitTypeName=SystemEnv.getHtmlLabelName(18083, user.getLanguage()); + } + } + title.put("title", SystemEnv.getHtmlLabelNames(fieldlabel, user.getLanguage())+ "(" + unitTypeName + ")"); + } + + Map mapChildColumnInfo = getChildColumnsInfo(id, user); + int childWidth = 65; + List childColumns = (List)mapChildColumnInfo.get("childColumns"); + if(childColumns.size()>0) {//跨列width取子列的width + title.put("children", childColumns); + childWidth = Util.getIntValue(Util.null2String(mapChildColumnInfo.get("sumChildColumnWidth")),65); + } + title.put("width", childWidth+""); + titleList.add(title); + } + } else { + KQReportFieldComInfo kqReportFieldComInfo = new KQReportFieldComInfo(); + while (kqReportFieldComInfo.next()) { + if (kqReportFieldComInfo.getParentid().equals(parentid)) { + if(!kqReportFieldComInfo.getReportType().equals("month"))continue; + title = new HashMap<>(); + title.put("title", SystemEnv.getHtmlLabelNames(kqReportFieldComInfo.getFieldlabel(), user.getLanguage()) + "(" + KQReportBiz.getUnitType(kqReportFieldComInfo, user) + ")"); + title.put("width", 30 * 256); + titleList.add(title); + } + } + } + returnMap.put("childColumns", titleList); + return returnMap; + } + + private List getCascadeKeyColumnsInfo(String cascadeKey, User user){ + List titleList = new ArrayList<>(); + Map title = null; + if(Util.null2String(cascadeKey).length()==0){ + return titleList; + } + List lsCascadeKey = Util.splitString2List(cascadeKey,","); + KQReportFieldComInfo kqReportFieldComInfo = new KQReportFieldComInfo(); + for(int i=0;i(); + title.put("title", SystemEnv.getHtmlLabelNames(kqReportFieldComInfo.getFieldlabel(), user.getLanguage()) + "(" + KQReportBiz.getUnitType(kqReportFieldComInfo, user) + ")"); + title.put("width", 30 * 256); + + titleList.add(title); + } + } + } + return titleList; + } + + private String getFieldValueByUnitType(String fieldValue,String unittype){ + if (Util.null2String(unittype).length() > 0) { + if (fieldValue.length() == 0) { + fieldValue = "0"; + } else { + if (unittype.equals("2")) { + fieldValue = KQDurationCalculatorUtil.getDurationRound(("" + (Util.getDoubleValue(fieldValue) / 60.0))); + } + } + } + return fieldValue; + } + @Override + public BizLogContext getLogContext() { + return null; + } +} diff --git a/领悦二开new/src/com/engine/kq/cmd/report/GetKQReportCmd.java b/领悦二开new/src/com/engine/kq/cmd/report/GetKQReportCmd.java new file mode 100644 index 0000000..f5a2208 --- /dev/null +++ b/领悦二开new/src/com/engine/kq/cmd/report/GetKQReportCmd.java @@ -0,0 +1,1004 @@ +package com.engine.kq.cmd.report; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.engine.common.biz.AbstractCommonCommand; +import com.engine.common.entity.BizLogContext; +import com.engine.core.interceptor.CommandContext; +import com.engine.kq.biz.*; +import com.engine.lingyue.util.KqUtil; +import com.weaver.file.Prop; +import com.engine.kq.util.KQDurationCalculatorUtil; +import com.engine.kq.util.PageUidFactory; +import com.google.common.collect.Maps; +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.general.TimeUtil; +import weaver.general.Util; +import weaver.hrm.User; +import weaver.hrm.company.DepartmentComInfo; +import weaver.hrm.company.SubCompanyComInfo; +import weaver.hrm.job.JobTitlesComInfo; +import weaver.hrm.resource.ResourceComInfo; +import weaver.systeminfo.SystemEnv; + +import java.math.BigDecimal; +import java.util.*; + +public class GetKQReportCmd extends AbstractCommonCommand> { + + public GetKQReportCmd(Map params, User user) { + this.user = user; + this.params = params; + } + + @Override + public Map execute(CommandContext commandContext) { + Map retmap = new HashMap(); + RecordSet rs = new RecordSet(); + String sql = ""; + try{ + String pageUid = PageUidFactory.getHrmPageUid("KQReport"); + + SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo(); + DepartmentComInfo departmentComInfo = new DepartmentComInfo(); + ResourceComInfo resourceComInfo = new ResourceComInfo(); + JobTitlesComInfo jobTitlesComInfo = new JobTitlesComInfo(); + KQLeaveRulesBiz kqLeaveRulesBiz = new KQLeaveRulesBiz(); + KQReportBiz kqReportBiz = new KQReportBiz(); + KQSettingsComInfo kqSettingsComInfo = new KQSettingsComInfo(); + String leavetype_is_on = Util.null2String(kqSettingsComInfo.getMain_val("leavetype_is_on"),"0"); + + JSONObject jsonObj = JSON.parseObject(Util.null2String(params.get("data"))); + String attendanceSerial = Util.null2String(jsonObj.get("attendanceSerial")); + String fromDate = Util.null2String(jsonObj.get("fromDate")); + String toDate = Util.null2String(jsonObj.get("toDate")); + String typeselect =Util.null2String(jsonObj.get("typeselect")); + if(typeselect.length()==0)typeselect = "3"; + if(!typeselect.equals("") && !typeselect.equals("0")&& !typeselect.equals("6")){ + if(typeselect.equals("1")){ + fromDate = TimeUtil.getCurrentDateString(); + toDate = TimeUtil.getCurrentDateString(); + }else{ + fromDate = TimeUtil.getDateByOption(typeselect,"0"); + toDate = TimeUtil.getDateByOption(typeselect,"1"); + } + } + //人员状态 + String status = Util.null2String(jsonObj.get("status")); + String subCompanyId = Util.null2String(jsonObj.get("subCompanyId")); + String departmentId = Util.null2String(jsonObj.get("departmentId")); + String resourceId = Util.null2String(jsonObj.get("resourceId")); + String allLevel = Util.null2String(jsonObj.get("allLevel")); + String isNoAccount = Util.null2String(jsonObj.get("isNoAccount")); + String viewScope = Util.null2String(jsonObj.get("viewScope")); + String isFromMyAttendance = Util.null2String(jsonObj.get("isFromMyAttendance"));//是否是来自我的考勤的请求,如果是,不加载考勤报表权限共享的限制,不然我的考勤会提示无权限 + int pageIndex = Util.getIntValue(Util.null2String(jsonObj.get("pageIndex")), 1); + int pageSize = KQReportBiz.getPageSize(Util.null2String(jsonObj.get("pageSize")),pageUid,user.getUID()); + boolean isKqReportHalfOpen = "1".equals(new KQSettingsComInfo().getMain_val("kq_report_half")); + if(isKqReportHalfOpen) { + pageSize = pageSize/2; + } + int count = 0; + int pageCount = 0; + int isHavePre = 0; + int isHaveNext = 0; + + + String rightSql = kqReportBiz.getReportRight("1",""+user.getUID(),"a"); + if(isFromMyAttendance.equals("1")){ + rightSql = ""; + } + + List> leaveRules = kqLeaveRulesBiz.getAllLeaveRules(); + List columns = new ArrayList(); + Map column = null; + List datas = new ArrayList(); + Map data = null; + Map mapChildColumnInfo = null; + List childColumns = null; + KQReportFieldComInfo kqReportFieldComInfo = new KQReportFieldComInfo(); + while (kqReportFieldComInfo.next()){ + if(Util.null2String(kqReportFieldComInfo.getParentid()).length()>0)continue; + if(kqReportFieldComInfo.getFieldname().equals("kqCalendar"))continue; + if(KQReportFieldComInfo.cascadekey2fieldname.keySet().contains(kqReportFieldComInfo.getFieldname()))continue; + if(!kqReportFieldComInfo.getReportType().equals("all") && !kqReportFieldComInfo.getReportType().equals("month"))continue; + if("leave".equalsIgnoreCase(kqReportFieldComInfo.getFieldname())&&leaveRules.size()==0)continue; + + column = new HashMap(); + column.put("title", SystemEnv.getHtmlLabelNames(kqReportFieldComInfo.getFieldlabel(), user.getLanguage())); + column.put("unit", KQReportBiz.getUnitType(kqReportFieldComInfo, user)); + column.put("dataIndex", kqReportFieldComInfo.getFieldname()); + column.put("type", kqReportFieldComInfo.getFieldname()); + column.put("key", kqReportFieldComInfo.getFieldname()); + column.put("isSystem", kqReportFieldComInfo.getIsSystem()); + mapChildColumnInfo = this.getChildColumnsInfo(kqReportFieldComInfo.getFieldname(),user); + childColumns = (List)mapChildColumnInfo.get("childColumns"); + if(childColumns.size()>0) {//跨列width取子列的width + column.put("rowSpan", 1); + column.put("width", mapChildColumnInfo.get("sumChildColumnWidth")); + column.put("children", childColumns); + }else{ + column.put("rowSpan", 3); + column.put("width", Util.getIntValue(kqReportFieldComInfo.getWidth())); + } + column.put("showDetial",kqReportFieldComInfo.getShowDetial()); + columns.add(column); + columns.addAll(this.getCascadeKeyColumnsInfo(kqReportFieldComInfo.getCascadekey(),user)); + } + + boolean isEnd = false; + Calendar cal = DateUtil.getCalendar(); + String today = DateUtil.getCurrentDate(); +// if(DateUtil.compDate(today, toDate)>0){//结束日期不大于今天 +// toDate = today; +// if(DateUtil.compDate(today, fromDate)>0){//结束日期不大于今天 +// fromDate = today; +// } +// } + + childColumns = new ArrayList<>(); + for(String date=fromDate; !isEnd;) { + if(date.equals(toDate)) isEnd = true; + column = new HashMap(); + column.put("title", DateUtil.geDayOfMonth(date)); + column.put("dataIndex", date); + column.put("key", date); + column.put("type", date); + column.put("rowSpan", 1); + column.put("width", 90); + column.put("isCalendar", 1); + childColumns.add(column); + cal.setTime(DateUtil.parseToDate(date)); + date = DateUtil.getDate(cal.getTime(), 1); + } + + column = new HashMap(); + column.put("title", SystemEnv.getHtmlLabelName(386476, user.getLanguage())); + column.put("dataIndex", "kqCalendar"); + column.put("key", "kqCalendar"); + if(childColumns.size()>0) {//跨列width取子列的width + column.put("rowSpan", 1); + column.put("width", childColumns.size()*90); + column.put("children", childColumns); + } + columns.add(column); + + + // 没有权限的人最大只支持查询本季 + Map getRealDate = new KQReportBiz().realDate(fromDate, toDate, user, "1"); + fromDate = getRealDate.get("fromDate"); + toDate = getRealDate.get("toDate"); + + String forgotBeginWorkCheck_field = " sum(b.forgotBeginWorkCheck) "; + + if(rs.getDBType().equalsIgnoreCase("oracle")) { + forgotBeginWorkCheck_field = " sum(nvl(b.forgotBeginWorkCheck,0)) "; + }else if((rs.getDBType()).equalsIgnoreCase("mysql")){ + forgotBeginWorkCheck_field = " sum(ifnull(b.forgotBeginWorkCheck,0)) "; + }else { + forgotBeginWorkCheck_field = " sum(isnull(b.forgotBeginWorkCheck,0)) "; + } + + Map definedFieldInfo = new KQFormatBiz().getDefinedField(); + String definedFieldSum = Util.null2String(definedFieldInfo.get("definedFieldSum")); + + String backFields = " (select sum(fdjbtians) as jbts from uf_kqgshsj u where u.xm = a.id and u.rq>='"+fromDate+"' and u.rq<= '"+toDate+"') as jbts,(select sum(gcyjzbts) as gzts from uf_kqgshsj u where u.xm = a.id and u.rq>='"+fromDate+"' and u.rq<= '"+toDate+"') as gzts,a.id,a.lastname,a.workcode,a.dsporder,b.resourceid,a.subcompanyid1 as subcompanyid,a.departmentid,a.jobtitle," + + " sum(b.workdays) as workdays,sum(b.workMins) as workMins,sum(b.attendancedays) as attendancedays," + + " sum(b.attendanceMins) as attendanceMins,sum(b.beLate) as beLate,sum(b.beLateMins) as beLateMins, " + + " sum(b.graveBeLate) as graveBeLate, sum(b.graveBeLateMins) as graveBeLateMins,sum(b.leaveEearly) as leaveEearly," + + " sum(b.leaveEarlyMins) as leaveEarlyMins, sum(b.graveLeaveEarly) as graveLeaveEarly, " + + " sum(b.graveLeaveEarlyMins) as graveLeaveEarlyMins,sum(b.absenteeism) as absenteeism, " + + " sum(b.signdays) as signdays,sum(b.signmins) as signmins, "+ + " sum(b.absenteeismMins) as absenteeismMins, sum(b.forgotCheck)+"+forgotBeginWorkCheck_field+" as forgotCheck "+(definedFieldSum.length()>0?","+definedFieldSum+"":""); + + if(rs.getDBType().equals("oracle")){ + backFields = "/*+ index(kq_format_total IDX_KQ_FORMAT_TOTAL_KQDATE) */ "+backFields; + } + String sqlFrom = " from hrmresource a, kq_format_total b where a.id= b.resourceid and b.kqdate >='"+fromDate+"' and b.kqdate <='"+toDate+"'"; + String sqlWhere = rightSql; + String groupBy = " group by a.id,a.lastname,a.workcode,a.dsporder,b.resourceid,a.subcompanyid1,a.departmentid,a.jobtitle "; + if(subCompanyId.length()>0){ + sqlWhere +=" and a.subcompanyid1 in("+subCompanyId+") "; + } + + if(departmentId.length()>0){ + sqlWhere +=" and a.departmentid in("+departmentId+") "; + } + + if(resourceId.length()>0){ + sqlWhere +=" and a.id in("+resourceId+") "; + } + + if(viewScope.equals("4")){//我的下属 + if(allLevel.equals("1")){//所有下属 + sqlWhere+=" and a.managerstr like '%,"+user.getUID()+",%'"; + }else{ + sqlWhere+=" and a.managerid="+user.getUID();//直接下属 + } + } + if (!"1".equals(isNoAccount)) { + sqlWhere += " and a.loginid is not null "+(rs.getDBType().equals("oracle")?"":" and a.loginid<>'' "); + } + + if(status.length()>0){ + if (!status.equals("8") && !status.equals("9")) { + sqlWhere += " and a.status = "+status+ ""; + }else if (status.equals("8")) { + sqlWhere += " and (a.status = 0 or a.status = 1 or a.status = 2 or a.status = 3) "; + } + } + + if("-1".equals(fromDate) || "-1".equals(toDate)) { + sqlWhere += " and 1=2 "; + } + sql = " select count(*) as c from ( select 1 as c "+sqlFrom+sqlWhere+groupBy+") t"; + rs.execute(sql); + if (rs.next()){ + count = rs.getInt("c"); + } + + if (count <= 0) { + pageCount = 0; + } + + pageCount = count / pageSize + ((count % pageSize > 0) ? 1 : 0); + + isHaveNext = (pageIndex + 1 <= pageCount) ? 1 : 0; + + isHavePre = (pageIndex - 1 >= 1) ? 1 : 0; + + String orderBy = " order by t.dsporder asc, t.lastname asc "; + String descOrderBy = " order by t.dsporder desc, t.lastname desc "; + + //默认排序设置 start,有性能问题,先取消,后面再看看有没有好的方式 +// String orderBySql = "select * from kq_report_order where userId=? and sort=1 order by orders"; +// rs.executeQuery(orderBySql, user.getUID()); +// if (rs.getCounts() <= 0) { +// orderBySql = "select * from kq_report_order where userId=0 and sort=1 order by orders"; +// rs.executeQuery(orderBySql); +// } +// while (rs.next()) { +// String dataIndex = rs.getString("dataIndex"); +// String ascOrDesc = rs.getString("ascOrDesc"); +// String ascOrDesc1 = (ascOrDesc.equals("")||ascOrDesc.equals("asc"))?"desc":"asc"; +// if (dataIndex.equals("organization")) { +// orderBy += ",showOrderOfDeptTree " + ascOrDesc + ",dept_id " + ascOrDesc; +// descOrderBy += ",showOrderOfDeptTree " + ascOrDesc1 + ",dept_id " + ascOrDesc1; +// } +// if (dataIndex.equalsIgnoreCase("dspOrder") || dataIndex.equalsIgnoreCase("lastName")) { +// orderBy += "," + dataIndex + " " + ascOrDesc + ",id " + ascOrDesc; +// descOrderBy += "," + dataIndex + " " + ascOrDesc1 + ",id " + ascOrDesc1; +// } else if (dataIndex.equalsIgnoreCase("deptShowOrder") || dataIndex.equalsIgnoreCase("deptName")) { +// orderBy += "," + dataIndex + " " + ascOrDesc + ",dept_id " + ascOrDesc; +// descOrderBy += "," + dataIndex + " " + ascOrDesc1 + ",dept_id " + ascOrDesc1; +// } else if (dataIndex.equalsIgnoreCase("subcomShowOrder") || dataIndex.equalsIgnoreCase("subcomName")) { +// orderBy += "," + dataIndex + " " + ascOrDesc + ",subcom_id " + ascOrDesc; +// descOrderBy += "," + dataIndex + " " + ascOrDesc1 + ",subcom_id " + ascOrDesc1; +// } +// } +// orderBy = orderBy.startsWith(",") ? orderBy.substring(1) : orderBy; +// descOrderBy = descOrderBy.startsWith(",") ? descOrderBy.substring(1) : descOrderBy; +// orderBy = orderBy.equals("") ? " t.dspOrder,t.id " : orderBy; +// descOrderBy = descOrderBy.equals("") ? " t.dspOrder,t.id " : descOrderBy; +// orderBy = "order by "+orderBy; + + sql = backFields + sqlFrom + sqlWhere + groupBy; + + if (pageIndex > 0 && pageSize > 0) { + if (rs.getDBType().equals("oracle")) { + sql = " select * from (select " + sql+") t "+orderBy; + sql = "select * from ( select row_.*, rownum rownum_ from ( " + sql + " ) row_ where rownum <= " + + (pageIndex * pageSize) + ") where rownum_ > " + ((pageIndex - 1) * pageSize); + } else if (rs.getDBType().equals("mysql")) { + sql = " select * from (select " + sql+") t "+orderBy; + sql = "select t1.* from (" + sql + ") t1 limit " + ((pageIndex - 1) * pageSize) + "," + pageSize; + } + else if (rs.getDBType().equals("postgresql")) { + sql = " select * from (select " + sql+") t "+orderBy; + sql = "select t1.* from (" + sql + ") t1 limit " +pageSize + " offset " + ((pageIndex - 1) * pageSize); + } + else { + orderBy = " order by dsporder asc, lastname asc "; + descOrderBy = " order by dsporder desc, lastname desc "; + if (pageIndex > 1) { + int topSize = pageSize; + if (pageSize * pageIndex > count) { + topSize = count - (pageSize * (pageIndex - 1)); + } + sql = " select top " + topSize + " * from ( select top " + topSize + " * from ( select top " + + (pageIndex * pageSize) + sql + orderBy+ " ) tbltemp1 " + descOrderBy + ") tbltemp2 " + orderBy; + } else { + sql = " select top " + pageSize + sql+orderBy; + } + } + } else { + sql = " select " + sql; + } + + + // #1475814-概述:满足考勤报分部部门显示及导出时显示全路径 + String fullPathMainKey = "show_full_path"; + String isShowFullPath = Util.null2String(kqSettingsComInfo.getMain_val(fullPathMainKey),"0"); + + String show_card_source = Util.null2String(kqSettingsComInfo.getMain_val("show_card_source"),"0");//是否显示打卡数据,以及打卡数据来源 + params.put("show_card_source",show_card_source); + KQOvertimeRulesBiz kqOvertimeRulesBiz = new KQOvertimeRulesBiz(); + int uintType = kqOvertimeRulesBiz.getMinimumUnit();//当前加班单位 + double hoursToDay = kqOvertimeRulesBiz.getHoursToDay();//当前天跟小时计算关系 + params.put("uintType",uintType); + params.put("hoursToDay",hoursToDay); + Map flowData = kqReportBiz.getFlowData(params,user); + + + rs.execute(sql); + while (rs.next()) { + data = new HashMap<>(); + kqReportFieldComInfo.setTofirstRow(); + String id = rs.getString("id"); + data.put("resourceId",id); + while (kqReportFieldComInfo.next()){ + if(!Util.null2String(kqReportFieldComInfo.getIsdataColumn()).equals("1"))continue; + if(!kqReportFieldComInfo.getReportType().equals("all") && !kqReportFieldComInfo.getReportType().equals("month"))continue; + if("leave".equalsIgnoreCase(kqReportFieldComInfo.getFieldname())&&leaveRules.size()==0){ + continue; + } + String fieldName = kqReportFieldComInfo.getFieldname(); + String fieldValue = ""; + if(fieldName.equals("subcompany")){ + String tmpSubcompanyId = Util.null2String(rs.getString("subcompanyid")); + if(tmpSubcompanyId.length()==0){ + tmpSubcompanyId = Util.null2String(resourceComInfo.getSubCompanyID(id)); + } + data.put("subcompanyId",tmpSubcompanyId); + + fieldValue = "1".equals(isShowFullPath) ? + SubCompanyComInfo.getSubcompanyRealPath(tmpSubcompanyId, "/", "0") : + subCompanyComInfo.getSubCompanyname(tmpSubcompanyId); + + // fieldValue = subCompanyComInfo.getSubCompanyname(tmpSubcompanyId); + }else if(fieldName.equals("department")){ + String tmpDepartmentId = Util.null2String(rs.getString("departmentid")); + if(tmpDepartmentId.length()==0){ + tmpDepartmentId = Util.null2String(resourceComInfo.getDepartmentID(id)); + } + data.put("departmentId",tmpDepartmentId); + + fieldValue = "1".equals(isShowFullPath) ? + departmentComInfo.getDepartmentRealPath(tmpDepartmentId, "/", "0") : + departmentComInfo.getDepartmentname(tmpDepartmentId); + + // fieldValue = departmentComInfo.getDepartmentname(tmpDepartmentId); + }else if(fieldName.equals("jobtitle")){ + String tmpJobtitleId = Util.null2String(rs.getString("jobtitle")); + if(tmpJobtitleId.length()==0){ + tmpJobtitleId = Util.null2String(resourceComInfo.getJobTitle(id)); + } + data.put("jobtitleId",tmpJobtitleId); + fieldValue = jobTitlesComInfo.getJobTitlesname(tmpJobtitleId); + }else if(fieldName.equals("attendanceSerial")){ + List serialIds = null; + if(attendanceSerial.length()>0){ + serialIds = Util.splitString2List(attendanceSerial,","); + } + for(int i=0;serialIds!=null&&i0) { + if(fieldValue.length() == 0){ + fieldValue="0"; + }else{ + if (kqReportFieldComInfo.getUnittype().equals("2")) { + fieldValue = KQDurationCalculatorUtil.getDurationRound(("" + (Util.getDoubleValue(fieldValue) / 60.0))); + } + } + } + } + data.put(fieldName,fieldValue); + } + + //请假 + List> allLeaveRules = kqLeaveRulesBiz.getAllLeaveRules(); + if(("1").equals(leavetype_is_on)) { + KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo(); + for (int i = allLeaveRules.size() - 1; i >= 0; i--) { + Map leaveRule = allLeaveRules.get(i); + String leaveId = Util.null2String(leaveRule.get("id")); + boolean flag = KQLeaveRulesBiz.filterSubLeaveRule(kqLeaveRulesComInfo, user, leaveId); + if (flag) { + allLeaveRules.remove(i); + } + } + } + Map leaveRule = null; + for(int i=0;allLeaveRules!=null&&i)allLeaveRules.get(i); + String flowType = Util.null2String("leaveType_"+leaveRule.get("id")); + String leaveData = Util.null2String(flowData.get(id+"|"+flowType)); + String flowLeaveBackType = Util.null2String("leavebackType_"+leaveRule.get("id")); + String leavebackData = Util.null2s(Util.null2String(flowData.get(id+"|"+flowLeaveBackType)),"0.0"); + String b_flowLeaveData = ""; + String flowLeaveData = ""; + try{ + //以防止出现精度问题 + if(leaveData.length() == 0){ + leaveData = "0.0"; + } + if(leavebackData.length() == 0){ + leavebackData = "0.0"; + } + BigDecimal b_leaveData = new BigDecimal(leaveData); + BigDecimal b_leavebackData = new BigDecimal(leavebackData); + b_flowLeaveData = b_leaveData.subtract(b_leavebackData).toString(); + if(Util.getDoubleValue(b_flowLeaveData, -1) < 0){ + b_flowLeaveData = "0.0"; + } + }catch (Exception e){ + writeLog("GetKQReportCmd:leaveData"+leaveData+":leavebackData:"+leavebackData+":"+e); + } + + //考虑下冻结的数据 + if(b_flowLeaveData.length() > 0){ + flowLeaveData = KQDurationCalculatorUtil.getDurationRound(b_flowLeaveData); + }else{ + flowLeaveData = KQDurationCalculatorUtil.getDurationRound(Util.null2String(Util.getDoubleValue(leaveData,0.0)-Util.getDoubleValue(leavebackData,0.0))); + } + data.put(flowType,flowLeaveData); + } + + Map amData = Maps.newHashMap(); + Map pmData = Maps.newHashMap(); + if(isKqReportHalfOpen) { + amData.putAll(data); + pmData.putAll(data); + } + + //入职日期 + String companystartdate = KqUtil.getCompanyStartDate(id); + data.put("companystartdate", companystartdate); + + //转正日期 + String comfirmdate = KqUtil.getComfirmDate(id); + data.put("comfirmdate", comfirmdate); + + //异动日期 + String transactiondate = KqUtil.getTransactionDate(fromDate,toDate,id); + data.put("transactiondate", transactiondate); + + //离职日期 + String terminationdate = KqUtil.getTerminationDate(id); + data.put("terminationdate", terminationdate); + + //片区 + String area = KqUtil.getArea(fromDate,toDate,id); + data.put("area", area); + + //分部 + String subcompany = KqUtil.getSubcompany(fromDate,toDate,id); + data.put("subcompany", subcompany); + + //部门 + String department = KqUtil.getDepartment(fromDate,toDate,id); + data.put("department", department); + + //岗位名称 + String positionname = KqUtil.getPosition(fromDate,toDate,id); + data.put("positionname", positionname); + + //应出勤天数 + String requiredworkdays = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getWorkDays(fromDate,toDate,id))); + data.put("requiredworkdays", requiredworkdays); + + //实际出勤天数(薪酬调整前) + String attenddaysbeforesalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getAttendDaysBeforeSalary(fromDate,toDate,id))); + data.put("attenddaysbeforesalary", attenddaysbeforesalary); + + //事假 + int leaveabsencetype = Util.getIntValue(rs.getPropValue("hrm_kqreport","leaveabsencetype")); + //病假 + int sickleavetype = Util.getIntValue(rs.getPropValue("hrm_kqreport","sickleavetype")); + //年假 + int annualleavetype = Util.getIntValue(rs.getPropValue("hrm_kqreport","annualleavetype")); + //陪产假 + int paternityleavetype = Util.getIntValue(rs.getPropValue("hrm_kqreport","paternityleavetype")); + //婚假 + int marriageleavetype = Util.getIntValue(rs.getPropValue("hrm_kqreport","marriageleavetype")); + //丧假 + int bereavementleavetype = Util.getIntValue(rs.getPropValue("hrm_kqreport","bereavementleavetype")); + //探亲假 + int homeleavetype = Util.getIntValue(rs.getPropValue("hrm_kqreport","homeleavetype")); + //哺乳假 + int breastfeedleavetype = Util.getIntValue(rs.getPropValue("hrm_kqreport","breastfeed_leave_id")); + //调休假 + int compensatoryleavetype = Util.getIntValue(rs.getPropValue("hrm_kqreport","compensatory_leave_id")); + //产假 + int maternityleavetype = Util.getIntValue(rs.getPropValue("hrm_kqreport","maternity_leave_id")); + + //事假天数(薪酬调整前) + String leaveabsencedaysbeforesalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getBeforeSalaryLeaveDays(leaveabsencetype,fromDate,toDate,id))); + data.put("leaveabsencedaysbeforesalary", leaveabsencedaysbeforesalary); + + //病假天数(薪酬调整前) + String sickleavedaysbeforesalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getBeforeSalaryLeaveDays(sickleavetype,fromDate,toDate,id))); + data.put("sickleavedaysbeforesalary", sickleavedaysbeforesalary); + + //年假(薪酬调整前) + String annualleavedaysbeforesalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getBeforeSalaryLeaveDays(annualleavetype,fromDate,toDate,id))); + data.put("annualleavedaysbeforesalary", annualleavedaysbeforesalary); + + //陪产假(薪酬调整前) + String paternityleavedaysbeforesalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getBeforeSalaryLeaveDays(paternityleavetype,fromDate,toDate,id))); + data.put("paternityleavedaysbeforesalary", paternityleavedaysbeforesalary); + + //婚假(薪酬调整前) + String marriageleavedaysbeforesalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getBeforeSalaryLeaveDays(marriageleavetype,fromDate,toDate,id))); + data.put("marriageleavedaysbeforesalary", marriageleavedaysbeforesalary); + + //丧假(薪酬调整前) + String bereavementleavedaysbeforesalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getBeforeSalaryLeaveDays(bereavementleavetype,fromDate,toDate,id))); + data.put("bereavementleavedaysbeforesalary", bereavementleavedaysbeforesalary); + + //探亲假(薪酬调整前) + String homeleavedaysbeforesalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getBeforeSalaryLeaveDays(homeleavetype,fromDate,toDate,id))); + data.put("homeleavedaysbeforesalary", homeleavedaysbeforesalary); + + //哺乳假(薪酬调整前) + String breastfeedleavedaysbeforesalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getBeforeSalaryLeaveDays(breastfeedleavetype,fromDate,toDate,id))); + data.put("breastfeedleavedaysbeforesalary", breastfeedleavedaysbeforesalary); + + //调休假(薪酬调整前) + String compensatoryleavedaysbeforesalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getBeforeSalaryLeaveDays(compensatoryleavetype,fromDate,toDate,id))); + data.put("compensatoryleavedaysbeforesalary", compensatoryleavedaysbeforesalary); + + //产假(薪酬调整前) + String maternityleavedaysbeforesalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getBeforeSalaryLeaveDays(maternityleavetype,fromDate,toDate,id))); + data.put("maternityleavedaysbeforesalary", maternityleavedaysbeforesalary); + + //旷工天数(薪酬调整前) + String absenteeismdaysbeforesalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getAbsenteeismDaysBeforeSalaryBefore(fromDate,toDate,id))); + data.put("absenteeismdaysbeforesalary", absenteeismdaysbeforesalary); + + //旷工天数(薪酬调整前)总计 + String absenteeismdayscountbeforesalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getAbsenteeismDaysCountAfterSalary(fromDate,toDate,id))); + data.put("absenteeismdayscountbeforesalary", absenteeismdayscountbeforesalary); + + //每次漏签计0.5天旷工 + String forgotcheckabsenteeismdays = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getForgotCheckAbsenteeismDaysAfter(fromDate,toDate,id))); + data.put("forgotcheckabsenteeismdays", forgotcheckabsenteeismdays); + + //严重迟到/早退每次计0.5天旷工 + String gravebelateleaveearlydays = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getGraveBeLateLeaveEarlyDaysAfter(fromDate,toDate,id))); + data.put("gravebelateleaveearlydays", gravebelateleaveearlydays); + + //实际出勤天数(薪酬调整后) + String attendDaysAfterSalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getAttendDaysAfterSalary(fromDate,toDate,id))); + data.put("attenddaysaftersalary", attendDaysAfterSalary); + + //事假天数(薪酬调整后) + String leaveabsencedaysaftersalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getAfterSalaryLeaveDays(leaveabsencetype,fromDate,toDate,id))); + data.put("leaveabsencedaysaftersalary", leaveabsencedaysaftersalary); + + //病假天数(薪酬调整后) + String sickleavedaysaftersalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getAfterSalaryLeaveDays(sickleavetype,fromDate,toDate,id))); + data.put("sickleavedaysaftersalary", sickleavedaysaftersalary); + + //年假(薪酬调整后) + String annualleavedaysaftersalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getAfterSalaryLeaveDays(annualleavetype,fromDate,toDate,id))); + data.put("annualleavedaysaftersalary", annualleavedaysaftersalary); + + //陪产假(薪酬调整后) + String paternityleavedaysaftersalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getAfterSalaryLeaveDays(paternityleavetype,fromDate,toDate,id))); + data.put("paternityleavedaysaftersalary", paternityleavedaysaftersalary); + + //婚假(薪酬调整后) + String marriageleavedaysaftersalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getAfterSalaryLeaveDays(marriageleavetype,fromDate,toDate,id))); + data.put("marriageleavedaysaftersalary", marriageleavedaysaftersalary); + + //丧假(薪酬调整后) + String bereavementleavedaysaftersalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getAfterSalaryLeaveDays(bereavementleavetype,fromDate,toDate,id))); + data.put("bereavementleavedaysaftersalary", bereavementleavedaysaftersalary); + + //探亲假(薪酬调整后) + String homeleavedaysaftersalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getAfterSalaryLeaveDays(homeleavetype,fromDate,toDate,id))); + data.put("homeleavedaysaftersalary", homeleavedaysaftersalary); + + //哺乳假(薪酬调整后) + String breastfeedleavedaysaftersalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getAfterSalaryLeaveDays(breastfeedleavetype,fromDate,toDate,id))); + data.put("breastfeedleavedaysaftersalary", breastfeedleavedaysaftersalary); + + //调休假(薪酬调整后) + String compensatoryleavedaysaftersalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getAfterSalaryLeaveDays(compensatoryleavetype,fromDate,toDate,id))); + data.put("compensatoryleavedaysaftersalary", compensatoryleavedaysaftersalary); + + //产假(薪酬调整后) + String maternityleavedaysaftersalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getAfterSalaryLeaveDays(maternityleavetype,fromDate,toDate,id))); + data.put("maternityleavedaysaftersalary", maternityleavedaysaftersalary); + + //旷工天数(薪酬调整后) + String absenteeismdaysaftersalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getAbsenteeismDaysAfterSalaryAfter(fromDate,toDate,id))); + data.put("absenteeismdaysaftersalary", absenteeismdaysaftersalary); + + //旷工天数(薪酬调整后)总计 +// String absenteeismdayscountaftersalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getAbsenteeismDaysCountAfterSalary(fromDate,toDate,id))); +// data.put("absenteeismdayscountaftersalary", absenteeismdayscountaftersalary); + + //旷工次数 + String absenteeismdays = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getAbsenteeismDays(fromDate,toDate,id))); + data.put("absenteeismdays", absenteeismdays); + + //旷工次数(薪酬用) + String absenteeNumsSalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getAbsenteeNumsSalary(fromDate,toDate,id))); + data.put("absenteeNumsSalary", absenteeNumsSalary); + + //产假天数(薪酬用) + String maternityLeaveDaySalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getMaternityLeaveDaySalary(fromDate,toDate,id))); + data.put("maternityLeaveDaySalary", maternityLeaveDaySalary); + + //工伤假天数(薪酬用) + String injuryLeaveDaySalary = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getInjuryLeaveDaySalary(fromDate,toDate,id))); + data.put("injuryLeaveDaySalary", injuryLeaveDaySalary); + + Map detialDatas = kqReportBiz.getDetialDatas(id,fromDate,toDate,user,flowData,false,uintType,show_card_source); +// new KQLog().info("id:"+id+":detialDatas:"+detialDatas); + String user_endDate = Util.null2String(resourceComInfo.getEndDate(id)); + String user_status = Util.null2String(resourceComInfo.getStatus(id)); + String begindate = Util.null2String(resourceComInfo.getCreatedate(id)).trim(); + String companyStartDate = Util.null2String(resourceComInfo.getCompanyStartDate(id)).trim(); + if(companyStartDate.length()!=10){ + companyStartDate = ""; + } + if(companyStartDate.length()>0 && companyStartDate.indexOf("-")>0){ + begindate=companyStartDate; + } + isEnd = false; + for(String date=fromDate; !isEnd;) { + if(date.equals(toDate)) isEnd = true; + if(DateUtil.compDate(today, date)>0){ + if(isKqReportHalfOpen) { + amData.put(date,""); + pmData.put(date,""); + } else { + data.put(date,""); + } + }else{ + if(!(user_status.equals("0")||user_status.equals("1")||user_status.equals("2")||user_status.equals("3"))){ + //其他状态 + if(user_endDate.length()>0 && date.compareTo(user_endDate)>0){//人员合同结束日期之后 + if(isKqReportHalfOpen) { + amData.put(date,""); + pmData.put(date,""); + } else { + data.put(date,""); + } + cal.setTime(DateUtil.parseToDate(date)); + date = DateUtil.getDate(cal.getTime(), 1); + continue; + } + } + if(begindate.length()>0 && date.compareTo(begindate)<0 ){//人员入职日期前无需计算考勤,如果没有入职日期,已创建日期为准 + if(isKqReportHalfOpen) { + amData.put(date,""); + pmData.put(date,""); + } else { + data.put(date,""); + } + cal.setTime(DateUtil.parseToDate(date)); + date = DateUtil.getDate(cal.getTime(), 1); + continue; + } + + if(isKqReportHalfOpen) { + Map tmpData = Maps.newHashMap(); + Object tmpValue = null; + if(detialDatas.get(id+"|"+date)==null){ + tmpValue = SystemEnv.getHtmlLabelName(26593, user.getLanguage()); + data.put(date,tmpValue); + amData.put(date,tmpValue); + pmData.put(date,tmpValue); + }else { + tmpData = (Map) detialDatas.get(id+"|"+date); + data.put(date,tmpData); + if(tmpData != null){ + tmpData.put("text",Util.null2String(tmpData.get("textAM"))); + + Map amTmpData = Maps.newHashMap(); + amTmpData.put("text",Util.null2String(tmpData.get("textAM"))); + Map pmTmpData = Maps.newHashMap(); + pmTmpData.put("text",Util.null2String(tmpData.get("textPM"))); + amData.put(date,amTmpData); + pmData.put(date,pmTmpData); + } + } + } else { + data.put(date,detialDatas.get(id+"|"+date)==null?SystemEnv.getHtmlLabelName(26593, user.getLanguage()):detialDatas.get(id+"|"+date)); + } + } + cal.setTime(DateUtil.parseToDate(date)); + date = DateUtil.getDate(cal.getTime(), 1); + } + if(isKqReportHalfOpen) { + amData.put("rowSpan", "2"); + pmData.put("rowSpan", "0"); + datas.add(amData); + datas.add(pmData); + } else { + datas.add(data); + } + } + + List lsHolidays = KQHolidaySetBiz.getHolidaySetListByScope(""+user.getUID(),fromDate,toDate); + retmap.put("holidays", lsHolidays); + + retmap.put("columns",columns); + retmap.put("datas",datas); + if(isKqReportHalfOpen) { + retmap.put("pagesize", pageSize*2); + retmap.put("count", count*2); + } else { + retmap.put("pagesize", pageSize); + retmap.put("count", count); + } + retmap.put("pageindex", pageIndex); + retmap.put("pagecount", pageCount); + retmap.put("ishavepre", isHavePre); + retmap.put("ishavenext", isHaveNext); + retmap.put("isKqReportHalfOpen", isKqReportHalfOpen); + }catch (Exception e){ + writeLog(e); + } + return retmap; + } + + private Map getChildColumnsInfo(String parentid, User user){ + Map returnMap = new HashMap<>(); + List lsChildColumns = new ArrayList<>(); + Map column = null; + int sumChildColumnWidth = 0; + KQSettingsComInfo kqSettingsComInfo = new KQSettingsComInfo(); + String leavetype_is_on = Util.null2String(kqSettingsComInfo.getMain_val("leavetype_is_on"),"0"); + if(parentid.equals("attendanceSerial")){//考勤班次 + KQShiftManagementComInfo kqShiftManagementComInfo = new KQShiftManagementComInfo(); + JSONObject jsonObj = JSON.parseObject(Util.null2String(params.get("data"))); + List serialIds = null; + if(Util.null2String(jsonObj.get("attendanceSerial")).length()>0){ + serialIds = Util.splitString2List(Util.null2String(jsonObj.get("attendanceSerial")),","); + } + for(int i=0;serialIds!=null&&i> leaveRules = kqLeaveRulesBiz.getAllLeaveRules(); + if (("1").equals(leavetype_is_on)) { + KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo(); + for (int i = leaveRules.size() - 1; i >= 0; i--) { + Map leaveRule = leaveRules.get(i); + String leaveId = Util.null2String(leaveRule.get("id")); + boolean flag = kqLeaveRulesBiz.filterSubLeaveRule(kqLeaveRulesComInfo, user, leaveId); + if (flag) { + leaveRules.remove(i); + } + } + } + for(int i=0;leaveRules!=null&&i leaveRule = leaveRules.get(i); + String id = "leaveType_"+Util.null2String(leaveRule.get("id")); + String name = Util.null2String(leaveRule.get("name")); + String unitType = Util.null2String(leaveRule.get("unitType")); + column = new HashMap(); + column.put("title", name); + column.put("unit", KQUnitBiz.isLeaveHour(unitType) ?SystemEnv.getHtmlLabelName(391, user.getLanguage()):SystemEnv.getHtmlLabelName(1925, user.getLanguage())); + column.put("width", 65); + column.put("dataIndex", id); + column.put("key", id); + column.put("rowSpan", 2); + column.put("colSpan", 1); + column.put("showDetial","1"); + sumChildColumnWidth+=65; + lsChildColumns.add(column); + } + }else if(parentid.equals("overtime")){ + String[] overtimeChild = {"overtime_nonleave","overtime_4leave","overtimeTotal"}; + for(int i=0;i0){ + if(unitType.equals("1")){ + unitTypeName=SystemEnv.getHtmlLabelName(1925, user.getLanguage()); + }else if(unitType.equals("2")){ + unitTypeName=SystemEnv.getHtmlLabelName(391, user.getLanguage()); + }else if(unitType.equals("3")){ + unitTypeName=SystemEnv.getHtmlLabelName(18083, user.getLanguage()); + } + } + column.put("unit", unitTypeName); + } + column.put("title", SystemEnv.getHtmlLabelNames(fieldlabel, user.getLanguage())); + column.put("dataIndex", id); + column.put("key", id); + column.put("rowSpan", 1); + Map mapChildColumnInfo = getChildColumnsInfo(id, user); + int childWidth = 65; + List childColumns = (List)mapChildColumnInfo.get("childColumns"); + if(childColumns.size()>0) {//跨列width取子列的width + column.put("children", childColumns); + childWidth = Util.getIntValue(Util.null2String(mapChildColumnInfo.get("sumChildColumnWidth")),65); + } + column.put("width", childWidth+""); + sumChildColumnWidth+=childWidth; + lsChildColumns.add(column); + } + }else{ + KQReportFieldComInfo kqReportFieldComInfo = new KQReportFieldComInfo(); + while (kqReportFieldComInfo.next()){ + if(kqReportFieldComInfo.getParentid().equals(parentid)) { + if(!kqReportFieldComInfo.getReportType().equals("month"))continue; + column = new HashMap(); + column.put("title", SystemEnv.getHtmlLabelNames(kqReportFieldComInfo.getFieldlabel(), user.getLanguage())); + column.put("unit", KQReportBiz.getUnitType(kqReportFieldComInfo, user)); + column.put("width", Util.getIntValue(kqReportFieldComInfo.getWidth())); + column.put("dataIndex", kqReportFieldComInfo.getFieldname()); + column.put("key", kqReportFieldComInfo.getFieldname()); + column.put("rowSpan", 1); + column.put("colSpan", 1); + column.put("showDetial",kqReportFieldComInfo.getShowDetial()); + sumChildColumnWidth+=Util.getIntValue(kqReportFieldComInfo.getWidth()); + lsChildColumns.add(column); + } + } + } + returnMap.put("childColumns",lsChildColumns); + returnMap.put("sumChildColumnWidth",sumChildColumnWidth); + return returnMap; + } + + private List getCascadeKeyColumnsInfo(String cascadeKey, User user){ + List lsChildColumns = new ArrayList<>(); + if(Util.null2String(cascadeKey).length()==0){ + return lsChildColumns; + } + Map column = null; + List lsCascadeKey = Util.splitString2List(cascadeKey,","); + KQReportFieldComInfo kqReportFieldComInfo = new KQReportFieldComInfo(); + for(int i=0;i= ? and jbksrq >= ? and sqr = ?"; + RecordSet rs = new RecordSet(); + rs.executeQuery(sql,fromDate, toDate, userid); + + while (rs.next()) { + String workdate = rs.getString("jbksrq"); + boolean workDay = kqWorkTime.isWorkDay(userid, workdate); + boolean isHoliday = KQHolidaySetBiz.isHoliday(userid,workdate); + double dxsc = rs.getDouble("dxsc"); + dxsc = (double)Math.round(dxsc*100)/100; + BigDecimal bigDecimalDxsc = new BigDecimal(Double.toString(dxsc)); + if(workDay){ + if("1".equals(leaveType)){ + bigDecimal.subtract(bigDecimalDxsc); + } + }else if(isHoliday ){ + if("2".equals(leaveType)){ + bigDecimal.subtract(bigDecimalDxsc); + } + + }else { + if("3".equals(leaveType)){ + bigDecimal.subtract(bigDecimalDxsc); + } + + } + } + return bigDecimal.doubleValue(); + } + + @Override + public BizLogContext getLogContext() { + return null; + } + + public static void main(String[] args) { + String s1 = String.format("%.2f", 1.2); + System.out.println(s1); + + } + +} diff --git a/领悦二开new/src/com/engine/kq/entity/KQBalanceOfLeaveEntity.java b/领悦二开new/src/com/engine/kq/entity/KQBalanceOfLeaveEntity.java new file mode 100644 index 0000000..3d6144d --- /dev/null +++ b/领悦二开new/src/com/engine/kq/entity/KQBalanceOfLeaveEntity.java @@ -0,0 +1,234 @@ +package com.engine.kq.entity; + +/** + * 假期余额 + */ +public class KQBalanceOfLeaveEntity { + /** + * 主键ID + */ + int id; + /** + * 假期规则ID + */ + int leaveRulesId; + /** + * 人员ID + */ + int resourceId; + /** + * 所属年份 + * 数据格式:yyyy + */ + String belongYear; + /** + * 假期余额基数 + * 混合模式下为法定年假的基数 + */ + double baseAmount = 0.00; + /** + * 已用的假期余额 + * 混合模式下为已用的法定年假的数量 + */ + double usedAmount = 0.00; + /** + * 额外的假期余额 + * 混合模式下为额外的法定年假的数量 + */ + double extraAmount = 0.00; + /** + * 仅用于混合模式下的福利年假的基数 + */ + double baseAmount2 = 0.00; + /** + * 仅用于混合模式下的已用的福利年假的数量 + */ + double usedAmount2 = 0.00; + /** + * 仅用于混合模式下的额外的福利年假的数量 + */ + double extraAmount2 = 0.00; + /** + * 是有有效:0-有效、1-无效 + */ + int status; + /** + * 失效日期 + */ + String expirationDate; + /** + * 生效日期 + */ + String effectiveDate; + /** + * 最小请假单位 + */ + int minimumUnit; + + public KQBalanceOfLeaveEntity() { + } + + public KQBalanceOfLeaveEntity(int id, int leaveRulesId, int resourceId, String belongYear, double baseAmount, double usedAmount, double extraAmount, double baseAmount2, double usedAmount2, double extraAmount2, int status, String expirationDate) { + this.id = id; + this.leaveRulesId = leaveRulesId; + this.resourceId = resourceId; + this.belongYear = belongYear; + this.baseAmount = baseAmount; + this.usedAmount = usedAmount; + this.extraAmount = extraAmount; + this.baseAmount2 = baseAmount2; + this.usedAmount2 = usedAmount2; + this.extraAmount2 = extraAmount2; + this.status = status; + this.expirationDate = expirationDate; + } + public KQBalanceOfLeaveEntity(int id, int leaveRulesId, int resourceId, String belongYear, double baseAmount, double usedAmount, double extraAmount, double baseAmount2, double usedAmount2, double extraAmount2, int status, String expirationDate ,String effectiveDate) { + this.id = id; + this.leaveRulesId = leaveRulesId; + this.resourceId = resourceId; + this.belongYear = belongYear; + this.baseAmount = baseAmount; + this.usedAmount = usedAmount; + this.extraAmount = extraAmount; + this.baseAmount2 = baseAmount2; + this.usedAmount2 = usedAmount2; + this.extraAmount2 = extraAmount2; + this.status = status; + this.expirationDate = expirationDate; + this.effectiveDate = effectiveDate; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public int getLeaveRulesId() { + return leaveRulesId; + } + + public void setLeaveRulesId(int leaveRulesId) { + this.leaveRulesId = leaveRulesId; + } + + public int getResourceId() { + return resourceId; + } + + public void setResourceId(int resourceId) { + this.resourceId = resourceId; + } + + public String getBelongYear() { + return belongYear; + } + + public void setBelongYear(String belongYear) { + this.belongYear = belongYear; + } + + public double getBaseAmount() { + return baseAmount; + } + + public void setBaseAmount(double baseAmount) { + this.baseAmount = baseAmount; + } + + public double getUsedAmount() { + return usedAmount; + } + + public void setUsedAmount(double usedAmount) { + this.usedAmount = usedAmount; + } + + public double getExtraAmount() { + return extraAmount; + } + + public void setExtraAmount(double extraAmount) { + this.extraAmount = extraAmount; + } + + public double getBaseAmount2() { + return baseAmount2; + } + + public void setBaseAmount2(double baseAmount2) { + this.baseAmount2 = baseAmount2; + } + + public double getUsedAmount2() { + return usedAmount2; + } + + public void setUsedAmount2(double usedAmount2) { + this.usedAmount2 = usedAmount2; + } + + public double getExtraAmount2() { + return extraAmount2; + } + + public void setExtraAmount2(double extraAmount2) { + this.extraAmount2 = extraAmount2; + } + + public int getStatus() { + return status; + } + + public void setStatus(int status) { + this.status = status; + } + + public String getExpirationDate() { + return expirationDate; + } + + public void setExpirationDate(String expirationDate) { + this.expirationDate = expirationDate; + } + + public String getEffectiveDate() { + return effectiveDate; + } + + public void setEffectiveDate(String effectiveDate) { + this.effectiveDate = effectiveDate; + } + + public int getMinimumUnit() { + return minimumUnit; + } + + public void setMinimumUnit(int minimumUnit) { + this.minimumUnit = minimumUnit; + } + + public boolean equals(KQBalanceOfLeaveEntity entity) { + if (this.baseAmount != entity.getBaseAmount() + || this.extraAmount != entity.getExtraAmount() + || this.usedAmount != entity.getUsedAmount() + || this.baseAmount2 != entity.getBaseAmount2() + || this.extraAmount2 != entity.getExtraAmount2() + || this.usedAmount2 != entity.getUsedAmount2()) { + return false; + } else { + return true; + } + } + + public boolean equalsByBaseAmount(KQBalanceOfLeaveEntity entity) { + if (this.baseAmount != entity.getBaseAmount() + || this.baseAmount2 != entity.getBaseAmount2()) { + return false; + } else { + return true; + } + } +} diff --git a/领悦二开new/src/com/engine/kq/entity/KQGroupEntity.java b/领悦二开new/src/com/engine/kq/entity/KQGroupEntity.java new file mode 100644 index 0000000..605255e --- /dev/null +++ b/领悦二开new/src/com/engine/kq/entity/KQGroupEntity.java @@ -0,0 +1,235 @@ +package com.engine.kq.entity; + +public class KQGroupEntity { + private String id; + private String groupname; + private String excludeid; + private String excludecount; + private String subcompanyid; + private String kqtype; + private String serialids; + private String weekday; + private String signstart; + private String workhour; + private String isdelete; + private String signintype; + private String ipscope; + private String locationcheck; + private String locationcheckscope; + private String wificheck; + private String outsidesign; + + private String outsignapprove; + private String validity; + private String validityfromdate; + private String validityenddate; + private String locationfacecheck; + private String locationshowaddress; + private String wififacecheck; + private String calmethod; + private String abnormalremind; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getGroupname() { + return groupname; + } + + public void setGroupname(String groupname) { + this.groupname = groupname; + } + + public String getExcludeid() { + return excludeid; + } + + public void setExcludeid(String excludeid) { + this.excludeid = excludeid; + } + + public String getExcludecount() { + return excludecount; + } + + public void setExcludecount(String excludecount) { + this.excludecount = excludecount; + } + + public String getSubcompanyid() { + return subcompanyid; + } + + public void setSubcompanyid(String subcompanyid) { + this.subcompanyid = subcompanyid; + } + + public String getKqtype() { + return kqtype; + } + + public void setKqtype(String kqtype) { + this.kqtype = kqtype; + } + + public String getSerialids() { + return serialids; + } + + public void setSerialids(String serialids) { + this.serialids = serialids; + } + + public String getWeekday() { + return weekday; + } + + public void setWeekday(String weekday) { + this.weekday = weekday; + } + + public String getSignstart() { + return signstart; + } + + public void setSignstart(String signstart) { + this.signstart = signstart; + } + + public String getWorkhour() { + return workhour; + } + + public void setWorkhour(String workhour) { + this.workhour = workhour; + } + + public String getIsdelete() { + return isdelete; + } + + public void setIsdelete(String isdelete) { + this.isdelete = isdelete; + } + + public String getSignintype() { + return signintype; + } + + public void setSignintype(String signintype) { + this.signintype = signintype; + } + + public String getIpscope() { + return ipscope; + } + + public void setIpscope(String ipscope) { + this.ipscope = ipscope; + } + + public String getLocationcheck() { + return locationcheck; + } + + public void setLocationcheck(String locationcheck) { + this.locationcheck = locationcheck; + } + + public String getLocationcheckscope() { + return locationcheckscope; + } + + public void setLocationcheckscope(String locationcheckscope) { + this.locationcheckscope = locationcheckscope; + } + + public String getOutsidesign() { + return outsidesign; + } + + public String getOutsignapprove() {return outsignapprove;} + + public String getValidity() { + return validity; + } + + public void setValidity(String validity) { + this.validity = validity; + } + + public String getValidityfromdate() { + return validityfromdate; + } + + public void setValidityfromdate(String validityfromdate) { + this.validityfromdate = validityfromdate; + } + + public String getValidityenddate() { + return validityenddate; + } + + public void setValidityenddate(String validityenddate) { + this.validityenddate = validityenddate; + } + + public void setOutsidesign(String outsidesign) {this.outsidesign = outsidesign;} + public void setOutsignapprove(String outsignapprove) { + this.outsignapprove = outsignapprove; + } + + public String getWificheck() { + return wificheck; + } + + public void setWificheck(String wificheck) { + this.wificheck = wificheck; + } + + public String getLocationfacecheck() { + return locationfacecheck; + } + + public void setLocationfacecheck(String locationfacecheck) { + this.locationfacecheck = locationfacecheck; + } + + public String getLocationshowaddress() { + return locationshowaddress; + } + + public void setLocationshowaddress(String locationshowaddress) { + this.locationshowaddress = locationshowaddress; + } + + public String getWififacecheck() { + return wififacecheck; + } + + public void setWififacecheck(String wififacecheck) { + this.wififacecheck = wififacecheck; + } + + public String getCalmethod() { + return calmethod; + } + + public void setCalmethod(String calmethod) { + this.calmethod = calmethod; + } + + public String getAbnormalremind() { + return this.abnormalremind; + } + + public void setAbnormalremind( String abnormalremind) { + this.abnormalremind = abnormalremind; + } + +} diff --git a/领悦二开new/src/com/engine/kq/entity/KQOvertimeRulesDetailEntity.java b/领悦二开new/src/com/engine/kq/entity/KQOvertimeRulesDetailEntity.java new file mode 100644 index 0000000..0437b68 --- /dev/null +++ b/领悦二开new/src/com/engine/kq/entity/KQOvertimeRulesDetailEntity.java @@ -0,0 +1,253 @@ +package com.engine.kq.entity; + +/** + * 加班规则明细 + */ +public class KQOvertimeRulesDetailEntity { + /** + * 加班规则明细表的ID + */ + int id; + /** + * 加班规则主表的ID + */ + int ruleId; + /** + * 日期类型:1-节假日、2-工作日、3-休息日 + */ + int dayType; + /** + * 是否允许加班:0-不允许、1-允许 + */ + int overtimeEnable = 0; + /** + * 加班计算方式: + * 1-需审批,以审批单为准 + * 2-需审批,以打卡为准,但是不能超过审批时长 + * 3-无需审批,根据打卡时间计算加班时长 + * 4-需审批,打卡和流程均统计,取两者的交集 + */ + int computingMode = -1; + /** + * 加班起算时间 + */ + int startTime = -1; + /** + * 最小加班时长 + */ + int minimumLen = -1; + + int maxmumLen = -1; + /** + * 是否允许加班转调休:0-不允许、1-允许 + */ + int paidLeaveEnable = 0; + /** + * 加班时长转调休时长的比例中的加班时长 + */ + double lenOfOvertime = -1; + /** + * 加班时长转调休时长的比例中的调休时长 + */ + double lenOfLeave = -1; + + /** + * 是否排除休息时间 + */ + int hasRestTime = 0; + /** + * 上班前 加班起算时间 + */ + int before_startTime = 0; + + /** + * 是否开启加班归属临界点 + */ + int has_cut_point = 0; + + /** + * 是否开启午休时间算加班 + */ + int isovertimecal=0; + /** + * 加班归属 临界点 + */ + String cut_point = ""; + /** + * 加班补偿方式 1-默认加班补偿规则、2-根据员工在加班流程上选择的加班补偿类型进行补偿两种 + */ + int paidLeaveEnableType = 1; + /** + * 默认加班补偿方式 里转调休的方式: 1-按加班时长比例转调休时长、2-按加班时长范围设置转调休时长、3-按加班的时间段设置转调休时长 + */ + int paidLeaveEnableDefaultType = 1; + /** + * 根据员工在加班流程上选择的加班补偿类型进行补偿 里转调休的方式: 1-按加班时长比例转调休时长、2-按加班时长范围设置转调休时长、3-按加班的时间段设置转调休时长 + */ + int paidLeaveEnableFlowType = 1; + /** + * 排除休息时间: 1-设置休息时间、2-根据加班时长扣除 + */ + int restTimeType = 1; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public int getRuleId() { + return ruleId; + } + + public void setRuleId(int ruleId) { + this.ruleId = ruleId; + } + + public int getDayType() { + return dayType; + } + + public void setDayType(int dayType) { + this.dayType = dayType; + } + + public int getOvertimeEnable() { + return overtimeEnable; + } + + public void setOvertimeEnable(int overtimeEnable) { + this.overtimeEnable = overtimeEnable; + } + + public int getComputingMode() { + return computingMode; + } + + public void setComputingMode(int computingMode) { + this.computingMode = computingMode; + } + + public int getStartTime() { + return startTime; + } + + public void setStartTime(int startTime) { + this.startTime = startTime; + } + + public int getMinimumLen() { + return minimumLen; + } + + public void setMinimumLen(int minimumLen) { + this.minimumLen = minimumLen; + } + + + public int getMaxmumLen() { + return maxmumLen; + } + + public void setMaxmumLen(int maxmumLen) { + this.maxmumLen = maxmumLen; + } + + public int getPaidLeaveEnable() { + return paidLeaveEnable; + } + + public void setPaidLeaveEnable(int paidLeaveEnable) { + this.paidLeaveEnable = paidLeaveEnable; + } + + public double getLenOfOvertime() { + return lenOfOvertime; + } + + public void setLenOfOvertime(double lenOfOvertime) { + this.lenOfOvertime = lenOfOvertime; + } + + public double getLenOfLeave() { + return lenOfLeave; + } + + public void setLenOfLeave(double lenOfLeave) { + this.lenOfLeave = lenOfLeave; + } + + public int getHasRestTime() { + return hasRestTime; + } + + public void setHasRestTime(int hasRestTime) { + this.hasRestTime = hasRestTime; + } + + public int getBefore_startTime() { + return before_startTime; + } + + public void setBefore_startTime(int before_startTime) { + this.before_startTime = before_startTime; + } + + public String getCut_point() { + return cut_point; + } + + public void setCut_point(String cut_point) { + this.cut_point = cut_point; + } + + public int getHas_cut_point() { + return has_cut_point; + } + + public void setHas_cut_point(int has_cut_point) { + this.has_cut_point = has_cut_point; + } + + public int getIsOvertimeCal() { + return isovertimecal; + } + + public void setIsOvertimeCal(int isovertimecal) { + this.isovertimecal = isovertimecal; + } + + public int getPaidLeaveEnableType() { + return paidLeaveEnableType; + } + + public void setPaidLeaveEnableType(int paidLeaveEnableType) { + this.paidLeaveEnableType = paidLeaveEnableType; + } + + public int getPaidLeaveEnableDefaultType() { + return paidLeaveEnableDefaultType; + } + + public void setPaidLeaveEnableDefaultType(int paidLeaveEnableDefaultType) { + this.paidLeaveEnableDefaultType = paidLeaveEnableDefaultType; + } + + public int getPaidLeaveEnableFlowType() { + return paidLeaveEnableFlowType; + } + + public void setPaidLeaveEnableFlowType(int paidLeaveEnableFlowType) { + this.paidLeaveEnableFlowType = paidLeaveEnableFlowType; + } + + public int getRestTimeType() { + return restTimeType; + } + + public void setRestTimeType(int restTimeType) { + this.restTimeType = restTimeType; + } +} diff --git a/领悦二开new/src/com/engine/kq/entity/KQScheduleSignEntity.java b/领悦二开new/src/com/engine/kq/entity/KQScheduleSignEntity.java new file mode 100644 index 0000000..f535f89 --- /dev/null +++ b/领悦二开new/src/com/engine/kq/entity/KQScheduleSignEntity.java @@ -0,0 +1,107 @@ +package com.engine.kq.entity; + +/** + * 考勤同步实体 + */ +public class KQScheduleSignEntity { + String loginid = ""; + String workcode = ""; + String lastname = ""; + String signdate = ""; + String signtime = ""; + String clientaddress = ""; + String longitude = ""; + String latitude = ""; + String createdate = ""; + + public String getLoginid() { + return loginid; + } + + public void setLoginid(String loginid) { + this.loginid = loginid; + } + + public String getWorkcode() { + return workcode; + } + + public void setWorkcode(String workcode) { + this.workcode = workcode; + } + + public String getLastname() { + return lastname; + } + + public void setLastname(String lastname) { + this.lastname = lastname; + } + + public String getSigndate() { + return signdate; + } + + public void setSigndate(String signdate) { + this.signdate = signdate; + } + + public String getSigntime() { + return signtime; + } + + public void setSigntime(String signtime) { + this.signtime = signtime; + } + + public String getClientaddress() { + return clientaddress; + } + + public void setClientaddress(String clientaddress) { + this.clientaddress = clientaddress; + } + + public String getLongitude() { + return longitude; + } + + public void setLongitude(String longitude) { + this.longitude = longitude; + } + + public String getLatitude() { + return latitude; + } + + public void setLatitude(String latitude) { + this.latitude = latitude; + } + + public String getAddr() { + return addr; + } + + public void setAddr(String addr) { + this.addr = addr; + } + + public String getMemo() { + return memo; + } + + public void setMemo(String memo) { + this.memo = memo; + } + + public String getCreatedate() { + return createdate; + } + + public void setCreatedate(String createdate) { + this.createdate = createdate; + } + + String addr = ""; + String memo = ""; +} diff --git a/领悦二开new/src/com/engine/kq/entity/KQShiftRuleEntity.java b/领悦二开new/src/com/engine/kq/entity/KQShiftRuleEntity.java new file mode 100644 index 0000000..6efc3a4 --- /dev/null +++ b/领悦二开new/src/com/engine/kq/entity/KQShiftRuleEntity.java @@ -0,0 +1,189 @@ +package com.engine.kq.entity; + +/** + * 考勤报表明细实体类 + */ +public class KQShiftRuleEntity { + private String userId = ""; + private String kqDate = ""; + private int belatemins = 0; + private int gravebelatemins = 0; + private int leaveearlymins = 0; + private int graveleaveearlymins = 0; + private int absenteeismmins = 0; + private int forgotcheckmins = 0; + private int forgotBeginWorkCheckMins = 0;//上班漏签 + private int earlyInMins = 0;//早到分钟数 + private int lateOutMins = 0;//晚走分钟数 + private String nosign_is_absent = "1"; + private String nosign_ishandle = "0"; + private String signInTime; + private String signOutTime; + private String early_one_mins; + //上午旷工 + private boolean isAMAbsent = false; + //下午旷工 + private boolean isPMAbsent = false; + private int on_absenteeismMins; + private int off_absenteeismMins; + + public int getForgotBeginWorkCheckMins() { + return forgotBeginWorkCheckMins; + } + + public void setForgotBeginWorkCheckMins(int forgotBeginWorkCheckMins) { + this.forgotBeginWorkCheckMins = forgotBeginWorkCheckMins; + } + + public int getBelatemins() { + return belatemins; + } + + public void setBelatemins(int belatemins) { + this.belatemins = belatemins; + } + + public int getGravebelatemins() { + return gravebelatemins; + } + + public void setGravebelatemins(int gravebelatemins) { + this.gravebelatemins = gravebelatemins; + } + + public int getLeaveearlymins() { + return leaveearlymins; + } + + public void setLeaveearlymins(int leaveearlymins) { + this.leaveearlymins = leaveearlymins; + } + + public int getGraveleaveearlymins() { + return graveleaveearlymins; + } + + public void setGraveleaveearlymins(int graveleaveearlymins) { + this.graveleaveearlymins = graveleaveearlymins; + } + + public int getAbsenteeismmins() { + return absenteeismmins; + } + + public void setAbsenteeismmins(int absenteeismmins) { + this.absenteeismmins = absenteeismmins; + } + + public int getForgotcheckmins() { + return forgotcheckmins; + } + + public void setForgotcheckmins(int forgotcheckmins) { + this.forgotcheckmins = forgotcheckmins; + } + + public int getEarlyInMins() { + return earlyInMins; + } + + public void setEarlyInMins(int earlyInMins) { + this.earlyInMins = earlyInMins; + } + + public int getLateOutMins() { + return lateOutMins; + } + + public void setLateOutMins(int lateOutMins) { + this.lateOutMins = lateOutMins; + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public String getKqDate() { + return kqDate; + } + + public void setKqDate(String kqDate) { + this.kqDate = kqDate; + } + + public String getNosign_is_absent() { + return nosign_is_absent; + } + + public void setNosign_is_absent(String nosign_is_absent) { + this.nosign_is_absent = nosign_is_absent; + } + + public String getNosign_ishandle() { + return nosign_ishandle; + } + + public void setNosign_ishandle(String nosign_ishandle) { + this.nosign_ishandle = nosign_ishandle; + } + + public String getSignInTime() { + return signInTime; + } + + public void setSignInTime(String signInTime) { + this.signInTime = signInTime; + } + + public String getSignOutTime() { + return signOutTime; + } + + public void setSignOutTime(String signOutTime) { + this.signOutTime = signOutTime; + } + + public String getEarly_one_mins() { + return early_one_mins; + } + + public void setEarly_one_mins(String early_one_mins) { + this.early_one_mins = early_one_mins; + } + + public boolean isAMAbsent() { + return isAMAbsent; + } + + public void setAMAbsent(boolean AMAbsent) { + isAMAbsent = AMAbsent; + } + + public boolean isPMAbsent() { + return isPMAbsent; + } + + public void setPMAbsent(boolean PMAbsent) { + isPMAbsent = PMAbsent; + } + + public int getOn_absenteeismMins() { + return on_absenteeismMins; + } + + public void setOn_absenteeismMins(int on_absenteeismMins) { + this.on_absenteeismMins = on_absenteeismMins; + } + + public int getOff_absenteeismMins() { + return off_absenteeismMins; + } + + public void setOff_absenteeismMins(int off_absenteeismMins) { + this.off_absenteeismMins = off_absenteeismMins; + } +} diff --git a/领悦二开new/src/com/engine/kq/entity/WorkTimeEntity.java b/领悦二开new/src/com/engine/kq/entity/WorkTimeEntity.java new file mode 100644 index 0000000..dfaae29 --- /dev/null +++ b/领悦二开new/src/com/engine/kq/entity/WorkTimeEntity.java @@ -0,0 +1,220 @@ +package com.engine.kq.entity; + +import java.util.List; +import java.util.Map; + +/*** + * 工作时间 + */ +public class WorkTimeEntity { + private String groupId;//所属考勤组 + private String groupName;//所属考勤组 + private String kqType;//考勤类型 + private String serialId;//班次 + private Map shiftRuleInfo;//班次人性化规则 + private List signTime;//允许打卡时间 + private List workTime;//工作时间 + private List restTime;//休息时间 + private int workMins;//工作时长 + private String isAcross;//是否跨天 + private String signstart;//自由工时开始打卡时间 + private boolean isExclude;//无需考勤人员 + private String calmethod;//自由班制计算方式 + private int signoutOnlyoff; + + private List halfWorkTime;//半天 + + private List halfWorkIndex; + + /** + * 是否是非工作日 1表示是非工作日班次 + */ + private int nonWorkShift; + /** + * 当前日期类型 + * playday 休息日 + * work 工作日 + * holiday 节假日 + */ + private String dayType; + + /** + * 应出勤折算天数 + */ + private String convertAttendDay = ""; + + public String getGroupId() { + return groupId; + } + + public void setGroupId(String groupId) { + this.groupId = groupId; + } + + public String getGroupName() { + return groupName; + } + + public void setGroupName(String groupName) { + this.groupName = groupName; + } + + public String getKQType() { + return kqType; + } + + public void setKQType(String kqType) { + this.kqType = kqType; + } + + public String getSerialId() { + return serialId; + } + + public void setSerialId(String serialId) { + this.serialId = serialId; + } + + public Map getShiftRuleInfo() { + return shiftRuleInfo; + } + + public void setShiftRuleInfo(Map shiftRuleInfo) { + this.shiftRuleInfo = shiftRuleInfo; + } + + public List getWorkTime() { + return workTime; + } + + public void setWorkTime(List workTime) { + this.workTime = workTime; + } + + public List getRestTime() { + return restTime; + } + + public void setRestTime(List restTime) { + this.restTime = restTime; + } + + public int getWorkMins() { + return workMins; + } + + public void setWorkMins(int workMins) { + this.workMins = workMins; + } + + public String getIsAcross() { + return isAcross; + } + + public void setIsAcross(String isAcross) { + this.isAcross = isAcross; + } + + public String getSignStart() { + return signstart; + } + + public void setSignStart(String signstart) { + this.signstart = signstart; + } + + public List getSignTime() { + return signTime; + } + + public void setSignTime(List signTime) { + this.signTime = signTime; + } + + public boolean getIsExclude() { + return isExclude; + } + + public void setIsExclude(boolean isExclude) { + this.isExclude = isExclude; + } + + public String getCalmethod() { + return calmethod; + } + + public void setCalmethod(String calmethod) { + this.calmethod = calmethod; + } + + public int getNonWorkShift() { + return nonWorkShift; + } + + public void setNonWorkShift(int restShift) { + this.nonWorkShift = restShift; + } + + public String getDayType() { + return dayType; + } + + public void setDayType(String dayType) { + this.dayType = dayType; + } + + public String getConvertAttendDay() { + return convertAttendDay; + } + + public void setConvertAttendDay(String convertAttendDay) { + this.convertAttendDay = convertAttendDay; + } + + public int getSignoutOnlyoff() { + return signoutOnlyoff; + } + + public void setSignoutOnlyoff(int signoutOnlyoff) { + this.signoutOnlyoff = signoutOnlyoff; + } + + public List getHalfWorkTime() { + return halfWorkTime; + } + + public void setHalfWorkTime(List halfWorkTime) { + this.halfWorkTime = halfWorkTime; + } + + public List getHalfWorkIndex() { + return halfWorkIndex; + } + + public void setHalfWorkIndex(List halfWorkIndex) { + this.halfWorkIndex = halfWorkIndex; + } + + @Override + public String toString() { + return "WorkTimeEntity{" + + "groupId='" + groupId + '\'' + + ", groupName='" + groupName + '\'' + + ", kqType='" + kqType + '\'' + + ", serialId='" + serialId + '\'' + + ", shiftRuleInfo=" + shiftRuleInfo + + ", signTime=" + signTime + + ", workTime=" + workTime + + ", restTime=" + restTime + + ", workMins=" + workMins + + ", isAcross='" + isAcross + '\'' + + ", signstart='" + signstart + '\'' + + ", isExclude=" + isExclude + + ", calmethod='" + calmethod + '\'' + + ", signoutOnlyoff=" + signoutOnlyoff + + ", nonWorkShift=" + nonWorkShift + + ", dayType='" + dayType + '\'' + + ", convertAttendDay='" + convertAttendDay + '\'' + + '}'; + } +} diff --git a/领悦二开new/src/com/engine/kq/jucailin/genid/DefaultWorker.java b/领悦二开new/src/com/engine/kq/jucailin/genid/DefaultWorker.java new file mode 100644 index 0000000..84652f2 --- /dev/null +++ b/领悦二开new/src/com/engine/kq/jucailin/genid/DefaultWorker.java @@ -0,0 +1,52 @@ +package com.engine.kq.jucailin.genid; + +import java.net.Inet4Address; +import java.net.InetAddress; +import java.net.NetworkInterface; +import java.util.Enumeration; +import java.util.Random; + +public class DefaultWorker implements Worker{ + private Random random = new Random(); + + public DefaultWorker() { + } + + public long getWorkerId() { + int max = 100000; + int min = 10000; + int s = this.random.nextInt(max) % (max - min + 1) + min; + String ip = this.getHostIp(); + long workerId = 0L; + if (ip != null) { + String str = ip.replaceAll("\\.", "") + s; + workerId = Long.parseLong(str); + workerId %= 1024L; + } + + return workerId; + } + + private String getHostIp() { + try { + Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces(); + + while(allNetInterfaces.hasMoreElements()) { + NetworkInterface netInterface = (NetworkInterface)allNetInterfaces.nextElement(); + Enumeration addresses = netInterface.getInetAddresses(); + + while(addresses.hasMoreElements()) { + InetAddress ip = (InetAddress)addresses.nextElement(); + if (ip != null && ip instanceof Inet4Address + && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) { + return ip.getHostAddress(); + } + } + } + } catch (Exception var5) { + var5.printStackTrace(); + } + + return "127.0.0.1"; + } +} diff --git a/领悦二开new/src/com/engine/kq/jucailin/genid/IdGenerator.java b/领悦二开new/src/com/engine/kq/jucailin/genid/IdGenerator.java new file mode 100644 index 0000000..2b2528f --- /dev/null +++ b/领悦二开new/src/com/engine/kq/jucailin/genid/IdGenerator.java @@ -0,0 +1,16 @@ +package com.engine.kq.jucailin.genid; + +/** + * id生成器 + */ +public class IdGenerator { + + public static long generate() { + SnowflakeId snowflakeId = new SnowflakeId(); + return snowflakeId.get(); + } + + public static void main(String[] args) { + System.out.println(generate()); + } +} diff --git a/领悦二开new/src/com/engine/kq/jucailin/genid/SnowflakeId.java b/领悦二开new/src/com/engine/kq/jucailin/genid/SnowflakeId.java new file mode 100644 index 0000000..c8585d9 --- /dev/null +++ b/领悦二开new/src/com/engine/kq/jucailin/genid/SnowflakeId.java @@ -0,0 +1,93 @@ +package com.engine.kq.jucailin.genid; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SnowflakeId { + private static final Logger logger = LoggerFactory.getLogger(SnowflakeId.class); + private DefaultWorker worker; + private long startTime = this._curSecond(); + private long time; + private long segment = 0L; + private long workerId = this.getWorker().getWorkerId(); + private long sequence = 0L; + private static final long segmentBits = 9L; + private static final long workerIdBits = 10L; + private static final long sequenceBits = 13L; + private static final long timestampShift = 32L; + private static final long segmentShift = 23L; + private static final long workerIdShift = 13L; + private static final long sequenceMask = 8191L; + private static final long maxSegment = 511L; + private long twepoch = 1483200000L; + private long _counter = 0L; + + public SnowflakeId() { + this.time = this.startTime - this.twepoch; + } + + public DefaultWorker getWorker() { + return new DefaultWorker(); + } + + public void setWorker(DefaultWorker worker) { + this.worker = worker; + } + + public synchronized long get() { + long id = this.getNextId(); + this.testSpeedLimit(); + return id; + } + + public synchronized long[] getRangeId(int sizeOfIds) { + long[] r = new long[]{this.getNextId(), 0L}; + this.sequence = this.sequence + (long)sizeOfIds - 1L - 1L; + this._counter = this._counter + (long)sizeOfIds - 1L - 1L; + if (this.sequence >> 13 > 0L) { + this.sequence &= 8191L; + if (this.segment >= 511L) { + ++this.time; + this.segment = 0L; + } else { + ++this.segment; + } + } + + r[1] = this.getNextId(); + this.testSpeedLimit(); + return r; + } + + private long getNextId() { + ++this.sequence; + ++this._counter; + if (this.sequence >> 13 > 0L) { + if (this.segment >= 511L) { + ++this.time; + } else { + this.sequence = 0L; + ++this.segment; + } + } + + return this.time << 32 | this.segment << 23 | this.workerId << 13 | this.sequence; + } + + private long _curSecond() { + return System.currentTimeMillis() / 1000L; + } + + private synchronized void testSpeedLimit() { + long spentTime = this._curSecond() - this.startTime + 1L; + if (spentTime <= 0L || spentTime << 22 <= this._counter) { + try { + this.wait(10L); + this.testSpeedLimit(); + } catch (Exception var4) { + logger.error(var4.getMessage(), var4); + } + + } + } +} diff --git a/领悦二开new/src/com/engine/kq/jucailin/genid/Worker.java b/领悦二开new/src/com/engine/kq/jucailin/genid/Worker.java new file mode 100644 index 0000000..421e0ab --- /dev/null +++ b/领悦二开new/src/com/engine/kq/jucailin/genid/Worker.java @@ -0,0 +1,5 @@ +package com.engine.kq.jucailin.genid; + +public interface Worker { + long getWorkerId(); +} diff --git a/领悦二开new/src/com/engine/kq/jucailin/util/KQDateUtil.java b/领悦二开new/src/com/engine/kq/jucailin/util/KQDateUtil.java new file mode 100644 index 0000000..3a39659 --- /dev/null +++ b/领悦二开new/src/com/engine/kq/jucailin/util/KQDateUtil.java @@ -0,0 +1,19 @@ +package com.engine.kq.jucailin.util; + +import java.sql.Date; +import java.sql.Timestamp; + +public class KQDateUtil { + + public static Date getUpdateDate(){ + Long now = System.currentTimeMillis(); + Date date = new Date(now); + return date; + } + + public static Timestamp getUpdateTimeStamp(){ + Long now = System.currentTimeMillis(); + Timestamp timestamp = new Timestamp(now); + return timestamp; + } +} diff --git a/领悦二开new/src/com/engine/kq/util/ExcelUtil.java b/领悦二开new/src/com/engine/kq/util/ExcelUtil.java new file mode 100644 index 0000000..23c954a --- /dev/null +++ b/领悦二开new/src/com/engine/kq/util/ExcelUtil.java @@ -0,0 +1,829 @@ +package com.engine.kq.util; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.OutputStream; +import java.net.URLEncoder; +import java.text.SimpleDateFormat; +import java.util.*; + +import com.engine.kq.biz.KQSettingsComInfo; +import org.apache.poi.ss.usermodel.*; +import org.apache.poi.xssf.streaming.SXSSFWorkbook; +import org.apache.poi.ss.util.CellRangeAddress; +import org.apache.poi.ss.util.CellRangeAddressList; +import org.apache.poi.ss.util.RegionUtil; +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.GCONST; +import weaver.general.Util; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +public class ExcelUtil extends BaseBean { + private boolean isKqReportHalfOpen = "1".equals(new KQSettingsComInfo().getMain_val("kq_report_half")); + /* + * 导出数据 + * */ + public Map export(Map workBook, HttpServletRequest request, HttpServletResponse response) throws Exception { + return export(workBook, request, response,false); + } + public Map export(Map workBook, HttpServletRequest request, HttpServletResponse response,boolean isWrap) throws Exception { + Map returnMap = new HashMap<>(); + String createFile = ""; + try { + SXSSFWorkbook workbook = new SXSSFWorkbook(); // 创建工作簿对象 + List lsSheet = (List) workBook.get("sheet"); + String fileName = Util.null2String(workBook.get("fileName")); + if (fileName.length() == 0||true) fileName = "" + UUID.randomUUID();//解决lunix下中文文件无法生成问题 + for (int sheetNum = 0; sheetNum < lsSheet.size(); sheetNum++) { + Map mySheet = (Map) lsSheet.get(sheetNum); + String mySheetName = Util.null2String(mySheet.get("sheetName")); + String sheetTitle = Util.null2String(mySheet.get("sheetTitle")); + List sheetMemo = (List) mySheet.get("sheetMemo"); + List titleList = (List) mySheet.get("titleList"); + List dataList = (List) mySheet.get("dataList"); + List> constraintList = (List>) mySheet.get("constraintList"); + createFile = Util.null2String(mySheet.get("createFile")); + int calIndex = Util.getIntValue(Util.null2String(mySheet.get("calIndex")),-1); + + Sheet sheet = workbook.createSheet(mySheetName); // 创建工作表 + + int rowIdx = 0; + // 产生表格标题行 + Row rowm = sheet.createRow(rowIdx); + Cell cellTiltle = rowm.createCell(0); + + CellStyle titleStyle = this.getTitleStyle(workbook);//获取列头样式对象 + CellStyle memoStyle = this.getMemoStyle(workbook);//获取备注样式对象 + CellStyle columnTopStyle = this.getColumnTopStyle(workbook);//获取列头样式对象 + CellStyle cellStyle = this.getCellStyle(workbook,isWrap); //单元格样式对象 + + int mergedRegion = titleList.size() - 1; + if (mergedRegion > 15) mergedRegion = 15; + mergedRegion = getColLength(titleList); + + CellRangeAddress region = new CellRangeAddress(rowIdx, ++rowIdx, 0, mergedRegion); + RegionUtil.setBorderBottom(BorderStyle.THIN, region, sheet); + RegionUtil.setBorderLeft(BorderStyle.THIN, region, sheet); + RegionUtil.setBorderRight(BorderStyle.THIN, region, sheet); + RegionUtil.setBorderTop(BorderStyle.THIN, region, sheet); + sheet.addMergedRegionUnsafe(region); + cellTiltle.setCellStyle(titleStyle); + cellTiltle.setCellValue(sheetTitle); + + for (int i = 0; sheetMemo != null && i < sheetMemo.size(); i++) { + rowm = sheet.createRow(++rowIdx); + Cell cellMemo = rowm.createCell(0); + region = new CellRangeAddress(rowIdx, ++rowIdx, 0, mergedRegion); + RegionUtil.setBorderBottom(BorderStyle.THIN, region, sheet); + RegionUtil.setBorderLeft(BorderStyle.THIN, region, sheet); + RegionUtil.setBorderRight(BorderStyle.THIN, region, sheet); + RegionUtil.setBorderTop(BorderStyle.THIN, region, sheet); + sheet.addMergedRegionUnsafe(region); + cellMemo.setCellStyle(memoStyle); + cellMemo.setCellValue(Util.null2String(sheetMemo.get(i))); + } + +// // 定义所需列数 +// int columnNum = titleList.size(); +// HSSFRow rowRowName = sheet.createRow(++rowIdx); // 在索引2的位置创建行(最顶端的行开始的第二行) +// +// // 将列头设置到sheet的单元格中 +// for (int n = 0; n < columnNum; n++) { +// Map title = (Map) titleList.get(n); +// +// HSSFCell cellRowName = rowRowName.createCell(n); //创建列头对应个数的单元格 +// cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); //设置列头单元格的数据类型 +// HSSFRichTextString text = new HSSFRichTextString(Util.null2String(title.get("title"))); +// cellRowName.setCellValue(text); //设置列头单元格的值 +// cellRowName.setCellStyle(columnTopStyle); //设置列头单元格样式 +// if (n == 0) { +// sheet.setColumnWidth(n, Util.getIntValue(Util.null2String(title.get("width")))); +// } else { +// sheet.setColumnWidth(n, Util.getIntValue(Util.null2String(title.get("width")))); +// } +// } + + rowIdx = this.initDynamicTitle(sheet, titleList, columnTopStyle, rowIdx); + + if(isKqReportHalfOpen) { + if(calIndex > -1){ + CellStyle style1 = workbook.createCellStyle(); + style1.setFillPattern(FillPatternType.SOLID_FOREGROUND); + short amColor = (short) Util.getIntValue("5"); + style1.setFillForegroundColor(amColor); + style1.setFillBackgroundColor(IndexedColors.BLUE.index); + style1.setAlignment(HorizontalAlignment.CENTER); + //设置底边框; + style1.setBorderBottom(BorderStyle.THIN); + //设置底边框颜色; + style1.setBottomBorderColor(IndexedColors.BLACK.index); + //设置左边框; + style1.setBorderLeft(BorderStyle.THIN); + //设置左边框颜色; + style1.setLeftBorderColor(IndexedColors.BLACK.index); + //设置右边框; + style1.setBorderRight(BorderStyle.THIN); + //设置右边框颜色; + style1.setRightBorderColor(IndexedColors.BLACK.index); + //设置顶边框; + style1.setBorderTop(BorderStyle.THIN); + //设置顶边框颜色; + style1.setTopBorderColor(IndexedColors.BLACK.index); + + CellStyle style2 = workbook.createCellStyle(); + style2.setFillPattern(FillPatternType.SOLID_FOREGROUND); + short pm_color = (short) Util.getIntValue("29"); + style2.setFillForegroundColor(pm_color); + style2.setFillBackgroundColor(IndexedColors.RED.index); + style2.setAlignment(HorizontalAlignment.CENTER); + //设置底边框; + style2.setBorderBottom(BorderStyle.THIN); + //设置底边框颜色; + style2.setBottomBorderColor(IndexedColors.BLACK.index); + //设置左边框; + style2.setBorderLeft(BorderStyle.THIN); + //设置左边框颜色; + style2.setLeftBorderColor(IndexedColors.BLACK.index); + //设置右边框; + style2.setBorderRight(BorderStyle.THIN); + //设置右边框颜色; + style2.setRightBorderColor(IndexedColors.BLACK.index); + //设置顶边框; + style2.setBorderTop(BorderStyle.THIN); + //设置顶边框颜色; + style2.setTopBorderColor(IndexedColors.BLACK.index); //设置单元格样式 + + //将查询出的数据设置到sheet对应的单元格中 + for (int i = 0; dataList != null && i < dataList.size(); ) { + List obj = (List) dataList.get(i);//遍历每个对象 + int rowNowIndex = i + rowIdx + 1; + Row row = sheet.createRow(rowNowIndex);//创建所需的行数 + for (int j = 0; j < obj.size(); j++) { + Cell cell = null; //设置单元格的数据类型 + cell = row.createCell(j, CellType.STRING); + if(j < calIndex){ + cell.setCellStyle(cellStyle); //设置单元格样式 + addMergedRegion(sheet, rowNowIndex, rowNowIndex+1, j, j); + }else{ + + addMergedRegion(sheet, rowNowIndex, rowNowIndex, j, j); + cell.setCellStyle(style1); //设置单元格样式 + } + String value_value = Util.null2String(obj.get(j)); + cell.setCellValue(value_value); //设置单元格的值 + } + List obj1 = (List) dataList.get(i+1);//遍历每个对象 + Row row1 = sheet.createRow(rowNowIndex + 1);//创建所需的行数 + for (int j = 0; j < obj1.size(); j++) { + Cell cell = null; //设置单元格的数据类型 + cell = row1.createCell(j, CellType.STRING); + if(j < calIndex){ + cell.setCellStyle(cellStyle); //设置单元格样式 + }else{ + addMergedRegion(sheet, rowNowIndex+1, rowNowIndex+1, j, j); + cell.setCellStyle(style2); + String value_value = Util.null2String(obj1.get(j)); + cell.setCellValue(value_value); //设置单元格的值 + } + } + i = i +2; + } + } + } else { + for (int i = 0; dataList != null && i < dataList.size(); i++) { + List obj = (List) dataList.get(i);//遍历每个对象 + Row row = sheet.createRow(i + rowIdx + 1);//创建所需的行数 + + for (int j = 0; j < obj.size(); j++) { + Cell cell = null; //设置单元格的数据类型 + cell = row.createCell(j, CellType.STRING); + cell.setCellValue(Util.null2String(obj.get(j))); //设置单元格的值 + cell.setCellStyle(cellStyle); //设置单元格样式 + } + } + } + +// int columnNum = this.getColumnLength(titleList); +// //让列宽随着导出的列长自动适应 +// for (int colNum = 0; colNum < columnNum; colNum++) { +// int columnWidth = sheet.getColumnWidth(colNum) / 256; +// for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) { +// HSSFRow currentRow; +// //当前行未被使用过 +// if (sheet.getRow(rowNum) == null) { +// currentRow = sheet.createRow(rowNum); +// } else { +// currentRow = sheet.getRow(rowNum); +// } +// if (currentRow.getCell(colNum) != null) { +// //取得当前的单元格 +// HSSFCell currentCell = currentRow.getCell(colNum); +// //如果当前单元格类型为字符串 +// if (currentCell.getCellTypeEnum() == CellType.STRING) { +// int length = currentCell.getStringCellValue().getBytes().length; +// if (columnWidth < length) { +// //将单元格里面值大小作为列宽度 +// columnWidth = length; +// } +// } +// } +// } +// //再根据不同列单独做下处理 +// if (colNum == 0) { +// sheet.setColumnWidth(colNum, (columnWidth - 2) * 256); +// } else { +// sheet.setColumnWidth(colNum, (columnWidth + 4) * 256); +// } +// } + for (int i = 0; constraintList != null && i < constraintList.size(); i++) { + Map constraint = constraintList.get(i); + int firstRow = Util.getIntValue(Util.null2String(constraint.get("firstRow")), 0); + int endRow = Util.getIntValue(Util.null2String(constraint.get("endRow")), 0); + int firstCol = Util.getIntValue(Util.null2String(constraint.get("firstCol")), 0); + int endCol = Util.getIntValue(Util.null2String(constraint.get("endCol")), 0); + //设置下拉框数据 + String[] datas = (String[]) constraint.get("constraintDatas"); + String hiddenSheetName = "constraintDataSheet"+i; + Sheet hiddenSheet = workbook.createSheet(hiddenSheetName); + workbook.setSheetHidden(workbook.getSheetIndex(hiddenSheet), true); + for (int j = 0; j< datas.length; j++) { + hiddenSheet.createRow(j).createCell(0).setCellValue(datas[j]); + } + DataValidationHelper helper = sheet.getDataValidationHelper(); + String formulaId = hiddenSheetName + "!$A$1:$A$" + datas.length; + DataValidationConstraint dataValidationConstraint = helper.createFormulaListConstraint(formulaId); + CellRangeAddressList cellRangeAddressList = new CellRangeAddressList(firstRow, endRow, firstCol, endCol); + DataValidation dataValidation = helper.createValidation(dataValidationConstraint, cellRangeAddressList); + //处理Excel兼容性问题 + if (dataValidation instanceof DataValidation) { + dataValidation.setSuppressDropDownArrow(true); + dataValidation.setShowErrorBox(true); + } else { + dataValidation.setSuppressDropDownArrow(false); + } + sheet.addValidationData(dataValidation); + } + + +// for (int i = 0; constraintList != null && i < constraintList.size(); i++) { +// Map constraint = constraintList.get(i); +// int firstRow = Util.getIntValue(Util.null2String(constraint.get("firstRow")), 0); +// int endRow = Util.getIntValue(Util.null2String(constraint.get("endRow")), 0); +// int firstCol = Util.getIntValue(Util.null2String(constraint.get("firstCol")), 0); +// int endCol = Util.getIntValue(Util.null2String(constraint.get("endCol")), 0); +// +// //设置下拉框数据 +// String[] datas = (String[]) constraint.get("constraintDatas"); +// DataValidationHelper helper = sheet.getDataValidationHelper(); +// DataValidationConstraint dataValidationConstraint = helper.createExplicitListConstraint(datas); +// CellRangeAddressList cellRangeAddressList = new CellRangeAddressList(firstRow, endRow, firstCol, endCol); +// DataValidation dataValidation = helper.createValidation(dataValidationConstraint, cellRangeAddressList); +// //处理Excel兼容性问题 +// if (dataValidation instanceof DataValidation) { +// dataValidation.setSuppressDropDownArrow(true); +// dataValidation.setShowErrorBox(true); +// } else { +// dataValidation.setSuppressDropDownArrow(false); +// } +// sheet.addValidationData(dataValidation); +// } + } + + if (workbook != null) { + if (createFile.equals("1")) { + String filePath = GCONST.getRootPath() + "/hrm/kq/tmpFile/"; + File file = new File(filePath); + if (!file.exists()) { + file.mkdirs(); + } + + fileName = fileName +"("+DateUtil.getNowDateTimeStr()+")"; + String url = filePath + fileName + ".xlsx"; + String realUrl = "/hrm/kq/tmpFile/" + fileName + ".xlsx"; + FileOutputStream fOut = new FileOutputStream(url); + workbook.write(fOut); + fOut.flush(); + fOut.close(); + returnMap.put("url", realUrl); + } else { + response.reset(); + response.setContentType("application/vnd.ms-excel;charset=utf-8"); +// response.setCharacterEncoding("utf-8"); + String header = request.getHeader("User-Agent").toUpperCase(); + if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) { + fileName = URLEncoder.encode(fileName, "utf-8"); + fileName = fileName.replace("+", "%20"); //IE下载文件名空格变+号问题 + } else { + fileName = new String(fileName.getBytes("utf-8"), "ISO_8859_1"); + } + response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx"); + response.setContentType("application/msexcel"); + response.setContentType("application/x-msdownload"); + OutputStream responseOutput = response.getOutputStream(); + workbook.write(responseOutput); + responseOutput.flush(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + + return returnMap; + } + + /* + * 列头单元格样式 + */ + private CellStyle getMemoStyle(SXSSFWorkbook workbook) { + // 设置字体 + Font font = workbook.createFont(); + //设置字体大小 + font.setFontHeightInPoints((short) 10); + //字体加粗 + font.setBold(true); + //设置字体名字 + font.setFontName("宋体"); + //设置样式; + CellStyle style = workbook.createCellStyle(); + //设置底边框; + style.setBorderBottom(BorderStyle.THIN); + //设置底边框颜色; + style.setBottomBorderColor(IndexedColors.BLACK.index); + //设置左边框; + style.setBorderLeft(BorderStyle.THIN); + //设置左边框颜色; + style.setLeftBorderColor(IndexedColors.BLACK.index); + //设置右边框; + style.setBorderRight(BorderStyle.THIN); + //设置右边框颜色; + style.setRightBorderColor(IndexedColors.BLACK.index); + //设置顶边框; + style.setBorderTop(BorderStyle.THIN); + //设置顶边框颜色; + style.setTopBorderColor(IndexedColors.BLACK.index); + //在样式用应用设置的字体; + style.setFont(font); + //设置自动换行; + style.setWrapText(false); + //设置水平对齐的样式为居中对齐; + style.setAlignment(HorizontalAlignment.LEFT); + //设置垂直对齐的样式为居中对齐; + style.setVerticalAlignment(VerticalAlignment.CENTER); + + return style; + + } + + /* + * 列头单元格样式 + */ + private CellStyle getTitleStyle(SXSSFWorkbook workbook) { + // 设置字体 + Font font = workbook.createFont(); + //设置字体大小 + font.setFontHeightInPoints((short) 14); + //字体加粗 + font.setBold(true); + //设置字体名字 + font.setFontName("宋体"); + //设置样式; + CellStyle style = workbook.createCellStyle(); + //设置底边框; + style.setBorderBottom(BorderStyle.THIN); + //设置底边框颜色; + style.setBottomBorderColor(IndexedColors.BLACK.index); + //设置左边框; + style.setBorderLeft(BorderStyle.THIN); + //设置左边框颜色; + style.setLeftBorderColor(IndexedColors.BLACK.index); + //设置右边框; + style.setBorderRight(BorderStyle.THIN); + //设置右边框颜色; + style.setRightBorderColor(IndexedColors.BLACK.index); + //设置顶边框; + style.setBorderTop(BorderStyle.THIN); + //设置顶边框颜色; + style.setTopBorderColor(IndexedColors.BLACK.index); + //在样式用应用设置的字体; + style.setFont(font); + //设置自动换行; + style.setWrapText(false); + //设置水平对齐的样式为居中对齐; + style.setAlignment(HorizontalAlignment.CENTER); + //设置垂直对齐的样式为居中对齐; + style.setVerticalAlignment(VerticalAlignment.CENTER); + return style; + + } + + /* + * 列头单元格样式 + */ + private CellStyle getColumnTopStyle(SXSSFWorkbook workbook) { + // 设置字体 + Font font = workbook.createFont(); + //设置字体大小 + font.setFontHeightInPoints((short) 11); + //字体加粗 + font.setBold(true); + //设置字体名字 + font.setFontName("宋体"); + //设置样式; + CellStyle style = workbook.createCellStyle(); + //设置底边框; + style.setBorderBottom(BorderStyle.THIN); + //设置底边框颜色; + style.setBottomBorderColor(IndexedColors.BLACK.index); + //设置左边框; + style.setBorderLeft(BorderStyle.THIN); + //设置左边框颜色; + style.setLeftBorderColor(IndexedColors.BLACK.index); + //设置右边框; + style.setBorderRight(BorderStyle.THIN); + //设置右边框颜色; + style.setRightBorderColor(IndexedColors.BLACK.index); + //设置顶边框; + style.setBorderTop(BorderStyle.THIN); + //设置顶边框颜色; + style.setTopBorderColor(IndexedColors.BLACK.index); + //在样式用应用设置的字体; + style.setFont(font); + //设置自动换行; + style.setWrapText(true); + //设置水平对齐的样式为居中对齐; + style.setAlignment(HorizontalAlignment.CENTER); + //设置垂直对齐的样式为居中对齐; + style.setVerticalAlignment(VerticalAlignment.CENTER); + + return style; + + } + + /* + * 列数据信息单元格样式 + */ + private CellStyle getCellStyle(SXSSFWorkbook workbook,boolean isWrap) { + // 设置字体 + Font font = workbook.createFont(); + //设置字体大小 + //font.setFontHeightInPoints((short)10); + //字体加粗 + //font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); + //设置字体名字 + font.setFontName("宋体"); + //设置样式; + CellStyle style = workbook.createCellStyle(); + //设置底边框; + style.setBorderBottom(BorderStyle.THIN); + //设置底边框颜色; + style.setBottomBorderColor(IndexedColors.BLACK.index); + //设置左边框; + style.setBorderLeft(BorderStyle.THIN); + //设置左边框颜色; + style.setLeftBorderColor(IndexedColors.BLACK.index); + //设置右边框; + style.setBorderRight(BorderStyle.THIN); + //设置右边框颜色; + style.setRightBorderColor(IndexedColors.BLACK.index); + //设置顶边框; + style.setBorderTop(BorderStyle.THIN); + //设置顶边框颜色; + style.setTopBorderColor(IndexedColors.BLACK.index); + //在样式用应用设置的字体; + style.setFont(font); + //设置自动换行; +// style.setWrapText(false); + if(isWrap){ + style.setWrapText(true); + }else{ + style.setWrapText(false); + } + //设置水平对齐的样式为居中对齐; + style.setAlignment(HorizontalAlignment.LEFT); + //设置垂直对齐的样式为居中对齐; + style.setVerticalAlignment(VerticalAlignment.CENTER); + + return style; + + } + + private CellStyle getCellStyle(SXSSFWorkbook workbook) { + // 设置字体 + Font font = workbook.createFont(); + //设置字体大小 + //font.setFontHeightInPoints((short)10); + //字体加粗 + //font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); + //设置字体名字 + font.setFontName("宋体"); + //设置样式; + CellStyle style = workbook.createCellStyle(); + //设置底边框; + style.setBorderBottom(BorderStyle.THIN); + //设置底边框颜色; + style.setBottomBorderColor(IndexedColors.BLACK.index); + //设置左边框; + style.setBorderLeft(BorderStyle.THIN); + //设置左边框颜色; + style.setLeftBorderColor(IndexedColors.BLACK.index); + //设置右边框; + style.setBorderRight(BorderStyle.THIN); + //设置右边框颜色; + style.setRightBorderColor(IndexedColors.BLACK.index); + //设置顶边框; + style.setBorderTop(BorderStyle.THIN); + //设置顶边框颜色; + style.setTopBorderColor(IndexedColors.BLACK.index); + //在样式用应用设置的字体; + style.setFont(font); + //设置自动换行; + style.setWrapText(false); + //设置水平对齐的样式为居中对齐; + style.setAlignment(HorizontalAlignment.LEFT); + //设置垂直对齐的样式为居中对齐; + style.setVerticalAlignment(VerticalAlignment.CENTER); + + return style; + + } + + public static void main(String[] args) { + String groupid = "1"; + String filename = "c://33e2a90d-3347-490c-afff-21de0ef3e3af.xlsx"; + int startRow = 3; + RecordSet rs = new RecordSet(); + String sql = ""; + try { + //必要的权限判断 + List lsParams = null; + List params = null; + + Workbook workbook = WorkbookFactory.create(new FileInputStream(filename)); + for (int idx = 0; idx < workbook.getNumberOfSheets(); idx++) { + Sheet sheet = workbook.getSheetAt(idx); + Row row = null; + Cell cell = null; + lsParams = new ArrayList(); + for (int i = startRow; startRow <= sheet.getLastRowNum() && i <= sheet.getLastRowNum(); i++) { + row = sheet.getRow(i); + if (row == null) { + continue; + } + params = new ArrayList(); + for (int cellIndex = 0; cellIndex < row.getLastCellNum(); cellIndex++) { + cell = row.getCell((short) cellIndex); + if (cell == null) continue; + params.add(getCellValue(cell).trim()); + } + params.add(groupid); + if (Util.null2String(params.get(0)).length() > 0) { + lsParams.add(params); + } + } + if (idx == 0) { + sql = "insert into kq_loaction (loactionname,longitude,latitude,address,groupid) values (?,?,?,?,?) "; + } else { + sql = "insert into kq_wifi (wifiname,mac,groupid) values (?,?,?) "; + } + rs.executeBatchSql(sql, lsParams); + } + } catch (Exception e) { + new BaseBean().writeLog(e); + } + } + + public int initDynamicTitle(Sheet sheet, List columns, CellStyle columnTopStyle, int rowIdx) { + int cur_rowIndx = rowIdx+1; + //title 总行数 + int title_rows = cur_rowIndx+getRowNums(columns)-1; + createHeaderRow(sheet, cur_rowIndx, 0,columns,columnTopStyle,title_rows); + return title_rows; + } + + /** + * 创建表头 + */ + private int createHeaderRow(Sheet sheet, int index, int cellIndex, + List columnName, CellStyle columnTopStyle, int title_rows) { + Row row = sheet.getRow(index) == null ? sheet.createRow(index) : sheet.getRow(index); + int rows = getRowNums(columnName); + for (int i = 0, exportFieldTitleSize = columnName.size(); i < exportFieldTitleSize; i++) { + Map column = (Map) columnName.get(i); + String title = Util.null2String(column.get("title")); + createStringCell(row, cellIndex, title, columnTopStyle); + if (column.get("children") != null) { + List childchildColumns = (List) column.get("children"); + // 保持原来的 + int tempCellIndex = cellIndex; + cellIndex = createHeaderRow(sheet, rows == 1 ? index : index + 1, cellIndex, childchildColumns,columnTopStyle, + title_rows); + if (childchildColumns.size() > 1) { + addMergedRegion(sheet, index, index, tempCellIndex, cellIndex - 1); + } + cellIndex--; + }else{ + addMergedRegion(sheet, index, title_rows, cellIndex, cellIndex); + } + cellIndex++; + } + return cellIndex; + } + + /** + * 合并单元格 + * @param sheet + * @param firstRow + * @param lastRow + * @param firstCol + * @param lastCol + */ + public void addMergedRegion(Sheet sheet, int firstRow, int lastRow, int firstCol, int lastCol) { + try { + if(firstRow == lastRow && firstCol == lastCol){ + return ; + } + CellRangeAddress region = new CellRangeAddress(firstRow, lastRow, firstCol, lastCol); + RegionUtil.setBorderBottom(BorderStyle.THIN, region, sheet); + RegionUtil.setBorderLeft(BorderStyle.THIN, region, sheet); + RegionUtil.setBorderRight(BorderStyle.THIN, region, sheet); + RegionUtil.setBorderTop(BorderStyle.THIN, region, sheet); + sheet.addMergedRegionUnsafe(region); + } catch (Exception e) { + e.printStackTrace(); + } + } + /** + * 创建文本类型的Cell + */ + public void createStringCell(Row row, int cellIndex, String title, CellStyle columnTopStyle) { + Cell cellRowName = row.createCell(cellIndex); //创建列头对应个数的单元格 + cellRowName.setCellType(CellType.STRING); //设置列头单元格的数据类型 + cellRowName.setCellValue(title); //设置列头单元格的值 + cellRowName.setCellStyle(columnTopStyle); //设置列头单元格样式 + } + + public int initTitle(Sheet sheet, List columns, CellStyle columnTopStyle, int rowIdx) { + List lsMergedRegion = new ArrayList<>(); + Map mergedRegion = null; + int firstTitleRow = rowIdx + 1; + int lastTitleRow = rowIdx + 2; + Row rowRowName = sheet.createRow(++rowIdx); // 在索引2的位置创建行(最顶端的行开始的第二行) + Row childRowRowName = null; + // 定义所需列数 + Map column = null; + List childColumn = null; + int colIdx = 0; + for (int i = 0; i < columns.size(); i++) { + column = (Map) columns.get(i); + childColumn = (List) column.get("children"); + Cell cellRowName = rowRowName.createCell(colIdx++); //创建列头对应个数的单元格 + cellRowName.setCellType(CellType.STRING); //设置列头单元格的数据类型 + cellRowName.setCellValue(Util.null2String(column.get("title"))); //设置列头单元格的值 + cellRowName.setCellStyle(columnTopStyle); //设置列头单元格样式 + + if (Util.getIntValue(Util.null2String(column.get("rowSpan"))) == 2) { + if (childRowRowName == null) { + childRowRowName = sheet.createRow(++rowIdx); + } + mergedRegion = new HashMap(); + mergedRegion.put("startRow", firstTitleRow); + mergedRegion.put("overRow", lastTitleRow); + mergedRegion.put("startCol", colIdx - 1); + mergedRegion.put("overCol", colIdx - 1); + lsMergedRegion.add(mergedRegion); + } + + if (childColumn != null) { + colIdx--; + mergedRegion = new HashMap(); + mergedRegion.put("startRow", firstTitleRow); + mergedRegion.put("overRow", firstTitleRow); + mergedRegion.put("startCol", colIdx); + for (int j = 0; j < childColumn.size(); j++) { + column = (Map) childColumn.get(j); + cellRowName = childRowRowName.createCell(colIdx++); //创建列头对应个数的单元格 + cellRowName.setCellType(CellType.STRING); //设置列头单元格的数据类型 + cellRowName.setCellValue(Util.null2String(column.get("title"))); //设置列头单元格的值 + cellRowName.setCellStyle(columnTopStyle); + } + mergedRegion.put("overCol", colIdx - 1); + if (childColumn.size() > 1) { + lsMergedRegion.add(mergedRegion); + } + } + } + + for (int i = 0; i < lsMergedRegion.size(); i++) { + mergedRegion = (Map) lsMergedRegion.get(i); + Integer startrow = Util.getIntValue(Util.null2String(mergedRegion.get("startRow"))); + Integer overrow = Util.getIntValue(Util.null2String(mergedRegion.get("overRow"))); + Integer startcol = Util.getIntValue(Util.null2String(mergedRegion.get("startCol"))); + Integer overcol = Util.getIntValue(Util.null2String(mergedRegion.get("overCol"))); + CellRangeAddress region = new CellRangeAddress(startrow, overrow, startcol, overcol); + RegionUtil.setBorderBottom(BorderStyle.THIN, region, sheet); + RegionUtil.setBorderLeft(BorderStyle.THIN, region, sheet); + RegionUtil.setBorderRight(BorderStyle.THIN, region, sheet); + RegionUtil.setBorderTop(BorderStyle.THIN, region, sheet); + sheet.addMergedRegionUnsafe(region); + } + return rowIdx; + } + + + + /** + * 获取具体总共有多少列 + * @param columns + * @return + */ + private int getColLength(List columns) { + int length = -1;// 从0开始计算单元格的 + for(int i =0 ; i < columns.size() ; i++){ + Map column = (Map) columns.get(i); + if (column.get("children") != null) { + List childchildColumns = (List) column.get("children"); + length += getColLength(childchildColumns) + 1; + } else { + length++; + } + } + return length; + } + + /** + * 获取具体总共有多少行 + */ + public int getRowNums(List columns) { + int cnt = 1; + for (int i = 0; i < columns.size(); i++) { + Map column = (Map) columns.get(i); + if (column.get("children") != null) { + List childchildColumns = (List) column.get("children"); + int tmpcnt = 1+getRowNums(childchildColumns); + if(tmpcnt > cnt){ + cnt = tmpcnt; + } + } + } + if(cnt > 1){ + return cnt; + }else{ + return 1; + } + } + + public int getColumnLength(List columns) { + int columnLength = 0; + Map column = null; + for (int i = 0; i < columns.size(); i++) { + column = (Map) columns.get(i); + if (column.get("colSpan") != null) { + columnLength += Util.getIntValue(Util.null2String(column.get("colSpan"))); + } else { + columnLength++; + } + } + return columnLength; + } + + /** + * /** + * 获取excel单元格值 + * + * @param cell 要读取的单元格对象 + * @return + */ + public static String getCellValue(Cell cell) { + String cellValue = ""; + if (cell == null) + return ""; + switch (cell.getCellType()) { + case BOOLEAN: // 得到Boolean对象的方法 + cellValue = String.valueOf(cell.getBooleanCellValue()); + break; + case NUMERIC: + if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {// 先看是否是日期格式 + SimpleDateFormat sft = new SimpleDateFormat("yyyy-MM-dd"); + cellValue = String.valueOf(sft.format(cell.getDateCellValue())); // 读取日期格式 + } else { + cellValue = String.valueOf(new Double(cell.getNumericCellValue())); // 读取数字 + if (cellValue.endsWith(".0")) + cellValue = cellValue.substring(0, cellValue.indexOf(".")); + } + break; + case FORMULA: // 读取公式 + cellValue = cell.getCellFormula(); + break; + case STRING: // 读取String + cellValue = cell.getStringCellValue(); + break; + } + + return cellValue; + } +} diff --git a/领悦二开new/src/com/engine/kq/util/KQLockAttendaUtil.java b/领悦二开new/src/com/engine/kq/util/KQLockAttendaUtil.java new file mode 100644 index 0000000..b21b6ee --- /dev/null +++ b/领悦二开new/src/com/engine/kq/util/KQLockAttendaUtil.java @@ -0,0 +1,1382 @@ +package com.engine.kq.util; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.engine.kq.bean.ImportSetting; +import com.engine.kq.bean.KqLockAttenda; +import com.engine.kq.biz.*; +import com.engine.kq.cmd.shiftmanagement.toolkit.ShiftManagementToolKit; +import com.engine.kq.entity.KQScheduleSignEntity; +import com.engine.kq.entity.WorkTimeEntity; +import com.engine.kq.enums.KqSplitFlowTypeEnum; +import com.engine.kq.log.KQLog; +import com.engine.kq.timer.KQQueue; +import com.engine.kq.timer.KQTaskBean; +import com.engine.kq.wfset.bean.ProcessChangeSplitBean; +import com.engine.kq.wfset.bean.SplitBean; +import com.engine.kq.wfset.util.*; +import com.engine.workflow.biz.freeNode.FreeNodeBiz; +import com.engine.workflow.biz.publicApi.RequestOperateBiz; +import com.engine.workflow.biz.workflowOvertime.OvertimeBiz; +import com.engine.workflow.constant.PAResponseCode; +import com.engine.workflow.entity.core.RequestInfoEntity; +import com.engine.workflow.entity.publicApi.PAResponseEntity; +import com.engine.workflow.entity.publicApi.ReqOperateRequestEntity; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.wbi.util.StringUtil; +import weaver.conn.BatchRecordSet; +import weaver.conn.RecordSet; +import weaver.conn.RecordSetDataSource; +import weaver.file.Prop; +import weaver.general.BaseBean; +import weaver.general.TimeUtil; +import weaver.general.Util; +import weaver.hrm.User; +import weaver.hrm.common.Tools; +import weaver.hrm.resource.ResourceComInfo; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; +import weaver.systeminfo.SystemEnv; +import weaver.wechat.util.DateUtil; +import weaver.workflow.agent.AgentManager; +import weaver.workflow.monitor.Monitor; +import weaver.workflow.monitor.MonitorDTO; +import weaver.workflow.workflow.WfForceOver; +import weaver.workflow.workflow.WfFunctionManageUtil; +import weaver.workflow.workflow.WorkflowComInfo; + +import java.math.BigDecimal; +import java.sql.Timestamp; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.*; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + + +@SuppressWarnings("unchecked") +public class KQLockAttendaUtil { + + private static final String LOCK_TABLE = Util.null2String(Prop.getPropValue("kqLockAttenda", "LOCK_TABLE")); + private static final String LOCK_COM = Util.null2String(Prop.getPropValue("kqLockAttenda", "LOCK_COM")); + private static final String LOCK_SUBCOM = Util.null2String(Prop.getPropValue("kqLockAttenda", "LOCK_SUBCOM")); + private static final String LOCK_DEPT = Util.null2String(Prop.getPropValue("kqLockAttenda", "LOCK_DEPT")); + private static final String LOCK_RESOURCE = Util.null2String(Prop.getPropValue("kqLockAttenda", "LOCK_RESOURCE")); + private static final String LOCK_FROMDATE = Util.null2String(Prop.getPropValue("kqLockAttenda", "LOCK_FROMDATE")); + private static final String LOCK_TODATE = Util.null2String(Prop.getPropValue("kqLockAttenda", "LOCK_TODATE")); + private static final String LOCK_LOCK = Util.null2String(Prop.getPropValue("kqLockAttenda", "LOCK_LOCK")); + + private static final String LOCK_DEGREE = Util.null2String(Prop.getPropValue("kqLockAttenda", "LOCK_DEGREE")); + private static KQLog kqLog = new KQLog(); + + public List sdkqbb_map; + + public static final ExecutorService EXECUTOR_SERVICE = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(100)); + + public KQLockAttendaUtil() { + this.sdkqbb_map = this.initModuleData(); + } + + + public List initModuleData() { + List list = new ArrayList<>(); + if ("".equals(LOCK_TABLE)) { + return list; + } + RecordSet rs = new RecordSet(); + StringBuilder sql = new StringBuilder(); + sql.append("select * from " + LOCK_TABLE + " where "); + sql.append(" " + LOCK_LOCK + "=1 "); + kqLog.info("sql>>>>>>>>>>>>>>>" + sql.toString()); + + KqLockAttenda bean = null; + rs.execute(sql.toString()); + while (rs.next()) { + bean = new KqLockAttenda(); + String iscompany = Util.null2String(rs.getString(LOCK_COM)); + bean.setLOCK_COM(iscompany); + String subcompanyIds = Util.null2String(rs.getString(LOCK_SUBCOM)); + bean.setLOCK_SUBCOM(subcompanyIds); + String departmentIds = Util.null2String(rs.getString(LOCK_DEPT)); + bean.setLOCK_DEPT(departmentIds); + String resouceIds = Util.null2String(rs.getString(LOCK_RESOURCE)); + bean.setLOCK_RESOURCE(resouceIds); + String fromdate = Util.null2String(rs.getString(LOCK_FROMDATE)); + bean.setLOCK_FROMDATE(fromdate); + String todate = Util.null2String(rs.getString(LOCK_TODATE)); + bean.setLOCK_TODATE(todate); + list.add(bean); + } + + return list; + } + + public boolean checkLockStatus(String resourceId, String kqdate) { + if (!LOCK_DEGREE.equals("0")&&!LOCK_DEGREE.equals("1")) { + return false; + } + try { + RecordSet rs = new RecordSet(); + ResourceComInfo resourceComInfo = new ResourceComInfo(); + String subcompanyId = resourceComInfo.getSubCompanyID(resourceId); + String departmentId = resourceComInfo.getDepartmentID(resourceId); + String sql = "select * from " + LOCK_TABLE + " where (" + LOCK_FROMDATE + "<='" + kqdate + "' and " + LOCK_TODATE + " >= '" + kqdate + "' ) "; + String sqlWhere = ""; + if (!"".equals(resourceId)) { + if (rs.getDBType().equals("oracle")||rs.getDBType().equals("postgresql")) { + sqlWhere=" and (','||CAST(" + LOCK_RESOURCE + " AS VARCHAR(2000))||',') like '%," + resourceId + ",%'"; + } else if (rs.getDBType().equals("mysql")) { + sqlWhere=" and concat(','," + LOCK_RESOURCE + ",',') like '%," + resourceId + ",%'" ; + } else { + sqlWhere=" and (','+CAST(" + LOCK_RESOURCE + " AS VARCHAR(2000))+',') like '%," + resourceId + ",%'" ; + } + rs.executeQuery(sql + sqlWhere); + rs.writeLog("KQLockAttendaUtil>sql="+sql + sqlWhere); + if (rs.next()) { + String lockValue = rs.getString(LOCK_LOCK); + if(lockValue.equals("1")){ + return true; + }else{ + return false; + } + } + } + if (!"".equals(departmentId)) { + if (rs.getDBType().equals("oracle")||rs.getDBType().equals("postgresql")) { + sqlWhere=" and (','||CAST(" + LOCK_DEPT + " AS VARCHAR(2000))||',') like '%," + departmentId + ",%'"; + } else if (rs.getDBType().equals("mysql")) { + sqlWhere=" and concat(','," + LOCK_DEPT + ",',') like '%," + departmentId + ",%'"; + } else { + sqlWhere=" and (','+CAST(" + LOCK_DEPT + " AS VARCHAR(2000))+',') like '%," + departmentId + ",%'"; + } + rs.writeLog("KQLockAttendaUtil>sql="+sql + sqlWhere); + rs.executeQuery(sql + sqlWhere); + if (rs.next()) { + String lockValue = rs.getString(LOCK_LOCK); + if(lockValue.equals("1")){ + return true; + }else{ + return false; + } + } + } + if (!"".equals(subcompanyId)) { + if (rs.getDBType().equals("oracle")||rs.getDBType().equals("postgresql")) { + sqlWhere=" and (','||CAST(" + LOCK_SUBCOM + " AS VARCHAR(2000))||',') like '%," + subcompanyId + ",%'"; + } else if (rs.getDBType().equals("mysql")) { + sqlWhere=" and concat(','," + LOCK_SUBCOM + ",',') like '%," + subcompanyId + ",%'"; + } else { + sqlWhere=" and (','+CAST(" + LOCK_SUBCOM + " AS VARCHAR(2000))+',') like '%," + subcompanyId + ",%'"; + } + rs.writeLog("KQLockAttendaUtil>sql="+sql + sqlWhere); + rs.executeQuery(sql + sqlWhere); + if (rs.next()) { + String lockValue = rs.getString(LOCK_LOCK); + if(lockValue.equals("1")){ + return true; + }else{ + return false; + } + } + } + sqlWhere=" and (" + LOCK_COM + "=1) "; + rs.writeLog("KQLockAttendaUtil>sql="+sql + sqlWhere); + rs.executeQuery(sql + sqlWhere); + if (rs.next()) { + String lockValue = rs.getString(LOCK_LOCK); + if(lockValue.equals("1")){ + return true; + }else{ + return false; + } + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + /** + * 判断当前范围内是否存在已被锁定的日期 + * + * @param fromDate 开始日期 + * @param toDate 结束日期 + */ + public boolean isLockDate(String fromDate, String toDate) { + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); + try { + Date startDate = format.parse(fromDate); + Date endDate = format.parse(toDate); + for (KqLockAttenda datas : this.sdkqbb_map) { + Date ksrqDate = format.parse(datas.getLOCK_FROMDATE()); + Date jsrqDate = format.parse(datas.getLOCK_TODATE()); + if (isInterSection(startDate, endDate, ksrqDate, jsrqDate)) { + return true; + } + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + /** + * 两个时间段是否存在交叉 + * + * @param startDateOne 第一个时间段的开始时间 + * @param endDateOne 第一个时间段的结束时间 + * @param startDateTwo 第二个时间段的开始时间 + * @param endDateTwo 第二个时间段的结束时间 + */ + private static boolean isInterSection(Date startDateOne, Date endDateOne, Date startDateTwo, Date endDateTwo) { + Date maxStartDate = startDateOne; + if (maxStartDate.before(startDateTwo)) { + maxStartDate = startDateTwo; + } + Date minEndDate = endDateOne; + if (endDateTwo.before(minEndDate)) { + minEndDate = endDateTwo; + } + return maxStartDate.before(minEndDate) || (maxStartDate.getTime() == minEndDate.getTime()); + } + + + + public boolean isLockDate(Map params) { + JSONObject jsonObj = JSON.parseObject(Util.null2String(params.get("data"))); + String fromDate = Util.null2String(jsonObj.getString("fromDate")); + String toDate = Util.null2String(jsonObj.getString("toDate")); + String typeselect = Util.null2String(jsonObj.getString("typeselect")); + if (typeselect.length() == 0) { + typeselect = "3"; + } + if (!typeselect.equals("0") && !typeselect.equals("6")) { + if (typeselect.equals("1")) { + fromDate = TimeUtil.getCurrentDateString(); + toDate = TimeUtil.getCurrentDateString(); + } else { + fromDate = TimeUtil.getDateByOption(typeselect, "0"); + toDate = TimeUtil.getDateByOption(typeselect, "1"); + } + } + return this.isLockDate(fromDate, toDate); + } + + /** + * 锁定日期范围内的考勤报表数据 + * + * @param params 参数 + * @param user 当前登录用户 + */ + public Map lockReport(Map params, User user) { + Map result = new HashMap<>(); + BaseBean baseBean = new BaseBean(); + JSONObject jsonObj = JSON.parseObject(Util.null2String(params.get("data"))); + String fromDate = Util.null2String(jsonObj.getString("fromDate")); + String toDate = Util.null2String(jsonObj.getString("toDate")); + String typeselect = Util.null2String(jsonObj.getString("typeselect")); + if (typeselect.length() == 0) { + typeselect = "3"; + } + if (!typeselect.equals("0") && !typeselect.equals("6")) { + if (typeselect.equals("1")) { + fromDate = TimeUtil.getCurrentDateString(); + toDate = TimeUtil.getCurrentDateString(); + } else { + fromDate = TimeUtil.getDateByOption(typeselect, "0"); + toDate = TimeUtil.getDateByOption(typeselect, "1"); + } + } + boolean lockDate = this.isLockDate(fromDate, toDate); + if (lockDate) { + result.put("status", "0"); + result.put("message", "当前日期范围内存在被锁定的数据,请重新选择日期范围!"); + return result; + } + // 保存锁定周期 + RecordSet recordSet = new RecordSet(); + String formModeId = baseBean.getPropValue("qc2648525", "sdkqbb.form.mode.id"); + String sql = "insert into uf_sdkqbb (ksrq, jsrq, sfsd, formmodeid) values ('" + fromDate + "', '" + toDate + "', 1, " + formModeId + ")"; + recordSet.execute(sql); +// RunnableTask runnableTask = new RunnableTask(user, fromDate, toDate, params, null, true, true); +// EXECUTOR_SERVICE.execute(runnableTask); +// String finalFromDate = fromDate; +// String finalToDate = toDate; +// new Thread(() -> { +// // 更新初始化缓存 +// this.sdkqbb_map = this.initModuleData(); +// // 未归档流程退回到发起节点 +// this.doForceOver(user); +// // 同步数据到建模表 +// this.syncKqData(user, finalFromDate, finalToDate, params); +// }).start(); + result.put("status", "1"); + result.put("message", "锁定成功!"); + return result; + } + + /** + * 强制归档 + */ + public void doForceOver(User user) { + BaseBean baseBean = new BaseBean(); + String workflowIds = baseBean.getPropValue("qc2648525", "kq.workflow.ids"); + RecordSet recordSet = new RecordSet(); + RecordSet newRecordSet = new RecordSet(); + String newSql = "select requestid, workflowid, requestnamenew from workflow_requestbase where workflowid in (" + workflowIds + ") and (currentnodetype = 1 or currentnodetype = 2)"; + String updateSql = "update workflow_requestbase set requestnamenew = ? where requestid = ?"; + recordSet.execute(newSql); + while (recordSet.next()) { + String requestId = Util.null2String(recordSet.getString("requestid")); + String workflowId = Util.null2String(recordSet.getString("workflowid")); + String requestNameNew = Util.null2String(recordSet.getString("requestnamenew")); + if (this.canContinueWorkflow(workflowId, requestId)) { + continue; + } + Map otherParams = new HashMap<>(); + otherParams.put("ismonitor", "1"); + ReqOperateRequestEntity reqOperateRequestEntity = new ReqOperateRequestEntity(); + reqOperateRequestEntity.setRequestId(Util.getIntValue(requestId)); + reqOperateRequestEntity.setRemark("流程日期存在被锁定的考勤数据,流程强制归档且不计入考勤数据"); + reqOperateRequestEntity.setOtherParams(otherParams); + this.doForceOver(user, reqOperateRequestEntity); + requestNameNew = "(已作废)" + requestNameNew; + newRecordSet.executeUpdate(updateSql, requestNameNew, requestId); + } + } + + /** + * 考勤数据同步到建模表 + * + * @param fromDate 开始日期 + * @param toDate 结束日期 + */ + public void syncKqData(User user, String fromDate, String toDate, Map params) { + try { + BigDecimal hourMins = new BigDecimal("60"); + ResourceComInfo resourceComInfo = new ResourceComInfo(); + RecordSet recordSet = new RecordSet(); + BatchRecordSet batchRecordSet = new BatchRecordSet(); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); + BaseBean baseBean = new BaseBean(); + String tableName = baseBean.getPropValue("qc2648525", "sync.table.name"); + String formModeId = baseBean.getPropValue("qc2648525", "sync.form.mode.id"); + KQReportBiz kqReportBiz = new KQReportBiz(); + List> allLeaveRules = KQLeaveRulesBiz.getAllLeaveRules(); + Map flowData = kqReportBiz.getDailyFlowData(params, user); + Date startDate = simpleDateFormat.parse(fromDate); + LocalDate l1 = LocalDate.parse(fromDate); + LocalDate l2 = LocalDate.parse(toDate); + long fromEpochDay = l1.toEpochDay(); + long toEpochDay = l2.toEpochDay(); + long diff = toEpochDay - fromEpochDay; + for (long i = 0; i <= diff; i++) { + List> values = new ArrayList<>(); + String syncDate = simpleDateFormat.format(DateUtil.addDay(startDate, (int) i)); + String newSql = "select * from kq_format_total where kqdate = ?"; + recordSet.executeQuery(newSql, syncDate); + while (recordSet.next()) { + List list = new ArrayList<>(); + list.add(formModeId); + String xm = recordSet.getString("resourceid"); + String gs = resourceComInfo.getSubCompanyID(xm); + String bm = resourceComInfo.getDepartmentID(xm); + String rq = recordSet.getString("kqdate"); + String bc = Util.null2s(recordSet.getString("serialid"), "-1"); + list.add(xm); + list.add(gs); + list.add(bm); + list.add(rq); + list.add(bc); + + Map signDetailInfo = getSignDetailInfo(xm, rq, user); + String sbdk1 = Util.null2s(Util.null2String(signDetailInfo.get("signintime1")), "-1"); + String qdkqjg1 = Util.null2s(Util.null2String(signDetailInfo.get("signinstatus1")), "-1"); + String xbdk1 = Util.null2s(Util.null2String(signDetailInfo.get("signouttime1")), "-1"); + String qtkqjg1 = Util.null2s(Util.null2String(signDetailInfo.get("signoutstatus1")), "-1"); + list.add(sbdk1); + list.add(qdkqjg1); + list.add(xbdk1); + list.add(qtkqjg1); + String sbdk2 = Util.null2s(Util.null2String(signDetailInfo.get("signintime2")), "-1"); + String qdkqjg2 = Util.null2s(Util.null2String(signDetailInfo.get("signinstatus2")), "-1"); + String xbdk2 = Util.null2s(Util.null2String(signDetailInfo.get("signouttime2")), "-1"); + String qtkqjg2 = Util.null2s(Util.null2String(signDetailInfo.get("signoutstatus2")), "-1"); + list.add(sbdk2); + list.add(qdkqjg2); + list.add(xbdk2); + list.add(qtkqjg2); + String sbdk3 = Util.null2s(Util.null2String(signDetailInfo.get("signintime3")), "-1"); + String qdkqjg3 = Util.null2s(Util.null2String(signDetailInfo.get("signinstatus3")), "-1"); + String xbdk3 = Util.null2s(Util.null2String(signDetailInfo.get("signouttime3")), "-1"); + String qtkqjg3 = Util.null2s(Util.null2String(signDetailInfo.get("signoutstatus3")), "-1"); + list.add(sbdk3); + list.add(qdkqjg3); + list.add(xbdk3); + list.add(qtkqjg3); + + double ycqts = Util.getDoubleValue(recordSet.getString("workdays"), 0); + BigDecimal ygzsc = new BigDecimal(Util.null2s(recordSet.getString("workmins"), "0")).divide(hourMins, 2, BigDecimal.ROUND_HALF_DOWN); + double sjcqts = Util.getDoubleValue(recordSet.getString("attendancedays"), 0); + BigDecimal sjgzsc = new BigDecimal(Util.null2s(recordSet.getString("attendanceMins"), "0")).divide(hourMins, 2, BigDecimal.ROUND_HALF_DOWN); + list.add(ycqts); + list.add(ygzsc.doubleValue()); + list.add(sjcqts); + list.add(sjgzsc.doubleValue()); + + double cd = Util.getDoubleValue(recordSet.getString("beLate"), 0); + BigDecimal cdsc = new BigDecimal(Util.null2s(recordSet.getString("beLateMins"), "0")).divide(hourMins, 2, BigDecimal.ROUND_HALF_DOWN); + double zt = Util.getDoubleValue(recordSet.getString("leaveEearly"), 0); + BigDecimal ztsc = new BigDecimal(Util.null2s(recordSet.getString("leaveEarlyMins"), "0")).divide(hourMins, 2, BigDecimal.ROUND_HALF_DOWN); + double kg = Util.getDoubleValue(recordSet.getString("absenteeism"), 0); + BigDecimal kgsc = new BigDecimal(Util.null2s(recordSet.getString("absenteeismMins"), "0")).divide(hourMins, 2, BigDecimal.ROUND_HALF_DOWN); + list.add(cd); + list.add(cdsc.doubleValue()); + list.add(zt); + list.add(ztsc.doubleValue()); + list.add(kg); + list.add(kgsc.doubleValue()); + + Map leaveInfo = getLeaveInfo(syncDate, xm, allLeaveRules, flowData); + double leaveType_2 = Util.getDoubleValue(leaveInfo.get("leaveType_2"), 0); + double leaveType_5 = Util.getDoubleValue(leaveInfo.get("leaveType_5"), 0); + double leaveType_6 = Util.getDoubleValue(leaveInfo.get("leaveType_6"), 0); + double leaveType_7 = Util.getDoubleValue(leaveInfo.get("leaveType_7"), 0); + double leaveType_8 = Util.getDoubleValue(leaveInfo.get("leaveType_8"), 0); + double leaveType_9 = Util.getDoubleValue(leaveInfo.get("leaveType_9"), 0); + double leaveType_10 = Util.getDoubleValue(leaveInfo.get("leaveType_10"), 0); + double leaveType_11 = Util.getDoubleValue(leaveInfo.get("leaveType_11"), 0); + double leaveType_12 = Util.getDoubleValue(leaveInfo.get("leaveType_12"), 0); + double leaveType_13 = Util.getDoubleValue(leaveInfo.get("leaveType_13"), 0); + double leaveType_14 = Util.getDoubleValue(leaveInfo.get("leaveType_14"), 0); + double leaveType_15 = Util.getDoubleValue(leaveInfo.get("leaveType_15"), 0); + double leaveType_16 = Util.getDoubleValue(leaveInfo.get("leaveType_16"), 0); + double leaveType_17 = Util.getDoubleValue(leaveInfo.get("leaveType_17"), 0); + list.add(leaveType_2); + list.add(leaveType_5); + list.add(leaveType_6); + list.add(leaveType_7); + list.add(leaveType_8); + list.add(leaveType_9); + list.add(leaveType_10); + list.add(leaveType_11); + list.add(leaveType_12); + list.add(leaveType_13); + list.add(leaveType_14); + list.add(leaveType_15); + list.add(leaveType_16); + list.add(leaveType_17); + + double bgldxgzrjb = Util.getDoubleValue(Util.null2String(flowData.get(xm + "|" + syncDate + "|workingDayOvertime_nonleave"))); + bgldxgzrjb = bgldxgzrjb < 0 ? 0 : bgldxgzrjb; + double bgldxzmjb = Util.getDoubleValue(Util.null2String(flowData.get(xm + "|" + syncDate + "|restDayOvertime_nonleave"))); + bgldxzmjb = bgldxzmjb < 0 ? 0 : bgldxzmjb; + double bgldxjjqjb = Util.getDoubleValue(Util.null2String(flowData.get(xm + "|" + syncDate + "|holidayOvertime_nonleave"))); + bgldxjjqjb = bgldxjjqjb < 0 ? 0 : bgldxjjqjb; + double gldxgzrjb = Util.getDoubleValue(Util.null2String(flowData.get(xm + "|" + syncDate + "|workingDayOvertime_4leave"))); + gldxgzrjb = gldxgzrjb < 0 ? 0 : gldxgzrjb; + double gldxzmjb = Util.getDoubleValue(Util.null2String(flowData.get(xm + "|" + syncDate + "|restDayOvertime_4leave"))); + gldxzmjb = gldxzmjb < 0 ? 0 : gldxzmjb; + double gldxjjrjb = Util.getDoubleValue(Util.null2String(flowData.get(xm + "|" + syncDate + "|holidayOvertime_4leave"))); + gldxjjrjb = gldxjjrjb < 0 ? 0 : gldxjjrjb; + double jbzj = Util.getDoubleValue(KQDurationCalculatorUtil.getDurationRound(String.valueOf(bgldxgzrjb + bgldxzmjb + bgldxjjqjb + gldxgzrjb + gldxzmjb + gldxjjrjb))); + list.add(bgldxgzrjb); + list.add(bgldxzmjb); + list.add(bgldxjjqjb); + list.add(gldxgzrjb); + list.add(gldxzmjb); + list.add(gldxjjrjb); + list.add(jbzj); + + double cc = Util.getDoubleValue(Util.null2String(flowData.get(xm + "|" + syncDate + "|businessLeave"))); + cc = cc < 0 ? 0 : cc; + double gc = Util.getDoubleValue(Util.null2String(flowData.get(xm + "|" + syncDate + "|officialBusiness"))); + gc = gc < 0 ? 0 : gc; + double lq1 = Util.getDoubleValue(recordSet.getString("forgotcheck"), 0); + double lq2 = Util.getDoubleValue(recordSet.getString("forgotBeginWorkCheck"), 0); + double lq = lq1 + lq2; + list.add(cc); + list.add(gc); + list.add(lq); + + values.add(list); + } + // 删除之前同步的数据 + newSql = "delete from " + tableName + " where rq = ?"; + recordSet.executeUpdate(newSql, syncDate); + // 同步新数据到到建模表 + newSql = "insert into " + tableName + "(formmodeid,xm,gs,bm,rq,bc,sbdk1,qdkqjg1,xbdk1,qtkqjg1,sbdk2,qdkqjg2,xbdk2,qtkqjg2,sbdk3,qdkqjg3,xbdk3,qtkqjg3,ycqts,ygzsc,sjcqts,sjgzsc,cd,cdsc,zt,ztsc,kg,kgsc,leaveType_2,leaveType_5,leaveType_6,leaveType_7,leaveType_8,leaveType_9,leaveType_10,leaveType_11,leaveType_12,leaveType_13,leaveType_14,leaveType_15,leaveType_16,leaveType_17,bgldxgzrjb,bgldxzmjb,bgldxjjqjb,gldxgzrjb,gldxzmjb,gldxjjrjb,jbzj,cc,gc,lq) " + + " values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + batchRecordSet.executeBatchSqlNew(newSql, values); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static Map getLeaveInfo(String kqdate, String id, List> allLeaveRules, Map flowData) { + Map map = new HashMap<>(); + for (int i = 0; allLeaveRules != null && i < allLeaveRules.size(); i++) { + Map leaveRule = allLeaveRules.get(i); + String flowType = Util.null2String("leaveType_" + leaveRule.get("id")); + String leaveData = Util.null2String(flowData.get(id + "|" + kqdate + "|" + flowType)); + String flowLeaveBackType = Util.null2String("leavebackType_" + leaveRule.get("id")); + String leavebackData = Util.null2s(Util.null2String(flowData.get(id + "|" + kqdate + "|" + flowLeaveBackType)), "0.0"); + String b_flowLeaveData = ""; + String flowLeaveData = ""; + try { + if (leaveData.length() == 0) { + leaveData = "0.0"; + } + if (leavebackData.length() == 0) { + leavebackData = "0.0"; + } + BigDecimal b_leaveData = new BigDecimal(leaveData); + BigDecimal b_leavebackData = new BigDecimal(leavebackData); + b_flowLeaveData = b_leaveData.subtract(b_leavebackData).toString(); + if (Util.getDoubleValue(b_flowLeaveData, -1) < 0) { + b_flowLeaveData = "0.0"; + } + } catch (Exception e) { + kqLog.info("GetKQReportCmd:leaveData" + leaveData + ":leavebackData:" + leavebackData + ":" + e); + } + if (b_flowLeaveData.length() > 0) { + flowLeaveData = KQDurationCalculatorUtil.getDurationRound(b_flowLeaveData); + } else { + flowLeaveData = KQDurationCalculatorUtil.getDurationRound(Util.null2String(Util.getDoubleValue(leaveData, 0.0) - Util.getDoubleValue(leavebackData, 0.0))); + } + map.put(flowType, flowLeaveData); + } + return map; + } + + public static Map getSignDetailInfo(String resourceId, String kqDate, User user) { + Map data = new HashMap<>(); + Map signStatusInfo = null; + RecordSet rs = new RecordSet(); + KQTimesArrayComInfo kqTimesArrayComInfo = new KQTimesArrayComInfo(); + try { + String sql = " select kqdate,resourceid,serialid,serialnumber,workbegindate,workbegintime, " + + " workenddate,workendtime,workmins,signindate,signintime,signoutdate,signouttime, \n" + + " attendanceMins,belatemins,graveBeLateMins,leaveearlymins,graveLeaveEarlyMins,absenteeismmins,forgotcheckMins,forgotBeginWorkCheckMins," + + " leaveMins,leaveInfo,evectionMins,outMins,signinid,signoutid \n" + + " from kq_format_detail b \n" + + " where resourceid = " + resourceId + " and kqdate ='" + kqDate + "' \n" + + " order by serialnumber \n"; + rs.execute(sql); + while (rs.next()) { + String serialid = Util.null2String(rs.getString("serialid")); + int serialnumber = rs.getInt("serialnumber") + 1; + String workbegindate = Util.null2String(rs.getString("workbegindate")).trim(); + String workbegintime = Util.null2String(rs.getString("workbegintime")).trim(); + String workenddate = Util.null2String(rs.getString("workenddate")).trim(); + String workendtime = Util.null2String(rs.getString("workendtime")).trim(); + String signintime = Util.null2String(rs.getString("signintime")).trim(); + String signouttime = Util.null2String(rs.getString("signouttime")).trim(); + String beLateMins = Util.null2String(rs.getString("beLateMins")).trim(); + String graveBeLateMins = Util.null2String(rs.getString("graveBeLateMins")).trim(); + String leaveEarlyMins = Util.null2String(rs.getString("leaveEarlyMins")).trim(); + String graveLeaveEarlyMins = Util.null2String(rs.getString("graveLeaveEarlyMins")).trim(); + String absenteeismMins = Util.null2String(rs.getString("absenteeismMins")).trim(); + String forgotCheckMins = Util.null2String(rs.getString("forgotcheckMins")).trim(); + String forgotBeginWorkCheckMins = Util.null2String(rs.getString("forgotBeginWorkCheckMins")).trim(); + String signinid = Util.null2String(rs.getString("signinid")).trim(); + String signoutid = Util.null2String(rs.getString("signoutid")).trim(); + int leaveMins = rs.getInt("leaveMins"); + String leaveInfo = Util.null2String(rs.getString("leaveInfo")); + int evectionMins = rs.getInt("evectionMins"); + int outMins = rs.getInt("outMins"); + + if (serialid.length() > 0) { + if (workbegintime.length() > 0) { + signStatusInfo = new HashMap<>(); + signStatusInfo.put("workdate", workbegindate); + signStatusInfo.put("worktime", workbegintime); + signStatusInfo.put("beLateMins", beLateMins); + signStatusInfo.put("forgotBeginWorkCheckMins", forgotBeginWorkCheckMins); + signStatusInfo.put("graveBeLateMins", graveBeLateMins); + signStatusInfo.put("absenteeismMins", absenteeismMins); + signStatusInfo.put("leaveMins", leaveMins); + signStatusInfo.put("leaveInfo", leaveInfo); + signStatusInfo.put("evectionMins", evectionMins); + signStatusInfo.put("outMins", outMins); + data.put("signintime" + serialnumber, signintime.length() == 0 ? SystemEnv.getHtmlLabelName(25994, user.getLanguage()) : signintime); + data.put("signinstatus" + serialnumber, KQReportBiz.getSignStatus(signStatusInfo, user, "on")); + } + + if (workendtime.length() > 0) { + signStatusInfo = new HashMap<>(); + signStatusInfo.put("workdate", workenddate); + signStatusInfo.put("worktime", kqTimesArrayComInfo.turn48to24Time(workendtime)); + signStatusInfo.put("leaveEarlyMins", leaveEarlyMins); + signStatusInfo.put("graveLeaveEarlyMins", graveLeaveEarlyMins); + signStatusInfo.put("forgotCheckMins", forgotCheckMins); + signStatusInfo.put("forgotBeginWorkCheckMins", forgotBeginWorkCheckMins); + signStatusInfo.put("absenteeismMins", absenteeismMins); + signStatusInfo.put("leaveMins", leaveMins); + signStatusInfo.put("leaveInfo", leaveInfo); + signStatusInfo.put("evectionMins", evectionMins); + signStatusInfo.put("outMins", outMins); + data.put("signouttime" + serialnumber, signouttime.length() == 0 ? SystemEnv.getHtmlLabelName(25994, user.getLanguage()) : signouttime); + data.put("signoutstatus" + serialnumber, KQReportBiz.getSignStatus(signStatusInfo, user, "off")); + } + } else { + signStatusInfo = new HashMap(); + signStatusInfo.put("leaveMins", leaveMins); + signStatusInfo.put("leaveInfo", leaveInfo); + signStatusInfo.put("evectionMins", evectionMins); + signStatusInfo.put("outMins", outMins); + if (signinid.length() > 0) { + data.put("signintime" + serialnumber, signintime.length() == 0 ? SystemEnv.getHtmlLabelName(25994, user.getLanguage()) : signintime); + data.put("signinstatus" + serialnumber, KQReportBiz.getSignStatus(signStatusInfo, user, "on")); + if (signoutid.length() > 0) { + data.put("signouttime" + serialnumber, signouttime.length() == 0 ? SystemEnv.getHtmlLabelName(25994, user.getLanguage()) : signouttime); + data.put("signoutstatus" + serialnumber, KQReportBiz.getSignStatus(signStatusInfo, user, "off")); + } + } else { + data.put("signinstatus" + serialnumber, KQReportBiz.getSignStatus(signStatusInfo, user, "on")); + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + return data; + } + + + /** + * 考勤流程是否能继续提交 + * + * @param request 请求详情 + */ + public String canSubmitWorkflow(RequestInfo request) { + String requestId = request.getRequestid(); + String workflowId = request.getWorkflowid(); + kqLog.info("do canSubmitWorkflow on workflowId:" + workflowId + "|requestId:" + requestId); + if (canContinueWorkflow(workflowId, requestId)) { + return Action.SUCCESS; + } + request.getRequestManager().setMessageid("11111" + request.getRequestid() + "22222"); + request.getRequestManager().setMessagecontent("当前日期周期内存在被锁定的考勤数据,请重新选择日期周期!"); + return Action.FAILURE_AND_CONTINUE; + } + + /** + * 考勤流程能否继续提交 + * + * @param workflowId 流程id + * @param requestId 请求id + */ + public boolean canContinueWorkflow(String workflowId, String requestId) { + try { + int requestIdInt = Util.getIntValue(requestId, 0); + String formId = new WorkflowComInfo().getFormId(workflowId); + // 是否是考勤变更流程 + boolean isProcessChange = false; + // 是否是销假流程 + boolean isLeaveBack = false; + List splitBeans = new ArrayList<>(); + RecordSet recordSet = new RecordSet(); + String sql = "select * from kq_att_proc_set where field001 = ? and field002 = ? "; + recordSet.executeQuery(sql, workflowId, formId); + if (recordSet.next()) { + String proc_set_id = recordSet.getString("id"); + String useDetails = recordSet.getString("usedetail"); + int kqType = Util.getIntValue(recordSet.getString("field006")); + Map map = new HashMap<>(); + if (requestIdInt > 0) { + map.put("requestId", "and t.requestId = " + requestIdInt); + } + KQFlowActiontBiz kqFlowActiontBiz = new KQFlowActiontBiz(); + ResourceComInfo resourceComInfo = new ResourceComInfo(); + DateTimeFormatter datetimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); + Map sqlMap = kqFlowActiontBiz.handleSql(proc_set_id, useDetails, requestIdInt, kqType, map); + if (kqType == KqSplitFlowTypeEnum.LEAVE.getFlowtype()) { + KQFlowLeaveUtil kqFlowLeaveUtil = new KQFlowLeaveUtil(); + kqFlowLeaveUtil.handleKQLeaveAction(sqlMap, splitBeans, datetimeFormatter, Util.getIntValue(workflowId), requestIdInt, resourceComInfo); + } else if (kqType == KqSplitFlowTypeEnum.EVECTION.getFlowtype()) { + KQFlowEvectionUtil kqFlowEvectionUtil = new KQFlowEvectionUtil(); + kqFlowEvectionUtil.handleKQEvectionAction(sqlMap, splitBeans, datetimeFormatter, Util.getIntValue(workflowId), requestIdInt, resourceComInfo); + } else if (kqType == KqSplitFlowTypeEnum.OUT.getFlowtype()) { + KQFlowOutUtil kqFlowOutUtil = new KQFlowOutUtil(); + kqFlowOutUtil.handleKQOutAction(sqlMap, splitBeans, datetimeFormatter, Util.getIntValue(workflowId), requestIdInt, resourceComInfo); + } else if (kqType == KqSplitFlowTypeEnum.OVERTIME.getFlowtype()) { + KQFlowOvertimeUtil kqFlowOvertimeUtil = new KQFlowOvertimeUtil(); + kqFlowOvertimeUtil.handleKQOvertimeAction(sqlMap, splitBeans, datetimeFormatter, Util.getIntValue(workflowId), requestIdInt, resourceComInfo, ""); + } else if (kqType == KqSplitFlowTypeEnum.CARD.getFlowtype()) { + String[] cardFields = KQAttFlowFieldsSetBiz.cardFields; + RecordSet newRecordSet = new RecordSet(); + if (!sqlMap.isEmpty()) { + for (Map.Entry entry : sqlMap.entrySet()) { + String value = entry.getValue(); + newRecordSet.execute(value); + while (newRecordSet.next()) { + String fDetailSignDate = cardFields[3]; + String signDate = Util.null2s(newRecordSet.getString(fDetailSignDate), ""); + if (this.isLockDate(signDate, signDate)) { + return false; + } + } + } + } + } else if (kqType == KqSplitFlowTypeEnum.LEAVEBACK.getFlowtype()) { + isLeaveBack = true; + KQFlowLeaveBackUtil kqFlowLeaveBackUtil = new KQFlowLeaveBackUtil(); + kqFlowLeaveBackUtil.handleKQLeaveBackAction(sqlMap, splitBeans, datetimeFormatter, Util.getIntValue(workflowId), requestIdInt, resourceComInfo); + } else if (kqType == KqSplitFlowTypeEnum.PROCESSCHANGE.getFlowtype()) { + isProcessChange = true; + KQFlowProcessChangeUtil kqFlowProcessChangeUtil = new KQFlowProcessChangeUtil(); + kqFlowProcessChangeUtil.handleKQProcessChangeAction(sqlMap, splitBeans, datetimeFormatter, Util.getIntValue(workflowId), requestIdInt, resourceComInfo); + } + } + for (SplitBean splitBean : splitBeans) { + String fromDate = ""; + String toDate = ""; + if (isProcessChange) { + ProcessChangeSplitBean processChangeSplitBean = splitBean.getProcessChangeSplitBean(); + fromDate = processChangeSplitBean.getFromdatedb(); + toDate = processChangeSplitBean.getTodatedb(); + if (this.isLockDate(fromDate, toDate)) { + return false; + } + fromDate = splitBean.getFromdatedb(); + toDate = splitBean.getTodatedb(); + } else if (isLeaveBack) { + String resourceId = splitBean.getResourceId(); + String leaveBackRequestId = splitBean.getLeavebackrequestid(); + sql = "select fromdatedb, todatedb from kq_flow_split_leave where resourceid = ? and requestid = ? group by fromdatedb, todatedb"; + recordSet.executeQuery(sql, resourceId, leaveBackRequestId); + if (recordSet.next()) { + fromDate = Util.null2String(recordSet.getString("fromdatedb")); + toDate = Util.null2String(recordSet.getString("todatedb")); + } + } else { + fromDate = splitBean.getFromdatedb(); + toDate = splitBean.getTodatedb(); + } + if (this.isLockDate(fromDate, toDate)) { + return false; + } + } + } catch (Exception e) { + return false; + } + return true; + } + + /** + * 强制归档 + * + * @param user 用户 + * @param requestParam 请求参数 + */ + public void doForceOver(User user, ReqOperateRequestEntity requestParam) { + int requestId = requestParam.getRequestId(); + Map otherParams = requestParam.getOtherParams(); + PAResponseEntity pAEntity = RequestOperateBiz.verifyBefore(user, requestId, otherParams); + if (pAEntity.getCode() != null) { + return; + } + WfFunctionManageUtil wfFunctionManageUtil = new WfFunctionManageUtil(); + RequestInfoEntity reqEntity = RequestOperateBiz.initRequestInfo(requestParam, user); + int isremark = reqEntity.getIsremark(); + int agentType = Util.getIntValue(Util.null2String(otherParams.get("agenttype"))); + int agentorByAgentId = Util.getIntValue(Util.null2String(otherParams.get("agentorbyagentid"))); + // 流程代理出去,本人提交,需先收回代理 + if (isremark == 2 && agentType == 1 && agentorByAgentId > 0) { + AgentManager agentManager = new AgentManager(user); + agentManager.agentBackRequest(agentorByAgentId, user.getUID(), reqEntity.getWorkflowId() + "", requestParam.getRequestId()); + reqEntity = RequestOperateBiz.initRequestInfo(requestParam, user); + isremark = reqEntity.getIsremark(); + } + int nodeid = Util.getIntValue(reqEntity.getCurrentNodeId()); + int takisremark = reqEntity.getTakisremark(); + HashMap map = wfFunctionManageUtil.wfFunctionManageByNodeid(reqEntity.getWorkflowId(), FreeNodeBiz.isFreeNode(nodeid) ? -9 : nodeid); + WfForceOver wfo = new WfForceOver(); + String ov = (String) map.get("ov"); + boolean hasRight = (isremark == 0 && (takisremark == 0 || takisremark == -1)) && "1".equals(ov) && wfo.isNodeOperator(requestId, user.getUID()) && !reqEntity.getCurrentNodeType().equals("3"); + boolean isMonitor = "1".equals(Util.null2String(otherParams.get("ismonitor"))); + if (!hasRight && isMonitor) { + MonitorDTO monitorInfo = new Monitor().getMonitorInfo(String.valueOf(user.getUID()), reqEntity.getCreatorId(), String.valueOf(reqEntity.getWorkflowId())); + hasRight = monitorInfo.getIsforceover() && !"3".equals(reqEntity.getCurrentNodeType()); + } + if (hasRight) { + ArrayList requestidlist = new ArrayList(); + requestidlist.add("" + requestId); + wfo.setRemark(requestParam.getRemark()); + wfo.doForceOver(requestidlist, null, null, user); + pAEntity.setCode(PAResponseCode.SUCCESS); + String isnew = new BaseBean().getPropValue("WorkflowOvertimeIsNew", "isNew"); + if ("1".equals(isnew)) { + OvertimeBiz.getInstance().cancelOvertimeTask(requestId, Util.getIntValue(reqEntity.getCurrentNodeId()));// 取消超时任务 + } + } else { + pAEntity.setCode(PAResponseCode.NO_PERMISSION); + } + } + + /** + * 同步建模表里面的打卡数据 + */ + public void importData() { + RecordSet rs = new RecordSet(); + String endDateTime = weaver.common.DateUtil.getDate(new Date(), "yyyy-MM-dd HH:mm"); + Calendar calendar = weaver.common.DateUtil.getCalendar(endDateTime); + calendar.add(Calendar.MINUTE, -45); + String startDateTime = weaver.common.DateUtil.getDate(calendar.getTime(), "yyyy-MM-dd HH:mm"); + + KQScheduleSignImport kqScheduleSignImport = new KQScheduleSignImport(); + BatchRecordSet bRs = new BatchRecordSet(); + List> lsParams = new ArrayList<>(); + List params = null; + List> lsDelParams = new ArrayList<>(); + List delParams = null; + List lsFormatData = new ArrayList<>(); + List> lsFormatParams = new ArrayList<>(); + List formatParams = null; + Map> users = kqScheduleSignImport.getUsers(7); + Map loginidMap = users.get("loginidMap"); + Map lastnameMap = users.get("lastnameMap"); + Map workcodeMap = users.get("workcodeMap"); + List keymap = new ArrayList<>(); + List lsImportSetting = new ArrayList<>(); + ImportSetting importSetting = null; + String sql = " select datasourceid, loginid, workcode, lastname, signdate, signtime, tablename, clientaddress,longitude,latitude,addr,memo from HrmScheduleSignSet "; + rs.execute(sql); + while (rs.next()) { + importSetting = new ImportSetting(); + importSetting.setDatasourceid(Util.null2String(rs.getString("datasourceid")).trim()); + importSetting.setLoginid(Util.null2String(rs.getString("loginid")).trim()); + importSetting.setWorkcode(Util.null2String(rs.getString("workcode")).trim()); + importSetting.setLastname(Util.null2String(rs.getString("lastname")).trim()); + importSetting.setSigndate(Util.null2String(rs.getString("signdate")).trim()); + importSetting.setSigntime(Util.null2String(rs.getString("signtime")).trim()); + importSetting.setTablename(Util.null2String(rs.getString("tablename")).trim()); + importSetting.setClientaddress(Util.null2String(rs.getString("clientaddress")).trim()); + importSetting.setLongitude(Util.null2String(rs.getString("longitude")).trim()); + importSetting.setLatitude(Util.null2String(rs.getString("latitude")).trim()); + importSetting.setAddr(Util.null2String(rs.getString("addr")).trim()); + importSetting.setMemo(Util.null2String(rs.getString("memo")).trim()); + lsImportSetting.add(importSetting); + } + List lsKQScheduleSignData = new ArrayList<>(); + KQScheduleSignEntity kqScheduleSignData = null; + for (int i = 0; i < lsImportSetting.size(); i++) { + try { + importSetting = lsImportSetting.get(i); + String datasourceid = importSetting.getDatasourceid(); + String loginid = importSetting.getLoginid(); + String workcode = importSetting.getWorkcode(); + String lastname = importSetting.getLastname(); + String signdate = importSetting.getSigndate(); + String signtime = importSetting.getSigntime(); + String tablename = importSetting.getTablename(); + String clientaddress = importSetting.getClientaddress(); + String longitude = importSetting.getLongitude(); + String latitude = importSetting.getLatitude(); + String addr = importSetting.getAddr(); + String memo = importSetting.getMemo(); + DateFormat df = new SimpleDateFormat("HH:mm:ss"); + if ("sqlserver".equals(rs.getDBType())) { + sql = "select * from " + tablename + " where " + " " + signdate + "+' '+" + signtime + " >= '" + startDateTime + "' and " + signdate + "+' '+" + signtime + " <= '" + endDateTime + "' "; + } else { + sql = "select * from " + tablename + " where " + " concat(" + signdate + ",' '," + signtime + ") >= '" + startDateTime + "' and concat(" + signdate + ",' '," + signtime + ") <= '" + endDateTime + "' "; + } + // 有遇到外部同步,上面的【conn = ds.getConnection();】这个阻塞住,导致下面的同步不执行,下面的用法和集成领导确认 + RecordSetDataSource rsds = new RecordSetDataSource(datasourceid); + rsds.execute(sql); + while (rsds.next()) { + String tmpLoginid = ""; + String tmpWorkcode = ""; + String tmpLastname = ""; + String tmpSigndate = ""; + String tmpSigntime = ""; + String tmpClientaddress = ""; + String tmpLongitude = ""; + String tmpLatitude = ""; + String tmpAddr = ""; + String tmpMemo = ""; + if (loginid.length() > 0) { + tmpLoginid = Util.null2String(rsds.getString(loginid)).trim(); + } + if (workcode.length() > 0) { + tmpWorkcode = Util.null2String(rsds.getString(workcode)).trim(); + } + if (lastname.length() > 0) { + tmpLastname = Util.null2String(rsds.getString(lastname)).trim(); + } + if (signdate.length() > 0) { + tmpSigndate = Util.null2String(rsds.getString(signdate)).trim(); + } + if (clientaddress.length() > 0) { + tmpClientaddress = Util.null2String(rsds.getString(clientaddress)); + } + if (longitude.length() > 0) { + tmpLongitude = Util.null2String(rsds.getString(longitude)).trim(); + } + if (latitude.length() > 0) { + tmpLatitude = Util.null2String(rsds.getString(latitude)).trim(); + } + if (addr.length() > 0) { + tmpAddr = Util.null2String(rsds.getString(addr)).trim(); + } + if (memo.length() > 0) { + tmpMemo = Util.null2String(rsds.getString(memo)).trim(); + } + if (signtime.length() > 0) { + tmpSigntime = Util.null2String(rsds.getString(signtime)).trim(); + // 判断tmpSigntime格式 08:21:11 如果为长格式需要格式化 + if (tmpSigntime.length() > 8) { + // 有遇到signtime格式为hh:mm:ss.0000的格式导致同步不成功 + if (tmpSigntime.length() < 16) { + tmpSigntime = tmpSigntime.substring(0, 8); + } + // 比如上yyyy-mm-dd hh:mm的格式走原逻辑 + else { + tmpSigntime = df.format(Timestamp.valueOf(tmpSigntime)); + } + } else if (tmpSigntime.length() < 8) { + // 不带秒的情况 自动补齐 + tmpSigntime += ":00"; + } + } else { + tmpSigntime = ""; + } + + if (tmpSigndate.length() > 10) { + // 如果时间为长格式,从signdate字段中格式化时间 + if (tmpSigndate.length() == 16) { + //不带秒的情况 自动补齐 + tmpSigntime += ":00"; + } + // 以signtime字段为有限 + if (tmpSigntime.length() == 0) { + tmpSigndate = tmpSigndate.length() > 19 ? tmpSigndate.substring(0, 19) : tmpSigndate; + tmpSigntime = df.format(Timestamp.valueOf(tmpSigndate)); + } + tmpSigndate = Tools.formatDate(tmpSigndate, "yyyy-MM-dd"); + } + // 如果时间格式不带秒补齐 + if (tmpSigntime.length() <= 5) { + tmpSigntime += ":00"; + } + kqScheduleSignData = new KQScheduleSignEntity(); + kqScheduleSignData.setLoginid(tmpLoginid); + kqScheduleSignData.setWorkcode(tmpWorkcode); + kqScheduleSignData.setLastname(tmpLastname); + kqScheduleSignData.setSigndate(tmpSigndate); + kqScheduleSignData.setSigntime(tmpSigntime); + kqScheduleSignData.setClientaddress(tmpClientaddress); + kqScheduleSignData.setLongitude(tmpLongitude); + kqScheduleSignData.setLatitude(tmpLatitude); + kqScheduleSignData.setAddr(tmpAddr); + kqScheduleSignData.setMemo(tmpMemo); + lsKQScheduleSignData.add(kqScheduleSignData); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + List noRepertSynData = new ArrayList<>(); + for (int i = 0; i < lsKQScheduleSignData.size(); i++) { + kqScheduleSignData = lsKQScheduleSignData.get(i); + String tmpLoginid = kqScheduleSignData.getLoginid(); + String tmpWorkcode = kqScheduleSignData.getWorkcode(); + String tmpLastname = kqScheduleSignData.getLastname(); + String tmpSigndate = kqScheduleSignData.getSigndate(); + String tmpSigntime = kqScheduleSignData.getSigntime(); + String tmpClientaddress = kqScheduleSignData.getClientaddress(); + String tmpLongitude = kqScheduleSignData.getLongitude(); + String tmpLatitude = kqScheduleSignData.getLatitude(); + String tmpAddr = kqScheduleSignData.getAddr(); + String tmpMemo = kqScheduleSignData.getMemo(); + int userid = 0; + if (Util.null2String(tmpLoginid).length() > 0) { + userid = weaver.common.StringUtil.parseToInt(loginidMap.get(tmpLoginid), 0); + } + if (userid == 0 && Util.null2String(tmpWorkcode).length() > 0) { + userid = weaver.common.StringUtil.parseToInt(workcodeMap.get(tmpWorkcode), 0); + } + if (userid == 0 && Util.null2String(tmpLastname).length() > 0) { + userid = weaver.common.StringUtil.parseToInt(lastnameMap.get(tmpLastname), 0); + } + if (userid <= 0) { + continue; + } + String dkParamData = userid + "#" + tmpSigndate + "#" + tmpSigntime; + if (noRepertSynData.contains(dkParamData)) { + continue; + } + noRepertSynData.add(dkParamData); + params = new ArrayList<>(); + params.add(userid); + params.add(1); + params.add(tmpSigndate); + params.add(tmpSigntime); + params.add(tmpClientaddress); + params.add(1); + params.add(1); + params.add("OutDataSourceSyn"); + params.add(tmpLongitude); + params.add(tmpLatitude); + params.add(tmpAddr); + params.add(tmpMemo); + lsParams.add(params); + String belongDate = getBelongDate(new User(userid), tmpSigndate, tmpSigntime); + String formatData = userid + "|" + tmpSigndate + "|" + belongDate; + if (!lsFormatData.contains(formatData)) { + lsFormatData.add(formatData); + } + } + Map> overtimeMap = Maps.newHashMap(); + List overtimeList = Lists.newArrayList(); + // 刷新报表数据 + for (int i = 0; i < lsFormatData.size(); i++) { + formatParams = new ArrayList<>(); + String key = lsFormatData.get(i); + String[] formatData = Util.splitString(lsFormatData.get(i), "|"); + String date_1 = weaver.common.DateUtil.addDate(formatData[1], -1); + formatParams.add(formatData[0]); + formatParams.add(date_1); + lsFormatParams.add(formatParams); + formatParams = new ArrayList<>(); + formatParams.add(formatData[0]); + formatParams.add(formatData[1]); + lsFormatParams.add(formatParams); + if (!keymap.contains(key)) { + keymap.add(key); + delParams = new ArrayList<>(); + delParams.add(formatData[0]); + // delParams.add(formatData[1]); + delParams.add(startDateTime + ":00"); + delParams.add(endDateTime + ":00"); + lsDelParams.add(delParams); + } + String resourceId = formatData[0]; + String kqdate = formatData[1]; + String belongDate = formatData[2]; + if (overtimeMap.containsKey(resourceId)) { + List tmp_overtimeList = overtimeMap.get(resourceId); + if (!tmp_overtimeList.contains(kqdate)) { + tmp_overtimeList.add(kqdate); + if (!kqdate.equals(belongDate)) { + tmp_overtimeList.add(belongDate); + } + } + } else { + if (!overtimeList.contains(kqdate)) { + overtimeList.add(kqdate); + if (!kqdate.equals(belongDate)) { + overtimeList.add(belongDate); + } + } + overtimeMap.put(resourceId, overtimeList); + } + } + // 删除本次同步数据 + // sql = " delete from hrmschedulesign where signfrom='OutDataSourceSyn' and userid =? and signdate = ? "; + if ("sqlserver".equals(rs.getDBType())) { + sql = "delete from hrmschedulesign where signfrom = 'OutDataSourceSyn' and userid = ? and signdate + ' ' + signtime >= ? and signdate + ' ' + signtime <= ?"; + } else { + sql = "delete from hrmschedulesign where signfrom = 'OutDataSourceSyn' and userid = ? and concat(signdate,' ',signtime) >= ? and concat(signdate,' ',signtime) <= ?"; + } + bRs.executeBatchSql(sql, lsDelParams); + sql = " insert into HrmScheduleSign (userid, usertype, signdate, signtime, clientaddress, isincom, isimport, signfrom, longitude, latitude, addr,memo) values(?,?,?,?,?,?,?,?,?,?,?,?)"; + bRs.executeBatchSql(sql, lsParams); + new KQFormatBiz().format(lsFormatParams); + // 处理加班生成 + List tasks = new ArrayList<>(); + for (Map.Entry> mme : overtimeMap.entrySet()) { + String resid = mme.getKey(); + List overList = mme.getValue(); + for (String date : overList) { + SplitActionUtil.pushOverTimeTasks(date, date, resid, tasks); + } + } + if (!tasks.isEmpty()) { + KQQueue.writeTasks(tasks); + } + } + + public String getBelongDate(User user, String curDate, String signDateTime) { + String belongDate = curDate; + Map todayLineMap = KQDurationCalculatorUtil.getWorkButton(user, curDate, true); + if (todayLineMap != null) { + List> preInfo = (ArrayList>) todayLineMap.get("pre_signTime"); + if (preInfo != null) { + for (Map entry : preInfo) { + String pre_endtime_across = entry.get("endtime_across"); + String pre_endtime = entry.get("endtime"); + String signEndInfo = "1".equals(pre_endtime_across) ? (curDate + " " + pre_endtime + ":00") : (weaver.common.DateUtil.addDate(curDate, -1) + " " + pre_endtime + ":00"); + String signOutDateTime = signDateTime; + if (signOutDateTime.compareTo(signEndInfo) < 0) { + belongDate = weaver.common.DateUtil.addDate(curDate, -1); + } + } + } + } + return belongDate; + } + + /** + * 线程池执行任务封装 + */ +// public static class RunnableTask implements Runnable { +// +// private final User user; +// +// private final boolean isSyncData; +// +// private final boolean isDoForceOver; +// +// private final String finalFromDate; +// +// private final String finalToDate; +// +// private Map params; +// +// private final List> formatValues; +// +// public RunnableTask(User user, String finalFromDate, String finalToDate, Map params, List> formatValues, boolean isSyncData, boolean isDoForceOver) { +// this.user = user; +// this.finalFromDate = finalFromDate; +// this.finalToDate = finalToDate; +// this.params = params; +// this.formatValues = formatValues; +// this.isSyncData = isSyncData; +// this.isDoForceOver = isDoForceOver; +// } +// +// @Override +// public void run() { +// BaseBean baseBean = new BaseBean(); +// QC2648525Util qc2648525Util = new QC2648525Util(); +// if (formatValues != null && formatValues.size() > 0) { +// long startTime = System.currentTimeMillis(); +// for (List objs : formatValues) { +// String userId = Util.null2String(objs.get(0)); +// String kqDate = Util.null2String(objs.get(1)); +// new KQFormatData().formatKqDate(userId, kqDate); +// } +// baseBean.writeLog("QC2648525 刷新考勤报表耗时:" + ((System.currentTimeMillis() - startTime) / 1000) + "秒"); +// } +// if (isDoForceOver) { +// long startTime = System.currentTimeMillis(); +// qc2648525Util.doForceOver(user); +// baseBean.writeLog("QC2648525 强制归档流程执行耗时:" + ((System.currentTimeMillis() - startTime) / 1000) + "秒"); +// } +// if (isSyncData) { +// long startTime = System.currentTimeMillis(); +// if (params == null || params.isEmpty()) { +// Map datas = new HashMap<>(); +// datas.put("typeselect", "6"); +// datas.put("fromDate", finalFromDate); +// datas.put("toDate", finalToDate); +// datas.put("attendanceSerial", ""); +// datas.put("isFromMyAttendance", "1"); +// params = new HashMap<>(); +// params.put("data", JSONObject.toJSONString(datas)); +// params.put("reportType", "month"); +// } +// qc2648525Util.syncKqData(user, finalFromDate, finalToDate, params); +// baseBean.writeLog("QC2648525 建模数据同步执行耗时:" + ((System.currentTimeMillis() - startTime) / 1000) + "秒"); +// } +// } +// } + + // --- 王宇负责部分 --- + + public static String[] colors = new String[]{"#47A9FC", "#70C06F", "#F6D65C", "#EA744D", "#4EBCCC", "#EA5C85", "#8F72F2", "#7297F2", "#CA4DE4", "#A7CC62"}; + + public static String getKQGroupId(String userId, String workDate, boolean containFixed) { + String groupId = ""; + KQGroupComInfo kqGroupComInfo = new KQGroupComInfo(); + KQGroupMemberComInfo kqGroupMemberComInfo = new KQGroupMemberComInfo(); + List lsGroupIds = kqGroupMemberComInfo.getKQGroups(userId,workDate); + for (int i = 0; lsGroupIds != null && i < lsGroupIds.size(); i++) { + String tmpGroupId = Util.null2String((String) lsGroupIds.get(i)); + String kqtype = kqGroupComInfo.getKqtype(tmpGroupId); + String validity = kqGroupComInfo.getValidity(tmpGroupId); + String validityfromdate = kqGroupComInfo.getValidityfromdate(tmpGroupId); + String validityenddate = kqGroupComInfo.getValidityenddate(tmpGroupId); + if (validity.equals("1")) { + if (weaver.common.DateUtil.isInDateRange(workDate, validityfromdate, validityenddate)) { + groupId = tmpGroupId; + } else { + continue; + } + } else { + groupId = tmpGroupId; + } + if (groupId.length() > 0) { + if (containFixed && kqtype.equals("2")) { + KQShiftScheduleComInfo kqShiftScheduleComInfo = new KQShiftScheduleComInfo(); + if (Util.null2String(kqShiftScheduleComInfo.getSerialId(userId, workDate)).length() > 0 && Util.null2String(kqShiftScheduleComInfo.getGroupId(userId, workDate)).equals(groupId)) { + break; + } + } else { + break; + } + } + } + return groupId; + } + + /** + * 从考勤报表中获取班次 + * + * @param resourceId 用户 + * @param kqDate 日期 + * @param groupId 原来的groupId + */ + public static String getGroupId(String resourceId, String kqDate, String groupId) { + + String newGroupId = ""; + String currentDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date()); + if (kqDate.compareTo(currentDate) > 0) { + return groupId; + } + RecordSet recordSet = new RecordSet(); + String sql = "select groupid from kq_format_total where resourceid = ? and kqdate = ?"; + recordSet.executeQuery(sql, resourceId, kqDate); + if (recordSet.next()) { + newGroupId = Util.null2String(recordSet.getString("groupid")); + } + return StringUtil.isBlank(newGroupId) ? groupId : newGroupId; + } + + /** + * 前台我的排班颜色添加 + * + * @param user 登录用户 + * @param resourceId 展示的用户id + * @param fromDate 开始日期 + * @param toDate 结束日期 + * @param result 结果集 + */ + public static void getScheduleReportInfo(User user, String resourceId, String fromDate, String toDate, Map result) { + RecordSet recordSet = new RecordSet(); + KQGroupComInfo kqGroupComInfo = new KQGroupComInfo(); + ShiftManagementToolKit shiftManagementToolKit = new ShiftManagementToolKit(); + KQWorkTime kqWorkTime = new KQWorkTime(); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + String sql = ""; + Map data = null; + String currentDate = weaver.common.DateUtil.getCurrentDate(); + // 今天之前的日期在考勤报表中查询 + if (fromDate.compareTo(currentDate) <= 0) { + // 结束日期小于当前日期 当前日期=结束日期 + if (toDate.compareTo(currentDate) < 0) { + LocalDate localDate = LocalDate.parse(toDate); + currentDate = formatter.format(localDate); + } + sql = "select kqdate, groupid, serialid from kq_format_total where resourceid = ? and kqdate >= ? and kqdate <= ?"; + recordSet.executeQuery(sql, resourceId, fromDate, currentDate); + while (recordSet.next()) { + String date = Util.null2String(recordSet.getString("kqdate")); + String serialId = Util.null2String(recordSet.getString("serialid")); + String groupId = Util.null2String(recordSet.getString("groupid")); + if (StringUtil.isBlank(serialId)) { + continue; + } + String color = ""; + String kqType = kqGroupComInfo.getKqtype(groupId); + if ("1".equals(kqType)) { + color = getColorBySerialId(kqGroupComInfo, groupId, serialId); + } else if ("2".equals(kqType)) { + color = getColorBySerialId(kqGroupComInfo, groupId, serialId); + } + String serial = shiftManagementToolKit.getShiftOnOffWorkSections(serialId, user.getLanguage()); + data = new HashMap<>(); + data.put("serial", serial); + data.put("bgColor", color); + result.put(date, data); + } + } + // 今天之后的日期 固定班次保持不变,排班在排班表中查询 + currentDate = weaver.common.DateUtil.getCurrentDate(); + + if (toDate.compareTo(currentDate) >= 0) { + + // 开始日期大于当前日期 当前日期=开始日期 + LocalDate localDate; + if (fromDate.compareTo(currentDate) > 0) { + localDate = LocalDate.parse(fromDate); + } else { + localDate = LocalDate.parse(currentDate).plusDays(1); + } + currentDate = formatter.format(localDate); + String kqGroupId = getKQGroupId(resourceId, currentDate, true); + LocalDate startDate = LocalDate.parse(currentDate); + LocalDate endDate = LocalDate.parse(toDate); + KQHolidaySetComInfo kqHolidaySetComInfo = new KQHolidaySetComInfo(); + long sd = startDate.toEpochDay(); + long ed = endDate.toEpochDay(); + long diff = ed - sd; + for (long i = 0; i <= diff; i++) { + LocalDate td = startDate.plusDays(i); + String targetDate = formatter.format(td); + String changeType = kqHolidaySetComInfo.getChangeType(kqGroupId, targetDate); + if ("1".equals(changeType) || "3".equals(changeType)) { + continue; + } + WorkTimeEntity workTime = kqWorkTime.getWorkTime(resourceId, targetDate); + String serialId = workTime.getSerialId(); + if (serialId != null) { + data = new HashMap<>(); + String serial = shiftManagementToolKit.getShiftOnOffWorkSections(serialId, user.getLanguage()); + data.put("serial", serial); + data.put("bgColor", "#000"); + result.put(targetDate, data); + } + } + } + } + + public static String getColorBySerialId(KQGroupComInfo kqGroupComInfo, String groupId, String serialId) { + String color = ""; + String serialIds = kqGroupComInfo.getSerialids(groupId); + if (StringUtil.isNotBlank(serialIds)) { + String[] serialArr = serialIds.split(","); + for (int i = 0; i < serialArr.length; i++) { + if (serialArr[i].trim().equals(serialId)) { + color = colors[i]; + break; + } + } + } + return color; + } + + /** + * 星期 + * + * @param date 日期 + */ + public static int getDayOfWeek(String date) { + try { + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); + // 创建Calendar类实例 + Calendar instance = Calendar.getInstance(); + // 根据指定日期获取周几 + instance.setTime(format.parse(date)); + // 因为数组下标从0开始,而返回的是数组的内容,是数组{1,2,3,4,5,6,7}中用1~7来表示 Saturday->7 + int i = instance.get(Calendar.DAY_OF_WEEK); + if (i >= Calendar.MONDAY && i <= Calendar.FRIDAY) { + i = i - 2; + } else if (i == Calendar.SATURDAY) { + i = 5; + } else if (i == Calendar.SUNDAY) { + i = 6; + } + return i; + } catch (Exception e) { + return -1; + } + } + +} diff --git a/领悦二开new/src/com/engine/kq/util/lingyuewuye/ExpirationDateMethod.java b/领悦二开new/src/com/engine/kq/util/lingyuewuye/ExpirationDateMethod.java new file mode 100644 index 0000000..52605b2 --- /dev/null +++ b/领悦二开new/src/com/engine/kq/util/lingyuewuye/ExpirationDateMethod.java @@ -0,0 +1,44 @@ +package com.engine.kq.util.lingyuewuye; + +import com.alibaba.fastjson.JSON; +import com.api.integration.Base; +import com.api.personalIncomeTax.web.BabyCareAction; +import com.engine.kq.biz.KQBalanceOfLeaveBiz; +import weaver.general.BaseBean; +import weaver.general.Util; +import weaver.systeminfo.SystemEnv; + +import java.util.Calendar; + +public class ExpirationDateMethod { + public String getBalanceStatusShow(String leaveRulesId, String otherParams) { + new BaseBean().writeLog("qc3286856 leaveRulesId="+leaveRulesId+";otherParams="+ JSON.toJSONString(otherParams)); + String statusShow = ""; + try { + String resourceId = otherParams.split("\\+", 5)[0]; + String belongYear = otherParams.split("\\+", 5)[1]; + String languageId = otherParams.split("\\+", 5)[2]; + String effectiveDate = otherParams.split("\\+", 5)[3]; + String expirationDate = otherParams.split("\\+", 5)[4]; + + /*获取今天的日期、此刻的时间*/ + Calendar today = Calendar.getInstance(); + String currentDate = Util.add0(today.get(Calendar.YEAR), 4) + "-" + + Util.add0(today.get(Calendar.MONTH) + 1, 2) + "-" + + Util.add0(today.get(Calendar.DAY_OF_MONTH), 2); + new BaseBean().writeLog("qc3286856 currentDate="+currentDate); + boolean status = false; + if (currentDate.compareTo(expirationDate) <= 0){ + status = true; + } + if (status) { + statusShow = SystemEnv.getHtmlLabelName(2246, Util.getIntValue(languageId, 7)); + } else { + statusShow = SystemEnv.getHtmlLabelName(2245, Util.getIntValue(languageId, 7)); + } + } catch (Exception e) { + e.printStackTrace(); + } + return statusShow; + } +} diff --git a/领悦二开new/src/com/engine/kq/util/lingyuewuye/NianJiaUtil.java b/领悦二开new/src/com/engine/kq/util/lingyuewuye/NianJiaUtil.java new file mode 100644 index 0000000..1c548df --- /dev/null +++ b/领悦二开new/src/com/engine/kq/util/lingyuewuye/NianJiaUtil.java @@ -0,0 +1,80 @@ +package com.engine.kq.util.lingyuewuye; + +import com.alibaba.fastjson.JSON; +import com.engine.kq.biz.KQBalanceOfLeaveBiz; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.BaseBean; +import weaver.general.TimeUtil; +import weaver.general.Util; + +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; + +public class NianJiaUtil { + + public void saveExpirationDate(String ruleId,String belongyear,int organizationType,String organizationIds){ + String nianjiaId = Prop.getInstance().getPropValue("lingyue_nianjia","nianjiaid"); + BaseBean bb = new BaseBean(); + bb.writeLog("qc3222529 nianjiaid = "+nianjiaId +";ruleId = "+ruleId); + if (!ruleId.equals(nianjiaId)){//如果传进来的假期id不是年假id,不执行下面的代码 + return; + } + String searchSql = "select id from hrmresource where (status in (0,1,2,3)) "; + if (organizationType == 1) { + searchSql += " and subCompanyId1 in (" + organizationIds + ") "; + } else if (organizationType == 2) { + searchSql += " and departmentId in (" + organizationIds + ") "; + } else if (organizationType == 3) { + searchSql += " and id in (" + organizationIds + ") "; + } + RecordSet searchRS = new RecordSet(); + searchRS.executeQuery(searchSql); + List sqlList = new ArrayList<>(); +// String resourceid = ""; + while (searchRS.next()){//因为同一个假期规则,它生成的失效日期是一样的,所以,取其中一个人的id出来,用于获取失效日期 + String resourceid = Util.null2String(searchRS.getString("id")); + String expirationDate = KQBalanceOfLeaveBiz.getExpirationDate(ruleId,resourceid,belongyear,"",""); + bb.writeLog("qc3222529 resourceid is not null ===="+resourceid+";expirationDate="+expirationDate+";ruleid="+ruleId+";belongyear="+belongyear); + List list = new ArrayList<>(); + list.add(expirationDate); + list.add(resourceid); + sqlList.add(list); +// resourceid = Util.null2String(searchRS.getString("id")); +// break; + } + bb.writeLog("qc3222529 sqlList:"+ JSON.toJSONString(sqlList)); +// if (!resourceid.equals("")){ + if (sqlList != null && sqlList.size() > 0){ +// bb.writeLog("qc3222529 resourceid is not null ===="+resourceid); + +// String expirationDate = KQBalanceOfLeaveBiz.getExpirationDate(ruleId,resourceid,belongyear,"",""); + String sql = "update kq_BalanceOfLeave set expirationDate=? where leaveRulesId ="+ ruleId +"and belongYear ='"+belongyear+"' and resourceId = ? and (ycts is null or ycts = 0)"; + RecordSet rs = new RecordSet(); + boolean flag = rs.executeBatchSql(sql, sqlList); + +// boolean flag = rs.executeUpdate(sql, expirationDate, ruleId,belongyear); + if (!flag){ + bb.writeLog("qc3222529 修改年假失效日期出错!"); + } + } + + } + public static String getNianJiaExpriationDate(String ruleid,String resourceid,String belongYear){ + String sql = "select * from kq_BalanceOfLeave where leaveRulesId = ? and resourceId = ? and belongYear = ?"; + RecordSet rs = new RecordSet(); + rs.executeQuery(sql,ruleid,resourceid,belongYear); + String expirationDate = ""; + while (rs.next()){ + expirationDate = Util.null2String(rs.getString("expirationDate")); +// int ycts = Util.getIntValue(rs.getString("ycts"),0); +// DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); +// // 解析输入的日期 +// LocalDate date = LocalDate.parse(expirationDate, formatter); +// expirationDate = date.plusDays(ycts).toString(); + } + return expirationDate; + } +} diff --git a/领悦二开new/src/com/engine/lingyue/util/KqUtil.java b/领悦二开new/src/com/engine/lingyue/util/KqUtil.java new file mode 100644 index 0000000..809be3c --- /dev/null +++ b/领悦二开new/src/com/engine/lingyue/util/KqUtil.java @@ -0,0 +1,2253 @@ +package com.engine.lingyue.util; + +import com.engine.kq.biz.KQGroupMemberComInfo; +import com.engine.kq.biz.KQWorkTime; +import com.engine.kq.entity.KQGroupEntity; +import com.engine.kq.entity.WorkTimeEntity; +import org.apache.commons.lang.StringUtils; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.company.DepartmentComInfo; +import weaver.hrm.company.SubCompanyComInfo; +import weaver.hrm.resource.ResourceComInfo; + +import java.math.BigDecimal; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.*; + +/** + * @Title + * @Author wangchaofa + * @CreateDate 2024/11/7 + * @Version 1.0 + * @Description + */ +public class KqUtil { + + /** + * 计算两个时间字符串日期的相差天数 + * + * @param sStartDate 字符串时间1 + * @param sEndDate 字符串时间2 + * @return 相差时间 + */ + public static int getDays(String sStartDate, String sEndDate) { + int days = 0; + try { + if (!"".equals(sStartDate) && !"".equals(sEndDate)) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + Date date1 = sdf.parse(sStartDate); + Date date2 = sdf.parse(sEndDate); + + long Days = (date2.getTime() - date1.getTime()) / (24*3600*1000); + if(Days < 0){ + days = 0; + }else{ + days = (int)Days+1; + } + } + }catch (Exception e){ + e.printStackTrace(); + } + return days; + } + + /** + * 计算天数 + * @param date1 日期 + * @param date2 日期 + * @return 天数 + */ + public static int calculateDays(Date date1, Date date2) { + Calendar cal1 = Calendar.getInstance(); + cal1.setTime(date1); + Calendar cal2 = Calendar.getInstance(); + cal2.setTime(date2); + int day1 = cal1.get(Calendar.DAY_OF_YEAR); + int day2 = cal2.get(Calendar.DAY_OF_YEAR); + int year1 = cal1.get(Calendar.YEAR); + int year2 = cal2.get(Calendar.YEAR); + if (year1 != year2) {//不同 年 + int timeDistance = 0; + if (year1 < year2) {//后面日期年大于前面日期 + for (int i = year1; i < year2; i++) { + if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {//闰年 + timeDistance += 366; + } else {//不是闰年 + timeDistance += 365; + } + } + } else { + for (int i = year2; i < year1; i++) { + if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {//闰年 + timeDistance += 366; + } else {//不是闰年 + timeDistance += 365; + timeDistance = 0 - timeDistance; + } + } + } + return timeDistance + (day2 - day1); + } else {//同一年 + return day2 - day1; + } + } + + /** + * @param a 任意数 + * @return 是 + */ + private static String isZero(String a) { + if (a==null || "".equals(a)) { + a = "0"; + } + return a; + } + + /** + * 大小比较 + * + * @param a + * @param b + * @return -1 小于 0 等于 1 大于 + */ + public static int floatCompare(String a, String b) { + a = isZero(a); + b = isZero(b); + BigDecimal bg1 = new BigDecimal(a); + BigDecimal bg2 = new BigDecimal(b); + return bg1.compareTo(bg2); + } + + /** + * 方法描述 : 对两个字符串进行金额的相加 + * @param a + * @param b + * @return + * String + */ + public static String floatAdd(String a, String b) { + a=a.equals("")?"0":a; + b=b.equals("")?"0":b; + BigDecimal bg1 = new BigDecimal(a); + BigDecimal bg2 = new BigDecimal(b); + BigDecimal bd = bg1.add(bg2); + return bd.toString(); + } + + /** + * + * 方法描述 : 对两个字符串进行金额的相减 + * @param a + * @param b + * @return + * String + */ + public static String floatSubtract(String a, String b) { + a=a.equals("")?"0":a; + b=b.equals("")?"0":b; + BigDecimal bg1 = new BigDecimal(a); + BigDecimal bg2 = new BigDecimal(b); + BigDecimal bd = bg1.subtract(bg2); + return bd.toString(); + } + + /** + * + * 方法描述 : 对两个字符串进行金额的相乘 + * @param a + * @param b + * @return + * String + */ + public static String floatMultiply(String a, String b) { + a=a.equals("")?"0":a; + b=b.equals("")?"0":b; + BigDecimal bg1 = new BigDecimal(a); + BigDecimal bg2 = new BigDecimal(b); + BigDecimal bd = bg1.multiply(bg2).setScale(4, BigDecimal.ROUND_HALF_UP); + return bd.toString(); + } + + /** + * + * 方法描述 : 对两个字符串进行金额的相除(默认保留两位小数) + * @param a + * @param b + * @return + * String + */ + public static String floatDivide(String a, String b) { + a=a.equals("")?"0":a; + b=b.equals("")?"0":b; + BigDecimal bg1 = new BigDecimal(a); + BigDecimal bg2 = new BigDecimal(b); + BigDecimal bd = bg1.divide(bg2, 2, BigDecimal.ROUND_HALF_UP); + return bd.toString(); + } + + /** + * 判断当月有几天 + * @param Year int 2020 + * @param Month int 8 + * @return + */ + public static int getMonthDays(String Year, String Month) { + int year = Integer.parseInt(Year); + int month = Integer.parseInt(Month); + if (month == 2) { + if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) { + return 29; + } else { + return 28; + } + } else if (month == 4 || month == 6 || month == 9 || month == 11) { + return 30; + } else { + return 31; + } + } + + /** + * 比较时间的大小 + * @param a + * @param b + * @return + * @throws ParseException + */ + public static boolean compareDate(String a, String b){ + boolean bool = false; + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + try { + long t1 = sdf.parse(a).getTime(); + long t2 = sdf.parse(b).getTime(); + if (t1 >= t2) { + bool = true; + } + return bool; + }catch (Exception e){ + e.printStackTrace(); + } + return bool; + } + + /** + * 获取 旷工天数(薪酬调整前) + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static double getAbsenteeismDaysBeforeSalaryBefore(String fromdate, String todate,String userid){ + double result = 0.00; + RecordSet rs = new RecordSet(); + // 薪资调整日期 + String salaryAdjustDate = getSalaryAdjustDate(fromdate,todate,userid); + if(salaryAdjustDate != null && !"".equals(salaryAdjustDate)){ + if(belongCalendar(salaryAdjustDate,fromdate,todate)) { + rs.executeQuery("select sum(absenteeism) as days from kq_format_total " + + " where resourceid = ? and kqdate >= ? and kqdate < ? ", userid, fromdate, salaryAdjustDate); + while (rs.next()) { + result = Util.getDoubleValue(rs.getString("days"), 0.00); + } + } +// else{ +// rs.executeQuery("select sum(absenteeism) as days from kq_format_total " + +// " where resourceid = ? and kqdate >= ? and kqdate < ? ", userid, fromdate, todate); +// while (rs.next()) { +// result = Util.getDoubleValue(rs.getString("days"), 0.00); +// } +// } + } + return result; + } + + /** + * 获取 旷工天数(薪酬调整后) + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static double getAbsenteeismDaysAfterSalaryAfter(String fromdate, String todate,String userid){ + double result = 0.00; + RecordSet rs = new RecordSet(); + // 薪资调整日期 + String salaryAdjustDate = getSalaryAdjustDate(fromdate,todate,userid); + if(salaryAdjustDate != null && !"".equals(salaryAdjustDate)){ + if(belongCalendar(salaryAdjustDate,fromdate,todate)) { + rs.executeQuery("select sum(absenteeism) as days from kq_format_total " + + " where resourceid = ? and kqdate >= ? and kqdate <= ? ", userid, salaryAdjustDate, todate); + while (rs.next()) { + result = Util.getDoubleValue(rs.getString("days"), 0.00); + } + }else{ + rs.executeQuery("select sum(absenteeism) as days from kq_format_total " + + " where resourceid = ? and kqdate >= ? and kqdate <= ? ", userid, fromdate, todate); + while (rs.next()) { + result = Util.getDoubleValue(rs.getString("days"), 0.00); + } + } + }else{ + rs.executeQuery("select sum(absenteeism) as days from kq_format_total "+ + " where resourceid = ? and kqdate >= ? and kqdate <= ? ",userid,fromdate,todate); + while(rs.next()){ + result = Util.getDoubleValue(rs.getString("days"),0.00); + } + } + return result; + } + + /** + * 获取 旷工次数 调整前旷工天数+调整后旷工天数 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static double getAbsenteeismDays(String fromdate, String todate,String userid){ + // 调整前旷工天数 + double absenteeismDaysBeforeSalary = getAbsenteeismDaysBeforeSalaryBefore(fromdate,todate,userid); + // 调整后旷工天数 + double absenteeismDaysAfterSalary = getAbsenteeismDaysAfterSalaryAfter(fromdate,todate,userid); + // 漏签、 计0.5天旷工 + double forgotcheckabsenteeismdays = getForgotCheckAbsenteeismDaysAfter(fromdate,todate,userid); + // 严重迟到、严重早退 计0.5天旷工 + double gravebelateleaveearlydays = getGraveBeLateLeaveEarlyDaysAfter(fromdate,todate,userid); + + return absenteeismDaysBeforeSalary + absenteeismDaysAfterSalary + forgotcheckabsenteeismdays + gravebelateleaveearlydays; + } + + /** + * 获取 旷工次数 标准旷工+标准漏签次数+标准严重迟到次数+标准严重早退次数 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static double getAbsenteeNumsSalary(String fromdate, String todate,String userid){ + double result = 0.00; + RecordSet rs = new RecordSet(); + // 旷工 + rs.executeQuery("select sum(absenteeism) as days from kq_format_total " + + " where resourceid = ? and kqdate >= ? and kqdate <= ? ", userid, fromdate, todate); + while (rs.next()) { + double count = Util.getDoubleValue(rs.getString("days"), 0.00); + result = result + count; + } + // 漏签 + rs.executeQuery("select sum(forgotCheck)+sum(forgotBeginWorkCheck) as count from kq_format_total "+ + " where resourceid = ? and kqdate >= ? and kqdate <= ? ",userid,fromdate,todate); + while(rs.next()){ + double count = Util.getDoubleValue(rs.getString("count"),0.00); + result = result + count; + } + //标准严重迟到次数 + 标准严重早退次数 + rs.executeQuery("select sum(gravebelate)+sum(graveleaveearly) as count from kq_format_total "+ + " where resourceid = ? and kqdate >= ? and kqdate <= ? ",userid,fromdate,todate); + while(rs.next()){ + double count = Util.getDoubleValue(rs.getString("count"),0.00); + result = result + count; + } + return result; + } + + /** + * 获取 产假天数(薪酬用) + * 职级为1和2:取标准产假天数 + * 职级不是1和2:【周一到周五】产假天数+【周六周日】调配工作日产假天数-【周一到周五】调配休息日产假天数 + * 2025-08-08 改成 如果不是职级 1和2 ,当天排了 非休息班次,产假,计数1天,否则 不计数 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static double getMaternityLeaveDaySalary(String fromdate, String todate,String userid){ + double result = 0.00; + RecordSet rs = new RecordSet(); + //职级 + int positionRank = getPositionRank(getPositionRankId(fromdate,todate,userid)); + // 产假 + String maternity_leave_id = rs.getPropValue("hrm_kqreport","maternity_leave_id"); + + if (positionRank == 1 || positionRank == 2) { + result = Double.valueOf(getLeaveTypeDays(maternity_leave_id,fromdate,todate,userid)); + }else{ + result = Double.valueOf(getRestLeaveDaysSalary(maternity_leave_id,fromdate,todate,userid)); + } + return result; + } + + /** + * 获取 日期范围内 假期天数 + * @param leaveType + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static String getLeaveTypeDays(String leaveType,String fromdate, String todate,String userid){ + String result = "0"; + RecordSet rs = new RecordSet(); + + String halfdays = "0"; + String halfbackdays = "0"; + + // 假 时长 + rs.executeQuery("select sum(duration) as count from kq_flow_split_leave where belongdate >= ? and belongdate <= ? and newleavetype in ("+ leaveType +") and resourceid = ? ",fromdate,todate,userid); + while(rs.next()){ + halfdays = Util.null2o(rs.getString("count")); + } + + // 销假时长 + rs.executeQuery("select sum(duration) as count from kq_flow_split_leaveback where belongdate >= ? and belongdate <= ? and newleavetype in ("+ leaveType +") and resourceid = ? ",fromdate,todate,userid); + while(rs.next()){ + halfbackdays = Util.null2o(rs.getString("count")); + } + + result = floatSubtract(halfdays,halfbackdays); + + return result; + } + + /** + * 获取 工伤假天数(薪酬用) + * 职级为1和2:取标准工伤假假天数 + * 职级不是1和2:【周一到周五】工伤假天数+【周六周日】调配工作日工伤假天数-【周一到周五】调配休息日工伤假天数 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static double getInjuryLeaveDaySalary(String fromdate, String todate,String userid){ + double result = 0.00; + RecordSet rs = new RecordSet(); + //职级 + int positionRank = getPositionRank(getPositionRankId(fromdate,todate,userid)); + // 产假 + String injuryLeave_leave_id = rs.getPropValue("hrm_kqreport","injuryLeave_leave_id"); + + if (positionRank == 1 || positionRank == 2) { + result = Double.valueOf(getLeaveTypeDays(injuryLeave_leave_id,fromdate,todate,userid)); + }else{ + result = Double.valueOf(getLeaveDaysSalary(injuryLeave_leave_id,fromdate,todate,userid)); + } + return result; + } + + /** + * 判断日期范围内是否 有产假 + * @param leaveType + * @param fromdate + * @param userid + * @return + */ + public static boolean checkHasMaternityLeave(String leaveType,String fromdate,String userid){ + boolean bool = false; + String result = "0"; + RecordSet rs = new RecordSet(); + + String halfdays = "0"; + String halfbackdays = "0"; + + // 假 时长 + rs.executeQuery("select sum(duration) as count from kq_flow_split_leave where belongdate = ? and newleavetype in ("+ leaveType +") and resourceid = ? ",fromdate,userid); + while(rs.next()){ + halfdays = Util.null2o(rs.getString("count")); + } + + // 销假时长 + rs.executeQuery("select sum(duration) as count from kq_flow_split_leaveback where belongdate = ? and newleavetype in ("+ leaveType +") and resourceid = ? ",fromdate,userid); + while(rs.next()){ + halfbackdays = Util.null2o(rs.getString("count")); + } + + result = floatSubtract(halfdays,halfbackdays); + if(floatCompare(result,"0") > 0){ + bool = true; + } + return bool; + } + + /** + * 获取 工伤假天数(薪酬用) + * @param leaveType + * @param fromDate + * @param toDate + * @param userid + * @return + */ + public static String getLeaveDaysSalary(String leaveType,String fromDate, String toDate,String userid){ + String result = "0"; + RecordSet rs = new RecordSet(); + // 格式化日期 + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + rs.executeQuery("select distinct groupid,kqdate from kq_format_total " + + " where resourceid = ? and kqdate >= ? and kqdate <= ?",userid,fromDate,toDate); + rs.next(); + //考勤组 id +// String groupid = Util.null2String(rs.getString("groupid")); + + String groupid = rs.getPropValue("hrm_kqreport","the_top_groupid"); + + // 周六或周日天数 + String weekdays = "0"; + // 周一到周五天数 + String workdays = "0"; + // 调配休息日天数 + String allocateRestDays = "0"; + // 调配工作日天数 + String allocateWorkDays = "0"; + + String[] dateStartArr = parseDate(fromDate); + String[] dateEndtArr = parseDate(toDate); + LocalDate startDate = LocalDate.of(Integer.parseInt(dateStartArr[0]), Integer.parseInt(dateStartArr[1]), Integer.parseInt(dateStartArr[2])); + LocalDate endDate = LocalDate.of(Integer.parseInt(dateEndtArr[0]), Integer.parseInt(dateEndtArr[1]), Integer.parseInt(dateEndtArr[2])); + // 遍历日期范围 + for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) { + // 输出格式化后的日期字符串 + String dateString = date.format(formatter); + // 是 周六或 周日 + if (isSaturdayOrSunday(dateString)) { + //是调配工作日、是公众假日 + if (isAllocateWorkDay(groupid, dateString) || isAllocateHolidayDay(groupid, dateString)) { + String leaveDays = getLeaveTypeDays(leaveType,dateString,dateString,userid); + if(floatCompare(leaveDays,"0") > 0) { + allocateWorkDays = floatAdd(allocateWorkDays, leaveDays); + } + } + } else { + // 是 调配休息日 + if(isAllocateRestDay(groupid,dateString)){ + String leaveDays = getLeaveTypeDays(leaveType,dateString,dateString,userid); + if(floatCompare(leaveDays,"0") > 0) { + allocateRestDays = floatAdd(allocateRestDays, leaveDays); + } + }else { + String leaveDays = getLeaveTypeDays(leaveType, dateString, dateString, userid); + if (floatCompare(leaveDays, "0") > 0) { + workdays = floatAdd(workdays, leaveDays); + } + } + } + } + result = floatAdd(result,floatAdd(workdays,allocateWorkDays)); + return result; + } + + /** + * 获取 产假天数(薪酬用) + * @param leaveType + * @param fromDate + * @param toDate + * @param userid + * @return + */ + public static String getRestLeaveDaysSalary(String leaveType,String fromDate, String toDate,String userid){ + String result = "0"; + RecordSet rs = new RecordSet(); + // 格式化日期 + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + rs.executeQuery("select distinct groupid,kqdate from kq_format_total " + + " where resourceid = ? and kqdate >= ? and kqdate <= ?",userid,fromDate,toDate); + rs.next(); + //考勤组 id +// String groupid = Util.null2String(rs.getString("groupid")); + + String groupid = rs.getPropValue("hrm_kqreport","the_top_groupid"); + + // 休息班次 + String rest_serial_id = rs.getPropValue("hrm_kqreport","rest_serial_id"); + + // 周六或周日天数 + String weekdays = "0"; + // 周一到周五天数 + String workdays = "0"; + // 调配休息日天数 + String allocateRestDays = "0"; + // 调配工作日天数 + String allocateWorkDays = "0"; + + String[] dateStartArr = parseDate(fromDate); + String[] dateEndtArr = parseDate(toDate); + LocalDate startDate = LocalDate.of(Integer.parseInt(dateStartArr[0]), Integer.parseInt(dateStartArr[1]), Integer.parseInt(dateStartArr[2])); + LocalDate endDate = LocalDate.of(Integer.parseInt(dateEndtArr[0]), Integer.parseInt(dateEndtArr[1]), Integer.parseInt(dateEndtArr[2])); + // 遍历日期范围 + for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) { + // 输出格式化后的日期字符串 + String dateString = date.format(formatter); +// // 是 周六或 周日 +// if (isSaturdayOrSunday(dateString)) { +// //是调配工作日、是公众假日 +// if (isAllocateWorkDay(groupid, dateString) || isAllocateHolidayDay(groupid, dateString)) { +// String leaveDays = getLeaveTypeDays(leaveType,dateString,dateString,userid); +// if(floatCompare(leaveDays,"0") > 0) { +// allocateWorkDays = floatAdd(allocateWorkDays, leaveDays); +// } +// } +// } else { +// // 是 调配休息日 +// if(isAllocateRestDay(groupid,dateString)){ +// String leaveDays = getLeaveTypeDays(leaveType,dateString,dateString,userid); +// if(floatCompare(leaveDays,"0") > 0) { +// allocateRestDays = floatAdd(allocateRestDays, leaveDays); +// } +// }else { +// String leaveDays = getLeaveTypeDays(leaveType, dateString, dateString, userid); +// if (floatCompare(leaveDays, "0") > 0) { +// workdays = floatAdd(workdays, leaveDays); +// } +// } +// } + KQWorkTime kqWorkTime = new KQWorkTime(); + WorkTimeEntity workTimeEntity = kqWorkTime.getWorkTime(userid, dateString); + String searIdFrom = workTimeEntity.getSerialId(); + if(searIdFrom != null && !"".equals(searIdFrom)){ + //当天请了产假 + if(checkHasMaternityLeave(leaveType,dateString,userid)) { + //非休息班次 + if (!rest_serial_id.equals(searIdFrom)) { + result = floatAdd(result, "1"); + } + } + } + } +// result = floatAdd(result,floatAdd(workdays,allocateWorkDays)); + return result; + } + + /** + * 获取 每次漏签、严重迟到、严重早退 计0.5天旷工 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static double getForgotCheckAbsenteeismDaysBefore(String fromdate, String todate,String userid){ + double result = 0.00; + RecordSet rs = new RecordSet(); + rs.executeQuery("select sum(forgotCheck)+sum(forgotBeginWorkCheck) as count from kq_format_total "+ + " where resourceid = ? and kqdate >= ? and kqdate <= ? ",userid,fromdate,todate); + while(rs.next()){ + String count = Util.null2o(rs.getString("count")); + result = Double.valueOf(floatMultiply(count,"0.5")); + } + return result; + } + + /** + * 获取 每次漏签、严重迟到、严重早退 计0.5天旷工 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static double getForgotCheckAbsenteeismDaysAfter(String fromdate, String todate,String userid){ + double result = 0.00; + RecordSet rs = new RecordSet(); + rs.executeQuery("select sum(forgotCheck)+sum(forgotBeginWorkCheck) as count from kq_format_total "+ + " where resourceid = ? and kqdate >= ? and kqdate <= ? ",userid,fromdate,todate); + while(rs.next()){ + String count = Util.null2o(rs.getString("count")); + result = Double.valueOf(floatMultiply(count,"0.5")); + } + return result; + } + + /** + * 获取 每次严重迟到/早退 0.5天旷工 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static double getGraveBeLateLeaveEarlyDaysBefore(String fromdate, String todate,String userid){ + double result = 0.00; + RecordSet rs = new RecordSet(); + rs.executeQuery("select sum(gravebelate)+sum(graveleaveearly) as count from kq_format_total "+ + " where resourceid = ? and kqdate >= ? and kqdate <= ? ",userid,fromdate,todate); + while(rs.next()){ + String count = Util.null2o(rs.getString("count")); + result = Double.valueOf(floatMultiply(count,"0.5")); + } + return result; + } + + /** + * 获取 每次严重迟到/早退 0.5天旷工 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static double getGraveBeLateLeaveEarlyDaysAfter(String fromdate, String todate,String userid){ + double result = 0.00; + RecordSet rs = new RecordSet(); + rs.executeQuery("select sum(gravebelate)+sum(graveleaveearly) as count from kq_format_total "+ + " where resourceid = ? and kqdate >= ? and kqdate <= ? ",userid,fromdate,todate); + while(rs.next()){ + String count = Util.null2o(rs.getString("count")); + result = Double.valueOf(floatMultiply(count,"0.5")); + } + return result; + } + + /** + * 获取 旷工天数(薪酬调整前)总计 取薪酬调动日期调整前的旷工天数(旷工+漏签+严重迟到/早退) + * @param fromdate + * @param todate + * @param userid + * @return + */ +// public static double getAbsenteeismDaysCountBeforeSalary(String fromdate, String todate,String userid){ +// double result = 0.00; +// // 薪资调整日期 +// String salaryAdjustDate = getSalaryAdjustDate(fromdate,todate,userid); +// if(salaryAdjustDate != null && !"".equals(salaryAdjustDate)){ +// if(belongCalendar(salaryAdjustDate,fromdate,todate)) { +// // 薪酬调动日期调整前的旷工天数 +// double absenteeismDaysBeforeSalary = getAbsenteeismDaysBeforeSalaryBefore(fromdate, salaryAdjustDate, userid); +// // 每次漏签计0.5天旷工 +// double forgotDays = getForgotCheckAbsenteeismDaysBefore(fromdate, salaryAdjustDate, userid); +// // 每次 严重迟到/早退每次计0.5天旷工 +// double belateearlydays = getGraveBeLateLeaveEarlyDaysBefore(fromdate, salaryAdjustDate, userid); +// +// result = Double.valueOf(floatAdd(String.valueOf(absenteeismDaysBeforeSalary), floatAdd(String.valueOf(forgotDays), String.valueOf(belateearlydays)))); +// }else{ +// // 薪酬调动日期调整前的旷工天数 +// double absenteeismDaysBeforeSalary = getAbsenteeismDaysBeforeSalaryBefore(fromdate, todate, userid); +// // 每次漏签计0.5天旷工 +// double forgotDays = getForgotCheckAbsenteeismDaysBefore(fromdate, todate, userid); +// // 每次 严重迟到/早退每次计0.5天旷工 +// double belateearlydays = getGraveBeLateLeaveEarlyDaysBefore(fromdate, todate, userid); +// +// result = Double.valueOf(floatAdd(String.valueOf(absenteeismDaysBeforeSalary), floatAdd(String.valueOf(forgotDays), String.valueOf(belateearlydays)))); +// } +// } +// return result; +// } + + public static double getAbsenteeismDaysCountBeforeSalary(String fromdate, String todate,String userid){ + double result = 0.00; + + // 薪酬调动日期调整前的旷工天数 +// double absenteeismDaysBeforeSalary = getAbsenteeismDaysAfterSalaryAfter(fromdate, todate, userid); + // 每次漏签计0.5天旷工 + double forgotDays = getForgotCheckAbsenteeismDaysBefore(fromdate, todate, userid); + // 每次 严重迟到/早退每次计0.5天旷工 + double belateearlydays = getGraveBeLateLeaveEarlyDaysBefore(fromdate, todate, userid); + +// result = Double.valueOf(floatAdd(String.valueOf(absenteeismDaysBeforeSalary), floatAdd(String.valueOf(forgotDays), String.valueOf(belateearlydays)))); + result = Double.valueOf(floatAdd(String.valueOf(forgotDays), String.valueOf(belateearlydays))); + return result; + } + + /** + * 获取 旷工天数(薪酬调整后)总计 取薪酬调动日期调整前的旷工天数(旷工+漏签+严重迟到/早退) + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static double getAbsenteeismDaysCountAfterSalary(String fromdate, String todate,String userid){ + double result = 0.00; + + // 薪酬调动日期调整前的旷工天数 + double absenteeismDaysBeforeSalary = getAbsenteeismDaysAfterSalaryAfter(fromdate, todate, userid); + // 每次漏签计0.5天旷工 + double forgotDays = getForgotCheckAbsenteeismDaysBefore(fromdate, todate, userid); + // 每次 严重迟到/早退每次计0.5天旷工 + double belateearlydays = getGraveBeLateLeaveEarlyDaysBefore(fromdate, todate, userid); + + result = Double.valueOf(floatAdd(String.valueOf(absenteeismDaysBeforeSalary), floatAdd(String.valueOf(forgotDays), String.valueOf(belateearlydays)))); + return result; + } + + /** + * 获取 法定(公众假日)天数 + * @param companystartdate + * @param fromDate + * @param toDate + * @param groupid + * @return + */ + public static String getPublicHolidays(String companystartdate,String fromDate, String toDate,String groupid,String userid){ + String result = "0"; + RecordSet rs = new RecordSet(); + // 产假 + String maternity_leave_id = rs.getPropValue("hrm_kqreport","maternity_leave_id"); + // 工伤假 + String injuryLeave_leave_id = rs.getPropValue("hrm_kqreport","injuryLeave_leave_id"); + // 离职日期 + String terminationdate = getTerminationDate(userid); + if(compareDate(toDate,terminationdate)){ + toDate = terminationdate; + } + + rs.executeQuery("select * from KQ_HolidaySet where holidayDate between ? and ? and changeType=1 and groupid = ?",fromDate,toDate,groupid); + while(rs.next()){ + String holidayDate = Util.null2String(rs.getString("holidayDate")); + //产假天数 + String maternityLeaveTypeDay = getLeaveTypeDays(maternity_leave_id, holidayDate, holidayDate, userid); + //工伤假天数 + String injuryLeaveLeaveTypeDay = getLeaveTypeDays(injuryLeave_leave_id, holidayDate, holidayDate, userid); + if (compareDate(holidayDate, companystartdate)) { + result = floatAdd(result, "1"); + } + if (floatCompare(maternityLeaveTypeDay, "0") == 1) { + result = floatSubtract(result, "1"); + } + if (floatCompare(injuryLeaveLeaveTypeDay, "0") == 1) { + result = floatSubtract(result, "1"); + } + } + return result; + } + + /** + * 获取 工作信息里的 自定义字段的 值 + * @param userid + * @return + */ + public static String getWorkCusFieldValue(String userid,String fieldid){ + String result = ""; + RecordSet rs = new RecordSet(); + rs.executeQuery("select "+ fieldid +" from cus_fielddata where scope='HrmCustomFieldByInfoType' and scopeid='3' and id=?",userid); + if(rs.next()){ + result = Util.null2String(rs.getString(fieldid)); + } + return result; + } + + /** + * 获取 入职日期 = 人力资源表 companystartdate 字段 + * @param userid + * @return + */ + public static String getCompanyStartDate(String userid){ + String result = ""; + RecordSet rs = new RecordSet(); + rs.executeQuery("select companystartdate from hrmresource where id = ?",userid); + if(rs.next()){ + result = Util.null2String(rs.getString("companystartdate")); + } + return result; + } + + /** + * 获取 转正日期 + * @param userid + * @return + */ + public static String getComfirmDate(String userid){ + String result = ""; + RecordSet rs = new RecordSet(); + String zzrq_fieldid = rs.getPropValue("hrm_kqreport","zzrq_fieldid"); + String zzrq = getWorkCusFieldValue(userid,zzrq_fieldid); + if(zzrq != null && !"".equals(zzrq)){ + result = zzrq; + } + return result; + } + + /** + * 获取 异动日期 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static String getTransactionDate(String fromdate,String todate,String userid){ + String result = ""; + RecordSet rs = new RecordSet(); + rs.executeQuery("select top 1 ydsj from formtable_main_75 where ygxm = ? and ydsj >= ? and ydsj <= ? order by ydsj desc",userid,fromdate,todate); + if(rs.next()){ + result = Util.null2String(rs.getString("ydsj")); + } + return result; + } + + /** + * 获取 快照 里的 字段信息 + * @param type + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static String getSnapShotData(String type,String fromdate,String todate,String userid){ + String result = ""; + RecordSet rs = new RecordSet(); + rs.executeQuery("select "+type+" from hrsa_hrm_snapshot where employee_id = ? and cast(snapshot_time as DATE) between ? and ? ",userid,fromdate,todate); + if(rs.next()){ + result = Util.null2String(rs.getString(type)); + } + return result; + } + + /** + * 获取 日期范围内是否有异动 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static boolean checkHasTransactionDate(String fromdate,String todate,String userid){ + boolean result = false; + RecordSet rs = new RecordSet(); + rs.executeQuery("select top 1 ydsj from formtable_main_75 where ygxm = ? and ydsj >= ? and ydsj <= ? order by ydsj desc",userid,fromdate,todate); + if(rs.next()){ + result = true; + } + return result; + } + + /** + * 获取 离职日期 + * @param userid + * @return + */ + public static String getTerminationDate(String userid){ + String result = ""; + RecordSet rs = new RecordSet(); + String lzrq_fieldid = rs.getPropValue("hrm_kqreport","lzrq_fieldid"); + String lzrq = getWorkCusFieldValue(userid,lzrq_fieldid); + if(lzrq != null && !"".equals(lzrq)){ + result = lzrq; + } + return result; + } + + /** + * 获取 片区 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static String getArea(String fromdate,String todate,String userid){ + String result = ""; + RecordSet rs = new RecordSet(); + String area_fieldid = rs.getPropValue("hrm_kqreport","area_fieldid"); + //日期范围内是否有异动 + boolean hasTransaction = checkHasTransactionDate(fromdate,todate,userid); + if(hasTransaction){ + String fieldid = getSnapShotData(area_fieldid,fromdate,todate,userid); + result = new SubCompanyComInfo().getSubCompanyname(fieldid); + }else { + // 片区 + rs.executeQuery("select distinct " + area_fieldid + " from cus_fielddata where scope='HrmCustomFieldByInfoType' and scopeid=-1 and id = ?", userid); + if (rs.next()) { + String areaid = Util.null2String(rs.getString(area_fieldid)); + if (areaid != null && !"".equals(areaid)) { + result = new SubCompanyComInfo().getSubCompanyname(areaid); + } + } + } + return result; + } + + /** + * 获取 分部 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static String getSubcompany(String fromdate,String todate,String userid){ + String result = ""; + RecordSet rs = new RecordSet(); + //日期范围内是否有异动 + boolean hasTransaction = checkHasTransactionDate(fromdate,todate,userid); + if(hasTransaction){ + String fieldid = getSnapShotData("SUBCOMPANYID1",fromdate,todate,userid); + result = new SubCompanyComInfo().getSubCompanyname(fieldid); + }else { + rs.executeQuery("select subcompanyid1 from hrmresource where id = ?", userid); + if (rs.next()) { + String subcomid = Util.null2String(rs.getString("subcompanyid1")); + result = new SubCompanyComInfo().getSubCompanyname(subcomid); + } + + } + return result; + } + + /** + * 获取 部门 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static String getDepartment(String fromdate,String todate,String userid){ + String result = ""; + RecordSet rs = new RecordSet(); + //日期范围内是否有异动 + boolean hasTransaction = checkHasTransactionDate(fromdate,todate,userid); + if(hasTransaction){ + String fieldid = getSnapShotData("DEPARTMENTID",fromdate,todate,userid); + result = new DepartmentComInfo().getDepartmentname(fieldid); + }else { + rs.executeQuery("select departmentid from hrmresource where id = ?", userid); + if (rs.next()) { + String subcomid = Util.null2String(rs.getString("departmentid")); + result = new DepartmentComInfo().getDepartmentname(subcomid); + } + } + return result; + } + + /** + * 获取 岗位名称 + * @param areaid + * @return + */ + public static String getPositionName(String areaid){ + String result = ""; + RecordSet rs = new RecordSet(); + rs.executeQuery("select * from uf_xcbz where id = ?",areaid); + if(rs.next()){ + result = Util.null2String(rs.getString("gwmc")); + } + return result; + } + + /** + * 获取 岗位名称 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static String getPosition(String fromdate,String todate,String userid){ + String result = ""; + RecordSet rs = new RecordSet(); + String position_fieldid = rs.getPropValue("hrm_kqreport","position_fieldid"); + //日期范围内是否有异动 + boolean hasTransaction = checkHasTransactionDate(fromdate,todate,userid); + if(hasTransaction){ + String fieldid = getSnapShotData("FIELD128",fromdate,todate,userid); + result = getPositionName(fieldid); + }else { + // 岗位名称 + rs.executeQuery("select distinct " + position_fieldid + " from cus_fielddata where scope='HrmCustomFieldByInfoType' and scopeid=-1 and id = ?", userid); + if (rs.next()) { + String positionid = Util.null2String(rs.getString(position_fieldid)); + if (positionid != null && !"".equals(positionid)) { + result = getPositionName(positionid); + } + } + } + return result; + } + + /** + * 获取 职等职级 id + * @param userid + */ + public static int getPositionRankId(String fromdate,String todate,String userid){ + int result = 0; + RecordSet rs = new RecordSet(); + //日期范围内是否有异动 + boolean hasTransaction = checkHasTransactionDate(fromdate,todate,userid); + if(hasTransaction){ + String fieldid = getSnapShotData("FIELD1",fromdate,todate,userid); + if (fieldid != null && !"".equals(fieldid)) { + result = Integer.parseInt(fieldid.split("_")[1]); + } + }else { + rs.executeQuery("select field1 from cus_fielddata where scope='HrmCustomFieldByInfoType' and scopeid=-1 and field1 is not null and field1 <> '' and id = ?", userid); + if (rs.next()) { + String field1 = Util.null2String(rs.getString("field1")); + if (field1 != null && !"".equals(field1)) { + result = Integer.parseInt(field1.split("_")[1]); + } + } + } + return result; + } + + /** + * 获取 岗位职级 + * @param mxid + * @return + */ + public static int getPositionRank(int mxid){ + int result = 0; + RecordSet rs = new RecordSet(); + rs.executeQuery("select gwzj from uf_zdzj_new where id = ?",mxid); + if(rs.next()){ + result = Util.getIntValue(rs.getString("gwzj")); + } + return result; + } + + /** + * 获取 应出勤天数 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static double getWorkDays(String fromdate,String todate,String userid){ + double result = 0.00; + int positionRank = getPositionRank(getPositionRankId(fromdate,todate,userid)); + // 对于职级为1和2的员工,应出勤天数默认为当月自然日的总天数 + // 对于不是这两个职级的员工,应出勤天数为:应出勤天数+法定节假日天数;若当月无法定节假日,就默认应出勤天数 + if(positionRank == 1 || positionRank == 2 || positionRank == 0){ + result = Double.valueOf(getDays(fromdate,todate)); + }else{ + result = Double.valueOf(getSpecialWorkDays(fromdate,todate,userid)); + } + return result; + } + + /** + * 应出勤天数为:应出勤天数+法定节假日天数;若当月无法定节假日,就默认应出勤天数 + * 周一到周五的天数 + 周六周日的调配工作日 - 周一到周五的调配休息日 + 周六周日的公众假日 = 最终的天数 + * @param fromDate + * @param toDate + * @param userid + * @return + */ + public static String getSpecialWorkDays(String fromDate,String toDate,String userid){ + String result = "0"; + RecordSet rs = new RecordSet(); + // + String groupid = rs.getPropValue("hrm_kqreport","the_top_groupid"); + // 周六或周日天数 + String weekdays = "0"; + // 周一到周五天数 + String workdays = "0"; + // 调配休息日天数 + String allocateRestDays = "0"; + // 调配工作日天数 + String allocateWorkDays = "0"; + // 格式化日期 + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + +// rs.executeQuery("select distinct groupid,kqdate from kq_format_total " + +// " where resourceid = ? and kqdate >= ? and kqdate <= ?",userid,fromDate,toDate); +// while(rs.next()){ +// // +// String dateString = Util.null2String(rs.getString("kqdate")); +// // 是 周六或 周日 +// if (isSaturdayOrSunday(dateString)) { +// //是调配工作日 +// if (isAllocateWorkDay(groupid, dateString)) { +// allocateWorkDays = floatAdd(allocateWorkDays,"1"); +// } +// //是公众假日 +// if(isAllocateHolidayDay(groupid, dateString)){ +// allocateWorkDays = floatAdd(allocateWorkDays,"1"); +// } +// } else { +// // 是 调配休息日 +// if(isAllocateRestDay(groupid,dateString)){ +// allocateRestDays = floatAdd(allocateRestDays,"1"); +// } +// workdays = floatAdd(workdays,"1"); +// } +// } + + String[] dateStartArr = parseDate(fromDate); + String[] dateEndtArr = parseDate(toDate); + LocalDate startDate = LocalDate.of(Integer.parseInt(dateStartArr[0]), Integer.parseInt(dateStartArr[1]), Integer.parseInt(dateStartArr[2])); + LocalDate endDate = LocalDate.of(Integer.parseInt(dateEndtArr[0]), Integer.parseInt(dateEndtArr[1]), Integer.parseInt(dateEndtArr[2])); + // 遍历日期范围 + for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) { + // 输出格式化后的日期字符串 + String dateString = date.format(formatter); + // 是 周六或 周日 + if (isSaturdayOrSunday(dateString)) { + //是调配工作日 + if (isAllocateWorkDay(groupid, dateString)) { + allocateWorkDays = floatAdd(allocateWorkDays,"1"); + } + //是公众假日 + if(isAllocateHolidayDay(groupid, dateString)){ + allocateWorkDays = floatAdd(allocateWorkDays,"1"); + } + } else { + // 是 调配休息日 + if(isAllocateRestDay(groupid,dateString)){ + allocateRestDays = floatAdd(allocateRestDays,"1"); + } + workdays = floatAdd(workdays,"1"); + } + } + + result = floatAdd(result,floatSubtract(floatAdd(workdays,allocateWorkDays),allocateRestDays)); + return result; + } + + /** + * 获取 薪酬调整日期、转正日期、入职日期 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static String getSalaryAdjustDate(String fromdate,String todate,String userid){ + String result = ""; + RecordSet rs = new RecordSet(); + RecordSet rs1 = new RecordSet(); + RecordSet rs2 = new RecordSet(); + String txrq = ""; + String zzrq = ""; + String rzrq = ""; + rs.executeQuery("select txrq from uf_ygxcda where yg = ? and txrq >= ? and txrq <= ? and dxyy != '入职' ",userid,fromdate,todate); + if(rs.next()){ + txrq = Util.null2String(rs.getString("txrq")); + } + rs1.executeQuery("select shjg as zzrq from uf_ygzzxx where lczt = '2' and xm = ? ",userid); + if(rs1.next()){ + zzrq = Util.null2String(rs1.getString("zzrq")); + } + rs2.executeQuery("select companystartdate from hrmresource where id = ?",userid); + if(rs2.next()){ + rzrq = Util.null2String(rs2.getString("companystartdate")); + } + if(txrq != null && !"".equals(txrq)){ + result = txrq; + }else if(zzrq != null && !"".equals(zzrq)){ + result = zzrq; + }else if(rzrq != null && !"".equals(rzrq)){ + result = rzrq; + } + return result; + } + + /** + * 获取 指定假期的时长 + * @param type + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static String getLeaveDaysBefore(int type,String fromdate,String todate,String userid){ + String result = "0"; + RecordSet rs = new RecordSet(); + String halfdays = "0"; + String halfbackdays = "0"; + // 假期 时长 + rs.executeQuery("select sum(duration) as count from kq_flow_split_leave where belongdate >= ? and belongdate < ? and newleavetype in ("+ type +") and resourceid = ? ",fromdate,todate,userid); + while(rs.next()){ + halfdays = Util.null2o(rs.getString("count")); + } + // 销假时长 + rs.executeQuery("select sum(duration) as count from kq_flow_split_leaveback where belongdate >= ? and belongdate < ? and newleavetype in ("+ type +") and resourceid = ? ",fromdate,todate,userid); + while(rs.next()){ + halfbackdays = Util.null2o(rs.getString("count")); + } + result = floatSubtract(halfdays,halfbackdays); + return result; + } + + /** + * 获取 指定假期的时长 + * @param type + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static String getLeaveDaysAfter(int type,String fromdate,String todate,String userid){ + String result = "0"; + RecordSet rs = new RecordSet(); + String halfdays = "0"; + String halfbackdays = "0"; + // 假期 时长 + rs.executeQuery("select sum(duration) as count from kq_flow_split_leave where belongdate >= ? and belongdate <= ? and newleavetype in ("+ type +") and resourceid = ? ",fromdate,todate,userid); + while(rs.next()){ + halfdays = Util.null2o(rs.getString("count")); + } + // 销假时长 + rs.executeQuery("select sum(duration) as count from kq_flow_split_leaveback where belongdate >= ? and belongdate <= ? and newleavetype in ("+ type +") and resourceid = ? ",fromdate,todate,userid); + while(rs.next()){ + halfbackdays = Util.null2o(rs.getString("count")); + } + result = floatSubtract(halfdays,halfbackdays); + return result; + } + + /** + * 获取 哺乳假的假期的时长 + * @param type + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static String getBreastfeedLeaveDays(int type,String fromdate,String todate,String userid){ + String result = "0"; + RecordSet rs1 = new RecordSet(); + String breastfeeddays = "0"; + String breastfeedbackdays = "0"; + //班次id + String serialid = getSerialId(fromdate,todate,userid); + String serialHours = getHoursBySerial(serialid); + + // 哺乳假 时长 + rs1.executeQuery("select sum(duration) as count from kq_flow_split_leave where belongDate >= ? and belongdate <= ? and newleavetype in ("+ type +") and resourceid = ? group by resourceid",fromdate,todate,userid); + while(rs1.next()){ + breastfeeddays = Util.null2o(rs1.getString("count")); + } + // 哺乳假 销假时长 + rs1.executeQuery("select sum(duration) as count from kq_flow_split_leave where belongDate >= ? and belongdate <= ? and newleavetype in ("+ type +") and resourceid = ? group by resourceid",fromdate,todate,userid); + while(rs1.next()){ + breastfeedbackdays = Util.null2o(rs1.getString("count")); + } + String breastdays = floatSubtract(breastfeeddays,breastfeedbackdays); + + if(floatCompare(serialHours,"0") > 0) { + String breadt_days = floatDivide(breastdays, serialHours); + result = floatAdd(result, breadt_days); + } + return result; + } + + /** + * 获取班次对应的工作时长 分钟数 转换为 小时 + * @param serialid + * @return + */ + public static String getHoursBySerial(String serialid){ + String result = ""; + RecordSet rs = new RecordSet(); + rs.executeQuery("select * from kq_ShiftManagement where id=?",serialid); + if(rs.next()) { + String worktime = Util.null2o(rs.getString("worktime")); + result = floatDivide(worktime,"60"); + } + return result; + } + + /** + * 获取 实际出勤天数(薪酬调整前) + * 对于职级为1和2的员工,实际出勤天数(标准)+带薪假(病、年、产、陪产、婚、丧、探亲、哺乳、调休)+迟到小时数(换算成班次所在天数)-每次漏签、严重迟到、严重早退 计0.5天旷工+休息班次 + * 对于不是这两个职级的员工,实际出勤天数(标准)+带薪假(病、年、产、陪产、婚、丧、探亲、哺乳、调休)+迟到小时数(换算成班次所在天数)-每次漏签、严重迟到、严重早退 计0.5天旷工+公众假日(当前日期范围内要有班次的) + * 病假 按半天请假 + * 年假 按半天请假 + * 产假 按半天请假 + * 陪产假 按半天请假 + * 婚假 按半天请假 + * 丧假 按半天请假 + * 探亲假 按半天请假 + * 哺乳假 按小时请假 + * 调休假 按半天请假 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static double getAttendDaysBeforeSalary(String fromdate,String todate,String userid){ + double result = 0.00; + RecordSet rs = new RecordSet(); + String attendancedays = "0"; + String publicHolidays = "0"; + // 入职日期 + String companystartdate = getCompanyStartDate(userid); + int positionRank = getPositionRank(getPositionRankId(fromdate,todate,userid)); + // 薪资调整日期 + String salaryAdjustDate = getSalaryAdjustDate(fromdate,todate,userid); + if(salaryAdjustDate != null && !"".equals(salaryAdjustDate)){ + if(belongCalendarBefore(salaryAdjustDate,fromdate,todate)) { + // 实际出勤天数(标准) + rs.executeQuery("select sum(attendancedays)as days from kq_format_total " + + " where resourceid = ? and kqdate >= ? and kqdate < ? and attendanceMins is not null and attendanceMins > 0 and absenteeismmins = 0", userid, fromdate, salaryAdjustDate); + while (rs.next()) { + attendancedays = Util.null2o(rs.getString("days")); + } + rs.writeLog("========= 实际出勤天数(薪酬调整前) 实际出勤天数 ======== "+ attendancedays); + + // 法定(公众假日)天数 + rs.executeQuery("select distinct groupid from kq_format_total " + + " where resourceid = ? and kqdate >= ? and kqdate < ?", userid, fromdate, todate); + while (rs.next()) { + String groupid = Util.null2String(rs.getString("groupid")); + // 法定(公众假日)天数 + publicHolidays = getPublicHolidays(companystartdate, fromdate, salaryAdjustDate, groupid, userid); + } + rs.writeLog("========= 实际出勤天数(薪酬调整前) 法定(公众假日)天数 ======== "+ publicHolidays); + + // 休息班 天数 + String restdays = getRestSerialDaysBefore(fromdate, salaryAdjustDate, userid); + + rs.writeLog("========= 实际出勤天数(薪酬调整前) 休息班 天数 ======== "+ restdays); + + // 假期 天数 + String attendLeaveDays = getAttendLeaveDaysBefore(fromdate, salaryAdjustDate, userid); + + rs.writeLog("========= 实际出勤天数(薪酬调整前) 假期 天数 ======== "+ attendLeaveDays); + + String days = floatAdd(attendancedays, attendLeaveDays); + +// // 迟到 天数 +// String latedays = getLateDaysBefore(fromdate, salaryAdjustDate, userid); +// days = floatAdd(days, latedays); +// +// // 早退 天数 +// String leaveearlydays = getLeaveEarlyDaysBefore(fromdate, salaryAdjustDate, userid); +// days = floatAdd(days, leaveearlydays); + + // 每次漏签、 计0.5天旷工 天数 + String forgotdays = String.valueOf(getAbsenteeismDaysCountBeforeSalary(fromdate, salaryAdjustDate, userid)); + days = floatSubtract(days, forgotdays); + +// // 严重迟到/严重早退 天数 计0.5天旷工 天数 +// String gravelateleavedays = String.valueOf(getGraveBeLateLeaveEarlyDaysBefore(fromdate, salaryAdjustDate, userid)); +// days = floatSubtract(days, gravelateleavedays); + + // 对于职级为1和2的员工,实际出勤天数(标准)+带薪假(病、年、产、陪产、婚、丧、探亲、哺乳、调休)+迟到小时数(换算成班次所在天数)-漏签次数*0.5+休息班次 + // 对于不是这两个职级的员工,实际出勤天数(标准)+带薪假(病、年、产、陪产、婚、丧、探亲、哺乳、调休)+迟到小时数(换算成班次所在天数)-漏签次数*0.5+公众假日(当前日期范围内要有班次的) + if (positionRank == 1 || positionRank == 2) { + result = Double.valueOf(floatAdd(days,restdays)); + } else if (positionRank == 0) { + result = Double.valueOf(floatSubtract(attendLeaveDays, forgotdays)); + } else { + result = Double.valueOf(floatAdd(days, publicHolidays)); + } + } + } + if(result < 0){ + result = 0.00; + } + return result; + } + + /** + * 获取 实际出勤天数(薪酬调整后) + * 对于职级为1和2的员工,实际出勤天数(标准)+带薪假(病、年、产、陪产、婚、丧、探亲、哺乳、调休)+迟到小时数(换算成班次所在天数)-漏签次数*0.5+休息班次 + * 对于不是这两个职级的员工,实际出勤天数(标准)+带薪假(病、年、产、陪产、婚、丧、探亲、哺乳、调休)+迟到小时数(换算成班次所在天数)-漏签次数*0.5+公众假日(当前日期范围内要有班次的) + * 病假 按半天请假 + * 年假 按半天请假 + * 产假 按半天请假 + * 陪产假 按半天请假 + * 婚假 按半天请假 + * 丧假 按半天请假 + * 探亲假 按半天请假 + * 哺乳假 按小时请假 + * 调休假 按半天请假 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static double getAttendDaysAfterSalary(String fromdate,String todate,String userid){ + double result = 0.00; + RecordSet rs = new RecordSet(); + String attendancedays = "0"; + String publicHolidays = "0"; + // 应出勤天数 + double requiredworkdays = 0.00; + int positionRank = getPositionRank(getPositionRankId(fromdate,todate,userid)); + // 入职日期 + String companystartdate = getCompanyStartDate(userid); + String salaryattencedays = "0"; + rs.executeQuery("select sum(attendancedays)as days from kq_format_total " + + " where resourceid = ? and kqdate >= ? and kqdate <= ? and attendanceMins is not null and attendanceMins > 0 and absenteeismmins = 0",userid,fromdate,todate); + while(rs.next()){ + attendancedays = Util.null2o(rs.getString("days")); + } + // 应出勤天数 + requiredworkdays = getWorkDays(fromdate, todate, userid); + // 薪资调整日期 + String salaryAdjustDate = getSalaryAdjustDate(fromdate,todate,userid); + if(salaryAdjustDate != null && !"".equals(salaryAdjustDate)){ + if(belongCalendar(salaryAdjustDate,fromdate,todate)) { + rs.executeQuery("select sum(attendancedays)as days from kq_format_total " + + " where resourceid = ? and kqdate >= ? and kqdate <= ? and attendanceMins is not null and attendanceMins > 0 and absenteeismmins = 0", userid, salaryAdjustDate, todate); + while (rs.next()) { + salaryattencedays = Util.null2o(rs.getString("days")); + } + // 法定(公众假日)天数 + rs.executeQuery("select distinct groupid from kq_format_total " + + " where resourceid = ? and kqdate >= ? and kqdate <= ?", userid, fromdate, todate); + while (rs.next()) { + String groupid = Util.null2String(rs.getString("groupid")); + // 法定(公众假日)天数 + publicHolidays = getPublicHolidays(companystartdate, salaryAdjustDate, todate, groupid, userid); + } + // 休息班 天数 + String restdays = getRestSerialDaysAfter(salaryAdjustDate, todate, userid); + + // 假期 天数 + String attendLeaveDays = getAttendLeaveDaysAfter(salaryAdjustDate, todate, userid); + + String days = floatAdd(salaryattencedays, attendLeaveDays); + +// // 迟到 天数 +// String latedays = getLateDaysAfter(salaryAdjustDate, todate, userid); +// days = floatAdd(days, latedays); +// +// // 早退 天数 +// String leaveearlydays = getLeaveEarlyDaysAfter(fromdate, salaryAdjustDate, userid); +// days = floatAdd(days, leaveearlydays); + + // 漏签 天数 + String forgotdays = String.valueOf(getAbsenteeismDaysCountBeforeSalary(salaryAdjustDate, todate, userid)); + days = floatSubtract(days, forgotdays); + +// // 严重迟到/严重早退 天数 +// String gravelateleavedays = String.valueOf(getGraveBeLateLeaveEarlyDaysAfter(salaryAdjustDate, todate, userid)); +// days = floatSubtract(days, gravelateleavedays); + + if (positionRank == 1 || positionRank == 2) { + result = Double.valueOf(floatAdd(days,restdays)); + } else { + if(positionRank == 0){ + result = Double.valueOf(days); + }else { + result = Double.valueOf(floatAdd(days, publicHolidays)); + } + } + }else{ + // 应出勤天数 + requiredworkdays = getWorkDays(fromdate,todate,userid); + + // 法定(公众假日)天数 + rs.executeQuery("select distinct groupid from kq_format_total " + + " where resourceid = ? and kqdate >= ? and kqdate <= ?",userid,fromdate,todate); + while(rs.next()){ + String groupid = Util.null2String(rs.getString("groupid")); + // 法定(公众假日)天数 + publicHolidays = getPublicHolidays(companystartdate,fromdate,todate,groupid,userid); + } + // 休息班 天数 + String restdays = getRestSerialDaysAfter(fromdate,todate,userid); + + // 假期 天数 + String attendLeaveDays = getAttendLeaveDaysAfter(fromdate,todate,userid); + + String days = floatAdd(attendancedays,attendLeaveDays); + +// // 迟到 天数 +// String latedays = getLateDaysAfter(fromdate,todate,userid); +// days = floatAdd(days,latedays); +// +// // 早退 天数 +// String leaveearlydays = getLeaveEarlyDaysAfter(fromdate,todate,userid); +// days = floatAdd(days,leaveearlydays); + + // 漏签 天数 + String forgotdays = String.valueOf(getAbsenteeismDaysCountBeforeSalary(fromdate,todate,userid)); + days = floatSubtract(days,forgotdays); + +// // 严重迟到/严重早退 天数 +// String gravelateleavedays = String.valueOf(getGraveBeLateLeaveEarlyDaysAfter(fromdate,todate,userid)); +// days = floatSubtract(days,gravelateleavedays); + + if(positionRank == 1 || positionRank == 2){ + result = Double.valueOf(floatAdd(days,restdays)); + }else{ + if(positionRank == 0){ + result = Double.valueOf(days); + }else { + result = Double.valueOf(floatAdd(days, publicHolidays)); + } + } + } + }else{ + // 应出勤天数 + requiredworkdays = getWorkDays(fromdate,todate,userid); + + // 法定(公众假日)天数 + rs.executeQuery("select distinct groupid from kq_format_total " + + " where resourceid = ? and kqdate >= ? and kqdate <= ?",userid,fromdate,todate); + while(rs.next()){ + String groupid = Util.null2String(rs.getString("groupid")); + // 法定(公众假日)天数 + publicHolidays = getPublicHolidays(companystartdate,fromdate,todate,groupid,userid); + } + // 休息班 天数 + String restdays = getRestSerialDaysAfter(fromdate,todate,userid); + + // 假期 天数 + String attendLeaveDays = getAttendLeaveDaysAfter(fromdate,todate,userid); + + String days = floatAdd(attendancedays,attendLeaveDays); + +// // 迟到 天数 +// String latedays = getLateDaysAfter(fromdate,todate,userid); +// days = floatAdd(days,latedays); +// +// // 早退 天数 +// String leaveearlydays = getLeaveEarlyDaysAfter(fromdate,todate,userid); +// days = floatAdd(days,leaveearlydays); + + // 漏签 天数 + String forgotdays = String.valueOf(getAbsenteeismDaysCountBeforeSalary(fromdate,todate,userid)); + days = floatSubtract(days,forgotdays); + +// // 严重迟到/严重早退 天数 +// String gravelateleavedays = String.valueOf(getGraveBeLateLeaveEarlyDaysAfter(fromdate,todate,userid)); +// days = floatSubtract(days,gravelateleavedays); + + if(positionRank == 1 || positionRank == 2){ + result = Double.valueOf(floatAdd(days,restdays)); + }else{ + if(positionRank == 0){ + result = Double.valueOf(days); + }else { + result = Double.valueOf(floatAdd(days, publicHolidays)); + } + } + } + String result_int = String.valueOf((int)result); + String result_int1 = floatAdd(String.valueOf(result_int),"0.1"); + String result_int5 = floatAdd(String.valueOf(result_int),"0.5"); + String resultadd1 = floatAdd(String.valueOf(result_int),"1"); + + //实际出勤天数(薪酬调整前) + double attenddaysbeforesalary = getAttendDaysBeforeSalary(fromdate,todate,userid); + // 大于 应出勤天数 + if(result > requiredworkdays){ + result = requiredworkdays; + }else{ + if(attenddaysbeforesalary+result > requiredworkdays){ + double chae = attenddaysbeforesalary+result-requiredworkdays; + result = result - chae; + } + } + if(result < 0){ + result = 0.00; + } + return result; + } + + /** + * 判断 当天是否请了产假 + * @param date + * @param userid + * @return + */ + public static boolean checkIsRestLeaveDay(String date,String userid){ + boolean bool = false; + RecordSet rs = new RecordSet(); + // 产假 + String maternity_leave_id = rs.getPropValue("hrm_kqreport","maternity_leave_id"); + rs.executeQuery("select id from kq_flow_split_leave where belongdate = ? and newleavetype in ("+ maternity_leave_id +") and resourceid = ? ",date,userid); + while(rs.next()){ + bool = true; + } + return bool; + } + + /** + * 获取 请假天数 + * + * 病假 按半天请假 + * 年假 按半天请假 + * 产假 按半天请假 + * 陪产假 按半天请假 + * 婚假 按半天请假 + * 丧假 按半天请假 + * 探亲假 按半天请假 + * 哺乳假 按小时请假 + * 调休假 按半天请假 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static String getAttendLeaveDaysBefore(String fromdate,String todate,String userid){ + String result = "0"; + RecordSet rs = new RecordSet(); + RecordSet rs1 = new RecordSet(); + String halfdays = "0"; + String halfbackdays = "0"; + String breastfeeddays = "0"; + String breastfeedbackdays = "0"; + // 病假 年假 产假 陪产假 婚假 丧假 探亲假 调休假 + String halfday_leave_ids = rs.getPropValue("hrm_kqreport","halfday_leave_ids"); + // 哺乳假 + String breastfeed_leave_id = rs.getPropValue("hrm_kqreport","breastfeed_leave_id"); + + // 病假 年假 陪产假 婚假 丧假 探亲假 时长 + rs.executeQuery("select sum(duration) as count from kq_flow_split_leave where belongdate >= ? and belongdate < ? and newleavetype in ("+ halfday_leave_ids +") and resourceid = ? ",fromdate,todate,userid); + while(rs.next()){ + halfdays = Util.null2o(rs.getString("count")); + } + + // 病假 年假 陪产假 婚假 丧假 探亲假 销假时长 + rs.executeQuery("select sum(duration) as count from kq_flow_split_leaveback where belongdate >= ? and belongdate < ? and newleavetype in ("+ halfday_leave_ids +") and resourceid = ? ",fromdate,todate,userid); + while(rs.next()){ + halfbackdays = Util.null2o(rs.getString("count")); + } + + result = floatSubtract(halfdays,halfbackdays); + +// //班次id +// String serialid = getSerialId(fromdate,todate,userid); +// String serialHours = getHoursBySerial(serialid); +// +// // 哺乳假 时长 +// rs1.executeQuery("select sum(duration) as count from kq_flow_split_leave where belongDate >= ? and belongdate < ? and newleavetype in ("+ breastfeed_leave_id +") and resourceid = ? group by resourceid",fromdate,todate,userid); +// while(rs1.next()){ +// breastfeeddays = Util.null2o(rs1.getString("count")); +// } +// // 哺乳假 销假时长 +// rs1.executeQuery("select sum(duration) as count from kq_flow_split_leave where belongDate >= ? and belongdate < ? and newleavetype in ("+ breastfeed_leave_id +") and resourceid = ? group by resourceid",fromdate,todate,userid); +// while(rs1.next()){ +// breastfeedbackdays = Util.null2o(rs1.getString("count")); +// } +// +// String breastdays = floatSubtract(breastfeeddays,breastfeedbackdays); +// +// if(floatCompare(serialHours,"0") > 0){ +// String breadt_days = floatDivide(breastdays,serialHours); +// result = floatAdd(result,breadt_days); +// } + + return result; + } + + /** + * 获取 请假天数 + * + * 病假 按半天请假 + * 年假 按半天请假 + * 产假 按半天请假 + * 陪产假 按半天请假 + * 婚假 按半天请假 + * 丧假 按半天请假 + * 探亲假 按半天请假 + * 哺乳假 按小时请假 + * 调休假 按半天请假 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static String getAttendLeaveDaysAfter(String fromdate,String todate,String userid){ + String result = "0"; + RecordSet rs = new RecordSet(); + RecordSet rs1 = new RecordSet(); + String halfdays = "0"; + String halfbackdays = "0"; + String breastfeeddays = "0"; + String breastfeedbackdays = "0"; + // 病假 年假 产假 陪产假 婚假 丧假 探亲假 调休假 + String halfday_leave_ids = rs.getPropValue("hrm_kqreport","halfday_leave_ids"); + // 哺乳假 + String breastfeed_leave_id = rs.getPropValue("hrm_kqreport","breastfeed_leave_id"); + + // 病假 年假 陪产假 婚假 丧假 探亲假 时长 + rs.executeQuery("select sum(duration) as count from kq_flow_split_leave where belongdate >= ? and belongdate <= ? and newleavetype in ("+ halfday_leave_ids +") and resourceid = ? ",fromdate,todate,userid); + while(rs.next()){ + halfdays = Util.null2o(rs.getString("count")); + } + + // 病假 年假 陪产假 婚假 丧假 探亲假 销假时长 + rs.executeQuery("select sum(duration) as count from kq_flow_split_leaveback where belongdate >= ? and belongdate <= ? and newleavetype in ("+ halfday_leave_ids +") and resourceid = ? ",fromdate,todate,userid); + while(rs.next()){ + halfbackdays = Util.null2o(rs.getString("count")); + } + + result = floatSubtract(halfdays,halfbackdays); + +// //班次id +// String serialid = getSerialId(fromdate,todate,userid); +// String serialHours = getHoursBySerial(serialid); +// +// // 哺乳假 时长 +// rs1.executeQuery("select sum(duration) as count from kq_flow_split_leave where belongDate >= ? and belongdate <= ? and newleavetype in ("+ breastfeed_leave_id +") and resourceid = ? group by resourceid",fromdate,todate,userid); +// while(rs1.next()){ +// breastfeeddays = Util.null2o(rs1.getString("count")); +// } +// // 哺乳假 销假时长 +// rs1.executeQuery("select sum(duration) as count from kq_flow_split_leaveback where belongDate >= ? and belongdate <= ? and newleavetype in ("+ breastfeed_leave_id +") and resourceid = ? group by resourceid",fromdate,todate,userid); +// while(rs1.next()){ +// breastfeedbackdays = Util.null2o(rs1.getString("count")); +// } +// +// String breastdays = floatSubtract(breastfeeddays,breastfeedbackdays); +// +// if(floatCompare(serialHours,"0") > 0){ +// String breadt_days = floatDivide(breastdays,serialHours); +// result = floatAdd(result,breadt_days); +// } + + return result; + } + + /** + * 获取哺乳假分钟数 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static int getBreastMins(String fromdate,String todate,String userid){ + int mins = 0; + RecordSet rs = new RecordSet(); + RecordSet rs1 = new RecordSet(); + // 哺乳假 + String breastfeed_leave_id = rs1.getPropValue("hrm_kqreport","breastfeed_leave_id"); + double breastfeeddays = 0; + double breastfeedbackdays = 0; + + // 哺乳假 时长 + rs.executeQuery("select sum(duration) as count from kq_flow_split_leave where belongDate >= ? and belongdate <= ? and newleavetype in ("+ breastfeed_leave_id +") and resourceid = ? group by resourceid",fromdate,todate,userid); + while(rs.next()){ + breastfeeddays = Util.getDoubleValue(rs.getString("count"),0); + } + // 哺乳假 销假时长 + rs1.executeQuery("select sum(duration) as count from kq_flow_split_leaveback where belongDate >= ? and belongdate <= ? and newleavetype in ("+ breastfeed_leave_id +") and resourceid = ? group by resourceid",fromdate,todate,userid); + while(rs1.next()){ + breastfeedbackdays = Util.getDoubleValue(rs1.getString("count"),0); + } + double breastdays = breastfeeddays-breastfeedbackdays; + if(breastdays > 0){ + mins = (int)breastdays * 60; + } + return mins; + } + /** + * 获取 假期天数(调薪前) + * @param leavetype + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static double getBeforeSalaryLeaveDays(int leavetype,String fromdate,String todate,String userid){ + double result = 0.00; + // 薪资调整日期 + String salaryAdjustDate = getSalaryAdjustDate(fromdate,todate,userid); + if(salaryAdjustDate != null && !"".equals(salaryAdjustDate)){ + if(belongCalendar(salaryAdjustDate,fromdate,todate)) { + String leavedays = getLeaveDaysBefore(leavetype, fromdate, salaryAdjustDate, userid); + result = Double.valueOf(leavedays); + } + } + return result; + } + + /** + * 获取 假期天数(调薪后) + * @param leavetype + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static double getAfterSalaryLeaveDays(int leavetype,String fromdate,String todate,String userid){ + double result = 0.00; + // 薪资调整日期 + String salaryAdjustDate = getSalaryAdjustDate(fromdate,todate,userid); + if(salaryAdjustDate != null && !"".equals(salaryAdjustDate)){ + if(belongCalendar(salaryAdjustDate,fromdate,todate)) { + String leavedays = getLeaveDaysAfter(leavetype, salaryAdjustDate, todate, userid); + result = Double.valueOf(leavedays); + }else{ + String leavedays = getLeaveDaysAfter(leavetype, fromdate, todate, userid); + result = Double.valueOf(leavedays); + } + }else{ + String leavedays = getLeaveDaysAfter(leavetype,fromdate,todate,userid); + result = Double.valueOf(leavedays); + } + return result; + } + + /** + * 获取 迟到 天数 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static String getLateDaysBefore(String fromdate,String todate,String userid){ + String result = "0"; + RecordSet rs = new RecordSet(); + String serialid = getSerialId(fromdate,todate,userid); + String serial_hours = getHoursBySerial(serialid); + // 迟到 + rs.executeQuery("select sum(belatemins) as count from kq_format_total where kqdate >= ? and kqdate < ? and resourceid = ? ",fromdate,todate,userid); + while(rs.next()){ + String latemins = Util.null2o(rs.getString("count")); + String latehours = floatDivide(latemins,"60"); + if(floatCompare(serial_hours,"0") > 0){ + result = floatDivide(latehours,serial_hours); + } + } + return result; + } + + /** + * 获取 迟到 天数 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static String getLateDaysAfter(String fromdate,String todate,String userid){ + String result = "0"; + RecordSet rs = new RecordSet(); + String serialid = getSerialId(fromdate,todate,userid); + String serial_hours = getHoursBySerial(serialid); + // 迟到 + rs.executeQuery("select sum(belatemins) as count from kq_format_total where kqdate >= ? and kqdate <= ? and resourceid = ? ",fromdate,todate,userid); + while(rs.next()){ + String latemins = Util.null2o(rs.getString("count")); + String latehours = floatDivide(latemins,"60"); + if(floatCompare(serial_hours,"0") > 0){ + result = floatDivide(latehours,serial_hours); + } + } + return result; + } + + /** + * 获取 早退 天数 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static String getLeaveEarlyDaysBefore(String fromdate,String todate,String userid){ + String result = "0"; + RecordSet rs = new RecordSet(); + String serialid = getSerialId(fromdate,todate,userid); + String serial_hours = getHoursBySerial(serialid); + // 早退 + rs.executeQuery("select sum(leaveearlymins) as count from kq_format_total where kqdate >= ? and kqdate < ? and resourceid = ? ",fromdate,todate,userid); + while(rs.next()){ + String latemins = Util.null2o(rs.getString("count")); + String latehours = floatDivide(latemins,"60"); + if(floatCompare(serial_hours,"0") > 0){ + result = floatDivide(latehours,serial_hours); + } + } + return result; + } + + /** + * 获取 早退 天数 + * @param fromdate + * @param todate + * @param userid + * @return + */ + public static String getLeaveEarlyDaysAfter(String fromdate,String todate,String userid){ + String result = "0"; + RecordSet rs = new RecordSet(); + String serialid = getSerialId(fromdate,todate,userid); + String serial_hours = getHoursBySerial(serialid); + // 早退 + rs.executeQuery("select sum(leaveearlymins) as count from kq_format_total where kqdate >= ? and kqdate <= ? and resourceid = ? ",fromdate,todate,userid); + while(rs.next()){ + String latemins = Util.null2o(rs.getString("count")); + String latehours = floatDivide(latemins,"60"); + if(floatCompare(serial_hours,"0") > 0){ + result = floatDivide(latehours,serial_hours); + } + } + return result; + } + + /** + * 获取 休息班次 天数 + * @param fromDate + * @param toDate + * @param userid + * @return + */ + public static String getRestSerialDaysBefore(String fromDate, String toDate,String userid){ + String result = "0"; + RecordSet rs = new RecordSet(); + KQGroupMemberComInfo groupMemberComInfo = new KQGroupMemberComInfo(); + String rest_serial_id = rs.getPropValue("hrm_kqreport","rest_serial_id"); + String rest2_serial_id = rs.getPropValue("hrm_kqreport","rest2_serial_id"); + rs.executeQuery("select count(resourceid) as count from kq_format_total where kqdate >= ? and kqdate < ? and resourceid = ? and serialid = ?",fromDate,toDate,userid,rest_serial_id); + while(rs.next()){ + result = Util.null2o(rs.getString("count")); + } + rs.executeQuery("select * from kq_format_total " + + " where resourceid = ? and kqdate >= ? and kqdate <= ? and serialid = ?",userid,fromDate,toDate,rest2_serial_id); + while(rs.next()) { + String groupid = Util.null2String(rs.getString("groupid")); + String kqdate = Util.null2String(rs.getString("kqdate")); + KQGroupEntity kqGroupEntity = groupMemberComInfo.getUserKQGroupInfo(userid,kqdate); + if(kqGroupEntity != null) { + String kqtype = kqGroupEntity.getKqtype(); + //固定班制 + if ("1".equals(kqtype)) { + if (isHolidayOrRelaxDay(groupid, kqdate)) { + result = floatAdd(result, "1"); + } + } + } + } + return result; + } + + /** + * 获取 休息班次 天数 + * @param fromDate + * @param toDate + * @param userid + * @return + */ + public static String getRestSerialDaysAfter(String fromDate, String toDate,String userid){ + String result = "0"; + RecordSet rs = new RecordSet(); + KQGroupMemberComInfo groupMemberComInfo = new KQGroupMemberComInfo(); + String rest_serial_id = rs.getPropValue("hrm_kqreport","rest_serial_id"); + String rest2_serial_id = rs.getPropValue("hrm_kqreport","rest2_serial_id"); + rs.executeQuery("select * from kq_format_detail where kqdate >= ? and kqdate <= ? and resourceid = ? and serialid = ? ",fromDate,toDate,userid,rest_serial_id); + while(rs.next()){ + String kqdate = Util.null2String(rs.getString("kqdate")); + //不是请了产假 + if(!checkIsRestLeaveDay(kqdate,userid)){ + result = floatAdd(result, "1"); + } + } + rs.executeQuery("select * from kq_format_total " + + " where resourceid = ? and kqdate >= ? and kqdate <= ? and serialid = ?",userid,fromDate,toDate,rest2_serial_id); + while(rs.next()) { + String groupid = Util.null2String(rs.getString("groupid")); + String kqdate = Util.null2String(rs.getString("kqdate")); + KQGroupEntity kqGroupEntity = groupMemberComInfo.getUserKQGroupInfo(userid,kqdate); + if(kqGroupEntity!=null){ + String kqtype = kqGroupEntity.getKqtype(); + //固定班制 + if("1".equals(kqtype)) { + if (isHolidayOrRelaxDay(groupid, kqdate)) { + //不是请了产假 + if(!checkIsRestLeaveDay(kqdate,userid)){ + result = floatAdd(result, "1"); + } + } + } + } + } + return result; + } + + /** + * 获取 班次id + * @param fromDate + * @param toDate + * @param userid + * @return + */ + public static String getSerialId(String fromDate, String toDate,String userid){ + String result = ""; + RecordSet rs = new RecordSet(); + rs.executeQuery("select distinct a.serialid from kq_format_total a,kq_ShiftManagement b " + + " where a.serialid=b.id and a.resourceid = ? and a.kqdate >= ? and a.kqdate <= ? and b.is_rest=0 ",userid,fromDate,toDate); + while(rs.next()){ + result = Util.null2String(rs.getString("serialid")); + } + return result; + } + + /** + * 判断 指定天数 是否是 公众假日 true 是 false 否 + * @param groupid + * @param date + * @return + */ + public static boolean isHolidayOrRelaxDay(String groupid,String date){ + boolean bool = false; + RecordSet rs = new RecordSet(); + rs.executeQuery("select * from kq_HolidaySet where groupid=? and holidayDate=?",groupid,date); + while(rs.next()){ + // 1-公众假日 2-调配工作日 3-调配休息日 + int changeType = Util.getIntValue(rs.getString("changeType")); + if(changeType == 1 || changeType == 3){ + bool = true; + } + } + return bool; + } + + /** + * 判断 指定天数 是否是 调配休息日 true 是 false 否 + * @param groupid + * @param date + * @return + */ + public static boolean isAllocateRestDay(String groupid,String date){ + boolean bool = false; + RecordSet rs = new RecordSet(); + rs.executeQuery("select * from kq_HolidaySet where groupid=? and holidayDate=?",groupid,date); + while(rs.next()){ + // 1-公众假日 2-调配工作日 3-调配休息日 + int changeType = Util.getIntValue(rs.getString("changeType")); + if(changeType == 3){ + bool = true; + } + } + return bool; + } + + /** + * 判断 指定天数 是否是 调配工作日 true 是 false 否 + * @param groupid + * @param date + * @return + */ + public static boolean isAllocateWorkDay(String groupid,String date){ + boolean bool = false; + RecordSet rs = new RecordSet(); + rs.executeQuery("select * from kq_HolidaySet where groupid=? and holidayDate=?",groupid,date); + while(rs.next()){ + // 1-公众假日 2-调配工作日 3-调配休息日 + int changeType = Util.getIntValue(rs.getString("changeType")); + if(changeType == 2){ + bool = true; + } + } + return bool; + } + + /** + * 判断 指定天数 是否是 调配工作日 true 是 false 否 + * @param groupid + * @param date + * @return + */ + public static boolean isAllocateHolidayDay(String groupid,String date){ + boolean bool = false; + RecordSet rs = new RecordSet(); + rs.executeQuery("select * from kq_HolidaySet where groupid=? and holidayDate=?",groupid,date); + while(rs.next()){ + // 1-公众假日 2-调配工作日 3-调配休息日 + int changeType = Util.getIntValue(rs.getString("changeType")); + if(changeType == 1){ + bool = true; + } + } + return bool; + } + + private static String[] parseDate(String date){ + if (StringUtils.isEmpty(date)) { + return new String[]{"1990", "1", "1"}; + } + try { + String[] split = date.split("-"); + List list = new ArrayList<>(Arrays.asList(split)); + // 只有年 + if (list.size() == 1) { + // 添加月 + list.add("1"); + // 添加日 + list.add("1"); + } + // 只有年月 + else if (list.size() == 2) { + list.add("1"); + } + return list.toArray(new String[]{}); + }catch (Exception e){ + e.printStackTrace(); + } + return null; + } + + /** + * 判断 日期是否是 周六 或 周日 + * @param dateString + * @return + */ + public static boolean isSaturdayOrSunday(String dateString) { + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); + Date date = null; + boolean flag = false; + try { + date = format.parse(dateString); + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK); + if(dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY){ + flag = true; + } + } catch (ParseException e) { + e.printStackTrace(); + } + return flag; + } + + /** + * 判断一个时间是否在一个时间段内 + * + * @param nowTimee 指定时间 + * @param beginTimee 开始时间 + * @param endTimee 结束时间 + */ + public static boolean belongCalendarBefore(String nowTimee, String beginTimee, String endTimee) { + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); + Date nowTime = null; + Date beginTime = null; + Date endTime = null; + boolean b = false; + try { + nowTime = format.parse(nowTimee); + beginTime = format.parse(beginTimee); + endTime = format.parse(endTimee); + + Calendar date = Calendar.getInstance(); + date.setTime(nowTime); + Calendar begin = Calendar.getInstance(); + begin.setTime(beginTime); + Calendar end = Calendar.getInstance(); + end.setTime(endTime); + + if(nowTimee.equals(endTimee)){ + b = true; + }else if(date.after(begin) && date.before(end)){//在时间段内 + b = true; + } + } catch (Exception ex) { + ex.printStackTrace(); + } + return b; + } + + /** + * 判断一个时间是否在一个时间段内 + * + * @param nowTimee 指定时间 + * @param beginTimee 开始时间 + * @param endTimee 结束时间 + */ + public static boolean belongCalendar(String nowTimee, String beginTimee, String endTimee) { + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); + Date nowTime = null; + Date beginTime = null; + Date endTime = null; + boolean b = false; + try { + nowTime = format.parse(nowTimee); + beginTime = format.parse(beginTimee); + endTime = format.parse(endTimee); + + Calendar date = Calendar.getInstance(); + date.setTime(nowTime); + Calendar begin = Calendar.getInstance(); + begin.setTime(beginTime); + Calendar end = Calendar.getInstance(); + end.setTime(endTime); + + if(nowTimee.equals(endTimee) || nowTimee.equals(beginTimee)){ + b = true; + }else if(date.after(begin) && date.before(end)){//在时间段内 + b = true; + } + } catch (Exception ex) { + ex.printStackTrace(); + } + return b; + } + +} diff --git a/领悦二开new/src/com/engine/lingyue/web/SynOtherKqInfoAction.java b/领悦二开new/src/com/engine/lingyue/web/SynOtherKqInfoAction.java new file mode 100644 index 0000000..b661e8e --- /dev/null +++ b/领悦二开new/src/com/engine/lingyue/web/SynOtherKqInfoAction.java @@ -0,0 +1,165 @@ +package com.engine.lingyue.web; + +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.engine.common.util.ParamUtil; +import com.engine.kq.biz.KQFormatBiz; +import com.engine.kq.timer.KQQueue; +import com.engine.kq.timer.KQTaskBean; +import com.engine.kq.wfset.util.SplitActionUtil; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; +import weaver.interfaces.lingyue.util.HttpUtil; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @Title + * @Author wangchaofa + * @CreateDate 2024/7/17 + * @Version 1.0 + * @Description + */ +public class SynOtherKqInfoAction { + + /** + * 获取 中控考勤数据 + * @param request + * @param response + * @return + */ + @POST + @Path("/ZkKqInfo") + @Produces({MediaType.TEXT_PLAIN}) + public String getReportData(@Context HttpServletRequest request, @Context HttpServletResponse response){ + Map apidatas = new HashMap(); + RecordSet rs = new RecordSet(); + int kq_number = Util.getIntValue(rs.getPropValue("hrm_zhongkong","kq_number")); + HttpUtil httpUtil = new HttpUtil(); + int success_num = 0; + int fail_num = 0; + try { + Map params = ParamUtil.request2Map(request); + + // 开始时间 + String startdatetime = Util.null2String(params.get("startdatetime")); + // 结束时间 + String enddatetime = Util.null2String(params.get("enddatetime")); + // 指定人员id + String xmids = Util.null2String(params.get("xmids")); + + List lsFormatData = new ArrayList<>(); + JSONObject json_main = new JSONObject(); + + if(startdatetime != null && !"".equals(startdatetime)){ + json_main.put("starttime",startdatetime); + } + if(enddatetime != null && !"".equals(enddatetime)){ + json_main.put("endtime",enddatetime); + } + if(xmids != null && !"".equals(xmids)){ + // 根据人员id 查询 自定义字段 考勤卡号,也就是中控考勤机那边的人员编号 + for(String xmid : xmids.split(",")){ + String cus_userid = httpUtil.getCusIdByUserid(xmid); + if(cus_userid != null && !"".equals(cus_userid)){ + json_main.put("pin",cus_userid); + int index = 1; + json_main.put("number",kq_number); + rs.writeLog("============= SynOtherKqInfoAction getReportData json_main =============== "+ json_main); + httpUtil.SynKqData(lsFormatData,index,json_main); + }else{ + apidatas.put("status", false); + apidatas.put("message", "HR系统中未维护该人员的考勤卡号!"); + fail_num++; + continue; + } + } + } + + + Map> overtimeMap = Maps.newHashMap(); + List overtimeList = Lists.newArrayList(); + List formatParams = null; + List> lsFormatParams = new ArrayList<>(); + List delParams = null; + List> lsDelParams = new ArrayList<>(); + + for(int i=0;lsFormatData!=null&&i(); + String[] formatData = Util.splitString(lsFormatData.get(i),"|"); + String date_1 = HttpUtil.addDateDay(formatData[1],-1); + formatParams.add(formatData[0]); + formatParams.add(date_1); + lsFormatParams.add(formatParams); + + formatParams = new ArrayList<>(); + formatParams.add(formatData[0]); + formatParams.add(formatData[1]); + lsFormatParams.add(formatParams); + + delParams = new ArrayList<>(); + delParams.add(formatData[0]); + delParams.add(formatData[1]); + delParams.add(formatData[2]); + lsDelParams.add(delParams); + + String resourceId = formatData[0]; + String kqdate = formatData[1]; + if(overtimeMap.containsKey(resourceId)){ + List tmp_overtimeList = overtimeMap.get(resourceId); + if(!tmp_overtimeList.contains(kqdate)){ + tmp_overtimeList.add(kqdate); + } + }else{ + if(!overtimeList.contains(kqdate)){ + overtimeList.add(kqdate); + } + overtimeMap.put(resourceId, overtimeList); + } + } + + new KQFormatBiz().format(lsFormatParams); + //处理加班生成 + List tasks = new ArrayList<>(); + for(Map.Entry> mme: overtimeMap.entrySet()){ + String resid = mme.getKey(); + List overList = mme.getValue(); + for(String date : overList){ + SplitActionUtil.pushOverTimeTasks(date,date,resid,tasks); + } + } + if(!tasks.isEmpty()){ + KQQueue.writeTasks(tasks); + } + + User user = HrmUserVarify.getUser(request, response); + + String message = "成功同步了 "+ success_num +" 条!失败了 "+ fail_num +" 条!"; + + apidatas.put("status", true); + apidatas.put("message",message); + } catch (Exception e) { + e.printStackTrace(); + apidatas.put("status", false); + apidatas.put("message", "catch exception : " + e.getMessage()); + } + return JSONObject.toJSONString(apidatas, SerializerFeature.DisableCircularReferenceDetect); + } + +} diff --git a/领悦二开new/src/com/fage/DemoTest.java b/领悦二开new/src/com/fage/DemoTest.java new file mode 100644 index 0000000..d239094 --- /dev/null +++ b/领悦二开new/src/com/fage/DemoTest.java @@ -0,0 +1,551 @@ +package com.fage; + + +import com.alibaba.fastjson.JSONObject; +import org.apache.commons.lang.StringUtils; +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.util.EntityUtils; +import weaver.common.DateUtil; +import weaver.general.TimeUtil; + +import java.io.IOException; +import java.math.BigDecimal; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.*; + +/** + * @Title + * @Author wangchaofa + * @CreateDate 2024/7/16 + * @Version 1.0 + * @Description + */ +public class DemoTest { + + private static final String CHARACTERS = "abcdefghijklmnopqrstuvwxyz0123456789"; + private static final int LENGTH = 32; + + public static void main(String[] args) throws Exception{ + +// String time = "12:12:13"; +// System.out.println(time.substring(0,5)); +// +// String a = "2024-11-01"; +// System.out.println(addDateMonth(a,-2)); + +// List list = new ArrayList<>(); +// +// list.add("17918368"); +// list.add("17918938"); +// list.add("17918678"); +// list.add("17918733"); +// list.add("17918392"); +// +// System.out.println(Collections.max(list)); +// +// String checktime = "2024-07-10 00:01:15"; +// String signDate = checktime.substring(0, 10); +// String signTime = checktime.substring(11, 19); +// +// System.out.println(signDate); +// System.out.println(signTime); +// +// String randomString = generateRandomString(); +// System.out.println(randomString); +// +// +// String deptcode = "eb341f9de10c4377848434087abf770c1"; +// +// boolean bool = false; +// +// // 获取所有部门信息 接口url +// // key +// String key = "56b2gxturpnypuumxq4bpwhrj1_82cpu0nqwrslzkgzp"; +// String get_all_dept_url = "http://222.212.88.118:8989/api/v2/department/get/?key=" + key; +// Map headers = new HashMap<>(); +// JSONObject json_main = new JSONObject(); +// +// json_main.put("deptnumber",deptcode); +// +// String encode = "utf-8"; +// String stringJson = json_main.toString(); +// +// String content = null; +// CloseableHttpResponse httpResponse = null; +// CloseableHttpClient closeableHttpClient = null; +// try { +// closeableHttpClient = HttpClients.createDefault(); +// HttpPost httpost = new HttpPost(get_all_dept_url); +// //设置header +// httpost.setHeader("Content-type", "application/json"); +// if (headers != null && headers.size() > 0) { +// for (Map.Entry entry : headers.entrySet()) { +// httpost.setHeader(entry.getKey(),entry.getValue()); +// } +// } +// //组织请求参数 +// StringEntity stringEntity = new StringEntity(stringJson, encode); +// httpost.setEntity(stringEntity); +// //响应信息 +// httpResponse = closeableHttpClient.execute(httpost); +// if(httpResponse != null) { +// HttpEntity entity = httpResponse.getEntity(); +// content = EntityUtils.toString(entity, encode); +// if (content != null && !"".equals(content)) { +// JSONObject json = JSONObject.parseObject(content); +// System.out.println("============= pushInfo json =================== " + json); +// int ret = Integer.parseInt(json.getString("ret")); +// if(ret == 0){ +// String data = json.getString("data"); +// JSONObject data_json = JSONObject.parseObject(data); +// if(data_json.isEmpty()){ +// System.out.println("5555555555"); +// }else{ +// System.out.println("666666666"); +// } +// } +// } +// } +// } catch (Exception e) { +// e.printStackTrace(); +// }finally{ +// try { +// httpResponse.close(); +// } catch (IOException e) { +// e.printStackTrace(); +// } +// } +// try { //关闭连接、释放资源 +// closeableHttpClient.close(); +// } catch (IOException e) { +// e.printStackTrace(); +// } + +// String aa = "2024-11-01"; +// String bb = "2024-11-30"; +// System.out.println(getDays(aa,bb)); +// +// String sStartDate = "2024-12-01"; +// String sEndDate = "2024-12-31"; +// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); +// Date date1 = sdf.parse(sStartDate); +// Date date2 = sdf.parse(sEndDate); +// long days = (date2.getTime() - date1.getTime()) / (24*3600*1000); +// long yushu = (date2.getTime() - date1.getTime()) % (24*3600*1000); +// +// System.out.println("days:" + days + ",yushu:" + yushu); +// +// //规整方法1 +// date1.setHours(0); +// date1.setMinutes(0); +// date1.setSeconds(0); +// long days2 = (date2.getTime() - date1.getTime()) / (24*3600*1000); +// long yushu2 = (date2.getTime() - date1.getTime()) % (24*3600*1000); +// +// System.out.println("days2:" + days2 + ",yushu2:" + yushu2); +// +// //规整方法2 +// String sdate1 = sdf.format(date1); +// date1 = sdf.parse(sdate1); +// +// long days3 = (date2.getTime() - date1.getTime()) / (24*3600*1000); +// long yushu3 = (date2.getTime() - date1.getTime()) % (24*3600*1000); +// +// System.out.println("days3:" + days3 + ",yushu3:" + yushu3); +// +// System.out.println(getDays(sStartDate,sEndDate)); +// +// +// // 周六或周日天数 +// int weekdays = 0; +// // 周一到周五天数 +// int workdays = 0; +// // 格式化日期 +// DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); +// String[] dateStartArr = parseDate(sStartDate); +// String[] dateEndtArr = parseDate(sEndDate); +// LocalDate startDate = LocalDate.of(Integer.parseInt(dateStartArr[0]), Integer.parseInt(dateStartArr[1]), Integer.parseInt(dateStartArr[2])); +// LocalDate endDate = LocalDate.of(Integer.parseInt(dateEndtArr[0]), Integer.parseInt(dateEndtArr[1]), Integer.parseInt(dateEndtArr[2])); +// // 遍历日期范围 +// for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) { +// // 输出格式化后的日期字符串 +// String dateString = date.format(formatter); +// // 是 周六或 周日 +// if(isSaturdayOrSunday(dateString)) { +// weekdays++; +// }else{ +// workdays++; +// } +// } +// System.out.println("workdays: "+workdays); +// System.out.println("weekdays: "+weekdays); + +// String latemins = "4"; +// String serial_hours = "8"; +// String result = ""; +// String latehours = floatDivide(latemins,"60"); +// System.out.println(latehours); +// if(floatCompare(serial_hours,"0") > 0){ +// result = floatDivide(latehours,serial_hours); +// } +// System.out.println(result); +// +// double aa = 21.00; +// String bb = "21.01"; +// if(Double.valueOf(bb) <= aa){ +// System.out.println("5555555555"); +// } + +// String aa = "2024-02-24 08:12:23"; +// String bb = "2024-11-01"; +// String cc = "2024-11-30"; +// System.out.println(belongEndCalendar(aa,bb,cc)); +// +// String ds = "2024-12-31"; +// System.out.println(addDateDay(ds,1)); +// +// int currentyear = Integer.valueOf(aa.substring(0, 4)); //年 +// int currentmonth = Integer.valueOf(aa.substring(5, 7)); //月 +// int currentday = Integer.valueOf(aa.substring(8, 10)); //月 + +// System.out.println(aa.length()); +// System.out.println(aa.substring(0,10)); + + String today = DateUtil.getCurrentDate(); + System.out.println(today); + String dismissDate = "2024-12-17"; + Calendar cal = DateUtil.getCalendar(); + boolean isEnd = false; + String fromDate = "2025-05-01"; + String toDate = "2025-05-31"; + for (String date = fromDate; !isEnd; ) { + if (date.equals(toDate)) isEnd = true; + if(!"".equals(dismissDate) && DateUtil.compDate(dismissDate, date) > 0) { + System.out.println("111 "+date); + }else if (DateUtil.compDate(today, date) > 0) { + System.out.println("222 "+date); + } + + + cal.setTime(DateUtil.parseToDate(date)); + date = DateUtil.getDate(cal.getTime(), 1); + } + } + + /** + * 判断一个时间是否在一个时间段内 + * + * @param nowTimee 指定时间 + * @param beginTimee 开始时间 + * @param endTimee 结束时间 + */ + public static boolean belongEndCalendar(String nowTimee, String beginTimee, String endTimee) { + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); + Date nowTime = null; + Date beginTime = null; + Date endTime = null; + boolean b = false; + try { + nowTime = format.parse(nowTimee); + beginTime = format.parse(beginTimee); + endTime = format.parse(endTimee); + + Calendar date = Calendar.getInstance(); + date.setTime(nowTime); + Calendar begin = Calendar.getInstance(); + begin.setTime(beginTime); + Calendar end = Calendar.getInstance(); + end.setTime(endTime); + + if(nowTimee.equals(endTimee) || nowTimee.equals(beginTimee)){ + b = true; + }else if(date.after(begin) && date.before(end)){//在时间段内 + b = true; + } + } catch (Exception ex) { + ex.printStackTrace(); + } + return b; + } + + public static String generateRandomString() { + Random random = new Random(); + StringBuilder sb = new StringBuilder(LENGTH); + for (int i = 0; i < LENGTH; i++) { + sb.append(CHARACTERS.charAt(random.nextInt(CHARACTERS.length()))); + } + return sb.toString(); + } + + /** + * 对时间的月数进行加减 + * @param daytime 时间的格式:yyyy-MM-dd + * @param month 月数 -1则代表减一月 + * @return + */ + public static String addDateMonth(String daytime, int month){ + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); + Date date = null; + try { + date = format.parse(daytime); + if (date == null){ + return ""; + } + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + cal.add(Calendar.MONTH, month);// 加 day 月 + date = cal.getTime(); + cal = null; + return format.format(date); + } catch (Exception ex) { + ex.printStackTrace(); + } + return ""; + } + + /** + * 计算两个时间字符串日期的相差天数 + * + * @param sStartDate 字符串时间1 + * @param sEndDate 字符串时间2 + * @return 相差时间 + */ + public static int getDays(String sStartDate, String sEndDate) { + int days = 0; + try { + if (!"".equals(sStartDate) && !"".equals(sEndDate)) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + Date date1 = sdf.parse(sStartDate); + Date date2 = sdf.parse(sEndDate); + + long Days = (date2.getTime() - date1.getTime()) / (24*3600*1000); + if(Days < 0){ + days = 0; + }else{ + days = (int)Days+1; + } + } + }catch (Exception e){ + e.printStackTrace(); + } + return days; + } + + /** + * 计算天数 + * @param date1 日期 + * @param date2 日期 + * @return 天数 + */ + public static int calculateDays(Date date1, Date date2) { + Calendar cal1 = Calendar.getInstance(); + cal1.setTime(date1); + Calendar cal2 = Calendar.getInstance(); + cal2.setTime(date2); + int day1 = cal1.get(Calendar.DAY_OF_YEAR); + int day2 = cal2.get(Calendar.DAY_OF_YEAR); + int year1 = cal1.get(Calendar.YEAR); + int year2 = cal2.get(Calendar.YEAR); + if (year1 != year2) {//不同 年 + int timeDistance = 0; + if (year1 < year2) {//后面日期年大于前面日期 + for (int i = year1; i < year2; i++) { + if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {//闰年 + timeDistance += 366; + } else {//不是闰年 + timeDistance += 365; + } + } + } else { + for (int i = year2; i < year1; i++) { + if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {//闰年 + timeDistance += 366; + } else {//不是闰年 + timeDistance += 365; + timeDistance = 0 - timeDistance; + } + } + } + return timeDistance + (day2 - day1); + } else {//同一年 + return day2 - day1; + } + } + + private static String[] parseDate(String date){ + if (StringUtils.isEmpty(date)) { + return new String[]{"1990", "1", "1"}; + } + try { + String[] split = date.split("-"); + List list = new ArrayList<>(Arrays.asList(split)); + // 只有年 + if (list.size() == 1) { + // 添加月 + list.add("1"); + // 添加日 + list.add("1"); + + } + // 只有年月 + else if (list.size() == 2) { + list.add("1"); + } + return list.toArray(new String[]{}); + }catch (Exception e){ + e.printStackTrace(); + } + return null; + } + + /** + * 判断 日期是否是 周六 或 周日 + * @param dateString + * @return + */ + public static boolean isSaturdayOrSunday(String dateString) { + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); + Date date = null; + boolean flag = false; + try { + date = format.parse(dateString); + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK); + if(dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY){ + flag = true; + } + } catch (ParseException e) { + e.printStackTrace(); + } + return flag; + } + + /** + * @param a 任意数 + * @return 是 + */ + private static String isZero(String a) { + if (a==null || "".equals(a)) { + a = "0"; + } + return a; + } + + /** + * 大小比较 + * + * @param a + * @param b + * @return -1 小于 0 等于 1 大于 + */ + public static int floatCompare(String a, String b) { + a = isZero(a); + b = isZero(b); + BigDecimal bg1 = new BigDecimal(a); + BigDecimal bg2 = new BigDecimal(b); + return bg1.compareTo(bg2); + } + + /** + * 方法描述 : 对两个字符串进行金额的相加 + * @param a + * @param b + * @return + * String + */ + public static String floatAdd(String a, String b) { + a=a.equals("")?"0":a; + b=b.equals("")?"0":b; + BigDecimal bg1 = new BigDecimal(a); + BigDecimal bg2 = new BigDecimal(b); + BigDecimal bd = bg1.add(bg2); + return bd.toString(); + } + + /** + * + * 方法描述 : 对两个字符串进行金额的相减 + * @param a + * @param b + * @return + * String + */ + public static String floatSubtract(String a, String b) { + a=a.equals("")?"0":a; + b=b.equals("")?"0":b; + BigDecimal bg1 = new BigDecimal(a); + BigDecimal bg2 = new BigDecimal(b); + BigDecimal bd = bg1.subtract(bg2); + return bd.toString(); + } + + /** + * + * 方法描述 : 对两个字符串进行金额的相乘 + * @param a + * @param b + * @return + * String + */ + public static String floatMultiply(String a, String b) { + a=a.equals("")?"0":a; + b=b.equals("")?"0":b; + BigDecimal bg1 = new BigDecimal(a); + BigDecimal bg2 = new BigDecimal(b); + BigDecimal bd = bg1.multiply(bg2).setScale(4, BigDecimal.ROUND_HALF_UP); + return bd.toString(); + } + + /** + * + * 方法描述 : 对两个字符串进行金额的相除(默认保留两位小数) + * @param a + * @param b + * @return + * String + */ + public static String floatDivide(String a, String b) { + a=a.equals("")?"0":a; + b=b.equals("")?"0":b; + BigDecimal bg1 = new BigDecimal(a); + BigDecimal bg2 = new BigDecimal(b); + BigDecimal bd = bg1.divide(bg2, 4, BigDecimal.ROUND_HALF_UP); + return bd.toString(); + } + + /** + * 对时间的天数进行加减 + * @param daytime 时间的格式:yyyy-MM-dd + * @param day 天数 -1则代表减一天 + * @return + */ + public static String addDateDay(String daytime, int day){ + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); + Date date = null; + try { + date = format.parse(daytime); + if (date == null){ + return ""; + } + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + cal.add(Calendar.DAY_OF_MONTH, day);// 加一天 + date = cal.getTime(); + cal = null; + return format.format(date); + } catch (Exception ex) { + ex.printStackTrace(); + } + return ""; + } + +} diff --git a/领悦二开new/src/com/lingyue/util/KqUtil.java b/领悦二开new/src/com/lingyue/util/KqUtil.java new file mode 100644 index 0000000..68787dc --- /dev/null +++ b/领悦二开new/src/com/lingyue/util/KqUtil.java @@ -0,0 +1,812 @@ +package com.lingyue.util; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.util.EntityUtils; +import weaver.conn.RecordSet; +import weaver.formmode.setup.ModeRightInfo; +import weaver.general.TimeUtil; +import weaver.general.Util; +import weaver.hrm.User; +import weaver.hrm.company.DepartmentComInfo; +import weaver.hrm.company.SubCompanyComInfo; +import weaver.hrm.companyvirtual.DepartmentVirtualComInfo; +import weaver.hrm.finance.SalaryManager; +import weaver.hrm.resource.CustomFieldTreeManager; +import weaver.hrm.resource.ResourceComInfo; +import weaver.hrm.settings.ChgPasswdReminder; +import weaver.hrm.settings.RemindSettings; +import weaver.system.SysRemindWorkflow; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +/** + * @Title + * @Author wangchaofa + * @CreateDate 2024/9/12 + * @Version 1.0 + * @Description + */ +public class KqUtil { + + /** + * 新增、更新 部门信息 同步至 中控考勤机 + * @param deptid + * @return + */ + public static boolean synAddOrUpdateDeptInfo(String deptid){ + boolean bool = false; + RecordSet rs = new RecordSet(); + // 新增、更新部门 接口url + // key + String key = rs.getPropValue("hrm_zhongkong","key"); + String url = rs.getPropValue("hrm_zhongkong","add_update_dept_url"); + url = url + "?key=" + key; + Map headers = new HashMap<>(); + JSONArray jsonArray = new JSONArray(); + JSONObject json_main = new JSONObject(); + + rs.executeQuery("select * from hrmdepartment where id = ?",deptid); + rs.next(); + String deptcode = Util.null2String(rs.getString("departmentcode")); + String detname = Util.null2String(rs.getString("departmentname")); + String supdepid = Util.null2String(rs.getString("supdepid")); + String subcompanyid1 = Util.null2String(rs.getString("subcompanyid1")); + if(supdepid != null && !"".equals(supdepid) && Integer.parseInt(supdepid) > 0){ + String sup_deptcode = ""; + String sup_Deptcode = getDeptCuscode(supdepid); + if (sup_Deptcode != null && !"".equals(sup_Deptcode)) { + sup_deptcode = sup_Deptcode; + } else { + sup_deptcode = new DepartmentComInfo().getDepartmentCode(supdepid); + } + json_main.put("parentnumber", sup_deptcode); + }else { + if (subcompanyid1 != null && !"".equals(subcompanyid1) && Integer.parseInt(subcompanyid1) > 0) { + String subcode = ""; + String subCode = getSubcomCuscode(subcompanyid1); + if (subCode != null && !"".equals(subCode)) { + subcode = subCode; + } else { + subcode = new SubCompanyComInfo().getSubCompanyCode(subcompanyid1); + } + json_main.put("parentnumber", subcode); + } + } + String dept_code = ""; + String deptCode = getDeptCuscode(deptid); + if(deptCode != null && !"".equals(deptCode)){ + dept_code = deptCode; + }else{ + dept_code = deptcode; + } + json_main.put("deptnumber",dept_code); + json_main.put("deptname",detname); + + jsonArray.add(json_main); + + rs.writeLog("========================== 新增或修改部门,同步至中控考勤机 ======================================"); + rs.writeLog(url+" ========= "+jsonArray.toString()); + + int result = -1; + String msg = ""; + String content = httpPost(url,headers,jsonArray.toString(),"utf-8"); + if (content != null && !"".equals(content)) { + JSONObject json = JSONObject.parseObject(content); + rs.writeLog("============= httpPost pushInfo json =================== " + json); + int resultt = Integer.parseInt(json.getString("ret")); + if(resultt == 0){ + result = 0; + }else{ + result = 1; + } + msg = Util.null2String(json.getString("msg")); + } + + //写入建模记录表 + insertHrToZkJl(1,url,jsonArray,result,msg,""); + + // 0:成功 + if(result == 0) { + bool = true; + } + return bool; + } + + /** + * 新增、更新 分部信息 同步至 中控考勤机 + * @param subcomid + * @return + */ + public static boolean synAddOrUpdateSubComInfo(String subcomid){ + boolean bool = false; + RecordSet rs = new RecordSet(); + // 新增、更新部门 接口url + // key + String key = rs.getPropValue("hrm_zhongkong","key"); + String url = rs.getPropValue("hrm_zhongkong","add_update_dept_url"); + url = url + "?key=" + key; + Map headers = new HashMap<>(); + JSONArray jsonArray = new JSONArray(); + JSONObject json_main = new JSONObject(); + + rs.executeQuery("select * from HrmSubCompany where id = ?",subcomid); + rs.next(); + String subcompanycode = Util.null2String(rs.getString("subcompanycode")); + String subcompanyname = Util.null2String(rs.getString("subcompanyname")); + String supsubcomid = Util.null2String(rs.getString("supsubcomid")); + if(supsubcomid != null && !"".equals(supsubcomid) && Integer.parseInt(supsubcomid) > 0){ + String subcode = ""; + String subCode = getSubcomCuscode(supsubcomid); + if (subCode != null && !"".equals(subCode)) { + subcode = subCode; + } else { + subcode = new SubCompanyComInfo().getSubCompanyCode(supsubcomid); + } + json_main.put("parentnumber", subcode); + } + String subcompany_code = ""; + String subcompanyCode = getSubcomCuscode(subcomid); + if (subcompanyCode != null && !"".equals(subcompanyCode)) { + subcompany_code = subcompanyCode; + } else { + subcompany_code = subcompanycode; + } + json_main.put("deptnumber",subcompany_code); + json_main.put("deptname",subcompanyname); + jsonArray.add(json_main); + + rs.writeLog("========================== 新增或修改分部,同步至中控考勤机 ======================================"); + rs.writeLog(url+" ========= "+jsonArray.toString()); + + int result = -1; + String msg = ""; + String content = httpPost(url,headers,jsonArray.toString(),"utf-8"); + if (content != null && !"".equals(content)) { + JSONObject json = JSONObject.parseObject(content); + rs.writeLog("============= httpPost pushInfo json =================== " + json); + int resultt = Integer.parseInt(json.getString("ret")); + if(resultt == 0){ + result = 0; + }else{ + result = 1; + } + msg = Util.null2String(json.getString("msg")); + } + + //写入建模记录表 + insertHrToZkJl(1,url,jsonArray,result,msg,""); + + // 0:成功 + if(result == 0) { + bool = true; + } + return bool; + } + + /** + * 删除 部门信息 同步至 中控考勤机 + * @param deptid + * @return + */ + public static boolean synDeleteDeptInfo(String deptid){ + boolean bool = false; + RecordSet rs = new RecordSet(); + // 删除部门 接口url + // key + String key = rs.getPropValue("hrm_zhongkong","key"); + String url = rs.getPropValue("hrm_zhongkong","delete_dept_url"); + url = url + "?key=" + key; + Map headers = new HashMap<>(); + JSONObject json_main = new JSONObject(); + + rs.executeQuery("select * from hrmdepartment where id = ?",deptid); + rs.next(); + String deptcode = Util.null2String(rs.getString("departmentcode")); + String detname = Util.null2String(rs.getString("departmentname")); + + json_main.put("deptnumber",deptcode); + + rs.writeLog("========================== 删除部门,同步至中控考勤机 ======================================"); + rs.writeLog(url+" ========= "+json_main.toString()); + + int result = -1; + String msg = ""; + String content = httpPost(url,headers,json_main.toString(),"utf-8"); + if (content != null && !"".equals(content)) { + JSONObject json = JSONObject.parseObject(content); + rs.writeLog("============= httpPost pushInfo json =================== " + json); + int resultt = Integer.parseInt(json.getString("ret")); + if(resultt == 0){ + result = 0; + }else{ + result = 1; + } + msg = Util.null2String(json.getString("msg")); + } + + JSONArray jsonArray = new JSONArray(); + jsonArray.add(json_main); + //写入建模记录表 + insertHrToZkJl(1,url,jsonArray,result,msg,""); + + // 0:成功 + if(result == 0) { + bool = true; + } + return bool; + } + + /** + * 删除 分部信息 同步至 中控考勤机 + * @param subcomid + * @return + */ + public static boolean synDeleteSubComInfo(String subcomid){ + boolean bool = false; + RecordSet rs = new RecordSet(); + // 新增、更新部门 接口url + // key + String key = rs.getPropValue("hrm_zhongkong","key"); + String url = rs.getPropValue("hrm_zhongkong","delete_dept_url"); + url = url + "?key=" + key; + Map headers = new HashMap<>(); + JSONObject json_main = new JSONObject(); + + rs.executeQuery("select * from HrmSubCompany where id = ?",subcomid); + rs.next(); + String subcompanycode = Util.null2String(rs.getString("subcompanycode")); + String subcompanyname = Util.null2String(rs.getString("subcompanyname")); + + json_main.put("deptnumber",subcompanycode); + + rs.writeLog("========================== 删除分部,同步至中控考勤机 ======================================"); + rs.writeLog(url+" ========= "+json_main.toString()); + + int result = -1; + String msg = ""; + String content = httpPost(url,headers,json_main.toString(),"utf-8"); + if (content != null && !"".equals(content)) { + JSONObject json = JSONObject.parseObject(content); + rs.writeLog("============= httpPost pushInfo json =================== " + json); + int resultt = Integer.parseInt(json.getString("ret")); + if(resultt == 0){ + result = 0; + }else{ + result = 1; + } + msg = Util.null2String(json.getString("msg")); + } + + JSONArray jsonArray = new JSONArray(); + jsonArray.add(json_main); + //写入建模记录表 + insertHrToZkJl(1,url,jsonArray,result,msg,""); + + // 0:成功 + if(result == 0) { + bool = true; + } + return bool; + } + + /** + * 新增、更新 人员信息 同步至 中控考勤机 + * @param userid + * @return + */ + public static boolean synAddOrUpdateUserInfo(String userid){ + boolean bool = false; + RecordSet rs = new RecordSet(); + RecordSet rst = new RecordSet(); + // 新增、更新人员 接口url + // key + String key = rs.getPropValue("hrm_zhongkong","key"); + String url = rs.getPropValue("hrm_zhongkong","add_update_user_url"); + url = url + "?key=" + key; + String restoreUserurl = rs.getPropValue("hrm_zhongkong","restore_user_url"); + restoreUserurl = restoreUserurl + "?key=" + key; + Map headers = new HashMap<>(); + JSONArray jsonArray = new JSONArray(); + JSONObject json_main = new JSONObject(); + + User user = new User(Integer.parseInt(userid)); + + String sfhl_fieldid = rs.getPropValue("hrm_zhongkong","sfhl_fieldid"); + String zksfhf_fieldid = rs.getPropValue("hrm_zhongkong","zksfhf_fieldid"); + String sfhl = getSfhl(userid); + + try { + DepartmentComInfo DepartmentComInfo = new DepartmentComInfo(); + ResourceComInfo ResourceComInfo = new ResourceComInfo(); + SalaryManager SalaryManager = new SalaryManager(); + ChgPasswdReminder reminder = new ChgPasswdReminder(); + RemindSettings settings = reminder.getRemindSettings(); + SysRemindWorkflow SysRemindWorkflow = new SysRemindWorkflow(); + CustomFieldTreeManager CustomFieldTreeManager = new CustomFieldTreeManager(); + DepartmentVirtualComInfo DepartmentVirtualComInfo = new DepartmentVirtualComInfo(); + + rs.executeQuery("select * from hrmresource where id = ?",userid); + rs.next(); + String workcode = Util.fromScreen3(rs.getString("workcode"), user.getLanguage()); + String lastname = Util.fromScreen3(rs.getString("lastname"), user.getLanguage()).trim(); + String sex = Util.fromScreen3(rs.getString("sex"), user.getLanguage()); + String departmentid = Util.fromScreen3(rs.getString("departmentid"), user.getLanguage()); + String deptcode = ""; + String sup_Deptcode = getDeptCuscode(departmentid); + if(sup_Deptcode != null && !"".equals(sup_Deptcode)){ + deptcode = sup_Deptcode; + }else{ + deptcode = new DepartmentComInfo().getDepartmentCode(departmentid); + } + String jobtitle = Util.fromScreen3(rs.getString("jobtitle"), user.getLanguage()); + String joblevel = Util.fromScreen3(rs.getString("joblevel"), user.getLanguage()); + String jobactivitydesc = Util.fromScreen3(rs.getString("jobactivitydesc"), user.getLanguage()); + String managerid = Util.fromScreen3(rs.getString("managerid"), user.getLanguage()); + String assistantid = Util.fromScreen3(rs.getString("assistantid"), user.getLanguage()); + String status = Util.fromScreen3(rs.getString("status"), user.getLanguage()); + String locationid = Util.fromScreen3(rs.getString("locationid"), user.getLanguage()); + String workroom = Util.fromScreen3(rs.getString("workroom"), user.getLanguage()); + String telephone = Util.fromScreen3(rs.getString("telephone"), user.getLanguage()); + String mobile = Util.fromScreen3(rs.getString("mobile"), user.getLanguage()); + String fax = Util.fromScreen3(rs.getString("fax"), user.getLanguage()); + String jobcall = Util.fromScreen3(rs.getString("jobcall"), user.getLanguage()); + String email = Util.fromScreen3(rs.getString("email"), user.getLanguage()); + String companystartdate = Util.fromScreen3(rs.getString("companystartdate"), user.getLanguage()); + String birthday = Util.null2String(rs.getString("birthday")); + String certificatenum = Util.fromScreen3(rs.getString("certificatenum"), user.getLanguage()); + + String pincode = ""; + String cuscode = KqUtil.getCusIdByUserid(userid); + if(cuscode != null && !"".equals(cuscode)){ + pincode = cuscode; + }else{ + pincode = workcode; + } + + // 是 + if("0".equals(sfhl)){ + jsonArray.add(pincode); + json_main.put("userpin",jsonArray); + + int result = -1; + String msg = ""; + String content = httpPost(restoreUserurl,headers,json_main.toString(),"utf-8"); + if (content != null && !"".equals(content)) { + JSONObject json = JSONObject.parseObject(content); + rs.writeLog("============= httpPost pushInfo json =================== " + json); + int resultt = Integer.parseInt(json.getString("ret")); + if(resultt == 0){ + result = 0; + //将对应的是否回流 自定义字段清空、中控是否恢复 自定义字段赋值为 是 + rst.executeUpdate("update cus_fielddata set "+ sfhl_fieldid +"=null,"+zksfhf_fieldid+"=‘0’ where scope = 'HrmCustomFieldByInfoType' and scopeid = '-1' and id = ?",userid); + }else{ + result = 1; + } + msg = Util.null2String(json.getString("msg")); + } + + //写入建模记录表 + insertHrToZkJl(1,restoreUserurl,jsonArray,result,msg,""); + + // 0:成功 + if(result == 0) { + bool = true; + } + }else{ + json_main.put("pin",pincode); + json_main.put("name",lastname); + json_main.put("deptnumber",deptcode); + json_main.put("telephone",telephone); + json_main.put("mobile",mobile); + json_main.put("gender","0".equals(sex)?"M":"F"); + json_main.put("email",email); + json_main.put("identitycard",certificatenum); + json_main.put("birthday",birthday); + json_main.put("hiredday",companystartdate); + + jsonArray.add(json_main); + + rs.writeLog("=============== synAddOrUpdateUserInfo jsonArray ============== "+ jsonArray.toString()); + + int result = -1; + String msg = ""; + String content = httpPost(url,headers,jsonArray.toString(),"utf-8"); + if (content != null && !"".equals(content)) { + JSONObject json = JSONObject.parseObject(content); + rs.writeLog("============= httpPost pushInfo json =================== " + json); + int resultt = Integer.parseInt(json.getString("ret")); + if(resultt == 0){ + result = 0; + }else{ + result = 1; + } + msg = Util.null2String(json.getString("msg")); + } + + //写入建模记录表 + insertHrToZkJl(1,url,jsonArray,result,msg,""); + + // 0:成功 + if(result == 0) { + bool = true; + } + } + return bool; + }catch (Exception e){ + e.printStackTrace(); + rs.writeLog(e); + } + return bool; + } + + /** + * 删除 人员信息 同步至 中控考勤机 + * @param userid + * @return + */ + public static boolean synDeleteUserInfo(String userid){ + boolean bool = false; + RecordSet rs = new RecordSet(); + // 删除部门 接口url + // key + String key = rs.getPropValue("hrm_zhongkong","key"); + String url = rs.getPropValue("hrm_zhongkong","delete_user_url"); + url = url + "?key=" + key; + Map headers = new HashMap<>(); + JSONObject json_main = new JSONObject(); + + rs.executeQuery("select * from hrmresource where id = ?",userid); + rs.next(); + String usercode = Util.null2String(rs.getString("workcode")); + String username = Util.null2String(rs.getString("lastname")); + + json_main.put("pin",usercode); + + int result = -1; + String msg = ""; + String content = httpPost(url,headers,json_main.toString(),"utf-8"); + if (content != null && !"".equals(content)) { + JSONObject json = JSONObject.parseObject(content); + rs.writeLog("============= httpPost pushInfo json =================== " + json); + int resultt = Integer.parseInt(json.getString("ret")); + if(resultt == 0){ + result = 0; + }else{ + result = 1; + } + msg = Util.null2String(json.getString("msg")); + } + + JSONArray jsonArray = new JSONArray(); + jsonArray.add(json_main); + //写入建模记录表 + insertHrToZkJl(1,url,jsonArray,result,msg,""); + + // 0:成功 + if(result == 0) { + bool = true; + } + return bool; + } + + /** + * 判断 部门编码 在 中控考勤机 是否存在 + * @param deptcode + * @return + */ + public static boolean checkIsExistDeptInfo(String deptcode){ + boolean bool = false; + RecordSet rs = new RecordSet(); + + // 获取所有部门信息 接口url + // key + String key = rs.getPropValue("hrm_zhongkong","key"); + String get_all_dept_url = rs.getPropValue("hrm_zhongkong","get_all_dept_url"); + get_all_dept_url = get_all_dept_url + "?key=" + key; + Map headers = new HashMap<>(); + JSONObject json_main = new JSONObject(); + + json_main.put("deptnumber",deptcode); + + String encode = "utf-8"; + String stringJson = json_main.toString(); + + String content = null; + CloseableHttpResponse httpResponse = null; + CloseableHttpClient closeableHttpClient = null; + try { + closeableHttpClient = HttpClients.createDefault(); + HttpPost httpost = new HttpPost(get_all_dept_url); + //设置header + httpost.setHeader("Content-type", "application/json"); + if (headers != null && headers.size() > 0) { + for (Map.Entry entry : headers.entrySet()) { + httpost.setHeader(entry.getKey(),entry.getValue()); + } + } + //组织请求参数 + StringEntity stringEntity = new StringEntity(stringJson, encode); + httpost.setEntity(stringEntity); + //响应信息 + httpResponse = closeableHttpClient.execute(httpost); + if(httpResponse != null) { + HttpEntity entity = httpResponse.getEntity(); + content = EntityUtils.toString(entity, encode); + if (content != null && !"".equals(content)) { + JSONObject json = JSONObject.parseObject(content); + rs.writeLog("============= checkIsExistDeptInfo pushInfo json =================== " + json); + int ret = Integer.parseInt(json.getString("ret")); + if(ret == 0){ + String data = json.getString("data"); + JSONObject data_json = JSONObject.parseObject(data); + if(data_json.isEmpty()){ + bool = false; + }else{ + bool = true; + } + } + } + } + } catch (Exception e) { + bool = false; + e.printStackTrace(); + rs.writeLog(e); + }finally{ + try { + httpResponse.close(); + } catch (IOException e) { + bool = false; + e.printStackTrace(); + } + } + try { //关闭连接、释放资源 + closeableHttpClient.close(); + } catch (IOException e) { + bool = false; + e.printStackTrace(); + } + return bool; + } + + /** + * 判断 人员编码 在 中控考勤机 是否存在 + * @param usercode + * @return + */ + public static boolean checkIsExistUserInfo(String usercode){ + boolean bool = false; + RecordSet rs = new RecordSet(); + + // 获取所有部门信息 接口url + // key + String key = rs.getPropValue("hrm_zhongkong","key"); + String get_all_user_url = rs.getPropValue("hrm_zhongkong","get_all_user_url"); + get_all_user_url = get_all_user_url + "?key=" + key; + Map headers = new HashMap<>(); + JSONObject json_main = new JSONObject(); + + json_main.put("pinlist",usercode); + + String encode = "utf-8"; + String stringJson = json_main.toString(); + + String content = null; + CloseableHttpResponse httpResponse = null; + CloseableHttpClient closeableHttpClient = null; + try { + closeableHttpClient = HttpClients.createDefault(); + HttpPost httpost = new HttpPost(get_all_user_url); + //设置header + httpost.setHeader("Content-type", "application/json"); + if (headers != null && headers.size() > 0) { + for (Map.Entry entry : headers.entrySet()) { + httpost.setHeader(entry.getKey(),entry.getValue()); + } + } + //组织请求参数 + StringEntity stringEntity = new StringEntity(stringJson, encode); + httpost.setEntity(stringEntity); + //响应信息 + httpResponse = closeableHttpClient.execute(httpost); + if(httpResponse != null) { + HttpEntity entity = httpResponse.getEntity(); + content = EntityUtils.toString(entity, encode); + if (content != null && !"".equals(content)) { + JSONObject json = JSONObject.parseObject(content); + rs.writeLog("============= checkIsExistUserInfo pushInfo json =================== " + json); + int ret = Integer.parseInt(json.getString("ret")); + if(ret == 0){ + String data = json.getString("data"); + JSONObject data_json = JSONObject.parseObject(data); + int count = Integer.parseInt(data_json.getString("count").toString()); + if(count>0){ + bool = true; + }else{ + bool = false; + } + } + } + } + } catch (Exception e) { + bool = false; + e.printStackTrace(); + rs.writeLog(e); + }finally{ + try { + httpResponse.close(); + } catch (IOException e) { + bool = false; + e.printStackTrace(); + } + } + try { //关闭连接、释放资源 + closeableHttpClient.close(); + } catch (IOException e) { + bool = false; + e.printStackTrace(); + } + return bool; + } + + + /** + * post 请求 json格式 + * @param url + * @param headers + * @param stringJson + * @param encode + * @return + */ + public static String httpPost(String url, Map headers, String stringJson, String encode){ + int result = 0; + if(encode == null){ + encode = "utf-8"; + } + RecordSet rs = new RecordSet(); + String content = ""; + CloseableHttpResponse httpResponse = null; + CloseableHttpClient closeableHttpClient = null; + try { + closeableHttpClient = HttpClients.createDefault(); + HttpPost httpost = new HttpPost(url); + //设置header + httpost.setHeader("Content-type", "application/json"); + if (headers != null && headers.size() > 0) { + for (Map.Entry entry : headers.entrySet()) { + httpost.setHeader(entry.getKey(),entry.getValue()); + } + } + //组织请求参数 + StringEntity stringEntity = new StringEntity(stringJson, encode); + httpost.setEntity(stringEntity); + //响应信息 + httpResponse = closeableHttpClient.execute(httpost); + if(httpResponse != null) { + HttpEntity entity = httpResponse.getEntity(); + content = EntityUtils.toString(entity, encode); +// if (content != null && !"".equals(content)) { +// JSONObject json = JSONObject.parseObject(content); +// rs.writeLog("============= httpPost pushInfo json =================== " + json); +// result = Integer.parseInt(json.getString("ret")); +// } + } + } catch (Exception e) { + e.printStackTrace(); + rs.writeLog(e); + }finally{ + try { + httpResponse.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + try { //关闭连接、释放资源 + closeableHttpClient.close(); + } catch (IOException e) { + e.printStackTrace(); + } + return content; + } + + /** + * 获取 部门中控系统id + * @param deptid + * @return + */ + public static String getDeptCuscode(String deptid){ + RecordSet rs = new RecordSet(); + String code = ""; + rs.executeQuery("select zkxtid from hrmdepartmentdefined where deptid = ?",deptid); + if(rs.next()){ + code = Util.null2String(rs.getString("zkxtid")); + } + return code; + } + + /** + * 获取 分部 中控系统id + * @param subcomid + * @return + */ + public static String getSubcomCuscode(String subcomid){ + RecordSet rs = new RecordSet(); + String code = ""; + rs.executeQuery("select zkid from hrmsubcompanydefined where subcomid = ?",subcomid); + if(rs.next()){ + code = Util.null2String(rs.getString("zkid")); + } + return code; + } + + /** + * 根据 人员id 获取 自定义 考勤卡号,也就是 中控考勤机那边的 人员编号 pin + * @param userid + * @return + */ + public static String getCusIdByUserid(String userid){ + String result = ""; + RecordSet rs = new RecordSet(); + String kq_fieldid = rs.getPropValue("hrm_zhongkong","kq_fieldid"); + rs.executeQuery("select "+ kq_fieldid +" from cus_fielddata where scope = 'HrmCustomFieldByInfoType' and scopeid = -1 and id = ?",userid); + if(rs.next()){ + result = Util.null2String(rs.getString(kq_fieldid)); + } + return result; + } + + public static void insertHrToZkJl(int type,String url,JSONArray jsonArray,int result,String msg,String requestid){ + RecordSet rs = new RecordSet(); + RecordSet rs1 = new RecordSet(); + RecordSet rs2 = new RecordSet(); + + String currentdate = TimeUtil.getCurrentDateString(); + String currenttime = TimeUtil.getOnlyCurrentTimeString(); +// String currentdatetime = currentdate+" "+currenttime; + // HR同步至中控考勤机记录表 + int hrtozkkqj_formmodeid = Util.getIntValue(rs.getPropValue("hrm_zhongkong","hrtozkkqj_formmodeid")); + String uuid = UUID.randomUUID().toString(); + int creater = 1; + + String insertSql = " insert into uf_hrtozkjlb(dyly,jkdz,jkrc,dyrq,dysj,fhjg,fhxx,lcid," + + "modedatacreater,modedatacreatedate,modedatacreatetime,formmodeid,modeuuid) " + + "values(?,?,?,?,?,?,?,?,?,?,?,?,?) "; + boolean exeRes = rs1.executeUpdate(insertSql,new Object[]{type,url,jsonArray.toString(),currentdate,currenttime,result,msg,requestid, + creater, currentdate, currenttime, hrtozkkqj_formmodeid, uuid}); + int billid = -1; + if (exeRes) { + //重构权限 + rs2.executeQuery(" select id from uf_hrtozkjlb where modeuuid=? ",new Object[]{uuid}); + rs2.next(); + billid = rs2.getInt("id"); + ModeRightInfo moderight = new ModeRightInfo(); + moderight.editModeDataShare(creater, hrtozkkqj_formmodeid, billid); + } + } + + /** + * 获取 是否回流 0-是 1-否 + * @param userid + * @return + */ + public static String getSfhl(String userid){ + String result = "1"; + RecordSet rs = new RecordSet(); + String sfhl_fieldid = rs.getPropValue("hrm_zhongkong","sfhl_fieldid"); + rs.executeQuery("select "+ sfhl_fieldid +" from cus_fielddata where scope = 'HrmCustomFieldByInfoType' and scopeid = '-1' and id = ?",userid); + if(rs.next()){ + result = Util.null2String(rs.getString(sfhl_fieldid)); + } + return result; + } + +} diff --git a/领悦二开new/src/weaver/interfaces/lingyue/action/SynAddUserAction.java b/领悦二开new/src/weaver/interfaces/lingyue/action/SynAddUserAction.java new file mode 100644 index 0000000..4ba50ae --- /dev/null +++ b/领悦二开new/src/weaver/interfaces/lingyue/action/SynAddUserAction.java @@ -0,0 +1,120 @@ +package weaver.interfaces.lingyue.action; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.lingyue.util.KqUtil; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.TimeUtil; +import weaver.general.Util; +import weaver.hrm.company.DepartmentComInfo; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.*; + +/** + * @Title 新员工入职 同步新增到 中控考勤机系统 + * @Author wangchaofa + * @CreateDate 2024/9/19 + * @Version 1.0 + * @Description + */ +public class SynAddUserAction extends BaseBean implements Action { + @Override + public String execute(RequestInfo requestInfo) { + try { + RecordSet rs = new RecordSet(); + RecordSet rs1 = new RecordSet(); + RecordSet rs2 = new RecordSet(); + + String tablename = requestInfo.getRequestManager().getBillTableName(); + String requestid = requestInfo.getRequestid(); + + String currentdate = TimeUtil.getCurrentDateString(); + String currenttime = TimeUtil.getOnlyCurrentTimeString(); + String currentdatetime = currentdate+" "+currenttime; + // HR同步至中控考勤机记录表 + int hrtozkkqj_formmodeid = Util.getIntValue(rs.getPropValue("hrm_zhongkong","hrtozkkqj_formmodeid")); + String uuid = UUID.randomUUID().toString(); + int creater = 1; + + String sql = " select * from "+ tablename +" where requestid = ? "; + rs.executeQuery(sql,requestid); + while(rs.next()){ + String workcode = Util.null2String(rs.getString("ygbh")); + String lastname = Util.null2String(rs.getString("xm")); + String sex = Util.null2String(rs.getString("xb")); + String departmentid = Util.null2String(rs.getString("bm")); + String deptcode = ""; + String Deptcode = KqUtil.getDeptCuscode(departmentid); + if(Deptcode != null && !"".equals(Deptcode)){ + deptcode = Deptcode; + }else{ + deptcode = new DepartmentComInfo().getDepartmentCode(departmentid); + } +// String jobtitle = Util.null2String(rs.getString("jobtitle")); +// String joblevel = Util.null2String(rs.getString("joblevel")); +// String jobactivitydesc = Util.null2String(rs.getString("jobactivitydesc")); +// String managerid = Util.null2String(rs.getString("managerid")); +// String assistantid = Util.null2String(rs.getString("assistantid")); +// String status = Util.null2String(rs.getString("status")); +// String locationid = Util.null2String(rs.getString("locationid")); +// String workroom = Util.null2String(rs.getString("workroom")); +// String telephone = Util.null2String(rs.getString("telephone")); + String mobile = Util.null2String(rs.getString("mobile")); +// String fax = Util.null2String(rs.getString("fax")); +// String jobcall = Util.null2String(rs.getString("jobcall")); +// String email = Util.null2String(rs.getString("email")); + String companystartdate = Util.null2String(rs.getString("cjgzsj")); + String birthday = Util.null2String(rs.getString("csrq")); + String certificatenum = Util.null2String(rs.getString("sfzhm")); + + // key + String key = rs.getPropValue("hrm_zhongkong","key"); + String url = rs.getPropValue("hrm_zhongkong","add_update_user_url"); + url = url + "?key=" + key; + Map headers = new HashMap<>(); + JSONArray jsonArray = new JSONArray(); + JSONObject json_main = new JSONObject(); + + json_main.put("pin",workcode); + json_main.put("name",lastname); + json_main.put("deptnumber",deptcode); + json_main.put("mobile",mobile); + json_main.put("gender","0".equals(sex)?"M":"F"); + json_main.put("identitycard",certificatenum); + json_main.put("birthday",birthday); + json_main.put("hiredday",companystartdate); + + jsonArray.add(json_main); + rs.writeLog("========================== 新增或修改人员,同步至中控考勤机 ======================================"); + rs.writeLog(url+" ========= "+jsonArray.toString()); + + int result = -1; + String msg = ""; + String content = KqUtil.httpPost(url,headers,jsonArray.toString(),"utf-8"); + if (content != null && !"".equals(content)) { + JSONObject json = JSONObject.parseObject(content); + rs.writeLog("============= httpPost pushInfo json =================== " + json); + int resultt = Integer.parseInt(json.getString("ret")); + if(resultt == 0){ + result = 0; + }else{ + result = 1; + } + msg = Util.null2String(json.getString("msg")); + } + writeLog(lastname +" ====== add user syn zhongkong result ========== "+ result); + + //写入建模记录表 + KqUtil.insertHrToZkJl(0,url,jsonArray,result,msg,requestid); + } + }catch (Exception e){ + e.printStackTrace(); + requestInfo.getRequestManager().setMessagecontent("新员工入职同步中控系统失败,请联系管理员!"); + return Action.FAILURE_AND_CONTINUE; + } + return Action.SUCCESS; + } +} diff --git a/领悦二开new/src/weaver/interfaces/lingyue/action/SynDeleteUserAction.java b/领悦二开new/src/weaver/interfaces/lingyue/action/SynDeleteUserAction.java new file mode 100644 index 0000000..b6bd5e3 --- /dev/null +++ b/领悦二开new/src/weaver/interfaces/lingyue/action/SynDeleteUserAction.java @@ -0,0 +1,74 @@ +//package weaver.interfaces.lingyue.action; +// +//import com.alibaba.fastjson.JSONObject; +//import com.lingyue.util.KqUtil; +//import weaver.conn.RecordSet; +//import weaver.general.BaseBean; +//import weaver.general.Util; +//import weaver.hrm.resource.ResourceComInfo; +//import weaver.interfaces.workflow.action.Action; +//import weaver.soa.workflow.request.RequestInfo; +// +//import java.util.HashMap; +//import java.util.Map; +// +///** +// * @Title 人员离职 同步删除 中控考勤机系统 人员 +// * @Author wangchaofa +// * @CreateDate 2024/9/19 +// * @Version 1.0 +// * @Description +// */ +//public class SynDeleteUserAction extends BaseBean implements Action { +// @Override +// public String execute(RequestInfo requestInfo) { +// try { +// RecordSet rs = new RecordSet(); +// String tablename = requestInfo.getRequestManager().getBillTableName(); +// String requestid = requestInfo.getRequestid(); +// +// String sql = " select * from "+ tablename +" where requestid = ? "; +// rs.executeQuery(sql,requestid); +// while(rs.next()){ +// String userid = Util.null2String(rs.getString("xm")); +// String lastname = new ResourceComInfo().getLastname(userid); +// String pincode = ""; +// String cuscode = KqUtil.getCusIdByUserid(userid); +// if(cuscode != null && !"".equals(cuscode)){ +// pincode = cuscode; +// }else{ +// pincode = new ResourceComInfo().getWorkcode(userid); +// } +// +// // key +// String key = rs.getPropValue("hrm_zhongkong","key"); +// String delete_user_url = rs.getPropValue("hrm_zhongkong","delete_user_url"); +// delete_user_url = delete_user_url + "?key=" + key; +// Map headers = new HashMap<>(); +// JSONObject json_main = new JSONObject(); +// +// json_main.put("pin",pincode); +// +// int result = -1; +// String content = KqUtil.httpPost(delete_user_url,headers,json_main.toString(),"utf-8"); +// writeLog(lastname +" ====== delete user syn zhongkong result ========== "+ result); +// if (content != null && !"".equals(content)) { +// JSONObject json = JSONObject.parseObject(content); +// rs.writeLog("============= httpPost pushInfo json =================== " + json); +// result = Integer.parseInt(json.getString("ret")); +// } +// if(result == 0){ +// return Action.SUCCESS; +// }else{ +// requestInfo.getRequestManager().setMessagecontent("员工离职同步中控系统失败,请联系管理员!"); +// return Action.FAILURE_AND_CONTINUE; +// } +// } +// }catch (Exception e){ +// e.printStackTrace(); +// requestInfo.getRequestManager().setMessagecontent("员工离职同步中控系统失败,请联系管理员!"); +// return Action.FAILURE_AND_CONTINUE; +// } +// return Action.SUCCESS; +// } +//} diff --git a/领悦二开new/src/weaver/interfaces/lingyue/action/SynTransUserAction.java b/领悦二开new/src/weaver/interfaces/lingyue/action/SynTransUserAction.java new file mode 100644 index 0000000..ed096a9 --- /dev/null +++ b/领悦二开new/src/weaver/interfaces/lingyue/action/SynTransUserAction.java @@ -0,0 +1,142 @@ +package weaver.interfaces.lingyue.action; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.lingyue.util.KqUtil; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.TimeUtil; +import weaver.general.Util; +import weaver.hrm.company.DepartmentComInfo; +import weaver.hrm.resource.ResourceComInfo; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +/** + * @Title 员工调动 同步新增到 中控考勤机系统 + * @Author wangchaofa + * @CreateDate 2024/9/20 + * @Version 1.0 + * @Description + */ +public class SynTransUserAction extends BaseBean implements Action { + + @Override + public String execute(RequestInfo requestInfo) { + try { + RecordSet rs = new RecordSet(); + RecordSet rs1 = new RecordSet(); + RecordSet rs2 = new RecordSet(); + + String tablename = requestInfo.getRequestManager().getBillTableName(); + String requestid = requestInfo.getRequestid(); + + String currentdate = TimeUtil.getCurrentDateString(); + String currenttime = TimeUtil.getOnlyCurrentTimeString(); + String currentdatetime = currentdate+" "+currenttime; + // HR同步至中控考勤机记录表 + int hrtozkkqj_formmodeid = Util.getIntValue(rs.getPropValue("hrm_zhongkong","hrtozkkqj_formmodeid")); + String uuid = UUID.randomUUID().toString(); + int creater = 1; + + // key + String key = rs.getPropValue("hrm_zhongkong","key"); + String url = rs.getPropValue("hrm_zhongkong","add_update_user_url"); + url = url + "?key=" + key; + Map headers = new HashMap<>(); + JSONArray jsonArray = new JSONArray(); + JSONObject json_main = new JSONObject(); + + String sql = " select * from "+ tablename +" where requestid = ? "; + rs.executeQuery(sql,requestid); + while(rs.next()){ + String userid = Util.null2String(rs.getString("ygxm")); + String lastname = new ResourceComInfo().getLastname(userid); +// String sex = Util.null2String(rs.getString("xb")); + String departmentid = Util.null2String(rs.getString("bm")); + String pincode = ""; + String cuscode = KqUtil.getCusIdByUserid(userid); + if(cuscode != null && !"".equals(cuscode)){ + pincode = cuscode; + }else{ + pincode = new ResourceComInfo().getWorkcode(userid); + } + json_main.put("pin",pincode); + + if(departmentid != null && !"".equals(departmentid)) { + String deptcode = ""; + String Deptcode = KqUtil.getDeptCuscode(departmentid); + if (Deptcode != null && !"".equals(Deptcode)) { + deptcode = Deptcode; + } else { + deptcode = new DepartmentComInfo().getDepartmentCode(departmentid); + } + json_main.put("deptnumber",deptcode); + } +// String jobtitle = Util.null2String(rs.getString("jobtitle")); +// String joblevel = Util.null2String(rs.getString("joblevel")); +// String jobactivitydesc = Util.null2String(rs.getString("jobactivitydesc")); +// String managerid = Util.null2String(rs.getString("managerid")); +// String assistantid = Util.null2String(rs.getString("assistantid")); +// String status = Util.null2String(rs.getString("status")); +// String locationid = Util.null2String(rs.getString("locationid")); +// String workroom = Util.null2String(rs.getString("workroom")); +// String telephone = Util.null2String(rs.getString("telephone")); +// String mobile = Util.null2String(rs.getString("mobile")); +// String fax = Util.null2String(rs.getString("fax")); +// String jobcall = Util.null2String(rs.getString("jobcall")); +// String email = Util.null2String(rs.getString("email")); +// String companystartdate = Util.null2String(rs.getString("cjgzsj")); +// String birthday = Util.null2String(rs.getString("csrq")); +// String certificatenum = Util.null2String(rs.getString("sfzhm")); + + + json_main.put("name",lastname); + +// json_main.put("mobile",mobile); +// json_main.put("gender","0".equals(sex)?"M":"F"); +// json_main.put("identitycard",certificatenum); +// json_main.put("birthday",birthday); +// json_main.put("hiredday",companystartdate); + + jsonArray.add(json_main); + + int result = -1; + String msg = ""; + String content = KqUtil.httpPost(url,headers,jsonArray.toString(),"utf-8"); + if (content != null && !"".equals(content)) { + JSONObject json = JSONObject.parseObject(content); + rs.writeLog("============= httpPost pushInfo json =================== " + json); + int resultt = Integer.parseInt(json.getString("ret")); + if(resultt == 0){ + result = 0; + }else{ + result = 1; + } + msg = Util.null2String(json.getString("msg")); + } + writeLog(lastname +" ====== trans user syn zhongkong result ========== "+ result); + + //写入建模记录表 + KqUtil.insertHrToZkJl(0,url,jsonArray,result,msg,requestid); + + if(result == 0){ + return Action.SUCCESS; + }else{ + requestInfo.getRequestManager().setMessagecontent("员工调动同步中控系统失败,请联系管理员!"); + return Action.FAILURE_AND_CONTINUE; + } + } + }catch (Exception e){ + e.printStackTrace(); + requestInfo.getRequestManager().setMessagecontent("员工调动同步中控系统失败,请联系管理员!"); + return Action.FAILURE_AND_CONTINUE; + } + return Action.SUCCESS; + } + +} diff --git a/领悦二开new/src/weaver/interfaces/lingyue/job/SynDeleteUserToZkJob.java b/领悦二开new/src/weaver/interfaces/lingyue/job/SynDeleteUserToZkJob.java new file mode 100644 index 0000000..5555bec --- /dev/null +++ b/领悦二开new/src/weaver/interfaces/lingyue/job/SynDeleteUserToZkJob.java @@ -0,0 +1,211 @@ +package weaver.interfaces.lingyue.job; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.lingyue.util.KqUtil; +import weaver.conn.RecordSet; +import weaver.general.TimeUtil; +import weaver.general.Util; +import weaver.hrm.resource.ResourceComInfo; +import weaver.interfaces.schedule.BaseCronJob; + +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +/** + * @Title + * @Author wangchaofa + * @CreateDate 2024/10/30 + * @Version 1.0 + * @Description + */ +public class SynDeleteUserToZkJob extends BaseCronJob { + @Override + public void execute() { + RecordSet rs = new RecordSet(); + + rs.writeLog("------------------------- start to syn unsyn HRM user info to zhongkong -----------------------------------"); + String tablename = rs.getPropValue("hrm_zhongkong","deleteuser_table"); + String key = rs.getPropValue("hrm_zhongkong","key"); + String url = rs.getPropValue("hrm_zhongkong","leave_user_url"); + url = url + "?key=" + key; + Map headers = new HashMap<>(); + // 当前日期 + String currentdate = TimeUtil.getCurrentDateString(); + // 2个月前的日期 + String lasttwomonth = addDateMonth(currentdate,-2); + + String where = " and (a.tyzhgzr >= '"+ lasttwomonth +"' and a.tyzhgzr <= '"+ currentdate +"') "; + try{ + // 查询最终离职日期 是在 2月前和当前日期范围内,并且流程是归档的 + String sql = "select a.*,b.lastoperatedate,b.lastoperatetime from "+tablename+" a,workflow_requestbase b where a.requestid=b.requestid and b.currentnodetype=3 "+ where; + rs.executeQuery(sql); + while(rs.next()){ + JSONObject json_main = new JSONObject(); + + String requestid = Util.null2String(rs.getString("requestid")); + + //姓名 + String userid = Util.null2String(rs.getString("xm")); + String workcode = new ResourceComInfo().getWorkcode(userid); + String pincode = ""; + String cuscode = KqUtil.getCusIdByUserid(userid); + if(cuscode != null && !"".equals(cuscode)){ + pincode = cuscode; + }else{ + pincode = workcode; + } + + // 离职原因 + String lzyyid = Util.null2String(rs.getString("lzyy")); + String lzyyname = getLzyyname(lzyyid); + + // 离职类型 下拉框 0 - 主动 1 - 被动 + int lzlxid = Util.getIntValue(rs.getString("lzlx")); + int lzlx = -1; + if(lzlxid==0){ + lzlx = 2; + }else{ + lzlx = 1; + } + + // 最后离职日期 + String tyzhgzr = Util.null2String(rs.getString("tyzhgzr")); + + String lastoperatetime = Util.null2String(rs.getString("lastoperatetime")); + String lasttime = lastoperatetime.substring(0,5); + + if(tyzhgzr != null && !"".equals(tyzhgzr)){ + // 加一天 + tyzhgzr = addDateDay(tyzhgzr,1); + } + //离职时间 + String leavetime = tyzhgzr+" "+lasttime; + + //中控是否恢复 0-是 1-否 + String zksfhf = getZksfhf(userid); + if("".equals(zksfhf) || "1".equals(zksfhf)){ + // 人员离职的入参 + json_main.put("pin",pincode); + json_main.put("leavedate",leavetime); + json_main.put("leavetype",lzlx); + json_main.put("reason",lzyyname); + + int result = -1; + String msg = ""; + String content = KqUtil.httpPost(url, headers, json_main.toString(), "utf-8"); + if (content != null && !"".equals(content)) { + JSONObject json = JSONObject.parseObject(content); + rs.writeLog("============= httpPost pushInfo json =================== " + json); + int resultt = Integer.parseInt(json.getString("ret")); + if (resultt == 0) { + result = 0; + } else { + result = 1; + } + msg = Util.null2String(json.getString("msg")); + } + + JSONArray jsonArray = new JSONArray(); + jsonArray.add(json_main); + //写入建模记录表 + KqUtil.insertHrToZkJl(3,url,jsonArray,result,msg,requestid); + } + + } + + }catch (Exception e){ + e.printStackTrace(); + } + } + + /** + * 获取 离职原因 名称 + * @param lzyyid + * @return + */ + public static String getLzyyname(String lzyyid){ + String result = ""; + RecordSet rs = new RecordSet(); + String lzyy_fieldid = rs.getPropValue("hrm_zhongkong","lzyy_fieldid"); + if (lzyyid != null && !"".equals(lzyyid)) { + rs.executeQuery("select selectname from workflow_selectitem where cancel=0 and fieldid = ? and selectvalue=?", lzyy_fieldid, lzyyid); + if (rs.next()) { + result = Util.null2String(rs.getString("selectname")); + } + } + return result; + } + + /** + * 对时间的月数进行加减 + * @param daytime 时间的格式:yyyy-MM-dd + * @param month 月数 -1则代表减一月 + * @return + */ + public static String addDateMonth(String daytime, int month){ + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); + Date date = null; + try { + date = format.parse(daytime); + if (date == null){ + return ""; + } + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + cal.add(Calendar.MONTH, month);// 加 day 月 + date = cal.getTime(); + cal = null; + return format.format(date); + } catch (Exception ex) { + ex.printStackTrace(); + } + return ""; + } + + /** + * 对时间的天数进行加减 + * @param daytime 时间的格式:yyyy-MM-dd + * @param day 天数 -1则代表减一天 + * @return + */ + public static String addDateDay(String daytime, int day){ + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); + Date date = null; + try { + date = format.parse(daytime); + if (date == null){ + return ""; + } + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + cal.add(Calendar.DAY_OF_MONTH, day);// 加一天 + date = cal.getTime(); + cal = null; + return format.format(date); + } catch (Exception ex) { + ex.printStackTrace(); + } + return ""; + } + + /** + * 获取 中控是否恢复 0-是 1-否 + * @param userid + * @return + */ + public static String getZksfhf(String userid){ + String result = ""; + RecordSet rs = new RecordSet(); + String zksfhf_fieldid = rs.getPropValue("hrm_zhongkong","zksfhf_fieldid"); + rs.executeQuery("select "+ zksfhf_fieldid +" from cus_fielddata where scope = 'HrmCustomFieldByInfoType' and scopeid = '-1' and id = ?",userid); + if(rs.next()){ + result = Util.null2String(rs.getString(zksfhf_fieldid)); + } + return result; + } + +} diff --git a/领悦二开new/src/weaver/interfaces/lingyue/job/SynNewUserToZkJob.java b/领悦二开new/src/weaver/interfaces/lingyue/job/SynNewUserToZkJob.java new file mode 100644 index 0000000..46e912a --- /dev/null +++ b/领悦二开new/src/weaver/interfaces/lingyue/job/SynNewUserToZkJob.java @@ -0,0 +1,96 @@ +package weaver.interfaces.lingyue.job; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.lingyue.util.KqUtil; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.company.DepartmentComInfo; +import weaver.interfaces.schedule.BaseCronJob; + +import java.util.HashMap; +import java.util.Map; + +/** + * @Title 该任务主要是 针对 新员工入职流程归档后同步中控考勤机,其中同步败的,再次同步 + * @Author wangchaofa + * @CreateDate 2024/10/9 + * @Version 1.0 + * @Description + */ +public class SynNewUserToZkJob extends BaseCronJob { + @Override + public void execute() { + RecordSet rs = new RecordSet(); + RecordSet rs1 = new RecordSet(); + RecordSet rs2 = new RecordSet(); + + rs.writeLog("------------------------- start to syn unsyn HRM user info to zhongkong -----------------------------------"); + String tablename = rs.getPropValue("hrm_zhongkong","newuser_table"); + String key = rs.getPropValue("hrm_zhongkong","key"); + String url = rs.getPropValue("hrm_zhongkong","add_update_user_url"); + url = url + "?key=" + key; + Map headers = new HashMap<>(); + JSONArray jsonArray = new JSONArray(); + try{ + + rs.executeQuery("select a.* from "+ tablename +" a,workflow_requestbase b where a.requestid=b.requestid and b.currentnodetype='3'"); + while(rs.next()){ + JSONObject json_main = new JSONObject(); + + String workcode = Util.null2String(rs.getString("ygbh")); + String lastname = Util.null2String(rs.getString("xm")); + String sex = Util.null2String(rs.getString("xb")); + String departmentid = Util.null2String(rs.getString("bm")); + String deptcode = ""; + String Deptcode = KqUtil.getDeptCuscode(departmentid); + if(Deptcode != null && !"".equals(Deptcode)){ + deptcode = Deptcode; + }else{ + deptcode = new DepartmentComInfo().getDepartmentCode(departmentid); + } + String mobile = Util.null2String(rs.getString("mobile")); + String companystartdate = Util.null2String(rs.getString("cjgzsj")); + String birthday = Util.null2String(rs.getString("csrq")); + String certificatenum = Util.null2String(rs.getString("sfzhm")); + + json_main.put("pin",workcode); + json_main.put("name",lastname); + json_main.put("deptnumber",deptcode); + json_main.put("mobile",mobile); + json_main.put("gender","0".equals(sex)?"M":"F"); + json_main.put("identitycard",certificatenum); + json_main.put("birthday",birthday); + json_main.put("hiredday",companystartdate); + + // 不存在 + if(!KqUtil.checkIsExistUserInfo(workcode)){ + jsonArray.add(json_main); + } + } + int result = -1; + String msg = ""; + String content = KqUtil.httpPost(url,headers,jsonArray.toString(),"utf-8"); + if (content != null && !"".equals(content)) { + JSONObject json = JSONObject.parseObject(content); + rs.writeLog("============= httpPost pushInfo json =================== " + json); + int resultt = Integer.parseInt(json.getString("ret")); + if(resultt == 0){ + result = 0; + }else{ + result = 1; + } + msg = Util.null2String(json.getString("msg")); + } + rs.writeLog(" ====== syn unsyn HRM user info to zhongkong result ========== "+ result); + + //写入建模记录表 + KqUtil.insertHrToZkJl(2,url,jsonArray,result,msg,""); + + }catch (Exception e){ + e.printStackTrace(); + rs.writeLog(e); + } + rs.writeLog("------------------------- end to syn unsyn HRM user info to zhongkong -----------------------------------"); + } +} diff --git a/领悦二开new/src/weaver/interfaces/lingyue/job/SynOtherKqInfoJob.java b/领悦二开new/src/weaver/interfaces/lingyue/job/SynOtherKqInfoJob.java new file mode 100644 index 0000000..f724012 --- /dev/null +++ b/领悦二开new/src/weaver/interfaces/lingyue/job/SynOtherKqInfoJob.java @@ -0,0 +1,129 @@ +//package weaver.interfaces.lingyue.job; +// +//import com.alibaba.fastjson.JSONObject; +//import com.engine.kq.biz.KQFormatBiz; +//import com.engine.kq.timer.KQQueue; +//import com.engine.kq.timer.KQTaskBean; +//import com.engine.kq.wfset.util.SplitActionUtil; +//import com.google.common.collect.Lists; +//import com.google.common.collect.Maps; +//import weaver.conn.RecordSet; +//import weaver.general.TimeUtil; +//import weaver.general.Util; +//import weaver.interfaces.lingyue.util.HttpUtil; +//import weaver.interfaces.schedule.BaseCronJob; +// +//import java.util.*; +// +///** +// * @Title +// * @Author wangchaofa +// * @CreateDate 2024/7/11 +// * @Version 1.0 +// * @Description +// */ +//public class SynOtherKqInfoJob extends BaseCronJob { +// +// @Override +// public void execute() { +// // 同步当日的考勤数据 +// SynTodayKqInfo(); +// } +// +// // 同步当天的考勤数据 +// public void SynTodayKqInfo(){ +// RecordSet rs = new RecordSet(); +// +// rs.writeLog("------------------------- start to syn today other kqinfo -----------------------------------"); +// String currentdate = TimeUtil.getCurrentDateString(); +// String currenttime = TimeUtil.getOnlyCurrentTimeString(); +// String currentdatetime = currentdate + " " + currenttime; +// +// String startTime = currentdate + " 00:00:00"; +// String endTime = ""; +// // 当前时间小于 12 点,那就查询 0点到11点的打卡数据 +// if(!HttpUtil.compareDate(currentdatetime,currentdate+" 12:00:00")){ +// endTime = currentdate + " 11:00:00"; +// } +// //查询 11点到23点的打卡数据 +// else{ +// startTime = currentdate + " 11:00:01"; +// endTime = currentdate + " 23:59:59"; +// } +// +// int kq_number = Util.getIntValue(rs.getPropValue("hrm_zhongkong","kq_number")); +// List lsFormatData = new ArrayList<>(); +// JSONObject json_main = new JSONObject(); +// try{ +// int index = 1; +// json_main.put("starttime",startTime); +// json_main.put("endtime",endTime); +// json_main.put("number",kq_number); +// +// HttpUtil httpUtil = new HttpUtil(); +// httpUtil.SynKqData(lsFormatData,index,json_main); +// +// Map> overtimeMap = Maps.newHashMap(); +// List overtimeList = Lists.newArrayList(); +// List formatParams = null; +// List> lsFormatParams = new ArrayList<>(); +// List delParams = null; +// List> lsDelParams = new ArrayList<>(); +// +// rs.writeLog("------------- lsFormatData size ------------- "+ lsFormatData.size()); +// +// for(int i=0;lsFormatData!=null&&i(); +// String[] formatData = Util.splitString(lsFormatData.get(i),"|"); +// String date_1 = HttpUtil.addDateDay(formatData[1],-1); +// formatParams.add(formatData[0]); +// formatParams.add(date_1); +// lsFormatParams.add(formatParams); +// +// formatParams = new ArrayList<>(); +// formatParams.add(formatData[0]); +// formatParams.add(formatData[1]); +// lsFormatParams.add(formatParams); +// +// delParams = new ArrayList<>(); +// delParams.add(formatData[0]); +// delParams.add(formatData[1]); +// delParams.add(formatData[2]); +// lsDelParams.add(delParams); +// +// String resourceId = formatData[0]; +// String kqdate = formatData[1]; +// if(overtimeMap.containsKey(resourceId)){ +// List tmp_overtimeList = overtimeMap.get(resourceId); +// if(!tmp_overtimeList.contains(kqdate)){ +// tmp_overtimeList.add(kqdate); +// } +// }else{ +// if(!overtimeList.contains(kqdate)){ +// overtimeList.add(kqdate); +// } +// overtimeMap.put(resourceId, overtimeList); +// } +// } +// +// new KQFormatBiz().format(lsFormatParams); +// //处理加班生成 +// List tasks = new ArrayList<>(); +// for(Map.Entry> mme: overtimeMap.entrySet()){ +// String resid = mme.getKey(); +// List overList = mme.getValue(); +// for(String date : overList){ +// SplitActionUtil.pushOverTimeTasks(date,date,resid,tasks); +// } +// } +// if(!tasks.isEmpty()){ +// KQQueue.writeTasks(tasks); +// } +// rs.writeLog("------------------------- end to syn today other kqinfo -----------------------------------"); +// }catch (Exception e){ +// e.printStackTrace(); +// rs.writeLog("------------------------- syn today other kqinfo error ----------------------------------- "+ e); +// } +// } +// +//} diff --git a/领悦二开new/src/weaver/interfaces/lingyue/job/SynSubcomDeptUserInfoJob.java b/领悦二开new/src/weaver/interfaces/lingyue/job/SynSubcomDeptUserInfoJob.java new file mode 100644 index 0000000..39ffa48 --- /dev/null +++ b/领悦二开new/src/weaver/interfaces/lingyue/job/SynSubcomDeptUserInfoJob.java @@ -0,0 +1,94 @@ +package weaver.interfaces.lingyue.job; + +import com.lingyue.util.KqUtil; +import weaver.conn.RecordSet; +import weaver.general.TimeUtil; +import weaver.general.Util; +import weaver.hrm.resource.ResourceComInfo; +import weaver.interfaces.schedule.BaseCronJob; + + +/** + * @Title 该计划任务主要是针对 1、遍历所有的分部信息到中控考勤系统,不存在的,再次同步 + * 2、遍历所有的部门信息到中控考勤系统,不存在的,再次同步 + * 3、遍历所有的人员信息到中控考勤系统,不存在的,再次同步 + * @Author wangchaofa + * @CreateDate 2024/7/19 + * @Version 1.0 + * @Description + */ +public class SynSubcomDeptUserInfoJob extends BaseCronJob { + + @Override + public void execute() { + SynHrmDeptInfo(); + } + + // 同步HR系统的部门数据 至 中控考勤机 里面 + public void SynHrmDeptInfo(){ + RecordSet rs = new RecordSet(); + RecordSet rs1 = new RecordSet(); + RecordSet rs2 = new RecordSet(); + + rs.writeLog("------------------------- start to syn HRM subcom、dept、user info to zhongkong -----------------------------------"); + String currentdate = TimeUtil.getCurrentDateString(); + String currenttime = TimeUtil.getOnlyCurrentTimeString(); + String currentdatetime = currentdate + " " + currenttime; + try{ + rs.executeQuery("select * from hrmsubcompany where 1=1 and (canceled = '0' or canceled is null) "); + while(rs.next()){ + //分部编码 + String subcomid = Util.null2String(rs.getString("id")); +// //分部编码 +// String subcompanycode = Util.null2String(rs.getString("subcompanycode")); +// //上级分部id +// String supsubcomid = Util.null2String(rs.getString("supsubcomid")); +// +// boolean bool = KqUtil.checkIsExistDeptInfo(subcompanycode); + //不存在,需要同步新增 +// if(!bool){ + KqUtil.synAddOrUpdateSubComInfo(subcomid); +// } + } + + rs1.executeQuery("select * from hrmdepartment where 1=1 and (canceled = '0' or canceled is null) "); + while(rs1.next()){ + //分部编码 + String deptid = Util.null2String(rs1.getString("id")); +// //分部编码 +// String departmentcode = Util.null2String(rs1.getString("departmentcode")); +// //上级分部id +// String supdeptid = Util.null2String(rs1.getString("supdepid")); +// +// boolean bool = KqUtil.checkIsExistDeptInfo(departmentcode); + //不存在,需要同步新增 +// if(!bool){ + KqUtil.synAddOrUpdateDeptInfo(deptid); +// } + } + + rs2.executeQuery("select * from hrmresource where status < 4 "); + while(rs2.next()){ + String userid = Util.null2String(rs2.getString("id")); + +// String pincode = ""; +// String cuscode = KqUtil.getCusIdByUserid(userid); +// if(cuscode != null && !"".equals(cuscode)){ +// pincode = cuscode; +// }else{ +// pincode = new ResourceComInfo().getWorkcode(userid); +// } +// boolean bool = KqUtil.checkIsExistUserInfo(pincode); +// 不存在,需要同步新增 +// if(!bool){ + KqUtil.synAddOrUpdateUserInfo(userid); +// } + } + rs.writeLog("------------------------- end to syn HRM subcom、dept、user info to zhongkong -----------------------------------"); + }catch (Exception e){ + e.printStackTrace(); + rs.writeLog("------------------------- syn HRM subcom、dept、user info to zhongkong is error ----------------------------------- "+ e); + } + } + +} diff --git a/领悦二开new/src/weaver/interfaces/lingyue/job/SyncKqDataFromZKJob.java b/领悦二开new/src/weaver/interfaces/lingyue/job/SyncKqDataFromZKJob.java new file mode 100644 index 0000000..ac46a42 --- /dev/null +++ b/领悦二开new/src/weaver/interfaces/lingyue/job/SyncKqDataFromZKJob.java @@ -0,0 +1,309 @@ +package weaver.interfaces.lingyue.job; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.time.util.DateUtil; +import org.apache.commons.lang3.StringUtils; +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.util.EntityUtils; +import weaver.conn.BatchRecordSet; +import weaver.conn.RecordSet; +import weaver.formmode.setup.ModeRightInfo; +import weaver.general.BaseBean; +import weaver.general.Util; +import weaver.interfaces.schedule.BaseCronJob; + +import java.io.IOException; +import java.util.*; + +/** + * 从中控考勤机机同步打卡数据计划任务 + * + */ + +public class SyncKqDataFromZKJob extends BaseCronJob { + + //已同步的数据记录 + private static List recordList; + //人员工号-id信息 + private static Map userMap; + //插入的建模数据 + private static List> plist; + + private String billid; + + + @Override + public void execute() { + BaseBean bb = new BaseBean(); + String url = Util.null2String(bb.getPropValue("hrm_zhongkong", "get_kqinfo_url")); + int kq_number = Util.getIntValue(bb.getPropValue("hrm_zhongkong","kq_number")); + String key = bb.getPropValue("hrm_zhongkong","key"); + url = url + "?key=" + key; + //考勤原始记录表模块id + String formmodeid = Util.null2String(bb.getPropValue("hrm_zhongkong", "zkkqjkqsj_formmodeid")); + String modedatacreater = "1"; //模块创建人id + String modedatacreatertype = "0"; //创建人类型(插入默认值0即可) + String modedatacreatedate = DateUtil.getCurrentTime("yyyy-MM-dd"); + String modedatacreatetime = DateUtil.getCurrentTime("HH:mm:ss"); + + recordList = new ArrayList<>(kq_number); + + userMap = getUserMap(); + plist = new ArrayList<>(kq_number); + RecordSet rs = new RecordSet(); + String sql = "select max(kqsjid) as lsid from uf_kqjysdkjl"; + rs.execute(sql); + rs.next(); + String maxid = Util.null2String(rs.getString("lsid")); + + if(StringUtils.isNotBlank(billid)){ + maxid = billid; + recordList = getRecordList(billid); + } + + + bb.writeLog("SyncKqDataFromZKJob plist1:" + plist.size()); + getTrafficRecords(formmodeid, modedatacreater, modedatacreatertype, modedatacreatedate, modedatacreatetime, url, maxid); + bb.writeLog("SyncKqDataFromZKJob plist2:" + plist.size()); + //批量插入建模数据 + StringBuffer sb = new StringBuffer(); + sb.append("insert into uf_kqjysdkjl("); + sb.append("MODEUUID,formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime,"); + sb.append("oary,kqsjid,pin,ename,deptnumber,deptname,checkdate,checktime,sn,alias"); + sb.append(")values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); + + BatchRecordSet batchRecordSet = new BatchRecordSet(); + batchRecordSet.executeBatchSql(sb.toString(), plist); + + //权限重构 + sql = "select id from uf_kqjysdkjl where modedatacreatedate = '" + modedatacreatedate + "' and modedatacreatetime='" + modedatacreatetime + "'"; + rs.execute(sql); + while (rs.next()) { + int billid = Integer.parseInt(rs.getString("id")); + ModeRightInfo info = new ModeRightInfo(); + info.setNewRight(true); + info.rebuildModeDataShareByEdit(1, Integer.parseInt(formmodeid), billid); + } + + + //更新人员的id + sql = "select id,pin from uf_kqjysdkjl where (oary is null or oary = '' or oary = '-9999' or loginid is null or loginid = '' or workcode is null or workcode = '')"; + rs.execute(sql); + while (rs.next()) { + String id = Util.null2String(rs.getString("id")); + String pin = Util.null2String(rs.getString("pin")); + String userid = Util.null2String(userMap.get(pin)); + if ("".equals(pin) || "".equals(userid)) { + continue; + } + updateUserId(id, userid); + } + + } + + /** + * 已同步考勤记录id + * + * @return + */ + private List getRecordList(String billid) { + RecordSet rs = new RecordSet(); + int kq_number = Util.getIntValue(rs.getPropValue("hrm_zhongkong","kq_number")); + List list = new ArrayList<>(kq_number); + rs.executeQuery("select kqsjid from uf_kqjysdkjl where kqsjid >= ?", billid); + while (rs.next()) { + String txjluuid = Util.null2String(rs.getString("kqsjid")); + list.add(txjluuid); + } + return list; + } + + + /** + * 人员id以及自定义考勤编号字段 + * + * @return + */ + private Map getUserMap() { + Map map = new HashMap<>(); + RecordSet rs = new RecordSet(); + String kq_fieldid = rs.getPropValue("hrm_zhongkong","kq_fieldid"); + String sql = "select a.id,b."+kq_fieldid+" as kqbh from hrmresource a left join cus_fielddata b on a.id=b.id where b.scope='HrmCustomFieldByInfoType' and a.status < 4 and b.scopeid=-1 and (b."+kq_fieldid+" != '' or b."+kq_fieldid+" is not null)"; + String id = ""; + String kqbh = ""; + rs.execute(sql); + while (rs.next()) { + id = Util.null2String(rs.getString("id")); + kqbh = Util.null2String(rs.getString("kqbh")); + map.put(kqbh, id); + } + return map; + } + + private void getTrafficRecords(String formmodeid, String modedatacreater, String modedatacreatertype, String modedatacreatedate, String modedatacreatetime, String url, String maxid) { + BaseBean bb = new BaseBean(); + int kq_number = Util.getIntValue(bb.getPropValue("hrm_zhongkong","kq_number")); + JSONObject requestBody = new JSONObject(); + requestBody.put("id", Util.getIntValue(maxid)); + requestBody.put("number", kq_number); + bb.writeLog("-SyncKqDataFromZKJob-url:" + url); + Map headers = new HashMap<>(); + String result = httpPostKqData(url,headers,requestBody.toString(),"utf-8"); + bb.writeLog("-SyncKqDataFromZKJob-result:" + result); + JSONObject resObj = JSONObject.parseObject(result); + + int ret = (int) resObj.get("ret"); + if (ret == 0) { + JSONObject data = (JSONObject) resObj.get("data"); + JSONArray listArr = (JSONArray) data.get("items"); + if (listArr.size() > 0) { + //插入数据到建模表 + for (int i = 0; i < listArr.size(); i++) { + JSONObject list = (JSONObject) listArr.get(i); + String id = Util.null2String(list.get("id")); + if (recordList.contains(id)) { + continue; + } else { + //插入数据到建模表 + //考勤编号 + String kqbh = Util.null2String(list.get("pin")); + //人员id + String userid = Util.null2String(userMap.get(kqbh)); + if ("".equals(kqbh) || "".equals(userid)) { + userid = "-9999"; + } + + String datetime = Util.null2String(list.get("checktime")); + + String checkdate = Util.null2String(datetime.substring(0, 10)); + String checktime = Util.null2String(datetime.substring(11, 19)); + + String ename = Util.null2String(list.get("ename")); + String deptnumber = Util.null2String(list.get("deptnumber")); + String deptname = Util.null2String(list.get("deptname")); + String sn = Util.null2String(list.get("sn")); + String alias = Util.null2String(list.get("alias")); + + + List listobj = new ArrayList<>(); + listobj.add(UUID.randomUUID().toString()); + listobj.add(formmodeid); + listobj.add(modedatacreater); + listobj.add(modedatacreatertype); + listobj.add(modedatacreatedate); + listobj.add(modedatacreatetime); + + //业务字段 + listobj.add(userid); + listobj.add(id); + listobj.add(kqbh); + listobj.add(ename); + listobj.add(deptnumber); + listobj.add(deptname); + listobj.add(checkdate); + listobj.add(checktime); + listobj.add(sn); + listobj.add(alias); + + plist.add(listobj); + } + } + } + } + } + + private void updateUserId(String id, String userid) { + RecordSet rs = new RecordSet(); + Map map = getUserInfoMap(userid); + String loginid = Util.null2String(map.get("loginid")); + String workcode = Util.null2String(map.get("workcode")); + rs.executeUpdate("update uf_kqjysdkjl set oary = ?,loginid = ?,workcode = ? where id = ?", userid, loginid, workcode, id); + } + + /** + * 获取员工信息 + * + * @param userid + * @return + */ + private Map getUserInfoMap(String userid) { + Map map = new HashMap<>(); + String sql = "select loginid,workcode from hrmresource where id = ?"; + RecordSet rs = new RecordSet(); + rs.executeQuery(sql, userid); + String loginid = ""; + String workcode = ""; + while (rs.next()) { + loginid = Util.null2String(rs.getString("loginid")); + workcode = Util.null2String(rs.getString("workcode")); + map.put("loginid", loginid); + map.put("workcode", workcode); + } + return map; + } + + /** + * post 请求 json格式 + * @param url + * @param headers + * @param stringJson + * @param encode + * @return + */ + public static String httpPostKqData(String url, Map headers, String stringJson, String encode){ + String result = ""; + if(encode == null){ + encode = "utf-8"; + } + RecordSet rs = new RecordSet(); + String content = null; + CloseableHttpResponse httpResponse = null; + CloseableHttpClient closeableHttpClient = null; + try { + closeableHttpClient = HttpClients.createDefault(); + HttpPost httpost = new HttpPost(url); + //设置header + httpost.setHeader("Content-type", "application/json"); + if (headers != null && headers.size() > 0) { + for (Map.Entry entry : headers.entrySet()) { + httpost.setHeader(entry.getKey(),entry.getValue()); + } + } + //组织请求参数 + StringEntity stringEntity = new StringEntity(stringJson, encode); + httpost.setEntity(stringEntity); + //响应信息 + httpResponse = closeableHttpClient.execute(httpost); + if(httpResponse != null) { + HttpEntity entity = httpResponse.getEntity(); + content = EntityUtils.toString(entity, encode); + if (content != null && !"".equals(content)) { + JSONObject json = JSONObject.parseObject(content); + result = json.toString(); + } + } + } catch (Exception e) { + e.printStackTrace(); + rs.writeLog(e); + }finally{ + try { + httpResponse.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + try { //关闭连接、释放资源 + closeableHttpClient.close(); + } catch (IOException e) { + e.printStackTrace(); + } + return result; + } + +} diff --git a/领悦二开new/src/weaver/interfaces/lingyue/util/HttpUtil.java b/领悦二开new/src/weaver/interfaces/lingyue/util/HttpUtil.java new file mode 100644 index 0000000..1155935 --- /dev/null +++ b/领悦二开new/src/weaver/interfaces/lingyue/util/HttpUtil.java @@ -0,0 +1,528 @@ +package weaver.interfaces.lingyue.util; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.wbi.util.Util; +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.util.EntityUtils; +import weaver.conn.RecordSet; +import weaver.formmode.setup.ModeRightInfo; +import weaver.general.TimeUtil; + +import java.io.IOException; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.*; + +/** + * @Title + * @Author wangchaofa + * @CreateDate 2024/7/11 + * @Version 1.0 + * @Description + */ +public class HttpUtil { + + /** + * post 请求 json格式 + * @param url + * @param headers + * @param stringJson + * @param encode + * @return + */ + public static int httpPost(String url, Map headers, String stringJson, String encode){ + int result = 0; + if(encode == null){ + encode = "utf-8"; + } + RecordSet rs = new RecordSet(); + String content = null; + CloseableHttpResponse httpResponse = null; + CloseableHttpClient closeableHttpClient = null; + try { + closeableHttpClient = HttpClients.createDefault(); + HttpPost httpost = new HttpPost(url); + //设置header + httpost.setHeader("Content-type", "application/json"); + if (headers != null && headers.size() > 0) { + for (Map.Entry entry : headers.entrySet()) { + httpost.setHeader(entry.getKey(),entry.getValue()); + } + } + //组织请求参数 + StringEntity stringEntity = new StringEntity(stringJson, encode); + httpost.setEntity(stringEntity); + //响应信息 + httpResponse = closeableHttpClient.execute(httpost); + if(httpResponse != null) { + HttpEntity entity = httpResponse.getEntity(); + content = EntityUtils.toString(entity, encode); + if (content != null && !"".equals(content)) { + JSONObject json = JSONObject.parseObject(content); + rs.writeLog("============= pushInfo json =================== " + json); + result = Integer.parseInt(json.getString("ret")); + } + } + } catch (Exception e) { + result = -1; + e.printStackTrace(); + rs.writeLog(e); + }finally{ + try { + httpResponse.close(); + } catch (IOException e) { + result = -1; + e.printStackTrace(); + } + } + try { //关闭连接、释放资源 + closeableHttpClient.close(); + } catch (IOException e) { + result = -1; + e.printStackTrace(); + } + return result; + } + + /** + * 对时间的天数进行加减 + * @param daytime 时间的格式:yyyy-MM-dd HH:mm:ss + * @param day 天数 -1则代表减一天 + * @return + */ + public static String addDateDay(String daytime, int day){ + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); + Date date = null; + try { + date = format.parse(daytime); + if (date == null){ + return ""; + } + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + cal.add(Calendar.DAY_OF_MONTH, day);// 加一天 + date = cal.getTime(); + cal = null; + return format.format(date); + } catch (Exception ex) { + ex.printStackTrace(); + } + return ""; + } + + /** + * 比较时间的大小 + * @param a + * @param b + * @return + * @throws ParseException + */ + public static boolean compareDate(String a, String b) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + boolean bool = false; + try { + long t1 = sdf.parse(a).getTime(); + long t2 = sdf.parse(b).getTime(); + if (t1 >= t2) { + bool = true; + } else { + bool = false; + } + }catch (Exception e){ + e.printStackTrace(); + } + return bool; + } + + /** + * post 请求 json格式 + * @param url + * @param headers + * @param stringJson + * @param encode + * @return + */ + public static String httpPostKqData(String url, Map headers, String stringJson, String encode){ + String result = ""; + if(encode == null){ + encode = "utf-8"; + } + RecordSet rs = new RecordSet(); + String content = null; + CloseableHttpResponse httpResponse = null; + CloseableHttpClient closeableHttpClient = null; + try { + closeableHttpClient = HttpClients.createDefault(); + HttpPost httpost = new HttpPost(url); + //设置header + httpost.setHeader("Content-type", "application/json"); + if (headers != null && headers.size() > 0) { + for (Map.Entry entry : headers.entrySet()) { + httpost.setHeader(entry.getKey(),entry.getValue()); + } + } + //组织请求参数 + StringEntity stringEntity = new StringEntity(stringJson, encode); + httpost.setEntity(stringEntity); + //响应信息 + httpResponse = closeableHttpClient.execute(httpost); + if(httpResponse != null) { + HttpEntity entity = httpResponse.getEntity(); + content = EntityUtils.toString(entity, encode); + if (content != null && !"".equals(content)) { + JSONObject json = JSONObject.parseObject(content); + rs.writeLog("============= pushInfo json =================== " + json); + int success = Integer.parseInt(json.getString("ret")); + String data = json.getString("data").toString(); + // 成功的 + if(success == 0){ + result = json.getString("data").toString(); + } + } + } + } catch (Exception e) { + e.printStackTrace(); + rs.writeLog(e); + }finally{ + try { + httpResponse.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + try { //关闭连接、释放资源 + closeableHttpClient.close(); + } catch (IOException e) { + e.printStackTrace(); + } + return result; + } + + /** + * 根据 自定义 考勤卡号 获取 人员id + * @param fieldvalue + * @return + */ + public String getUserIdByPin(String fieldvalue){ + String result = ""; + RecordSet rs = new RecordSet(); + String kq_fieldid = rs.getPropValue("hrm_zhongkong","kq_fieldid"); +// rs.executeQuery("select id from hrmresource where workcode = ?",fieldvalue); + rs.executeQuery("select a.id from cus_fielddata a,hrmresource b where a.id=b.id and a.scope = 'HrmCustomFieldByInfoType' and a.scopeid = -1 and "+ kq_fieldid +" = ?",fieldvalue); + if(rs.next()){ + result = Util.null2String(rs.getString("id")); + } + return result; + } + + /** + * 根据 人员id 获取 自定义 考勤卡号,也就是 中控考勤机那边的 人员编号 pin + * @param userid + * @return + */ + public String getCusIdByUserid(String userid){ + String result = ""; + RecordSet rs = new RecordSet(); + String kq_fieldid = rs.getPropValue("hrm_zhongkong","kq_fieldid"); + rs.executeQuery("select "+ kq_fieldid +" from cus_fielddata where scope = 'HrmCustomFieldByInfoType' and scopeid = -1 and id = ?",userid); +// rs.executeQuery("select workcode from hrmresource where id = ?",userid); + if(rs.next()){ + result = Util.null2String(rs.getString(kq_fieldid)); +// result = Util.null2String(rs.getString("workcode")); + } + return result; + } + + public void SynKqData(List lsFormatData, int index, JSONObject json_main){ + RecordSet rs = new RecordSet(); + RecordSet rs1 = new RecordSet(); + RecordSet rs2 = new RecordSet(); + RecordSet rst = new RecordSet(); + String currentdate = TimeUtil.getCurrentDateString(); + String currenttime = TimeUtil.getOnlyCurrentTimeString(); + String currentdatetime = currentdate + " " + currenttime; + + Map headers = new HashMap<>(); + String key = rs.getPropValue("hrm_zhongkong","key"); + String get_kqinfo_url = rs.getPropValue("hrm_zhongkong","get_kqinfo_url"); + int zkkqjkqsj_formmodeid = weaver.general.Util.getIntValue(rs.getPropValue("hrm_zhongkong","zkkqjkqsj_formmodeid")); + int creater = 1; + + boolean bool = false; + + get_kqinfo_url = get_kqinfo_url + "?key=" + key; + List> lsParams = new ArrayList<>(); + List idList = new ArrayList<>(); + json_main.put("id",index); + + rs.writeLog("============= SynKqData json_main =============== "+ json_main); + + String result = httpPostKqData(get_kqinfo_url,headers,json_main.toString(),"utf-8"); + if(result != null && !"".equals(result)) { + JSONObject json1 = JSONObject.parseObject(result); + String items = json1.getString("items").toString(); + JSONArray data_jsonArray = JSONArray.parseArray(items); + rs.writeLog("============= SynKqData data_jsonArray size =============== "+ data_jsonArray.size()); + if (data_jsonArray.size() > 1) { + bool = true; + for (int i = 0; i < data_jsonArray.size(); i++) { + JSONObject jsonObject = JSONObject.parseObject(data_jsonArray.get(i).toString()); + + String lsh = ""; + String pin = ""; + String ename = ""; + String deptnumber = ""; + String deptname = ""; + String checktime = ""; + String sn = ""; + String alias = ""; + String verify = ""; + String stateno = ""; + String state = ""; + + if (jsonObject.containsKey("id")) { + lsh = jsonObject.get("id").toString(); + idList.add(lsh); + } + if (jsonObject.containsKey("pin")) { + pin = jsonObject.get("pin").toString(); + } + if (jsonObject.containsKey("ename")) { + ename = jsonObject.get("ename").toString(); + } + if (jsonObject.containsKey("deptnumber")) { + deptnumber = jsonObject.get("deptnumber").toString(); + } + if (jsonObject.containsKey("deptname")) { + deptname = jsonObject.get("deptname").toString(); + } + if (jsonObject.containsKey("checktime")) { + checktime = jsonObject.get("checktime").toString(); + } + if (jsonObject.containsKey("sn")) { + sn = jsonObject.get("sn").toString(); + } + if (jsonObject.containsKey("alias")) { + alias = jsonObject.get("alias").toString(); + } + if (jsonObject.containsKey("verify")) { + verify = jsonObject.get("verify").toString(); + } + if (jsonObject.containsKey("stateno")) { + stateno = jsonObject.get("stateno").toString(); + } + if (jsonObject.containsKey("state")) { + state = jsonObject.get("state").toString(); + } + + String userid = getUserIdByPin(pin); + if(userid != null && !"".equals(userid)){ + String signDate = ""; + String signTime = ""; + int usertype = 1; + int signType = 1; + int isincom = 1; + String signfrom = "OutDataSourceSyn"; + String addr = ""; + int isimport = 1; + + signDate = checktime.substring(0, 10); + signTime = checktime.substring(11, 19); + signType = 1; + + List params = new ArrayList<>(); + params.add(userid); + params.add(usertype); + params.add(signType); + params.add(signDate); + params.add(signTime); + params.add(""); + params.add(isincom); + params.add(isimport); + params.add(signfrom); + params.add(""); + params.add(""); + params.add(addr); + params.add("中控考勤机数据同步"); + lsParams.add(params); + String formatData = userid + "|" + signDate + "|" + signTime; + if (!lsFormatData.contains(formatData)) { + lsFormatData.add(formatData); + } + + boolean isdelte = deleteByInfo(userid,signDate,signTime); + boolean isok = InsertByInfo(userid,usertype,signDate,signTime,"",isincom,isimport,signfrom,"","",addr,"中控考勤机数据同步"); + rs.writeLog("isdelte:" + isdelte+"isok:"+isok); + + rs1.executeQuery("select * from uf_zkkqjkqsj where lsh = ?",lsh); + //不存在 + if(!rs1.next()) { + int billid = -1; + String uuid = UUID.randomUUID().toString(); + boolean exeRes = rst.executeUpdate("insert into uf_zkkqjkqsj(lsh,verify,checktime,sn,alias,pin,ename,deptnumber,deptname,stateno,state,modedatacreater,modedatacreatedate,modedatacreatetime,formmodeid,modeuuid) values(?,?,?,?,?,?,?,?," + + "?,?,?,?,?,?,?,?)", + new Object[]{lsh, verify, checktime, sn, alias, pin, ename, deptnumber, deptname, stateno, state, creater, currentdate, currenttime, zkkqjkqsj_formmodeid, uuid}); + if (exeRes) { + //重构权限 + rs2.executeQuery(" select id from uf_zkkqjkqsj where modeuuid=? ", new Object[]{uuid}); + rs2.next(); + billid = rs2.getInt("id"); + ModeRightInfo moderight = new ModeRightInfo(); + moderight.editModeDataShare(creater, zkkqjkqsj_formmodeid, billid); + } + } + } + } + }else{ + if(data_jsonArray.size() > 0){ + JSONObject jsonObject = JSONObject.parseObject(data_jsonArray.get(0).toString()); + + String lsh = ""; + String pin = ""; + String ename = ""; + String deptnumber = ""; + String deptname = ""; + String checktime = ""; + String sn = ""; + String alias = ""; + String verify = ""; + String stateno = ""; + String state = ""; + + if (jsonObject.containsKey("id")) { + lsh = jsonObject.get("id").toString(); + idList.add(lsh); + } + if (jsonObject.containsKey("pin")) { + pin = jsonObject.get("pin").toString(); + } + if (jsonObject.containsKey("ename")) { + ename = jsonObject.get("ename").toString(); + } + if (jsonObject.containsKey("deptnumber")) { + deptnumber = jsonObject.get("deptnumber").toString(); + } + if (jsonObject.containsKey("deptname")) { + deptname = jsonObject.get("deptname").toString(); + } + if (jsonObject.containsKey("checktime")) { + checktime = jsonObject.get("checktime").toString(); + } + if (jsonObject.containsKey("sn")) { + sn = jsonObject.get("sn").toString(); + } + if (jsonObject.containsKey("alias")) { + alias = jsonObject.get("alias").toString(); + } + if (jsonObject.containsKey("verify")) { + verify = jsonObject.get("verify").toString(); + } + if (jsonObject.containsKey("stateno")) { + stateno = jsonObject.get("stateno").toString(); + } + if (jsonObject.containsKey("state")) { + state = jsonObject.get("state").toString(); + } + + String userid = getUserIdByPin(pin); + if(userid != null && !"".equals(userid)){ + String signDate = ""; + String signTime = ""; + int usertype = 1; + int signType = 1; + int isincom = 1; + String signfrom = "OutDataSourceSyn"; + String addr = ""; + int isimport = 1; + + signDate = checktime.substring(0, 10); + signTime = checktime.substring(11, 19); + signType = 1; + + List params = new ArrayList<>(); + params.add(userid); + params.add(usertype); + params.add(signType); + params.add(signDate); + params.add(signTime); + params.add(""); + params.add(isincom); + params.add(isimport); + params.add(signfrom); + params.add(""); + params.add(""); + params.add(addr); + params.add("中控考勤机数据同步"); + lsParams.add(params); + String formatData = userid + "|" + signDate + "|" + signTime; + if (!lsFormatData.contains(formatData)) { + lsFormatData.add(formatData); + } + + boolean isdelte = deleteByInfo(userid,signDate,signTime); + boolean isok = InsertByInfo(userid,usertype,signDate,signTime,"",isincom,isimport,signfrom,"","",addr,"中控考勤机数据同步"); + rs.writeLog("isdelte:" + isdelte+"isok:"+isok); + + rs1.executeQuery("select * from uf_zkkqjkqsj where lsh = ?",lsh); + //不存在 + if(!rs1.next()) { + int billid = -1; + String uuid = UUID.randomUUID().toString(); + boolean exeRes = rst.executeUpdate("insert into uf_zkkqjkqsj(lsh,verify,checktime,sn,alias,pin,ename,deptnumber,deptname,stateno,state,modedatacreater,modedatacreatedate,modedatacreatetime,formmodeid,modeuuid) values(?,?,?,?,?,?,?,?," + + "?,?,?,?,?,?,?,?)", + new Object[]{lsh, verify, checktime, sn, alias, pin, ename, deptnumber, deptname, stateno, state, creater, currentdate, currenttime, zkkqjkqsj_formmodeid, uuid}); + if (exeRes) { + //重构权限 + rs2.executeQuery(" select id from uf_zkkqjkqsj where modeuuid=? ", new Object[]{uuid}); + rs2.next(); + billid = rs2.getInt("id"); + ModeRightInfo moderight = new ModeRightInfo(); + moderight.editModeDataShare(creater, zkkqjkqsj_formmodeid, billid); + } + } + } + } + } + } + if(bool){ + index = Integer.parseInt(Collections.max(idList)); + json_main.put("id",index); + SynKqData(lsFormatData,index,json_main); + } + } + + /** + * 删除 + * @param userId + * @param signdate + * @param signtime + */ + public static Boolean deleteByInfo(String userId,String signdate,String signtime){ + RecordSet rs = new RecordSet(); + String sql = "delete from hrmschedulesign where signfrom='OutDataSourceSyn' and userid =? and signdate = ? and signtime = ? "; + boolean isdelete = rs.executeUpdate(sql,userId,signdate,signtime); + return isdelete; + } + + /** + * 新增 + * @param userId + * @param signdate + * @param signtime + */ + public static Boolean InsertByInfo(String userId,Integer usertype,String signdate,String signtime,String clientaddress,Integer isincom,Integer isimport,String signfrom,String longitude,String latitude,String addr,String memo){ + RecordSet rs = new RecordSet(); + String sql = " insert into HrmScheduleSign (userid, usertype, signdate, signtime, clientaddress, isincom, isimport, signfrom, longitude, latitude, addr,memo) " + + " values(?,?,?,?,?,?,?,?,?,?,?,?)"; + boolean isok = rs.executeUpdate(sql,userId,usertype,signdate,signtime,clientaddress,isincom,isimport,signfrom,longitude,latitude,addr,memo); + return isok; + } + + +}