From 6a4991b054f59f52fbf9c7142abda0b8ae01154c Mon Sep 17 00:00:00 2001 From: shilei <798989044@qq.com> Date: Mon, 18 Nov 2024 15:57:37 +0800 Subject: [PATCH] =?UTF-8?q?#hansang-01#=20svn=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../service/impl/ResourceBrowserService.java | 4102 ++++++++++++ .../qc2988837/Util/KqCustomUtil.java | 33 + .../hrm/service/HrmResourceTreeService.java | 149 + src/com/api/hs/HsCheckApi.java | 10 + .../web/EntryCommitFormModeController.java | 13 + .../web/EntryWorkflowSaveEventAction.java | 13 + .../web/KqWorkflowRangeLimitAction.java | 13 + .../leshanvc/web/LeaverWorkflowAction.java | 12 + .../leshanvc/web/LzWorkflowManageAction.java | 13 + .../api/leshanvc/web/ResourceCardAction.java | 12 + .../api/leshanvc/web/SyncXcDataAction.java | 7 + .../api/leshanvc/web/WorkflowCheckAction.java | 13 + .../dev/api/service/Service_DevTable.java | 3165 +++++++++ .../leshanvc/HsGetOutWorkDurationCmd.java | 40 + .../leshanvc/HsGetTravelRulesFormCmd.java | 30 + .../cube/cmd/app/GetBatchImportInfo.java | 855 +++ .../cube/cmd/card/LayoutFieldAttrExcute.java | 663 ++ .../action/UpdateMarriageLeaveBalance.java | 131 + .../hansang/job/CountOvertimeWorkersJob.java | 268 + .../hansang/job/UpdateHrmLastNameJob.java | 78 + .../hrm/cmd/codeseting/RegenerateCodeCmd.java | 61 + src/com/engine/hsCheck/cmd/CheckCmd.java | 231 + .../engine/hsCheck/service/CheckService.java | 19 + .../service/impl/CheckServiceImpl.java | 578 ++ src/com/engine/hsCheck/web/QkCheckAction.java | 101 + src/com/engine/kq/biz/KQAttFlowSetBiz.java | 1131 ++++ .../engine/kq/biz/KQBalanceOfLeaveBiz.java | 4233 ++++++++++++ .../engine/kq/biz/KQClearFormatPoolJob.java | 19 + src/com/engine/kq/biz/KQFlowActiontBiz.java | 913 +++ src/com/engine/kq/biz/KQFormatBiz.java | 301 + src/com/engine/kq/biz/KQFormatData.java | 1281 ++++ src/com/engine/kq/biz/KQFormatJob.java | 90 + src/com/engine/kq/biz/KQFormatSignData.java | 544 ++ src/com/engine/kq/biz/KQFormatThread.java | 57 + src/com/engine/kq/biz/KQLeaveRulesBiz.java | 911 +++ src/com/engine/kq/biz/KQOverTimeFlowBiz.java | 848 +++ .../engine/kq/biz/KQOverTimeRuleCalBiz.java | 2798 ++++++++ src/com/engine/kq/biz/KQOvertimeLogBiz.java | 261 + src/com/engine/kq/biz/KQReportBiz.java | 2325 +++++++ src/com/engine/kq/biz/KQSettingsBiz.java | 220 + .../kq/biz/KQShiftManagementComInfo.java | 759 +++ .../engine/kq/biz/KQShiftManagementRedis.java | 299 + src/com/engine/kq/biz/KQWorkTime.java | 426 ++ .../chain/cominfo/ShiftInfoCominfoBean.java | 519 ++ .../biz/chain/cominfo/WorkShiftComIndex.java | 37 + .../cmd/attendanceButton/PunchButtonCmd.java | 618 ++ .../GetOverTimeWorkDurationCmd.java | 100 + .../cmd/balanceofleaverp/ExportExcelCmd.java | 468 ++ .../balanceofleaverp/GetSearchListCmd.java | 426 ++ .../cmd/leaverules/GetLeaveRulesFormCmd.java | 808 +++ .../GetHrmKQMonthReportInfoCmd.java | 1089 +++ .../myattendance/GetHrmKQReportInfoCmd.java | 430 ++ .../cmd/myattendance/GetHrmKQSignInfoCmd.java | 466 ++ .../engine/kq/cmd/report/ExportExcelCmd.java | 941 +++ .../engine/kq/cmd/report/GetKQReportCmd.java | 906 +++ .../GetShiftManagementBaseFormCmd.java | 424 ++ .../SaveShiftManagementBaseFormCmd.java | 489 ++ .../shiftschedule/GetShiftScheduleCmd.java | 313 + .../GetShiftScheduleTotalCmd.java | 119 + .../kq/cmd/shiftschedule/ImportExcelCmd.java | 309 + src/com/engine/kq/entity/WorkTimeEntity.java | 136 + .../kq/util/KQDurationCalculatorUtil.java | 633 ++ src/com/engine/kq/util/KQTransMethod.java | 1384 ++++ src/com/engine/kq/util/UtilKQHS.java | 148 + src/com/engine/kq/wfset/util/KQFlowUtil.java | 471 ++ .../cmd/EntryWorkflowSaveEventCmd.java | 42 + .../leshanvc/cmd/KqWorkflowRangeLimitCmd.java | 60 + .../engine/leshanvc/cmd/WorkflowCheckCmd.java | 56 + .../leshanvc/enums/MessageContentEnum.java | 42 + .../exception/CustomizeRunTimeException.java | 22 + .../service/EntryCommitFormModeService.java | 21 + .../EntryWorkflowSaveEventService.java | 19 + .../service/KqWorkflowRangeLimitService.java | 19 + .../service/LeaverWorkflowService.java | 19 + .../service/LzWorkflowManageService.java | 13 + .../leshanvc/service/ResourceCardService.java | 17 + .../leshanvc/service/SyncXcDataService.java | 39 + .../service/WorkflowCheckService.java | 19 + .../impl/EntryCommitFormModeServiceImpl.java | 247 + .../EntryWorkflowSaveEventServiceImpl.java | 21 + .../impl/KqWorkflowRangeLimitServiceImpl.java | 21 + .../impl/LeaverWorkflowServiceImpl.java | 92 + .../impl/LzWorkflowManageServiceImpl.java | 269 + .../service/impl/ResourceCardServiceImpl.java | 105 + .../service/impl/SyncXcDataServiceImpl.java | 322 + .../impl/WorkflowCheckServiceImpl.java | 21 + .../engine/leshanvc/util/ExceptionUtil.java | 20 + src/com/engine/leshanvc/util/HsDateUtil.java | 93 + .../engine/leshanvc/util/ResponseResult.java | 171 + .../web/EntryCommitFormModeController.java | 42 + .../web/EntryWorkflowSaveEventAction.java | 43 + .../web/KqWorkflowRangeLimitAction.java | 39 + .../leshanvc/web/LeaverWorkflowAction.java | 38 + .../leshanvc/web/LzWorkflowManageAction.java | 38 + .../leshanvc/web/ResourceCardAction.java | 39 + .../engine/leshanvc/web/SyncXcDataAction.java | 55 + .../leshanvc/web/WorkflowCheckAction.java | 39 + .../workflow/biz/requestForm/Html2Pdf.java | 220 + .../workflow/cmd/monitor/DoArchivingCmd.java | 234 + .../cmd/requestForm/FunctionManageCmd.java | 375 ++ src/weaver/formmode/excel/ImpExcelReader.java | 5832 +++++++++++++++++ src/weaver/formmode/excel/ImpExcelServer.java | 2497 +++++++ src/weaver/hrm/settings/BirthdayReminder.java | 652 ++ .../action/BussinessTripAutoSignAction.java | 84 + .../action/OfficeOutAutoSignAction.java | 72 + .../hansang/action/RefreshKqReportAction.java | 62 + .../action/RefreshKqReportBatchAction.java | 62 + .../job/AnnualLeaveBaseCalculateJob.java | 84 + .../job/AttendanceDaysCalculateJob.java | 96 + .../hansang/job/DepartRefreshKqReportJob.java | 53 + .../hansang/job/EntryDaysCalculateJob.java | 147 + .../hansang/job/HrmGroupMemberSyn.java | 101 + .../hansang/job/InternAttDaySynJob.java | 188 + .../hansang/job/KqAbnormalRemind.java | 143 + .../hansang/job/KqAutoScheduleJob.java | 104 + .../hansang/job/KqGroupMemberSyn.java | 80 + .../hansang/job/LeaveDateUpdateJob.java | 39 + .../hansang/job/LeaveDaysCalculateJob.java | 172 + .../hansang/job/ManagerMemberSyn.java | 54 + .../hansang/job/NurseLeaveCalculateJob.java | 65 + .../hansang/job/OutSignUserSynJob.java | 50 + .../hansang/job/OvertimeCalculateJob.java | 121 + .../hansang/job/OvertimeSignCalculateJob.java | 153 + .../job/ParentalLeaveCalculateJob.java | 142 + .../job/RecommendBonusCalculateJob.java | 154 + .../hansang/job/RegularDaysCalculateJob.java | 152 + .../hansang/job/SalaryTaxMemSynJob.java | 107 + .../job/SickLeaveSalaryCalculateJob.java | 212 + .../hansang/job/UserCardInfoUpdateJob.java | 94 + .../hansang/util/ReportTransMethod.java | 65 + .../hskq/action/BmChangeAction.java | 352 + .../hskq/action/DkCreateEveryDay.java | 114 + .../hskq/action/KqBaseInfoCreateEveryDay.java | 547 ++ .../interfaces/hskq/util/BatchIdsParams.java | 35 + .../leshanvc/cronjob/ApplyCronJob.java | 258 + .../cronjob/AutoCancelDepartmentJob.java | 65 + .../cronjob/SyncQualificationsJob.java | 71 + .../leshanvc/cronjob/SyncResignJob.java | 111 + .../leshanvc/cronjob/SyncStatusByDate.java | 43 + .../formmode/EntryCommitBtnShowTemplate.java | 38 + .../formmode/LeaveCheckInCutPayBtnShow.java | 45 + .../formmode/NonOfficeUploadExpand.java | 111 + .../leshanvc/formmode/RegisterSaveExpand.java | 87 + .../action/BatchWorkOverTimeAction.java | 141 + .../action/MessagePushWeChatWorkAction.java | 223 + .../workflow/action/OutSplitAction.java | 48 + .../action/ShuttleRouteSyncAction.java | 62 + .../action/SyncHrmInfoToCardAction.java | 420 ++ .../UpdateStatusAfterRegularAction.java | 50 + .../workflow/entity/FieldMapEntity.java | 19 + .../leshanvc/workflow/util/CodeRuleUtil.java | 21 + .../workflow/util/ConvertDurationUtil.java | 29 + .../util/FunctionInterfaceMessage.java | 40 + .../workflow/util/ResourceSyncUtil.java | 1106 ++++ .../dmlaction/commands/actions/DMLAction.java | 1936 ++++++ 155 files changed, 60001 insertions(+) create mode 100644 src/com/api/browser/service/impl/ResourceBrowserService.java create mode 100644 src/com/api/customization/qc2988837/Util/KqCustomUtil.java create mode 100644 src/com/api/hrm/service/HrmResourceTreeService.java create mode 100644 src/com/api/hs/HsCheckApi.java create mode 100644 src/com/api/leshanvc/web/EntryCommitFormModeController.java create mode 100644 src/com/api/leshanvc/web/EntryWorkflowSaveEventAction.java create mode 100644 src/com/api/leshanvc/web/KqWorkflowRangeLimitAction.java create mode 100644 src/com/api/leshanvc/web/LeaverWorkflowAction.java create mode 100644 src/com/api/leshanvc/web/LzWorkflowManageAction.java create mode 100644 src/com/api/leshanvc/web/ResourceCardAction.java create mode 100644 src/com/api/leshanvc/web/SyncXcDataAction.java create mode 100644 src/com/api/leshanvc/web/WorkflowCheckAction.java create mode 100644 src/com/cloudstore/dev/api/service/Service_DevTable.java create mode 100644 src/com/customization/leshanvc/HsGetOutWorkDurationCmd.java create mode 100644 src/com/customization/leshanvc/HsGetTravelRulesFormCmd.java create mode 100644 src/com/engine/cube/cmd/app/GetBatchImportInfo.java create mode 100644 src/com/engine/cube/cmd/card/LayoutFieldAttrExcute.java create mode 100644 src/com/engine/hansang/action/UpdateMarriageLeaveBalance.java create mode 100644 src/com/engine/hansang/job/CountOvertimeWorkersJob.java create mode 100644 src/com/engine/hansang/job/UpdateHrmLastNameJob.java create mode 100644 src/com/engine/hrm/cmd/codeseting/RegenerateCodeCmd.java create mode 100644 src/com/engine/hsCheck/cmd/CheckCmd.java create mode 100644 src/com/engine/hsCheck/service/CheckService.java create mode 100644 src/com/engine/hsCheck/service/impl/CheckServiceImpl.java create mode 100644 src/com/engine/hsCheck/web/QkCheckAction.java create mode 100644 src/com/engine/kq/biz/KQAttFlowSetBiz.java create mode 100644 src/com/engine/kq/biz/KQBalanceOfLeaveBiz.java create mode 100644 src/com/engine/kq/biz/KQClearFormatPoolJob.java create mode 100644 src/com/engine/kq/biz/KQFlowActiontBiz.java create mode 100644 src/com/engine/kq/biz/KQFormatBiz.java create mode 100644 src/com/engine/kq/biz/KQFormatData.java create mode 100644 src/com/engine/kq/biz/KQFormatJob.java create mode 100644 src/com/engine/kq/biz/KQFormatSignData.java create mode 100644 src/com/engine/kq/biz/KQFormatThread.java create mode 100644 src/com/engine/kq/biz/KQLeaveRulesBiz.java create mode 100644 src/com/engine/kq/biz/KQOverTimeFlowBiz.java create mode 100644 src/com/engine/kq/biz/KQOverTimeRuleCalBiz.java create mode 100644 src/com/engine/kq/biz/KQOvertimeLogBiz.java create mode 100644 src/com/engine/kq/biz/KQReportBiz.java create mode 100644 src/com/engine/kq/biz/KQSettingsBiz.java create mode 100644 src/com/engine/kq/biz/KQShiftManagementComInfo.java create mode 100644 src/com/engine/kq/biz/KQShiftManagementRedis.java create mode 100644 src/com/engine/kq/biz/KQWorkTime.java create mode 100644 src/com/engine/kq/biz/chain/cominfo/ShiftInfoCominfoBean.java create mode 100644 src/com/engine/kq/biz/chain/cominfo/WorkShiftComIndex.java create mode 100644 src/com/engine/kq/cmd/attendanceButton/PunchButtonCmd.java create mode 100644 src/com/engine/kq/cmd/attendanceEvent/GetOverTimeWorkDurationCmd.java create mode 100644 src/com/engine/kq/cmd/balanceofleaverp/ExportExcelCmd.java create mode 100644 src/com/engine/kq/cmd/balanceofleaverp/GetSearchListCmd.java create mode 100644 src/com/engine/kq/cmd/leaverules/GetLeaveRulesFormCmd.java create mode 100644 src/com/engine/kq/cmd/myattendance/GetHrmKQMonthReportInfoCmd.java create mode 100644 src/com/engine/kq/cmd/myattendance/GetHrmKQReportInfoCmd.java create mode 100644 src/com/engine/kq/cmd/myattendance/GetHrmKQSignInfoCmd.java create mode 100644 src/com/engine/kq/cmd/report/ExportExcelCmd.java create mode 100644 src/com/engine/kq/cmd/report/GetKQReportCmd.java create mode 100644 src/com/engine/kq/cmd/shiftmanagement/GetShiftManagementBaseFormCmd.java create mode 100644 src/com/engine/kq/cmd/shiftmanagement/SaveShiftManagementBaseFormCmd.java create mode 100644 src/com/engine/kq/cmd/shiftschedule/GetShiftScheduleCmd.java create mode 100644 src/com/engine/kq/cmd/shiftschedule/GetShiftScheduleTotalCmd.java create mode 100644 src/com/engine/kq/cmd/shiftschedule/ImportExcelCmd.java create mode 100644 src/com/engine/kq/entity/WorkTimeEntity.java create mode 100644 src/com/engine/kq/util/KQDurationCalculatorUtil.java create mode 100644 src/com/engine/kq/util/KQTransMethod.java create mode 100644 src/com/engine/kq/util/UtilKQHS.java create mode 100644 src/com/engine/kq/wfset/util/KQFlowUtil.java create mode 100644 src/com/engine/leshanvc/cmd/EntryWorkflowSaveEventCmd.java create mode 100644 src/com/engine/leshanvc/cmd/KqWorkflowRangeLimitCmd.java create mode 100644 src/com/engine/leshanvc/cmd/WorkflowCheckCmd.java create mode 100644 src/com/engine/leshanvc/enums/MessageContentEnum.java create mode 100644 src/com/engine/leshanvc/exception/CustomizeRunTimeException.java create mode 100644 src/com/engine/leshanvc/service/EntryCommitFormModeService.java create mode 100644 src/com/engine/leshanvc/service/EntryWorkflowSaveEventService.java create mode 100644 src/com/engine/leshanvc/service/KqWorkflowRangeLimitService.java create mode 100644 src/com/engine/leshanvc/service/LeaverWorkflowService.java create mode 100644 src/com/engine/leshanvc/service/LzWorkflowManageService.java create mode 100644 src/com/engine/leshanvc/service/ResourceCardService.java create mode 100644 src/com/engine/leshanvc/service/SyncXcDataService.java create mode 100644 src/com/engine/leshanvc/service/WorkflowCheckService.java create mode 100644 src/com/engine/leshanvc/service/impl/EntryCommitFormModeServiceImpl.java create mode 100644 src/com/engine/leshanvc/service/impl/EntryWorkflowSaveEventServiceImpl.java create mode 100644 src/com/engine/leshanvc/service/impl/KqWorkflowRangeLimitServiceImpl.java create mode 100644 src/com/engine/leshanvc/service/impl/LeaverWorkflowServiceImpl.java create mode 100644 src/com/engine/leshanvc/service/impl/LzWorkflowManageServiceImpl.java create mode 100644 src/com/engine/leshanvc/service/impl/ResourceCardServiceImpl.java create mode 100644 src/com/engine/leshanvc/service/impl/SyncXcDataServiceImpl.java create mode 100644 src/com/engine/leshanvc/service/impl/WorkflowCheckServiceImpl.java create mode 100644 src/com/engine/leshanvc/util/ExceptionUtil.java create mode 100644 src/com/engine/leshanvc/util/HsDateUtil.java create mode 100644 src/com/engine/leshanvc/util/ResponseResult.java create mode 100644 src/com/engine/leshanvc/web/EntryCommitFormModeController.java create mode 100644 src/com/engine/leshanvc/web/EntryWorkflowSaveEventAction.java create mode 100644 src/com/engine/leshanvc/web/KqWorkflowRangeLimitAction.java create mode 100644 src/com/engine/leshanvc/web/LeaverWorkflowAction.java create mode 100644 src/com/engine/leshanvc/web/LzWorkflowManageAction.java create mode 100644 src/com/engine/leshanvc/web/ResourceCardAction.java create mode 100644 src/com/engine/leshanvc/web/SyncXcDataAction.java create mode 100644 src/com/engine/leshanvc/web/WorkflowCheckAction.java create mode 100644 src/com/engine/workflow/biz/requestForm/Html2Pdf.java create mode 100644 src/com/engine/workflow/cmd/monitor/DoArchivingCmd.java create mode 100644 src/com/engine/workflow/cmd/requestForm/FunctionManageCmd.java create mode 100644 src/weaver/formmode/excel/ImpExcelReader.java create mode 100644 src/weaver/formmode/excel/ImpExcelServer.java create mode 100644 src/weaver/hrm/settings/BirthdayReminder.java create mode 100644 src/weaver/interfaces/hansang/action/BussinessTripAutoSignAction.java create mode 100644 src/weaver/interfaces/hansang/action/OfficeOutAutoSignAction.java create mode 100644 src/weaver/interfaces/hansang/action/RefreshKqReportAction.java create mode 100644 src/weaver/interfaces/hansang/action/RefreshKqReportBatchAction.java create mode 100644 src/weaver/interfaces/hansang/job/AnnualLeaveBaseCalculateJob.java create mode 100644 src/weaver/interfaces/hansang/job/AttendanceDaysCalculateJob.java create mode 100644 src/weaver/interfaces/hansang/job/DepartRefreshKqReportJob.java create mode 100644 src/weaver/interfaces/hansang/job/EntryDaysCalculateJob.java create mode 100644 src/weaver/interfaces/hansang/job/HrmGroupMemberSyn.java create mode 100644 src/weaver/interfaces/hansang/job/InternAttDaySynJob.java create mode 100644 src/weaver/interfaces/hansang/job/KqAbnormalRemind.java create mode 100644 src/weaver/interfaces/hansang/job/KqAutoScheduleJob.java create mode 100644 src/weaver/interfaces/hansang/job/KqGroupMemberSyn.java create mode 100644 src/weaver/interfaces/hansang/job/LeaveDateUpdateJob.java create mode 100644 src/weaver/interfaces/hansang/job/LeaveDaysCalculateJob.java create mode 100644 src/weaver/interfaces/hansang/job/ManagerMemberSyn.java create mode 100644 src/weaver/interfaces/hansang/job/NurseLeaveCalculateJob.java create mode 100644 src/weaver/interfaces/hansang/job/OutSignUserSynJob.java create mode 100644 src/weaver/interfaces/hansang/job/OvertimeCalculateJob.java create mode 100644 src/weaver/interfaces/hansang/job/OvertimeSignCalculateJob.java create mode 100644 src/weaver/interfaces/hansang/job/ParentalLeaveCalculateJob.java create mode 100644 src/weaver/interfaces/hansang/job/RecommendBonusCalculateJob.java create mode 100644 src/weaver/interfaces/hansang/job/RegularDaysCalculateJob.java create mode 100644 src/weaver/interfaces/hansang/job/SalaryTaxMemSynJob.java create mode 100644 src/weaver/interfaces/hansang/job/SickLeaveSalaryCalculateJob.java create mode 100644 src/weaver/interfaces/hansang/job/UserCardInfoUpdateJob.java create mode 100644 src/weaver/interfaces/hansang/util/ReportTransMethod.java create mode 100644 src/weaver/interfaces/hskq/action/BmChangeAction.java create mode 100644 src/weaver/interfaces/hskq/action/DkCreateEveryDay.java create mode 100644 src/weaver/interfaces/hskq/action/KqBaseInfoCreateEveryDay.java create mode 100644 src/weaver/interfaces/hskq/util/BatchIdsParams.java create mode 100644 src/weaver/interfaces/leshanvc/cronjob/ApplyCronJob.java create mode 100644 src/weaver/interfaces/leshanvc/cronjob/AutoCancelDepartmentJob.java create mode 100644 src/weaver/interfaces/leshanvc/cronjob/SyncQualificationsJob.java create mode 100644 src/weaver/interfaces/leshanvc/cronjob/SyncResignJob.java create mode 100644 src/weaver/interfaces/leshanvc/cronjob/SyncStatusByDate.java create mode 100644 src/weaver/interfaces/leshanvc/formmode/EntryCommitBtnShowTemplate.java create mode 100644 src/weaver/interfaces/leshanvc/formmode/LeaveCheckInCutPayBtnShow.java create mode 100644 src/weaver/interfaces/leshanvc/formmode/NonOfficeUploadExpand.java create mode 100644 src/weaver/interfaces/leshanvc/formmode/RegisterSaveExpand.java create mode 100644 src/weaver/interfaces/leshanvc/workflow/action/BatchWorkOverTimeAction.java create mode 100644 src/weaver/interfaces/leshanvc/workflow/action/MessagePushWeChatWorkAction.java create mode 100644 src/weaver/interfaces/leshanvc/workflow/action/OutSplitAction.java create mode 100644 src/weaver/interfaces/leshanvc/workflow/action/ShuttleRouteSyncAction.java create mode 100644 src/weaver/interfaces/leshanvc/workflow/action/SyncHrmInfoToCardAction.java create mode 100644 src/weaver/interfaces/leshanvc/workflow/action/UpdateStatusAfterRegularAction.java create mode 100644 src/weaver/interfaces/leshanvc/workflow/entity/FieldMapEntity.java create mode 100644 src/weaver/interfaces/leshanvc/workflow/util/CodeRuleUtil.java create mode 100644 src/weaver/interfaces/leshanvc/workflow/util/ConvertDurationUtil.java create mode 100644 src/weaver/interfaces/leshanvc/workflow/util/FunctionInterfaceMessage.java create mode 100644 src/weaver/interfaces/leshanvc/workflow/util/ResourceSyncUtil.java create mode 100644 src/weaver/workflow/dmlaction/commands/actions/DMLAction.java diff --git a/src/com/api/browser/service/impl/ResourceBrowserService.java b/src/com/api/browser/service/impl/ResourceBrowserService.java new file mode 100644 index 0000000..dc14e31 --- /dev/null +++ b/src/com/api/browser/service/impl/ResourceBrowserService.java @@ -0,0 +1,4102 @@ +package com.api.browser.service.impl; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.api.browser.bean.BrowserTabBean; +import com.api.browser.bean.ListHeadBean; +import com.api.browser.bean.SearchConditionItem; +import com.api.browser.bean.SearchConditionOption; +import com.api.browser.biz.*; +import com.api.browser.service.BrowserService; +import com.api.browser.util.BoolAttr; +import com.api.browser.util.BrowserConstant; +import com.api.browser.util.ConditionFactory; +import com.api.browser.util.ConditionType; +import com.cloudstore.dev.api.util.Util_TableMap; +import com.engine.blog.util.BlogDiscussShareUtil; +import com.engine.common.biz.EncryptConfigBiz; +import com.engine.common.service.WorkflowCommonService; +import com.engine.common.service.impl.WorkflowCommonServiceImpl; +import com.engine.common.util.ParamUtil; +import com.engine.encrypt.biz.EncryptFieldViewScopeConfigComInfo; +import com.engine.hrm.service.impl.BrowserDisplayFieldServiceImpl; +import com.engine.msgcenter.constant.HrmPracticalConstant; +import com.engine.msgcenter.util.HrmPracticalUtil; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import weaver.conn.RecordSet; +import weaver.general.AccountType; +import weaver.general.SplitPageParaBean; +import weaver.general.SplitPageUtil; +import weaver.general.Util; +import weaver.general.browserData.BrowserManager; +import weaver.hrm.HrmTransMethod; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; +import weaver.hrm.appdetach.AppDetachComInfo; +import weaver.hrm.cachecenter.CacheLoadQueueManager; +import weaver.hrm.cachecenter.entry.OrgUpOrDownTypeStyle; +import weaver.hrm.cachecenter.entry.SimpleObjtypeInfo; +import weaver.hrm.cachecenter.util.ObjtypeComparor; +import weaver.hrm.common.database.dialect.DialectUtil; +import weaver.hrm.company.CompanyComInfo; +import weaver.hrm.company.DepartmentComInfo; +import weaver.hrm.company.SubCompanyComInfo; +import weaver.hrm.companyvirtual.CompanyVirtualComInfo; +import weaver.hrm.companyvirtual.DepartmentVirtualComInfo; +import weaver.hrm.companyvirtual.ResourceVirtualComInfo; +import weaver.hrm.companyvirtual.SubCompanyVirtualComInfo; +import weaver.hrm.group.HrmGroupTreeComInfo; +import weaver.hrm.job.JobActivitiesComInfo; +import weaver.hrm.job.JobCallComInfo; +import weaver.hrm.job.JobGroupsComInfo; +import weaver.hrm.job.JobTitlesComInfo; +import weaver.hrm.moduledetach.ManageDetachComInfo; +import weaver.hrm.privacy.PrivacyComInfo; +import weaver.hrm.resource.MutilResourceBrowser; +import weaver.hrm.resource.ResourceComInfo; +import weaver.hrm.resource.controller.HrmWorkflowAdvanceManager; +import weaver.hrm.resource.controller.analysis.HrmOrgForwardBean; +import weaver.hrm.settings.ChgPasswdReminder; +import weaver.hrm.settings.RemindSettings; +import weaver.systeminfo.SystemEnv; +import weaver.systeminfo.setting.HrmUserSettingComInfo; +import weaver.systeminfo.systemright.CheckSubCompanyRight; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import java.util.*; + +/** + * 人力资源 + * + * @author jhy Apr 18, 2017 + */ +public class ResourceBrowserService extends BrowserService { + private List browserFieldConfig = new ArrayList<>(); + private List displayFields = new ArrayList(); + private String displayFieldsStr = ""; + private List browserFieldFilterKeys = new ArrayList<>(Arrays.asList( +// "lastnamespan", + "departmentidspan", + "subcompanyid1span", + "orgidspan" + )); + + private List dataRanageAllSubCompanyIds = new ArrayList(); + private List dataRanageAllDepartmentIds = new ArrayList(); + private int[] allSubComIds = null;//有权限的机构,包含必要的构成树的上级 + private int[] subComIds = null;//有权限的机构,不包含必要的构成树的上级 + private String rightStr= null;//权限字符串 + private String[] allChildSubComIds = null;//人员所属分部的下级分部 + private String[] allChildDeptIds = null;//人员所属部门的下级部门 + private int[] depIds= null;//角色级别是部门的,只能看到自己的部门 + private boolean isExecutionDetach = false;//是否执行力分权 + private Map params = null; + @Override + public Map browserAutoComplete(HttpServletRequest request, HttpServletResponse response) throws Exception { + Map apidatas = new HashMap(); + ResourceComInfo resourceComInfo = new ResourceComInfo(); + SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo(); + String virtualtype = Util.null2String(request.getParameter("virtualtype")); + //人力资源 165 分权单人力 166 分权多人力 + String whereClause = Util.null2String(request.getParameter("sqlwhere")); + + WorkflowCommonService WorkflowCommonService = new WorkflowCommonServiceImpl(); + Map params = ParamUtil.request2Map(request); + this.params = params; + + String agentorbyagentid = Util.null2String(params.get("agentorbyagentid")); + User finalUser = CacheLoadQueueManager.getFinalUser(user, agentorbyagentid); + user = finalUser; + + params.put("tableAlias", "t1"); + Map dataRanage = WorkflowCommonService.getDataDefinitionDataRanageSet(params, user, 1); + + if (Util.null2String(dataRanage.get("sqlWhere")).length() > 0) { + if (whereClause.length() > 0) + whereClause += "and"; + whereClause += Util.null2String(dataRanage.get("sqlWhere")); + } + + if (whereClause.equals("")) { + whereClause = "t1.departmentid = t2.id"; + } else { + whereClause += " and t1.departmentid = t2.id"; + } + if (Util.getIntValue(virtualtype) < -1) { + whereClause += " and t1.virtualtype = " + virtualtype; + } + + //二开查询所有人员 取消以下代码 + //if (whereClause.indexOf("status") != -1) { + // //包含status 说明外部已控制状态 + //} else { + // //只显示在职人员 + // if (whereClause.equals("")) { + // whereClause += " (t1.status = 0 or t1.status = 1 or t1.status = 2 or t1.status = 3) "; + // } else { + // whereClause += " and (t1.status = 0 or t1.status = 1 or t1.status = 2 or t1.status = 3) "; + // } + //} + + HttpSession session = request.getSession(); + if (browserType.equals("165") || browserType.equals("166")) { + int beagenter = Util.getIntValue((String) session.getAttribute("beagenter_" + user.getUID())); + if (beagenter <= 0) { + beagenter = user.getUID(); + } + int fieldid = Util.getIntValue(request.getParameter("fieldid")); + int isdetail = Util.getIntValue(request.getParameter("viewtype")); + int isbill = Util.getIntValue(request.getParameter("isbill"), 1); + if (fieldid != -1) { + CheckSubCompanyRight checkSubCompanyRight = new CheckSubCompanyRight(); + checkSubCompanyRight.setDetachable(1); + checkSubCompanyRight.setIsbill(isbill); + checkSubCompanyRight.setFieldid(fieldid); + checkSubCompanyRight.setIsdetail(isdetail); + boolean onlyselfdept = checkSubCompanyRight.getDecentralizationAttr(beagenter, "Resources:decentralization", fieldid, isdetail, isbill); + boolean isall = checkSubCompanyRight.getIsall(); + String departments = Util.null2String(checkSubCompanyRight.getDepartmentids()); + String subcompanyids = Util.null2String(checkSubCompanyRight.getSubcompanyids()); + if (!isall) { + if (onlyselfdept) { + if (departments.length() > 0 && !departments.equals("0")) { + whereClause += " and t1.departmentid in(" + departments + ")"; + } + } else { + if (subcompanyids.length() > 0 && !subcompanyids.equals("0")) { + whereClause += " and t1.subcompanyid1 in(" + subcompanyids + ")"; + } + } + } + } + } else if (browserType.equals("160")) { + String roleids = Util.null2String(request.getParameter("roleid")); + ArrayList resourcrole = Util.TokenizerString(roleids, "_"); + String roleid = "0"; + int uid = user.getUID(); + if (resourcrole.size() > 0) roleid = "" + resourcrole.get(0); + int index = roleid.indexOf("a"); + int rolelevel = 0; + if (index > -1) { + int roledid_tmp = Util.getIntValue(roleid.substring(0, index), 0); + String rolelevelStr = roleid.substring(index + 1); + + roleid = "" + roledid_tmp; + index = rolelevelStr.indexOf("b"); + if (index > -1) { + rolelevel = Util.getIntValue(rolelevelStr.substring(0, index), 0); + uid = Util.getIntValue(rolelevelStr.substring(index + 1), 0); + if (uid <= 0) { + uid = user.getUID(); + } + } else { + rolelevel = Util.getIntValue(rolelevelStr); + } + } + + if (roleid.length() == 0) { + whereClause += " and 1=2 "; + } else { + whereClause += " and t1.ID in (select ResourceID from hrmrolemembers a,hrmroles b where a.roleid = b.ID and b.ID=" + roleid + ")"; + } + + if (rolelevel != 0) { + if (rolelevel == 1) { + int subcomid = Util.getIntValue(resourceComInfo.getSubCompanyID("" + uid), 0); + whereClause += " and t1.subcompanyid1=" + subcomid + " "; + } else if (rolelevel == 2) { + int subcomid = Util.getIntValue(resourceComInfo.getSubCompanyID("" + uid), 0); + int supsubcomid = Util.getIntValue(subCompanyComInfo.getSupsubcomid("" + subcomid), 0); + whereClause += " and t1.subcompanyid1=" + supsubcomid + " "; + } else if (rolelevel == 3) { + int departid = Util.getIntValue(resourceComInfo.getDepartmentID("" + uid), 0); + whereClause += " and t1.departmentid=" + departid + " "; + } + } + } + //Added by wcd 2014-11-28 增加分权控制 start + AppDetachComInfo appDetachComInfo = new AppDetachComInfo(); + String tempSql = appDetachComInfo.getScopeSqlByHrmResourceSearch(String.valueOf(user.getUID()), true, "resource_t1"); + whereClause += (tempSql == null || tempSql.length() == 0) ? "" : (" and " + tempSql); + //Added by wcd 2014-11-28 增加分权控制 end + + String workflowid = Util.null2String(params.get("bdf_wfid")); + String nodeid = Util.null2String(params.get("nodeid")); + String forwardflag = Util.null2String(params.get("forwardflag")); + + + HrmOrgForwardBean hrmOrgForwardBean = CacheLoadQueueManager.getForwordBean(workflowid, nodeid, forwardflag, finalUser, false, true); + whereClause = HrmWorkflowAdvanceManager.resetSqlWhere(hrmOrgForwardBean, whereClause, "t1"); + + BrowserManager browserManager = new BrowserManager(); + browserManager.setType(browserType); + browserManager.setOrderKey("t1.dsporder"); + browserManager.setOrderWay("asc"); + String result = ""; + //加载人力资源浏览按钮显示列定义 + List browserDisplayColumns = loadDisplayColumnConfig(); + if (Util.getIntValue(virtualtype) < -1) { + result = browserManager.getResult(request, "t1.id,lastname,departmentname", "HrmResourcevirtualview t1,hrmdepartmentvirtual t2", whereClause, PAGENUM, "t1"); + } else { + result = browserManager.getResult(request, "t1.id,lastname,departmentname", "hrmresource t1,hrmdepartment t2", whereClause, PAGENUM, "t1"); + } + + DepartmentComInfo deptComInfo = new DepartmentComInfo(); + JSONArray arr = (JSONArray) JSON.parse(result); + + List> users = new ArrayList>(); + List ids = new ArrayList(); + for (int i = 0; i < arr.size(); i++) { + JSONObject userInfo = (JSONObject) arr.get(i); + ids.add(userInfo.getString("id")); + } + + // 做广播权限和应用分权的交集 + String radioType = Util.null2String(request.getParameter("radioType")); + if(HrmPracticalConstant.RADIO_TYPE.equals(radioType)){ + + List userIdList = HrmPracticalUtil.getUserIdS(user.getUID(),HrmPracticalConstant.BROAD_CASTER,HrmPracticalConstant.SEND_RANGE); + + List userIdListBak = new ArrayList<>(); + if(CollectionUtils.isEmpty(userIdList)) + ids.clear(); + else { + for(String userId : userIdList) + if(ids.contains(userId)) + userIdListBak.add(userId); + ids = userIdListBak; + } + } + + + if(ids.size() > 0){ + for(String id : ids){ + Map userInfo = getUserInfo(id, user, false); + String title = ""; + for(int i = 0; i < browserFieldConfig.size(); i++){ + Map f = browserFieldConfig.get(i); + String fieldName = Util.null2String(f.get("fieldName")) + "span"; + String value = Util.null2String(userInfo.get(fieldName)); + + if(i == 0) + title += value; + else{ + if(title.equals("")) + title += value; + else if(!value.equals("")) + title += "|" + value; + } + } + userInfo.put("name", userInfo.get("lastname")); + userInfo.put("title", title); + users.add(userInfo); + } + } + apidatas.put(BrowserConstant.BROWSER_RESULT_DATA, net.sf.json.JSONArray.fromObject(users)); + +// for (int i = 0; i < arr.size(); i++) { +// JSONObject userInfo = (JSONObject) arr.get(i); +// String resourceid = userInfo.getString("id"); +// userInfo.put("lastname", resourceComInfo.getLastname(resourceid)); +// userInfo.put("jobtitlename", MutilResourceBrowser.getJobTitlesname(resourceid)); +// userInfo.put("icon", resourceComInfo.getMessagerUrls(resourceid)); +// userInfo.put("type", "resource"); +// userInfo.put("departmentid", resourceComInfo.getDepartmentID(resourceid)); +// userInfo.put("departmentname", deptComInfo.getDepartmentmark(resourceComInfo.getDepartmentID(resourceid))); +// String subcompanyid = deptComInfo.getSubcompanyid1(resourceComInfo.getDepartmentID(resourceid)); +// String parentsubcompanyid = subCompanyComInfo.getSupsubcomid(subcompanyid); +// userInfo.put("subcompanyid", subcompanyid); +// userInfo.put("subcompanyname", subCompanyComInfo.getSubcompanyname(subcompanyid)); +// userInfo.put("supsubcompanyid", parentsubcompanyid); +// userInfo.put("supsubcompanyname", subCompanyComInfo.getSubcompanyname(parentsubcompanyid)); +// userInfo.put("title", userInfo.get("lastname") + "|" + userInfo.get("departmentname")); +// } +// apidatas.put(BrowserConstant.BROWSER_RESULT_DATA, arr); + return apidatas; + } + + @Override + public Map getBrowserConditionInfo(Map params) throws Exception { + + String workflowid = Util.null2String(params.get("bdf_wfid")); + String nodeid = Util.null2String(params.get("nodeid")); + String forwardflag = Util.null2String(params.get("forwardflag")); + String agentorbyagentid = Util.null2String(params.get("agentorbyagentid")); + String bdShare = Util.null2String(params.get("bdShare")); //微博模块 单独加的条件 + User finalUser = CacheLoadQueueManager.getFinalUser(user, agentorbyagentid); + user = finalUser; + + + + + + HrmOrgForwardBean hrmOrgForwardBean = CacheLoadQueueManager.getForwordBean(workflowid, nodeid, forwardflag, finalUser, false, true); + + Map apidatas = new HashMap(); + List conditions = new ArrayList(); + apidatas.put(BrowserConstant.BROWSER_RESULT_CONDITIONS, conditions); + ConditionFactory conditionFactory = new ConditionFactory(user); + //姓名 + conditions.add(conditionFactory.createCondition(ConditionType.INPUT, 413, "lastname", true)); + + + //微博模块 单独条件返回 + if(!"".equals(bdShare)){ + conditions.add(conditionFactory.createCondition(ConditionType.BROWSER, 141, "subcompanyid", "194")); + //部门 + conditions.add(conditionFactory.createCondition(ConditionType.BROWSER, 124, "departmentid", "57")); + return apidatas; + } + + + //组织维度 + CompanyComInfo companyComInfo = new CompanyComInfo(); + CompanyVirtualComInfo companyVirtualComInfo = new CompanyVirtualComInfo(); + List comOptions = new ArrayList(); + if (companyComInfo.getCompanyNum() > 0) { + companyComInfo.setTofirstRow(); + while (companyComInfo.next()) { + comOptions.add(new SearchConditionOption(companyComInfo.getCompanyid(), companyComInfo.getCompanyname(), true)); + } + } + companyVirtualComInfo.setTofirstRow(); + while (companyVirtualComInfo.next()) { + if ("1".equals(companyVirtualComInfo.getCancel())){ + continue; + } + comOptions.add(new SearchConditionOption(companyVirtualComInfo.getCompanyid(), companyVirtualComInfo.getVirtualType())); + } + SearchConditionItem searchConditionItem = conditionFactory.createCondition(ConditionType.SELECT, 34069, "virtualtype", comOptions); + searchConditionItem.setValue(companyComInfo.getCompanyid()); + conditions.add(conditionFactory.createCondition(ConditionType.SELECT, 34069, "virtualtype", comOptions)); + //状态 + //流程状态 + List statuOptions = new ArrayList(); + conditions.add(conditionFactory.createCondition(ConditionType.SELECT, 602, "status", statuOptions)); + String conditionType = Util.null2String(params.get("changeType")); //人员状态变更类型 + if (conditionType.length() == 0) { + + RemindSettings settings = new ChgPasswdReminder().getRemindSettings(); + String checkUnJob = Util.null2String(settings.getCheckUnJob(), "0");//非在职人员信息查看控制 启用后,只有有“离职人员查看”权限的用户才能检索非在职人员 + if ("1".equals(checkUnJob)) { + if (HrmUserVarify.checkUserRight("hrm:departureView", user)) { + statuOptions.add(new SearchConditionOption("9", SystemEnv.getHtmlLabelName(332, user.getLanguage()))); + } + } else { + statuOptions.add(new SearchConditionOption("9", SystemEnv.getHtmlLabelName(332, user.getLanguage()))); + } + statuOptions.add(new SearchConditionOption("8", SystemEnv.getHtmlLabelName(1831, user.getLanguage()), true)); + statuOptions.add(new SearchConditionOption("0", SystemEnv.getHtmlLabelName(15710, user.getLanguage()))); + statuOptions.add(new SearchConditionOption("1", SystemEnv.getHtmlLabelName(15711, user.getLanguage()))); + statuOptions.add(new SearchConditionOption("2", SystemEnv.getHtmlLabelName(480, user.getLanguage()))); + statuOptions.add(new SearchConditionOption("3", SystemEnv.getHtmlLabelName(15844, user.getLanguage()))); + if ("1".equals(checkUnJob)) { + if (HrmUserVarify.checkUserRight("hrm:departureView", user)) { + statuOptions.add(new SearchConditionOption("4", SystemEnv.getHtmlLabelName(6094, user.getLanguage()))); + statuOptions.add(new SearchConditionOption("5", SystemEnv.getHtmlLabelName(6091, user.getLanguage()))); + statuOptions.add(new SearchConditionOption("6", SystemEnv.getHtmlLabelName(6092, user.getLanguage()))); + statuOptions.add(new SearchConditionOption("7", SystemEnv.getHtmlLabelName(2245, user.getLanguage()))); + } + } else { + statuOptions.add(new SearchConditionOption("4", SystemEnv.getHtmlLabelName(6094, user.getLanguage()))); + statuOptions.add(new SearchConditionOption("5", SystemEnv.getHtmlLabelName(6091, user.getLanguage()))); + statuOptions.add(new SearchConditionOption("6", SystemEnv.getHtmlLabelName(6092, user.getLanguage()))); + statuOptions.add(new SearchConditionOption("7", SystemEnv.getHtmlLabelName(2245, user.getLanguage()))); + } + } else { + statuOptions.add(new SearchConditionOption("9", SystemEnv.getHtmlLabelName(332, user.getLanguage()), true)); + if (conditionType.equals("hrmtry")) { + statuOptions.add(new SearchConditionOption("2", SystemEnv.getHtmlLabelName(480, user.getLanguage()))); + } else if (conditionType.equals("retire")) { + statuOptions.add(new SearchConditionOption("1", SystemEnv.getHtmlLabelName(15711, user.getLanguage()))); + } else if (conditionType.equals("rehire")) { + statuOptions.add(new SearchConditionOption("4", SystemEnv.getHtmlLabelName(6094, user.getLanguage()))); + statuOptions.add(new SearchConditionOption("5", SystemEnv.getHtmlLabelName(6091, user.getLanguage()))); + statuOptions.add(new SearchConditionOption("6", SystemEnv.getHtmlLabelName(6092, user.getLanguage()))); + statuOptions.add(new SearchConditionOption("7", SystemEnv.getHtmlLabelName(2245, user.getLanguage()))); + } else if (conditionType.equals("redeploy") || conditionType.equals("fire") || conditionType.equals("extend")) { + statuOptions.add(new SearchConditionOption("0", SystemEnv.getHtmlLabelName(15710, user.getLanguage()))); + statuOptions.add(new SearchConditionOption("1", SystemEnv.getHtmlLabelName(15711, user.getLanguage()))); + statuOptions.add(new SearchConditionOption("2", SystemEnv.getHtmlLabelName(480, user.getLanguage()))); + statuOptions.add(new SearchConditionOption("3", SystemEnv.getHtmlLabelName(15844, user.getLanguage()))); + } else if (conditionType.equals("hire")) { + statuOptions.add(new SearchConditionOption("0", SystemEnv.getHtmlLabelName(15710, user.getLanguage()))); + statuOptions.add(new SearchConditionOption("2", SystemEnv.getHtmlLabelName(480, user.getLanguage()))); + statuOptions.add(new SearchConditionOption("3", SystemEnv.getHtmlLabelName(15844, user.getLanguage()))); + } else if (conditionType.equals("dismiss")) { + statuOptions.add(new SearchConditionOption("8", SystemEnv.getHtmlLabelName(1831, user.getLanguage()))); + statuOptions.add(new SearchConditionOption("0", SystemEnv.getHtmlLabelName(15710, user.getLanguage()))); + statuOptions.add(new SearchConditionOption("1", SystemEnv.getHtmlLabelName(15711, user.getLanguage()))); + statuOptions.add(new SearchConditionOption("2", SystemEnv.getHtmlLabelName(480, user.getLanguage()))); + statuOptions.add(new SearchConditionOption("3", SystemEnv.getHtmlLabelName(15844, user.getLanguage()))); + } + } + + //分部 + conditions.add(conditionFactory.createCondition(ConditionType.BROWSER, 141, "subcompanyid", "194")); + //部门 + conditions.add(conditionFactory.createCondition(ConditionType.BROWSER, 124, "departmentid", "57")); + //岗位 + conditions.add(conditionFactory.createCondition(ConditionType.INPUT, 6086, "jobtitle")); + //角色 + conditions.add(conditionFactory.createCondition(ConditionType.BROWSER, 122, "roleid", "267")); + + List tabs = new ArrayList(); + tabs.add(new BrowserTabBean("1", SystemEnv.getHtmlLabelName(24515, user.getLanguage()))); + tabs.add(new BrowserTabBean("2", SystemEnv.getHtmlLabelName(18511, user.getLanguage()))); + tabs.add(new BrowserTabBean("3", SystemEnv.getHtmlLabelName(15089, user.getLanguage()))); + tabs.add(new BrowserTabBean("4", SystemEnv.getHtmlLabelName(18770, user.getLanguage()))); + tabs.add(new BrowserTabBean("5", SystemEnv.getHtmlLabelName(81554, user.getLanguage()))); + //tabs.add(new BrowserTabBean("6", SystemEnv.getHtmlLabelName(1340, user.getLanguage()))); + + return apidatas; + } + + private static final ThreadLocal localHrmOrgForwardBean = new ThreadLocal(); + + @Override + public Map getBrowserData(Map params) throws Exception { + this.params = params; + String cmd = Util.null2String(params.get("cmd")); + // + String workflowid = Util.null2String(params.get("bdf_wfid")); + String workplan = Util.null2String(params.get("workplan")); + String nodeid = Util.null2String(params.get("nodeid")); + String forwardflag = Util.null2String(params.get("forwardflag")); + String agentorbyagentid = Util.null2String(params.get("agentorbyagentid")); + User finalUser = CacheLoadQueueManager.getFinalUser(user, agentorbyagentid); + String filterids = Util.null2String(params.get("filterids")); + String bdShare = Util.null2String(params.get("bdShare")); //微博模块单独条件 + String virtualtype = Util.null2String(params.get("virtualtype")); + this.rightStr = Util.null2String(params.get("rightStr")); + String from = Util.null2String(params.get("from")); + // 公文模块 + String odoc = Util.null2String(params.get("odoc")); + String classification = Util.null2String(params.get("classification")); + + user = finalUser; + + HrmOrgForwardBean hrmOrgForwardBean = CacheLoadQueueManager.getForwordBean(workflowid, nodeid, forwardflag, finalUser, false); + localHrmOrgForwardBean.set(hrmOrgForwardBean); + String sqlwhere = Util.null2String(params.get("sqlwhere")); + if (hrmOrgForwardBean != null) { + sqlwhere = HrmWorkflowAdvanceManager.wrapUnqinueSqlwhere(sqlwhere, workflowid, nodeid, forwardflag); + sqlwhere = HrmWorkflowAdvanceManager.resetSqlWhere(hrmOrgForwardBean, sqlwhere, "hr"); + params.put("sqlwhere", sqlwhere); + + } + if(!"".equals(filterids)){ + sqlwhere += " hr.id not in ("+filterids+")"; + params.put("sqlwhere", sqlwhere); + } + + //微博模块 单独条件 + if(!"".equals(bdShare)&&!cmd.equals("resource")){ + cmd = "bdShare"; + } + //微博模块 单独条件 + if(!"".equals(bdShare)&&cmd.equals("resource")){ + cmd = "bdShareUsers"; + } + + + if("email".equals(from)){ + sqlwhere += " hr.email is not null " + (new RecordSet().getDBType().equals("oracle") ? "" : " and hr.email<>'' "); + params.put("sqlwhere", sqlwhere); + } + + if(classification.length()>0){//根据资源密集过滤人员 + sqlwhere += " hr.classification in (select seclevel from UserClassification where Optionalresourceseclevel like '%"+classification+"%')"; + params.put("sqlwhere", sqlwhere); + } + + Map result = null; + WorkflowCommonService WorkflowCommonService = new WorkflowCommonServiceImpl(); + Map dataRanage = WorkflowCommonService.getDataDefinitionDataRanageSet(params, user, 1); + + generateRange(dataRanage, virtualtype); + + //加载人力资源浏览按钮显示列定义 + List browserDisplayColumns = loadDisplayColumnConfig(); + + if (cmd.equals("newly")) { + if (Util.null2String(dataRanage.get("sqlWhere")).length() > 0) { + result = getSearchList(params); + } else { + String isDelete = Util.null2String(params.get("isDelete")); + if (isDelete.equals("1")) { + String resourceid = Util.null2String(params.get("resourceid")); + RecordSet rs = new RecordSet(); + String sql = "delete from hrmresourceselectrecord where resourceid=" + user.getUID(); + if (resourceid.length() > 0) { + sql += " and selectid=" + resourceid; + } + rs.executeUpdate(sql); + result = new HashMap<>(); + result.put("datas", new ArrayList()); + result.put("count", 0); + } else { + result = getList(params); + } + } + } else if (cmd.equals("search")) { + result = getSearchList(params); + } else if (cmd.equals("role")) { + result = getRoleList(params); + } else if (cmd.equals("underling")) { + result = "".equals(workplan) ? getUnderlingList(params) : getUnderlingList4WorkPlan(params); + } else if (cmd.equals("branch")) { + result = "".equals(workplan) ? getbranchList(params) : getbranchList4WorkPlan(params); + } else if (cmd.equals("addList")) { + result = addList(params); + } else if (cmd.equals("companyvirtual")) { + result = getcompanyvirtual(params); + } else if (cmd.equals("v2resourcetree")) { + // 公文流程模块 qc1081999 只返回当前人员所在的分部 + if ("1".equals(odoc) && !user.isAdmin()) { + dataRanageAllSubCompanyIds = new ArrayList<>(); + ResourceComInfo resourceComInfo = new ResourceComInfo(); + String subCompanyID = resourceComInfo.getSubCompanyID(user.getUID() + ""); + dataRanageAllSubCompanyIds.add(subCompanyID); + } + result = getv2resource(params); + } else if (cmd.equals("v2grouptree")) { + result = getV2grouptree(params); + } else if (cmd.equals("status")) { + result = gethrmstatus(params); + } else if (cmd.equals("allResource")) { + result = getAllResourceList(params); + } else if (cmd.equals("getResourceListByLetter")) { + result = getResourceListByLetter(params); + } else if (cmd.equals("resource")) { + result = getOrgResource(params); + } else if(cmd.equals("bdShare")){ //微博单独条件 + result = getBlogHrmResource(params); + } else if(cmd.equals("bdShareUsers")){ + result = getBlogSelectedHrmResource(params); + } + + if(browserDisplayColumns.size() > 0)//抛出显示列定义 + result.put("columns", browserDisplayColumns); + if (result.get("datas") != null) { + result.put("mobileshowtemplate", getMobileShowTemplate()); + //em7人力资源浏览按钮list模板 + result.put("mobiletemplate",getMobileTemplate()); + } + String mobileResourceId = Util.null2String(params.get("mobileResourceId"));//手机端参数 + if (!mobileResourceId.equals("")) { + ResourceComInfo resourceComInfo = new ResourceComInfo(); + result.put("lastname", resourceComInfo.getLastname(mobileResourceId)); + } + localHrmOrgForwardBean.remove(); + return result; + } + + private Map getList(Map params) { + Map jo = new HashMap<>(); + jo.put("status", false); + + try { + RecordSet rs = new RecordSet(); + AppDetachComInfo adci = new AppDetachComInfo(); + ResourceComInfo rci = new ResourceComInfo(); + Dao_Hrm4Ec d = null; + if (!"oracle".equals(rs.getDBType())) { + d = Dao_Hrm4EcFactory.getInstance().getDao("Dao_Hrm4EcSqlServer"); + } else { + d = Dao_Hrm4EcFactory.getInstance().getDao("Dao_Hrm4EcOracle"); + } + + String lastname = Util.null2String(params.get("lastname")); + String min = Util.null2String(params.get("min")); + String max = Util.null2String(params.get("max")); + String sqlwhere = Util.null2String(params.get("sqlwhere")); + String virtualtype = Util.null2String(params.get("virtualtype")); + String ids = user.getUID() + ""; + String belongtoshow = new HrmUserSettingComInfo().getBelongtoshowByUserId(user.getUID()+ ""); + if (belongtoshow.equals("1") && "0".equals(user.getAccount_type())) { + String belongtoids = user.getBelongtoids(); + ids = ids + "," + belongtoids; + } + + // 暂时先写死sql语句,后期拓展 + String newlistsql = "select distinct hr.id as id, hrsd.id as dsporder0" + displayFieldsStr + ",dsporder,ROW_NUMBER() OVER(order by hrsd.id desc ,dsporder asc,hr.id asc)rn from " + (!"".equals(virtualtype) && Util.getIntValue(virtualtype) < 0 ? "HrmResourceVirtualView" : "hrmresource") + " hr, HrmResourceSelectRecord hrsd where (status =0 or status = 1 or status = 2 or status = 3) and loginid is not null and loginid<>'' and hr.id = selectid and resourceid in (" + ids+")"; + if (DialectUtil.isMySql(rs.getDBType())) { + newlistsql = "select distinct hr.id as id, hrsd.id as dsporder0" + displayFieldsStr + ",dsporder from " + (!"".equals(virtualtype) && Util.getIntValue(virtualtype) < 0 ? "HrmResourceVirtualView" : "hrmresource") + " hr, HrmResourceSelectRecord hrsd where (status =0 or status = 1 or status = 2 or status = 3) and loginid is not null and loginid<>'' and hr.id = selectid and resourceid in (" + ids+")"; + } + + if (!"".equals(lastname)) { + newlistsql += "and( lastname like '%" + lastname + "%' or pinyinlastname like '%" + lastname +"%' or mobile like '%" + lastname + "%' or workcode like '%" + lastname + "%') "; + } + + WorkflowCommonService WorkflowCommonService = new WorkflowCommonServiceImpl(); + params.put("tableAlias", "hr"); + Map dataRanage = WorkflowCommonService.getDataDefinitionDataRanageSet(params, user, 1); + String dataRanageResourceIds = Util.null2String(dataRanage.get("sqlWhere")); + if (dataRanageResourceIds.length() > 0) { + newlistsql += " " + dataRanageResourceIds; + } + + if (!"".equals(sqlwhere)) { + newlistsql += " and " + sqlwhere; + } + + if (adci.isUseAppDetach()) { + String appdetawhere = adci.getScopeSqlByHrmResourceSearch(user.getUID() + "", true, "resource_hr"); + String tempstr = (appdetawhere != null && !"".equals(appdetawhere) ? (" and " + appdetawhere) : ""); + newlistsql += tempstr; + } + newlistsql = getSearchSQL(params, newlistsql, user); + + String orderby = " order by dsporder0 desc, dsporder "; + + List getList = new ArrayList(); + getList.add("id"); + + getList.addAll(getDisplayFields()); +// getList.add("lastname"); +// getList.add("pinyinlastname"); +// getList.add("departmentid"); +// getList.add("subcompanyid1"); +// getList.add("workcode"); + List> getRList = d.getNewlyList(newlistsql, min, max, orderby, getList); + getRList = EditGetMap(getRList); + int count = d.getCount(newlistsql); + jo.put("status", true); + if (null != getRList && 0 < getRList.size()) { + for (int i = 0; i < getRList.size(); i++) { + getRList.get(i).put("icon", rci.getMessagerUrls(getRList.get(i).get("id"))); + getRList.get(i).put("requestParams", rci.getUserIconInfoStr(getRList.get(i).get("id"),user)); + } + + jo.put("datas", getRList); + jo.put("count", count); + } else { + jo.put("datas", new ArrayList()); + jo.put("count", 0); + } + +// getRList = EditGetMap(getRList); + } catch (Exception e) { + writeLog(e); + } + return jo; + } + + private Map getSearchList(Map params) { + Map jo = new HashMap<>(); + jo.put("status", false); + + try { + RecordSet rs = new RecordSet(); + AppDetachComInfo adci = new AppDetachComInfo(); + ResourceComInfo rci = new ResourceComInfo(); + Dao_Hrm4Ec d = null; + if (!"oracle".equals(rs.getDBType())) { + d = Dao_Hrm4EcFactory.getInstance().getDao("Dao_Hrm4EcSqlServer"); + } else { + d = Dao_Hrm4EcFactory.getInstance().getDao("Dao_Hrm4EcOracle"); + } + + String virtual = Util.null2String(params.get("virtualtype")); + String min = Util.null2String(params.get("min")); + String max = Util.null2String(params.get("max")); + String sql = Util.null2String(params.get("sqlwhere")); + + String ids = user.getUID() + ""; + if ("".equals(ids)) { + jo = getWrongCode(403, jo); + return jo; + } + String sqlwhere = " where 1=1 "; + String cmd = Util.null2String(params.get("cmd")); +// if("newly".equals(cmd)) { +// sqlwhere += " and exists( select * from HrmResourceSelectRecord hrsd where hrsd.selectid= HR.id)"; +// } + if (sql.length() != 0) sqlwhere += " and " + sql; + String mobileResourceId = Util.null2String(params.get("mobileResourceId")); + if (!mobileResourceId.equals("")) { + String alllevel = Util.null2String(params.get("alllevel")); + ids = mobileResourceId; + if (alllevel.equals("1")) { + // 显示所有下属 + sqlwhere += " and hr.managerstr like '%," + ids + ",%'"; + } else { + sqlwhere += " and hr.managerid = " + ids; + } + } + + WorkflowCommonService WorkflowCommonService = new WorkflowCommonServiceImpl(); + params.put("tableAlias", "hr"); + Map dataRanage = WorkflowCommonService.getDataDefinitionDataRanageSet(params, user, 1); + String dataRanageResourceIds = Util.null2String(dataRanage.get("sqlWhere")); + if (dataRanageResourceIds.length() > 0) { + sqlwhere += " " + dataRanageResourceIds; + } + + String sqlfrom = "HrmResource hr "; + if (!"".equals(virtual) && -1 > Integer.valueOf(virtual)) { + sqlfrom = "HrmResourceVirtualView hr "; + } + + String backfields = " hr.id as id, " + String.join(",", this.getDisplayFields()) + ", dsporder "; + + if("newly".equals(cmd)){ + backfields = " hr.id as id,hrsd.id as dsporder0, " + String.join(",", this.getDisplayFields()) + ", dsporder "; + } + String lastsql =null; + + if("newly".equals(cmd)){ + //2020/02/06mwl修复浏览按钮最近页签数据显示不准确的bug + String sqlfrom2= ",HrmResourceSelectRecord hrsd"; + sqlwhere += " AND hr.id = selectid and hrsd.resourceid="+user.getUID(); + + lastsql = "select Distinct " + + backfields + + ",ROW_NUMBER() OVER(order by hrsd.id desc, dsporder asc,lastname asc)rn from " + + sqlfrom +sqlfrom2+ sqlwhere; + }else{ + lastsql = "select Distinct " + + backfields + + ",ROW_NUMBER() OVER(order by dsporder asc,lastname asc)rn from " + + sqlfrom + sqlwhere; + } + + lastsql = getSearchSQL(params, lastsql, user); + + String orderby = " order by dsporder "; + if("newly".equals(cmd)) { + orderby = " order by dsporder0 desc, dsporder "; + } + List getList = new ArrayList(); + getList.add("id"); + getList.addAll(getDisplayFields()); +// getList.add("lastname"); +// getList.add("pinyinlastname"); +// getList.add("jobtitle"); +// getList.add("dsporder"); +// getList.add("workcode"); + List> getRList = d.getNewlyList(lastsql, min, max, orderby, getList); + int count = d.getCount(lastsql); + jo.put("status", true); + if (null != getRList && 0 < getRList.size()) { + getRList = EditGetMap(getRList); + jo.put("datas", getRList); + jo.put("count", count); + } else { + jo.put("datas", new ArrayList()); + jo.put("count", 0); + } + } catch (Exception e) { + writeLog(e); + } + return jo; + } + + private Map getRoleList(Map params) { + Map jo = new HashMap<>(); + jo.put("status", false); + + String rolesname = Util.null2String(params.get("rolesname")); + String rolesmark = Util.null2String(params.get("rolesmark")); + String sqlwhere = Util.null2String(params.get("sqlwhere")); + + String ids = user.getUID() + ""; + if ("".equals(ids)) { + jo = getWrongCode(403, jo); + return jo; + } + + int ishead = 0; + if (!sqlwhere.equals("")) + ishead = 1; + if (!rolesname.equals("")) { + if (ishead == 0) { + ishead = 1; + sqlwhere += " where rolesname like '%" + Util.fromScreen2(rolesname, user.getLanguage()) + "%' "; + } else + sqlwhere += " and rolesname like '%" + Util.fromScreen2(rolesname, user.getLanguage()) + "%' "; + } + if (!rolesmark.equals("")) { + if (ishead == 0) { + ishead = 1; + sqlwhere += " where rolesmark like '%" + Util.fromScreen2(rolesmark, user.getLanguage()) + "%' "; + } else + sqlwhere += " and rolesmark like '%" + Util.fromScreen2(rolesmark, user.getLanguage()) + "%' "; + } + + if (!rolesmark.equals("")) { + if (ishead == 0) { + ishead = 1; + sqlwhere += " where rolesmark like '%" + Util.fromScreen2(rolesmark, user.getLanguage()) + "%' "; + } else + sqlwhere += " and rolesmark like '%" + Util.fromScreen2(rolesmark, user.getLanguage()) + "%' "; + } + + WorkflowCommonService WorkflowCommonService = new WorkflowCommonServiceImpl(); + params.put("tableAlias", "hr"); + Map dataRanage = WorkflowCommonService.getDataDefinitionDataRanageSet(params, user, 1); + String dataRanageResourceIds = Util.null2String(dataRanage.get("sqlWhere")); + if (dataRanageResourceIds.length() > 0) { + if (ishead == 0) { + ishead = 1; + sqlwhere += " where 1=1 " + dataRanageResourceIds; + } else { + sqlwhere += " " + dataRanageResourceIds; + } + } + + // 暂时先写死sql语句,后期拓展 + String pageUid = "0068f8a8-958d-4fef-a62c-ed728cc974c8"; + String tableString = "" + + "" + + "" + + " " + + " " + + " " + + " " + + "" + "
"; + String sessionkey = Util.getEncrypt(Util.getRandom()); + Util_TableMap.setVal(sessionkey, tableString); + return jo; + } + + private Map getUnderlingList(Map params) { + Map jo = new HashMap<>(); + jo.put("status", false); + try { + RecordSet rs = new RecordSet(); + AppDetachComInfo adci = new AppDetachComInfo(); + ResourceVirtualComInfo rv = new ResourceVirtualComInfo(); + + Dao_Hrm4Ec d = null; + if (!"oracle".equals(rs.getDBType())) { + d = Dao_Hrm4EcFactory.getInstance().getDao("Dao_Hrm4EcSqlServer"); + } else { + d = Dao_Hrm4EcFactory.getInstance().getDao("Dao_Hrm4EcOracle"); + } + + String virtual = Util.null2String(params.get("virtualtype")); + String min = Util.null2String(params.get("min")); + String max = Util.null2String(params.get("max")); + + String ids = user.getUID() + ""; + if ("".equals(ids)) { + jo = getWrongCode(403, jo); + return jo; + } + + String whereClause = Util.null2String(params.get("sqlwhere")); + String sqlwhere = " where 1=1 "; + if (whereClause.length() != 0) sqlwhere += " and " + whereClause + " "; + + WorkflowCommonService WorkflowCommonService = new WorkflowCommonServiceImpl(); + params.put("tableAlias", "hr"); + Map dataRanage = WorkflowCommonService.getDataDefinitionDataRanageSet(params, user, 1); + String dataRanageResourceIds = Util.null2String(dataRanage.get("sqlWhere")); + if (dataRanageResourceIds.length() > 0) { + sqlwhere += " " + dataRanageResourceIds; + } + + String sqlfrom = "HrmResource hr "; + if (!"".equals(virtual) && -1 > Integer.valueOf(virtual)) { + sqlfrom = "HrmResourceVirtualView hr "; + } + if (!"".equals(virtual) && -1 > Integer.valueOf(virtual)) { + String departmentid = rv.getDepartmentid(virtual, "" + ids); + if (null != departmentid && !"".equals(departmentid)) { + sqlwhere += " and hr.departmentid = " + departmentid + " and virtualtype=" + virtual; + } else { + sqlwhere += " and hr.departmentid = " + user.getUserDepartment() + " and virtualtype=" + virtual; + } + } else { + sqlwhere += " and hr.departmentid = '" + user.getUserDepartment() + "'"; + } + + if (adci.isUseAppDetach() && (Util.getIntValue(virtual) >= 0 || Util.getIntValue(virtual) == -10000)) { + String appdetawhere = adci.getScopeSqlByHrmResourceSearch(user.getUID() + "", true, "resource_hr"); + String tempstr = (appdetawhere != null && !"".equals(appdetawhere) ? (" and " + appdetawhere) : ""); + sqlwhere += tempstr; + } + + String backfields = " hr.id as id," + String.join(",", this.getDisplayFields()) + ", dsporder "; + String lastsql = "select " + + backfields + + ",ROW_NUMBER() OVER(order by dsporder asc,lastname asc)rn from " + + sqlfrom + sqlwhere; + + lastsql = getSearchSQL(params, lastsql, user); + // 拼接插入参数; + List getList = new ArrayList(); + getList.add("id"); + getList.addAll(getDisplayFields()); +// getList.add("lastname"); +// getList.add("pinyinlastname"); +// getList.add("jobtitle"); +// getList.add("dsporder"); +// getList.add("workcode"); + List> getRList = d.getNewlyList(lastsql, min, max, getList); + int count = d.getCount(lastsql); + jo.put("status", true); + if (null != getRList && 0 < getRList.size()) { + getRList = EditGetMap(getRList); + jo.put("datas", getRList); + jo.put("count", count); + } else { + jo.put("datas", new ArrayList()); + jo.put("count", 0); + } + } catch (Exception e) { + writeLog(e); + } + + return jo; + } + + private Map getUnderlingList4WorkPlan(Map params) { + Map jo = new HashMap<>(); + jo.put("status", false); + try { + RecordSet rs = new RecordSet(); + AppDetachComInfo adci = new AppDetachComInfo(); + ResourceVirtualComInfo rv = new ResourceVirtualComInfo(); + DepartmentComInfo departmentComInfo = new DepartmentComInfo(); + + Dao_Hrm4Ec d = null; + if (!"oracle".equals(rs.getDBType())) { + d = Dao_Hrm4EcFactory.getInstance().getDao("Dao_Hrm4EcSqlServer"); + } else { + d = Dao_Hrm4EcFactory.getInstance().getDao("Dao_Hrm4EcOracle"); + } + + String virtual = Util.null2String(params.get("virtualtype")); + String min = Util.null2String(params.get("min")); + String max = Util.null2String(params.get("max")); + + String ids = user.getUID() + ""; + if ("".equals(ids)) { + jo = getWrongCode(403, jo); + return jo; + } + + String whereClause = Util.null2String(params.get("sqlwhere")); + String alllevel = Util.null2String(params.get("alllevel")); + String sqlwhere = " where 1=1 "; + if (whereClause.length() != 0) sqlwhere += " and " + whereClause + " "; + + WorkflowCommonService WorkflowCommonService = new WorkflowCommonServiceImpl(); + params.put("tableAlias", "hr"); + Map dataRanage = WorkflowCommonService.getDataDefinitionDataRanageSet(params, user, 1); + String dataRanageResourceIds = Util.null2String(dataRanage.get("sqlWhere")); + if (dataRanageResourceIds.length() > 0) { + sqlwhere += " " + dataRanageResourceIds; + } + + String sqlfrom = "HrmResource hr "; + if (!"".equals(virtual) && -1 > Integer.valueOf(virtual)) { + sqlfrom = "HrmResourceVirtualView hr "; + } + if (!"".equals(alllevel) && 1 == Integer.valueOf(alllevel)) { + ArrayList childDepts = new ArrayList<>(); + childDepts.add(user.getUserDepartment() + ""); + departmentComInfo.getAllChildDeptByDepId(childDepts, user.getUserDepartment() + ""); + sqlwhere += " and " + Util.getSubINClause(String.join(",", childDepts), "hr.departmentid", "IN"); + } else { + sqlwhere += " and hr.departmentid = '" + user.getUserDepartment() + "'"; + } + + if (adci.isUseAppDetach() && (Util.getIntValue(virtual) >= 0 || Util.getIntValue(virtual) == -10000)) { + String appdetawhere = adci.getScopeSqlByHrmResourceSearch(user.getUID() + "", true, "resource_hr"); + String tempstr = (appdetawhere != null && !"".equals(appdetawhere) ? (" and " + appdetawhere) : ""); + sqlwhere += tempstr; + } + + String backfields = " hr.id as id," + String.join(",", this.getDisplayFields()) + ", dsporder "; + String lastsql = "select " + + backfields + + ",ROW_NUMBER() OVER(order by dsporder asc,lastname asc)rn from " + + sqlfrom + sqlwhere; + + lastsql = getSearchSQL(params, lastsql, user); + // 拼接插入参数; + List getList = new ArrayList(); + getList.add("id"); + getList.addAll(getDisplayFields()); + List> getRList = d.getNewlyList(lastsql, min, max, getList); + int count = d.getCount(lastsql); + jo.put("status", true); + if (null != getRList && 0 < getRList.size()) { + getRList = EditGetMap(getRList); + jo.put("datas", getRList); + jo.put("count", count); + } else { + jo.put("datas", new ArrayList()); + jo.put("count", 0); + } + } catch (Exception e) { + writeLog(e); + } + + return jo; + } + + private String getSearchSQL(Map params, String lastsql, User user) throws Exception { + try { + AppDetachComInfo adci = new AppDetachComInfo(); + RecordSet rs = new RecordSet(); + + String lastname = Util.null2String(params.get("lastname")); + String virtualtype = Util.null2String(params.get("virtualtype")); + String subcompanyid = Util.null2String(params.get("subcompany")); + if (subcompanyid.length() == 0) { + subcompanyid = Util.null2String(params.get("subcompanyid")); + } + String departmentid = Util.null2String(params.get("department")); + if (departmentid.length() == 0) { + departmentid = Util.null2String(params.get("departmentid")); + } + String jobtitle = Util.null2String(params.get("jobtitle")); + String isNoAccount = Util.null2String(params.get("isNoAccount"));// 是否显示无账号人员 + String roleid = Util.null2String(params.get("role"));// 角色 + if (roleid.length() == 0) { + roleid = Util.null2String(params.get("roleid")); + } + if (!"".equals(lastname)) { + lastsql += "and( lastname like '%" + Util.fromScreen2(lastname, user.getLanguage()) + "%' or pinyinlastname like '%" + Util.fromScreen2(lastname, user.getLanguage()) + "%'" + " or workcode like '%" + lastname + "%' or mobile like '%" + lastname + "%') "; + } + // 状态值 + String status = Util.null2String(params.get("status")); + String fromHrmStatusChange = Util.null2String(params.get("fromHrmStatusChange")); + if (status.equals("-1")) + status = ""; + if (!status.equals("") && !status.equals("9") && !status.equals("8")) { + lastsql += " and status =" + status + " "; + } + if (fromHrmStatusChange.equals("")) { + if (status.equals("") || status.equals("8")) { + lastsql += " and (status =0 or status = 1 or status = 2 or status = 3) "; + } + } + // 维度开始 + if (!fromHrmStatusChange.equals("")) { + if (Util.getIntValue(virtualtype) < -1) { + lastsql = lastsql.replace("hr.subcompanyid1", "hr.hrmsubcompanyid1"); + lastsql = lastsql.replace("hr.departmentid", "hr.hrmdepartmentid"); + } + } + if (Util.getIntValue(virtualtype) < -1) { + lastsql += " and virtualtype=" + virtualtype; + } + + // 分部 + if (subcompanyid.equals("0")) + subcompanyid = ""; + if (departmentid.equals("0")) + departmentid = ""; + + if (!departmentid.equals("")) { + lastsql += " and departmentid in(" + departmentid + ") "; + } + if (departmentid.equals("") && !subcompanyid.equals("")) { + lastsql += " and subcompanyid1 in(" + subcompanyid + ") "; + } + + // 是否显示全部 + if (!"1".equals(isNoAccount)) { + lastsql += " and loginid is not null " + (rs.getDBType().equals("oracle") ? "" : " and loginid<>'' "); + } + + //增加应用分权控制 + if (adci.isUseAppDetach()) { + String appdetawhere = adci.getScopeSqlByHrmResourceSearch(user.getUID() + "", true, "resource_hr"); + String tempstr = (appdetawhere != null && !"".equals(appdetawhere) ? (" and " + appdetawhere) : ""); + lastsql += tempstr; + } + + /* + * 执行力管理分权增加控制,未开启,查询部门(包括下级)人员,分部(包括下级)人员, + * */ + if(this.rightStr.equals("Execution:PerformanceSet") || this.rightStr.equals("Execution:ReportSet")){ + String appdetawhere = checkBlogAppLoadSub(this.rightStr); + String tempstr = (appdetawhere != null && !"".equals(appdetawhere) ? (appdetawhere) : ""); + lastsql += tempstr; + } + + //增加广播类型控制 + String radioType = Util.null2String(params.get("radioType")); + if(HrmPracticalConstant.RADIO_TYPE.equals(radioType)){ + + List userIdList = HrmPracticalUtil.getUserIdS(user.getUID(),HrmPracticalConstant.BROAD_CASTER,HrmPracticalConstant.SEND_RANGE); + + if(userIdList != null){ + lastsql += " and hr.ID in (" + StringUtils.join(userIdList, ",") + ")"; + } + } + + + // 角色 + if (!roleid.equals("")) { + lastsql += " and hr.ID in (select t1.ResourceID from hrmrolemembers t1,hrmroles t2 where t1.roleid = t2.ID and t2.ID=" + roleid + " ) "; + } + // 岗位 + if (!jobtitle.equals("")) { + lastsql += " and jobtitle in(select id from HrmJobTitles where jobtitlename like '%" + Util.fromScreen2(jobtitle, user.getLanguage()) + "%') "; + } + } catch (Exception e) { + writeLog(e); + } + return lastsql; + } + + private Map getbranchList(Map params) { + Map jo = new HashMap<>(); + jo.put("status", false); + try { + AppDetachComInfo adci = new AppDetachComInfo(); + RecordSet rs = new RecordSet(); + Dao_Hrm4Ec d = null; + if (!"oracle".equals(rs.getDBType())) { + d = Dao_Hrm4EcFactory.getInstance().getDao("Dao_Hrm4EcSqlServer"); + } else { + d = Dao_Hrm4EcFactory.getInstance().getDao("Dao_Hrm4EcOracle"); + } + String virtual = Util.null2String(params.get("virtualtype")); + String min = Util.null2String(params.get("min")); + String max = Util.null2String(params.get("max")); + String lastname = Util.null2String(params.get("lastname")); + String isNoAccount = Util.null2String(params.get("isNoAccount"));// 是否显示无账号人员 + String alllevel = Util.null2String(params.get("alllevel"));// 是否显示子成员 + String ids = user.getUID() + ""; + String mobileResourceId = Util.null2String(params.get("mobileResourceId")); + if (!mobileResourceId.equals("")) { + ids = mobileResourceId; + } + if ("".equals(ids)) { + jo = getWrongCode(403, jo); + return jo; + } + + String whereClause = Util.null2String(params.get("sqlwhere")); + String sqlwhere = " where 1=1 "; + if (whereClause.length() != 0) sqlwhere += " and " + whereClause + " "; + WorkflowCommonService WorkflowCommonService = new WorkflowCommonServiceImpl(); + params.put("tableAlias", "hr"); + Map dataRanage = WorkflowCommonService.getDataDefinitionDataRanageSet(params, user, 1); + String dataRanageResourceIds = Util.null2String(dataRanage.get("sqlWhere")); + if (dataRanageResourceIds.length() > 0) { + sqlwhere += " " + dataRanageResourceIds; + } + String sqlfrom = "HrmResource hr "; + if (!"".equals(virtual) && -1 > Integer.valueOf(virtual)) { + sqlfrom = "HrmResourceVirtualView hr "; + } + // if (!"".equals(lastname)) { + // sqlwhere += "and( lastname like '%" + Util.fromScreen2(lastname, user.getLanguage()) + "%' or pinyinlastname like '%" + Util.fromScreen2(lastname, user.getLanguage()) + "%' or mobile like '%" + Util.fromScreen2(lastname, user.getLanguage()) + "%' or workcode like '%" + Util.fromScreen2(lastname, user.getLanguage())+ "%') "; + // } + // sqlwhere += " and (status =0 or status = 1 or status = 2 or status = 3) "; + if (!isNoAccount.equals("1")) { + sqlwhere += " and loginid is not null " + (rs.getDBType().equals("oracle") ? "" : " and loginid<>'' "); + } + + //增加应用分权控制 + if (adci.isUseAppDetach() && (Util.getIntValue(virtual) >= 0 || Util.getIntValue(virtual) == -10000)) { + String appdetawhere = adci.getScopeSqlByHrmResourceSearch(user.getUID() + "", true, "resource_hr"); + String tempstr = (appdetawhere != null && !"".equals(appdetawhere) ? (" and " + appdetawhere) : ""); + sqlwhere += tempstr; + } + + if (!"".equals(virtual) && -1 > Integer.valueOf(virtual)) { + sqlwhere += " and virtualtype=" + virtual; + + } + + + //二开修改考勤我的下属数据 ,这里没有参数判断是考勤页面,只能通过这两个参数临时处理 + String fromModule = Util.null2String(params.get("fromModule")); + String fieldid = Util.null2String(params.get("fieldid")); + if(!StringUtils.isNotBlank(fromModule) && !StringUtils.isNotBlank(fieldid) ){ + sqlfrom += ",(select a.id,b.field89,c.kqwy from hrmresource a left join cus_fielddata b on a.id=b.id and b.scope='HrmCustomFieldByInfoType' and b.scopeid=-1 left join hrmdepartmentdefined c on a.departmentid=c.deptid) t"; + if (alllevel.equals("1")) { + sqlwhere += " and hr.id = t.id and (field89="+ids+" or hr.managerstr like '%," + ids + ",%' or kqwy="+ids+") "; + }else{ + sqlwhere += " and hr.id = t.id and (field89="+ids+" or hr.managerid="+ids+" or kqwy="+ids+") "; + } + + }else{ + if (alllevel.equals("1")) { + // 显示所有下属 + sqlwhere += " and hr.managerstr like '%," + ids + ",%'"; + } else { + sqlwhere += " and hr.managerid = " + ids + " "; + } + } + + String backfields = " hr.id as id," + String.join(",", this.getDisplayFields()) + ", dsporder"; + + String lastsql = "select " + + backfields + + ",ROW_NUMBER() OVER(order by dsporder asc,lastname asc)rn from " + + sqlfrom + sqlwhere; + lastsql = getSearchSQL(params, lastsql, user); + writeLog("lastsql====>"+lastsql); + + + // 拼接插入参数; + List getList = new ArrayList(); + getList.add("id"); + getList.addAll(getDisplayFields()); +// getList.add("lastname"); +// getList.add("pinyinlastname"); +// getList.add("jobtitle"); +// getList.add("dsporder"); +// getList.add("workcode"); + List> getRList = d.getNewlyList(lastsql, min, max, getList); + int count = d.getCount(lastsql); + jo.put("status", true); + if (null != getRList && 0 < getRList.size()) { + getRList = EditGetMap(getRList); + jo.put("datas", getRList); + jo.put("count", count); + } else { + + jo.put("datas", new ArrayList()); + jo.put("count", 0); + } + } catch (Exception e) { + writeLog(e); + } + + return jo; + } + + private Map getbranchList4WorkPlan(Map params) { + Map jo = new HashMap<>(); + jo.put("status", false); + try { + AppDetachComInfo adci = new AppDetachComInfo(); + RecordSet rs = new RecordSet(); + Dao_Hrm4Ec d = null; + if (!"oracle".equals(rs.getDBType())) { + d = Dao_Hrm4EcFactory.getInstance().getDao("Dao_Hrm4EcSqlServer"); + } else { + d = Dao_Hrm4EcFactory.getInstance().getDao("Dao_Hrm4EcOracle"); + } + String virtual = Util.null2String(params.get("virtualtype")); + String min = Util.null2String(params.get("min")); + String max = Util.null2String(params.get("max")); + String lastname = Util.null2String(params.get("lastname")); + String isNoAccount = Util.null2String(params.get("isNoAccount"));// 是否显示无账号人员 + String alllevel = Util.null2String(params.get("alllevel"));// 是否显示子成员 + String ids = user.getUID() + ""; + String mobileResourceId = Util.null2String(params.get("mobileResourceId")); + if (!mobileResourceId.equals("")) { + ids = mobileResourceId; + } + if ("".equals(ids)) { + jo = getWrongCode(403, jo); + return jo; + } + + String whereClause = Util.null2String(params.get("sqlwhere")); + String sqlwhere = " where 1=1 "; + if (whereClause.length() != 0) sqlwhere += " and " + whereClause + " "; + WorkflowCommonService WorkflowCommonService = new WorkflowCommonServiceImpl(); + params.put("tableAlias", "hr"); + Map dataRanage = WorkflowCommonService.getDataDefinitionDataRanageSet(params, user, 1); + String dataRanageResourceIds = Util.null2String(dataRanage.get("sqlWhere")); + if (dataRanageResourceIds.length() > 0) { + sqlwhere += " " + dataRanageResourceIds; + } + String sqlfrom = "HrmResource hr "; + if (!"".equals(virtual) && -1 > Integer.valueOf(virtual)) { + sqlfrom = "HrmResourceVirtualView hr "; + } + // if (!"".equals(lastname)) { + // sqlwhere += "and( lastname like '%" + Util.fromScreen2(lastname, user.getLanguage()) + "%' or pinyinlastname like '%" + Util.fromScreen2(lastname, user.getLanguage()) + "%' or mobile like '%" + Util.fromScreen2(lastname, user.getLanguage()) + "%' or workcode like '%" + Util.fromScreen2(lastname, user.getLanguage())+ "%') "; + // } + // sqlwhere += " and (status =0 or status = 1 or status = 2 or status = 3) "; + if (!isNoAccount.equals("1")) { + sqlwhere += " and loginid is not null " + (rs.getDBType().equals("oracle") ? "" : " and loginid<>'' "); + } + + //增加应用分权控制 + if (adci.isUseAppDetach() && (Util.getIntValue(virtual) >= 0 || Util.getIntValue(virtual) == -10000)) { + String appdetawhere = adci.getScopeSqlByHrmResourceSearch(user.getUID() + "", true, "resource_hr"); + String tempstr = (appdetawhere != null && !"".equals(appdetawhere) ? (" and " + appdetawhere) : ""); + sqlwhere += tempstr; + } + + if (!"".equals(virtual) && -1 > Integer.valueOf(virtual)) { + sqlwhere += " and virtualtype=" + virtual; + + } + + if (alllevel.equals("1")) { + // 显示所有下属 + sqlwhere += " and hr.managerstr like '%," + ids + ",%'"; + } else { + sqlwhere += " and hr.managerid = " + ids + " "; + } + + String backfields = " hr.id as id," + String.join(",", this.getDisplayFields()) + ", dsporder"; + + String lastsql = "select " + + backfields + + ",ROW_NUMBER() OVER(order by dsporder asc,lastname asc)rn from " + + sqlfrom + sqlwhere; + lastsql = getSearchSQL(params, lastsql, user); + + // 拼接插入参数; + List getList = new ArrayList(); + getList.add("id"); + getList.addAll(getDisplayFields()); +// getList.add("lastname"); +// getList.add("pinyinlastname"); +// getList.add("jobtitle"); +// getList.add("dsporder"); +// getList.add("workcode"); + List> getRList = d.getNewlyList(lastsql, min, max, getList); + int count = d.getCount(lastsql); + jo.put("status", true); + if (null != getRList && 0 < getRList.size()) { + getRList = EditGetMap(getRList); + jo.put("datas", getRList); + jo.put("count", count); + } else { + + jo.put("datas", new ArrayList()); + jo.put("count", 0); + } + } catch (Exception e) { + writeLog(e); + } + + return jo; + } + + private List> EditGetMap(List> getRList) { + try { + PrivacyComInfo pc = new PrivacyComInfo(); + Map mapShowSets = pc.getMapShowSets(); + + DepartmentComInfo rsDepartment = new DepartmentComInfo(); + ResourceComInfo rci = new ResourceComInfo(); + SubCompanyComInfo scc = new SubCompanyComInfo(); + MutilResourceBrowser mrb = new MutilResourceBrowser(); + AccountType accountType = new AccountType(); + JobActivitiesComInfo jobActivitiesComInfo = new JobActivitiesComInfo(); + HrmTransMethod hrmTransMethod = new HrmTransMethod(); + JobTitlesComInfo jobTitlesComInfo = new JobTitlesComInfo(); + EncryptFieldViewScopeConfigComInfo encryptFieldViewScopeConfigComInfo = new EncryptFieldViewScopeConfigComInfo(); + if (null != getRList && 0 < getRList.size()) { + for (int i = 0; i < getRList.size(); i++) { + String userid = getRList.get(i).get("id"); + String departmentid = rci.getDepartmentID(userid); + String subcomid = rsDepartment.getSubcompanyid1(departmentid); + String supsubcomid = scc.getSupsubcomid(subcomid); + getRList.get(i).put("img", rci.getMessagerUrls(userid)); + getRList.get(i).put("messagerurl", rci.getMessagerUrls(userid)); + getRList.get(i).put("requestParams", rci.getUserIconInfoStr(userid,user)); + getRList.get(i).put("lastname", Util.formatMultiLang(getRList.get(i).get("lastname"))); + getRList.get(i).put("pinyinlastname", Util.formatMultiLang(getRList.get(i).get("pinyinlastname"))); + getRList.get(i).put("jobtitlename", mrb.getJobTitlesname(userid)); + getRList.get(i).put("departmentid", departmentid); + getRList.get(i).put("departmentname", rsDepartment.getDepartmentmark(departmentid)); + getRList.get(i).put("subcompanyid", subcomid); + getRList.get(i).put("subcompanyname", scc.getSubCompanyname(subcomid)); + getRList.get(i).put("supsubcompanyid", supsubcomid); + getRList.get(i).put("supsubcompanyname", scc.getSubCompanyname(supsubcomid)); + getRList.get(i).put("email", rci.getEmail(userid)); + for(Map m : browserFieldConfig){ + String fieldName = Util.null2String(m.get("fieldName")); + String fullPath = Util.null2String(m.get("fullPath")); + String fullPathDelimiter = Util.null2String(m.get("fullPathDelimiter")); + if(fullPathDelimiter.equals("")) + fullPathDelimiter = "|"; + else + fullPathDelimiter = "" + fullPathDelimiter + ""; + String orderType = Util.null2String(m.get("orderType")); + String key = fieldName + "span"; + switch(fieldName){ + case "departmentid": + String fullDeptPath = rsDepartment.getDepartmentRealPath(departmentid, fullPathDelimiter, orderType); + getRList.get(i).put(key, fullPath.equals("1") ? fullDeptPath : rsDepartment.getDepartmentmark(departmentid)); + break; + case "subcompanyid1": + getRList.get(i).put(key, fullPath.equals("1") ? scc.getSubcompanyRealPath(subcomid, fullPathDelimiter, orderType) : scc.getSubCompanyname(subcomid)); + break; + case "accounttype": + getRList.get(i).put(key, accountType.getAccountType(rci.getAccountType(userid), user.getLanguage() + "")); + break; + case "sex": + getRList.get(i).put(key, rci.getSexName(Util.null2String(getRList.get(i).get("sex")),""+user.getLanguage())); + break; + case "managerid": + getRList.get(i).put(key, rci.getResourcename(rci.getManagerID(userid))); + break; + case "assistantid": + getRList.get(i).put(key, rci.getResourcename(getRList.get(i).get("assistantid"))); + break; + case "jobtitle": + getRList.get(i).put(key, mrb.getJobTitlesname(userid)); + break; + case "status": + getRList.get(i).put(key, ResourceComInfo.getStatusName(Util.null2String(getRList.get(i).get("status")), user.getLanguage()+"")); + break; + case "jobactivity": + getRList.get(i).put(key, Util.null2String(jobActivitiesComInfo.getJobActivitiesname(jobTitlesComInfo.getJobactivityid(rci.getJobTitle(userid))))); + break; + case "orgid": + getRList.get(i).put(key, rsDepartment.getAllParentDepartmentBlankNames(departmentid, subcomid, "|")); + break; + case "jobcall": + getRList.get(i).put(key, Util.null2String(new JobCallComInfo().getJobCallname(rci.getJobCall(userid)))); + break; + case "jobGroupId": + String jobtitleid = rci.getJobTitle(userid) ; + String jobActivityId = new JobTitlesComInfo().getJobactivityid(jobtitleid); + String groupId = jobActivitiesComInfo.getJobgroupid(jobActivityId); + getRList.get(i).put(key, Util.null2String(new JobGroupsComInfo().getJobGroupsname(groupId))); + break; + case "joblevel": + getRList.get(i).put(key, Util.null2String(rci.getJoblevel(userid))); + break; + case "jobactivitydesc": + getRList.get(i).put(key, Util.null2String(rci.getJobActivityDesc(userid))); + break; + case "workroom": + getRList.get(i).put(key, Util.null2String(rci.getWorkroom(userid))); + break; + default: + String value = ""; + switch(fieldName){ + case "loginid": + value = rci.getLoginID(userid); + break; + case "workcode": + value = rci.getWorkcode(userid); + break; + case "lastname": + value = rci.getLastname(userid); + break; + case "locationid": + value = rci.getLocationid(userid); + break; + case "mobile": + value = encryptFieldViewScopeConfigComInfo.fieldCanView(""+user.getUID(),"hrmresource","mobile")? EncryptConfigBiz.getDecryptData(rci.getMobile(userid)):rci.getMobile(userid); + break; + case "telephone": + value = encryptFieldViewScopeConfigComInfo.fieldCanView(""+user.getUID(),"hrmresource","telephone")? EncryptConfigBiz.getDecryptData(rci.getTelephone(userid)):rci.getTelephone(userid); + break; + case "mobilecall": + value = encryptFieldViewScopeConfigComInfo.fieldCanView(""+user.getUID(),"hrmresource","mobilecall")? EncryptConfigBiz.getDecryptData(rci.getMobileCall(userid)):rci.getMobileCall(userid); + break; + case "fax": + value = encryptFieldViewScopeConfigComInfo.fieldCanView(""+user.getUID(),"hrmresource","fax")? EncryptConfigBiz.getDecryptData(rci.getFax(userid)):rci.getFax(userid); + break; + case "email": + value = encryptFieldViewScopeConfigComInfo.fieldCanView(""+user.getUID(),"hrmresource","email")? EncryptConfigBiz.getDecryptData(rci.getEmail(userid)):rci.getEmail(userid); + break; + case "managerid": + value = rci.getManagerID(userid); + break; + case "assistantid": + value = rci.getAssistantID(userid); + break; + } + if (mapShowSets != null && mapShowSets.get(fieldName) != null) { + getRList.get(i).put(key, pc.getSearchContent(Util.null2String(value), (userid + "+" + user.getUID() + "+" + fieldName))); + } else { + getRList.get(i).put(key, hrmTransMethod.getDefineContent(Util.null2String(value), fieldName + ":" + user.getLanguage())); + } + break; + } + } + } + } + } catch (Exception e) { + writeLog(e); + } + return getRList; + } + + private Map addList(Map params) { + Map jo = new HashMap<>(); + jo.put("status", false); + + try { + AppDetachComInfo adci = new AppDetachComInfo(); + RecordSet rs = new RecordSet(); + Dao_Hrm4Ec d = null; + if (!"oracle".equals(rs.getDBType())) { + d = Dao_Hrm4EcFactory.getInstance().getDao("Dao_Hrm4EcSqlServer"); + } else { + d = Dao_Hrm4EcFactory.getInstance().getDao("Dao_Hrm4EcOracle"); + } + + String ids = Util.null2String(params.get("ids")); + String id = Util.null2String(params.get("id")); + if ("".equals(id)) { + int ida = user.getUID(); + if (0 == ida) { + jo = getWrongCode(402, jo); + return jo; + } + id = String.valueOf(ida); + } + if ("".equals(ids)) { + jo = getWrongCode(403, jo); + } else { + String[] idslist = ids.split(","); + Map getMap = new HashMap(); + getMap.put("resourceid", id); + + for (int i = 0; i < idslist.length; i++) { + getMap.put("selectid", idslist[i]); + if (i > 20) + break; + d.deleteObjectSql("HrmResourceSelectRecord", getMap); + d.insertObjectSql("HrmResourceSelectRecord", getMap); + } + d.deleteRecord(id); + jo.put("status", true); + } + } catch (Exception e) { + writeLog(e); + } + + return jo; + } + + private Map getcompanyvirtual(Map params) { + JSONObject jo = new JSONObject(); + jo.put("status", false); + try { + String workplan = Util.null2String(params.get("workplan")); + String type = Util.null2String(params.get("type")); + + if("".equals(workplan) || ("1".equals(workplan) && "v2resourcetree".equals(type))) { + AppDetachComInfo adci = new AppDetachComInfo(); + RecordSet rs = new RecordSet(); + Dao_Hrm4Ec d = null; + if (!"oracle".equals(rs.getDBType())) { + d = Dao_Hrm4EcFactory.getInstance().getDao("Dao_Hrm4EcSqlServer"); + } else { + d = Dao_Hrm4EcFactory.getInstance().getDao("Dao_Hrm4EcOracle"); + } + HrmComVirtualBean hb = new HrmComVirtualBean(); + hb.setId(1); + hb.setShoworder("0"); + int language = 7; + if (user != null) { + language = user.getLanguage(); + } + hb.setVirtualdesc(SystemEnv.getHtmlLabelName(83179, language)); + hb.setVirtualtype(SystemEnv.getHtmlLabelName(83179, language)); + List getList = new ArrayList(); + getList.add(hb); + getList.addAll(d.gethrmcompanyvirtualList()); + jo.put("status", true); + jo.put("datas", getList); + }else{ + if(!"".equals(type)) + jo.put("status", true); + List list = new ArrayList(); + HrmComVirtualBean hb = null; + switch (type){ + case "underling": + hb = new HrmComVirtualBean(); + hb.setId(0); + hb.setShoworder("0"); + hb.setVirtualdesc(SystemEnv.getHtmlLabelName(21837, user.getLanguage())); + hb.setVirtualtype(SystemEnv.getHtmlLabelName(21837, user.getLanguage())); + list.add(hb); + + hb = new HrmComVirtualBean(); + hb.setId(1); + hb.setShoworder("1"); + hb.setVirtualdesc(SystemEnv.getHtmlLabelName(522006, user.getLanguage())); + hb.setVirtualtype(SystemEnv.getHtmlLabelName(522006, user.getLanguage())); + list.add(hb); + break; + case "branch": + hb = new HrmComVirtualBean(); + hb.setId(0); + hb.setShoworder("0"); + hb.setVirtualdesc(SystemEnv.getHtmlLabelName(81863, user.getLanguage())); + hb.setVirtualtype(SystemEnv.getHtmlLabelName(81863, user.getLanguage())); + list.add(hb); + + hb = new HrmComVirtualBean(); + hb.setId(1); + hb.setShoworder("1"); + hb.setVirtualdesc(SystemEnv.getHtmlLabelName(17494, user.getLanguage())); + hb.setVirtualtype(SystemEnv.getHtmlLabelName(17494, user.getLanguage())); + list.add(hb); + break; + } + jo.put("datas", list); + } + } catch (Exception e) { + writeLog(e); + } + return jo; + + } + + private Map getv2resource(Map params) { + Map jo = new HashMap<>(); + jo.put("status", false); + + HrmOrgForwardBean hrmOrgForwardBean = localHrmOrgForwardBean.get(); + if (hrmOrgForwardBean != null) hrmOrgForwardBean.checkInited(true); + + try { + ResourceComInfo resourceComInfo = new ResourceComInfo(); + CompanyComInfo cci = new CompanyComInfo(); + CompanyVirtualComInfo cvci = new CompanyVirtualComInfo(); + SubCompanyVirtualComInfo scvc = new SubCompanyVirtualComInfo(); + + if (null == user) { + jo = getWrongCode(402, jo); + return jo; + } + String id = Util.null2String(params.get("id")); + String isNoAccount = Util.null2String(params.get("isNoAccount")); + String sqlwhere = Util.null2String(params.get("sqlwhere")); + String selectedids = Util.null2String(params.get("selectedids")); + String virtualtype = Util.null2String(params.get("virtualtype")); + String type = Util.null2String(params.get("type")); + String alllevel = Util.null2String(params.get("alllevel")); + String cmd = Util.null2String(params.get("cmd")); + + WorkflowCommonService WorkflowCommonService = new WorkflowCommonServiceImpl(); + params.put("tableAlias", "hr"); + Map dataRanage = WorkflowCommonService.getDataDefinitionDataRanageSet(params, user, 1); + String dataRanageResourceIds = Util.null2String(dataRanage.get("sqlWhere")); + if (dataRanageResourceIds.length() > 0) { + sqlwhere += " " + dataRanageResourceIds; + } + + List selectList = new ArrayList(); + if (selectedids.length() > 0) { + String[] tmp_selectedids = selectedids.split(","); + for (String selectedid : tmp_selectedids) { + selectList.add(selectedid); + } + } + if(this.rightStr.equals("Execution:PerformanceSet") || this.rightStr.equals("Execution:ReportSet")){ + this.getSubCompanyTreeListByRight(user.getUID(),this.rightStr);//加载分权数据 + } + //todo + String resultString = ""; + TreeNode envelope = new TreeNode(); + if (cmd.equals("getNum")) { + String nodeids = Util.null2String(params.get("nodeids")); + resultString = getResourceNumJson(nodeids, selectList, sqlwhere); + jo.put("status", true); + jo.put("datas", resultString); + } else { + if (id.equals("")) { + // 初始化 + String companyname = ""; + TreeNode root = new TreeNode(); + if(Util.getIntValue(virtualtype, 1) >= 0) + companyname = cci.getCompanyname("1"); + else + companyname = cvci.getVirtualType(virtualtype); + root.setLastname(companyname); + if (!"".equals(virtualtype) && !"1".equals(virtualtype)) { + root.setId(virtualtype); + root.setNodeid("com_" + virtualtype + "x"); + } else { + root.setNodeid("com_" + 1 + "x"); + root.setId("0"); + } + + root.setOpen("true"); + root.setTarget("_self"); + root.setIcon("/images/treeimages/global_wev8.gif"); + root.setType("com"); + getV2SubCompanyTreeList(root, "0", virtualtype, selectList, isNoAccount, user, sqlwhere); + + jo.put("status", true); + jo.put("datas", root); + } else if (type.equals("com") || type.equals("subcom")) { + if (!"".equals(virtualtype) && !"1".equals(virtualtype)) { + virtualtype = scvc.getCompanyid(id); + } + + getV2SubCompanyTreeList(envelope, id, virtualtype, selectList, isNoAccount, user, sqlwhere); + ArrayList lsChild = envelope.getChildren(); + + jo.put("status", true); + jo.put("datas", lsChild); + } else if (type.equals("dept")) { + String subId = ""; + if (!"".equals(virtualtype) && !"1".equals(virtualtype)) { + DepartmentVirtualComInfo DepartmentComInfo = new DepartmentVirtualComInfo(); + subId = DepartmentComInfo.getSubcompanyid1(id); + } else { + DepartmentComInfo DepartmentComInfo = new DepartmentComInfo(); + subId = DepartmentComInfo.getSubcompanyid1(id); + } + + getV2DepartTreeList(envelope, subId, id, selectList, isNoAccount, user, sqlwhere, virtualtype); + ArrayList lsChild = envelope.getChildren(); + /** + * 浏览按钮自定义显示字段 + */ + List ids = new ArrayList(); + for(TreeNode tn : lsChild){ + if(tn.getType().equals("resource")) + ids.add(tn.getId()); + } + Map> map = new HashMap(); + if(ids.size() > 0){ + for(String resourceId : ids){ + Map userInfo = getUserInfo(resourceId, user, false); + map.put(resourceId, userInfo); + } + } + JSONArray jsonArray = (JSONArray)JSONArray.toJSON(lsChild); + for(int i = 0; i < jsonArray.size(); i++){ + JSONObject jsonObject = (JSONObject)jsonArray.get(i); + String k = jsonObject.getString("id"); + String loopType = jsonObject.getString("type") ; + if(map.containsKey(k) && "resource".equals(loopType)) { + jsonObject.putAll(map.get(k)); +// jsonObject.put("columnControled", true); + } + } + jo.put("status", true); + jo.put("datas", jsonArray); + } + } + + } catch (Exception e) { + writeLog(e); + } + return jo; + } + + private TreeNode getV2DepartTreeList(TreeNode departTreeList, String subId, String departmentId, List selectedids, String isNoAccount, User user, String sqlwhere, String vituraltype) throws Exception { + AppDetachComInfo adci = new AppDetachComInfo(user); + + if (!"".equals(vituraltype) && !"1".equals(vituraltype)) { + if (Util.getIntValue(departmentId) < 0) { + getResourceTreeListV2(departTreeList, departmentId, selectedids, isNoAccount, user, sqlwhere, vituraltype); + } + + DepartmentVirtualComInfo rsDepartment = new DepartmentVirtualComInfo(); + rsDepartment.setTofirstRow(); + while (rsDepartment.next()) { + if (departmentId.equals(rsDepartment.getDepartmentid())) { + continue; + } + String supdepid = rsDepartment.getDepartmentsupdepid(); + if (departmentId.equals("0") && supdepid.equals("")) { + supdepid = "0"; + } + if (!(rsDepartment.getSubcompanyid1().equals(subId) && (supdepid.equals(departmentId) + || (!rsDepartment.getSubcompanyid1(supdepid).equals(subId) && departmentId.equals("0"))))) { + continue; + } + String id = rsDepartment.getDepartmentid(); + + if (this.dataRanageAllDepartmentIds != null && !this.dataRanageAllDepartmentIds.isEmpty()) { + if (!this.dataRanageAllDepartmentIds.contains(id)) { + continue; + } + } + + //if (!ObjtypeComparor.isSourceHasTarget(localHrmOrgForwardBean.get(), SimpleObjtypeInfo.initDepartment(id, OrgUpOrDownTypeStyle.ORG_ALL_DOWN))) { + // continue; + //} + + + String name = Util.formatMultiLang(rsDepartment.getDepartmentmark()); + String canceled = rsDepartment.getDeparmentcanceled(); + + if (adci.isUseAppDetach()) { + if ((Util.getIntValue(vituraltype) >= 0 || Util.getIntValue(vituraltype) == -10000) && adci.checkUserAppDetach(id, "3") == 0) { + continue; + } + } + + TreeNode departmentNode = new TreeNode(); + departmentNode.setLastname(name); + departmentNode.setNocheck("Y"); + departmentNode.setId(id); + departmentNode.setNodeid("dept_" + id + "x"); + departmentNode.setType("dept"); + departmentNode.setIcon("/images/treeimages/subCopany_Colse_wev8.gif"); + if (hasChild("dept", id)) { + departmentNode.setIsParent("true"); + } + if (!"1".equals(canceled)) { + departTreeList.AddChildren(departmentNode); + } + } + } else { + if (departmentId.length() > 0) { + getResourceTreeListV2(departTreeList, departmentId, selectedids, isNoAccount, user, sqlwhere, ""); + } + DepartmentComInfo rsDepartment = new DepartmentComInfo(); + rsDepartment.setTofirstRow(); + while (rsDepartment.next()) { + String id = rsDepartment.getDepartmentid(); + + if (this.dataRanageAllDepartmentIds != null && !this.dataRanageAllDepartmentIds.isEmpty()) { + if (!this.dataRanageAllDepartmentIds.contains(id)) { + continue; + } + } + if((this.rightStr.equals("Execution:PerformanceSet") || this.rightStr.equals("Execution:ReportSet"))&&!this.checkBlogAppSetting("dept",this.rightStr,id)){ + continue; + } + + if (departmentId.equals(rsDepartment.getDepartmentid())) { + continue; + } + String supdepid = rsDepartment.getDepartmentsupdepid(); + + String name = Util.formatMultiLang(rsDepartment.getDepartmentmark()); + String canceled = rsDepartment.getDeparmentcanceled(); + if (departmentId.equals("0") && supdepid.equals("")) { + supdepid = "0"; + } + if (!(rsDepartment.getSubcompanyid1().equals(subId) && (supdepid.equals(departmentId) + || (!rsDepartment.getSubcompanyid1(supdepid).equals(subId) && departmentId.equals("0"))))) { + continue; + } + + if (adci.isUseAppDetach()) { + if ((Util.getIntValue(vituraltype) >= 0 ) && adci.checkUserAppDetach(id, "3") == 0) { + continue; + } + } + + if (!ObjtypeComparor.isSourceHasTarget(localHrmOrgForwardBean.get(), SimpleObjtypeInfo.initDepartment(id, OrgUpOrDownTypeStyle.ORG_ALL_DOWN))) { + continue; + } + + TreeNode departmentNode = new TreeNode(); + departmentNode.setLastname(name); + + departmentNode.setNocheck("Y"); + departmentNode.setId(id); + departmentNode.setNodeid("dept_" + id + "x"); + departmentNode.setType("dept"); + departmentNode.setIcon("/images/treeimages/subCopany_Colse_wev8.gif"); + if (hasChild("dept", id)) { + departmentNode.setIsParent("true"); + } + if (!"1".equals(canceled)) { + departTreeList.AddChildren(departmentNode); + } + } + } + + return departTreeList; + } + + private TreeNode getResourceTreeListV2(TreeNode resourceTreeList, String departmentId, List selectedids, String isNoAccount, User user, String sqlwhere, String vituraltype) throws Exception { + try { + RecordSet rs = new RecordSet(); + AppDetachComInfo adci = new AppDetachComInfo(); + ResourceComInfo rci = new ResourceComInfo(); + MutilResourceBrowser mrb = new MutilResourceBrowser(); + SubCompanyComInfo scc = new SubCompanyComInfo(); + + Dao_Hrm4Ec d = null; + if (!"oracle".equals(rs.getDBType())) { + d = Dao_Hrm4EcFactory.getInstance().getDao("Dao_Hrm4EcSqlServer"); + } else { + d = Dao_Hrm4EcFactory.getInstance().getDao("Dao_Hrm4EcOracle"); + } + + DepartmentComInfo rsDepartment = new DepartmentComInfo(); + rsDepartment.setTofirstRow(); + if (!"".equals(vituraltype)) { + String sql = " select hr.id, hr.loginid, hr.account, lastname, hr.pinyinlastname, hr.subcompanyid1, hr.jobtitle,hr.workcode, hr.mobile" + + " from hrmresource hr " + "where 1=1 "; + if (sqlwhere.length() > 0) { + if (sqlwhere.trim().startsWith("and")) { + sqlwhere = " " + sqlwhere; + } else { + sqlwhere = " and " + sqlwhere; + } + } + + sqlwhere += " and hr.status in (0,1,2,3)"; + if (!isNoAccount.equals("1")) { + sqlwhere += " and loginid is not null " + (rs.getDBType().equals("oracle") ? "" : " and loginid<>'' "); + } + if (adci.isUseAppDetach()) { + String appdetawhere = adci.getScopeSqlByHrmResourceSearch(user.getUID() + "", true, "resource_hr"); + String tempstr = (appdetawhere != null && !"".equals(appdetawhere) ? (" and " + appdetawhere) : ""); + sqlwhere += tempstr; + } + if (sqlwhere.length() > 0) + sql += sqlwhere; + sql += "and exists (select * from hrmresourcevirtual where hr.id = resourceid and departmentid=" + + departmentId + ") order by hr.dsporder, hr.id "; + + resourceTreeList = d.getHrmResourceV2(resourceTreeList, sql, isNoAccount, selectedids); + if (null != resourceTreeList) { + int j = resourceTreeList.getChildren().size(); + for (int i = 0; i < j; i++) { + String id = resourceTreeList.getChildren().get(i).getId(); + String subcomid = rsDepartment.getSubcompanyid1(rci.getDepartmentID(id)); + String supsubcomid = scc.getSupsubcomid(subcomid); + resourceTreeList.getChildren().get(i).setDepartmentname(rsDepartment.getDepartmentmark(rci.getDepartmentID(id))); + resourceTreeList.getChildren().get(i).setSubcompanyname(scc.getSubCompanyname(subcomid)); + resourceTreeList.getChildren().get(i).setSupsubcompanyname(scc.getSubCompanyname(supsubcomid)); + resourceTreeList.getChildren().get(i).setIcon(rci.getMessagerUrls(id)); + resourceTreeList.getChildren().get(i).setRequestParams(rci.getUserIconInfoStr(id,user)); + resourceTreeList.getChildren().get(i).setJobtitlename(mrb.getJobTitlesname(id)); + } + } + } else { + String sql = "select hr.id, lastname, hr.pinyinlastname, hr.subcompanyid1, hr.jobtitle, loginid, account ,hr.workcode,hr.mobile,hr.departmentid" + + " from hrmresource hr, hrmdepartment t2 " + + " where hr.departmentid=t2.id and t2.id=" + departmentId; + if (sqlwhere.length() > 0) { + if(sqlwhere.trim().startsWith("and id in")) + sqlwhere = sqlwhere.replaceFirst("id in", "hr.id in"); + if (sqlwhere.trim().startsWith("and")) { + sqlwhere = " " + sqlwhere; + } else { + sqlwhere = " and " + sqlwhere; + } + } + sqlwhere += " and hr.status in (0,1,2,3)"; + if (!isNoAccount.equals("1")) { + sqlwhere += " and loginid is not null " + (rs.getDBType().equals("oracle") ? "" : " and loginid<>'' "); + } + if (adci.isUseAppDetach()) { + String appdetawhere; + appdetawhere = adci.getScopeSqlByHrmResourceSearch(user.getUID() + "", true, "resource_hr"); + + String tempstr = (appdetawhere != null && !"".equals(appdetawhere) ? (" and " + appdetawhere) : ""); + sqlwhere += tempstr; + } + if (sqlwhere.length() > 0) + sql += sqlwhere; + sql += " order by hr.dsporder "; + resourceTreeList = d.getHrmResourceV2(resourceTreeList, sql, isNoAccount, selectedids); + if (null != resourceTreeList) { + int j = resourceTreeList.getChildren().size(); + for (int i = 0; i < j; i++) { + String id = resourceTreeList.getChildren().get(i).getId(); + String subcomid = rsDepartment.getSubcompanyid1(rci.getDepartmentID(id)); + String supsubcomid = scc.getSupsubcomid(subcomid); + resourceTreeList.getChildren().get(i).setDepartmentname(rsDepartment.getDepartmentmark(rci.getDepartmentID(id))); + resourceTreeList.getChildren().get(i).setSubcompanyname(scc.getSubCompanyname(subcomid)); + resourceTreeList.getChildren().get(i).setSupsubcompanyname(scc.getSubCompanyname(supsubcomid)); + resourceTreeList.getChildren().get(i).setIcon(rci.getMessagerUrls(id)); + resourceTreeList.getChildren().get(i).setRequestParams(rci.getUserIconInfoStr(id,user)); + resourceTreeList.getChildren().get(i).setJobtitlename(mrb.getJobTitlesname(id)); + } + } + } + } catch (Exception e) { + writeLog(e); + } + + return resourceTreeList; + } + + private TreeNode getV2SubCompanyTreeList(TreeNode companyTreeList, String subId, String virtualtype, List selectedids, String isNoAccount, User user, String sqlwhere) throws Exception { + getV2DepartTreeList(companyTreeList, subId, "0", selectedids, isNoAccount, user, sqlwhere, virtualtype); + AppDetachComInfo adci = new AppDetachComInfo(user); + + if (null != virtualtype && !"".equals(virtualtype) && !"1".equals(virtualtype)) { + SubCompanyVirtualComInfo scvc = new SubCompanyVirtualComInfo(); + scvc.setTofirstRow(); + while (scvc.next()) { + String id = scvc.getSubCompanyid(); + + if (this.dataRanageAllSubCompanyIds != null && !this.dataRanageAllSubCompanyIds.isEmpty()) { + if (!this.dataRanageAllSubCompanyIds.contains(id)) { + continue; + } + } + + String supsubcomid = scvc.getSupsubcomid(); + String tmp_virtualtype = scvc.getCompanyid(); + if (null != virtualtype && !"".equals(virtualtype) && !"1".equals(virtualtype)) { + if (!virtualtype.equals(tmp_virtualtype)) continue; + } + + if (supsubcomid.equals("")) + supsubcomid = "0"; + if (!supsubcomid.equals(subId)) + continue; + + if (adci.isUseAppDetach()) { + if ((Util.getIntValue(virtualtype) >= 0 || Util.getIntValue(virtualtype) == -10000) && adci.checkUserAppDetach(id, "2") == 0) { + continue; + } + } + + //if (!ObjtypeComparor.isSourceHasTarget(localHrmOrgForwardBean.get(), SimpleObjtypeInfo.initSubCompany(id, OrgUpOrDownTypeStyle.ORG_ALL_DOWN))) { + // writeLog(">>>>>>>"); + // continue; + //} + + String name = Util.formatMultiLang(scvc.getSubCompanyname()); + String canceled = scvc.getCompanyiscanceled(); + + TreeNode subCompanyNode = new TreeNode(); + subCompanyNode.setLastname(name); + subCompanyNode.setId(id); + subCompanyNode.setNodeid("subcom_" + id + "x"); + subCompanyNode.setPid(subId); + subCompanyNode.setIcon("/images/treeimages/Home_wev8.gif"); + subCompanyNode.setNocheck("N"); + subCompanyNode.setType("subcom"); + if (hasChild("subcompany", id)) { + subCompanyNode.setIsParent("true"); + } + + if (!"1".equals(canceled)) { + companyTreeList.AddChildren(subCompanyNode); + } + } + } else { + SubCompanyComInfo scvc = new SubCompanyComInfo(); + scvc.setTofirstRow(); + while (scvc.next()) { + String id = scvc.getSubCompanyid(); + + if (this.dataRanageAllSubCompanyIds != null && !this.dataRanageAllSubCompanyIds.isEmpty()) { + if (!this.dataRanageAllSubCompanyIds.contains(id)) { + continue; + } + } + //todo + if((this.rightStr.equals("Execution:PerformanceSet") || this.rightStr.equals("Execution:ReportSet"))&&!this.checkBlogAppSetting("com",this.rightStr,id)){ + continue; + } + + String supsubcomid = scvc.getSupsubcomid(); + String tmp_virtualtype = scvc.getCompanyid(); + if (null != virtualtype && !"".equals(virtualtype) + && !"1".equals(virtualtype)) { + if (!virtualtype.equals(tmp_virtualtype)) + continue; + } + + if (supsubcomid.equals("")) + supsubcomid = "0"; + if (!supsubcomid.equals(subId)) + continue; + + if (adci.isUseAppDetach()) { + if ((Util.getIntValue(virtualtype) >= 0 || Util.getIntValue(virtualtype) == -10000) && adci.checkUserAppDetach(id, "2") == 0) { + continue; + } + } + + if (!ObjtypeComparor.isSourceHasTarget(localHrmOrgForwardBean.get(), SimpleObjtypeInfo.initSubCompany(id, OrgUpOrDownTypeStyle.ORG_ALL_DOWN))) { + continue; + } + + String name = Util.formatMultiLang(scvc.getSubCompanyname()); + String canceled = scvc.getCompanyiscanceled(); + + TreeNode subCompanyNode = new TreeNode(); + subCompanyNode.setLastname(name); + subCompanyNode.setId(id); + subCompanyNode.setNodeid("subcom_" + id + "x"); + subCompanyNode.setPid(subId); + subCompanyNode.setIcon("/images/treeimages/Home_wev8.gif"); + subCompanyNode.setNocheck("N"); + subCompanyNode.setType("subcom"); + if (hasChild("subcompany", id)) { + subCompanyNode.setIsParent("true"); + } + + if (!"1".equals(canceled)) + companyTreeList.AddChildren(subCompanyNode); + } + } + + return companyTreeList; + } + + private String getResourceNumJson(String nodeids, List selectedids, String sqlwhere) throws Exception { + JSONArray jsonArr = new JSONArray(); + try { + RecordSet rs = new RecordSet(); + ResourceComInfo rci = new ResourceComInfo(); + MutilResourceBrowser mrb = new MutilResourceBrowser(); + SubCompanyComInfo scc = new SubCompanyComInfo(); + + Dao_Hrm4Ec d = null; + if (!"oracle".equals(rs.getDBType())) { + d = Dao_Hrm4EcFactory.getInstance().getDao("Dao_Hrm4EcSqlServer"); + } else { + d = Dao_Hrm4EcFactory.getInstance().getDao("Dao_Hrm4EcOracle"); + } + + String[] arr_nodeid = Util.TokenizerString2(nodeids, ","); + for (String nodeid : arr_nodeid) { + + String type = nodeid.split("_")[0]; + String id = nodeid.split("_")[1]; + String sql = "select count(*) from HrmResourceVirtualView hr where hr.status in (0,1,2,3) and 1=1 "; + JSONObject jo = d.getResourceNumJson(type, id, sql, sqlwhere, + selectedids); + if (null != jo) { + jo.put("nodeid", nodeid); + jsonArr.add(jo); + } + } + + } catch (Exception e) { + writeLog(e); + } + + return jsonArr.toString(); + } + + private Map getV2grouptree(Map params) throws Exception { + Map jo = new JSONObject(); + ResourceComInfo resourceComInfo = new ResourceComInfo(); + jo.put("status", false); + + try { + if (user == null) { + jo = getWrongCode(402, jo); + return jo; + } + boolean hasRight = HrmUserVarify.checkUserRight("CustomGroup:Edit", user); + jo.put("hasRight", hasRight ? 1 : 0); + MutilResourceBrowser mrb = new MutilResourceBrowser(); + String id = Util.null2String(params.get("id")); + String alllevel = Util.null2String(params.get("alllevel")); + String selectedids = Util.null2String(params.get("selectedids")); + String isNoAccount = Util.null2String(params.get("isNoAccount")); + String virtualtype = Util.null2String(params.get("virtualtype")); + String cmd = Util.null2String(params.get("cmd")); + String sqlwhere = Util.null2String(params.get("sqlwhere")); + selectedids = mrb.getExcludeSqlWhere(selectedids, alllevel, isNoAccount, user, sqlwhere); + String groupName = Util.null2String(params.get("groupName")); + String showNum = Util.null2String(params.get("showNum")); + + WorkflowCommonService WorkflowCommonService = new WorkflowCommonServiceImpl(); + params.put("tableAlias", "hr"); + Map dataRanage = WorkflowCommonService.getDataDefinitionDataRanageSet(params, user, 1); + String dataRanageResourceIds = Util.null2String(dataRanage.get("sqlWhere")); + if (dataRanageResourceIds.length() > 0) { + sqlwhere += " " + dataRanageResourceIds; + } + + List selectList = new ArrayList(); + if (selectedids.length() > 0) { + String[] tmp_selectedids = selectedids.split(","); + for (String selectedid : tmp_selectedids) { + selectList.add(selectedid); + } + } + JSONArray jsonArr = new JSONArray(); + String resultStr = ""; + if (cmd.equals("getComDeptResource")) { + String comdeptnodeids = Util.null2String(params.get("comdeptnodeids")); + String[] groupids = Util.TokenizerString2(comdeptnodeids, ","); + for (String groupid : groupids) { + getV2ResourceByGroupid(jsonArr, user, groupid, selectList, isNoAccount, sqlwhere, virtualtype); + } + resultStr = JSON.toJSONString(jsonArr); + jo.put("status", true); + jo.put("datas", resultStr); + } else if (cmd.equals("getAll")) { + jsonArr = getV2ResourceByGroupid(jsonArr, user, "-1", selectList, isNoAccount, sqlwhere, virtualtype); + resultStr = jsonArr.toString(); + jo.put("status", true); + jo.put("datas", resultStr); + } else if (cmd.equals("getNum")) { + String nodeids = Util.null2String(params.get("nodeids")); + resultStr = getV2ResourceJson(nodeids, selectList, user, isNoAccount, sqlwhere); + jo.put("status", true); + jo.put("datas", resultStr); + } else { + if (id.length() == 0) { + // init + TreeNode a = getV2GroupTree(user, selectList, isNoAccount, sqlwhere, showNum); + if (!groupName.equals("")) { + a = getV2GroupTree(user, selectList, isNoAccount, sqlwhere, groupName, showNum); + } + jo.put("status", true); + jo.put("datas", a); + } else { + List a = getV2ResourceTree(id, selectList, isNoAccount, user, sqlwhere, virtualtype); + /** + * 浏览按钮自定义显示字段 + */ + List ids = new ArrayList(); + for(TreeNode tn : a){ + if(tn.getType().equals("resource")) + ids.add(tn.getId()); + } + Map> map = new HashMap(); + if(ids.size() > 0){ + for(String resourceId : ids){ + Map userInfo = getUserInfo(resourceId, user, true); + map.put(resourceId, userInfo); + } + } + JSONArray jsonArray = (JSONArray)JSONArray.toJSON(a); + for(int i = 0; i < jsonArray.size(); i++){ + JSONObject jsonObject = (JSONObject)jsonArray.get(i); + String k = jsonObject.getString("id"); + if(map.containsKey(k)) { + jsonObject.putAll(map.get(k)); +// jsonObject.put("columnControled", true); + } + } + jo.put("status", true); + jo.put("datas", jsonArray); + + } + } + } catch (Exception e) { + writeLog(e); + } + + return jo; + } + + private Map gethrmstatus(Map params) throws Exception { + Map jo = new HashMap<>(); + jo.put("status", true); + + List> getMapList = new ArrayList(); + for (int i = 0; i < 5; i++) { + Map getMap = new HashMap(); + switch (i) { + case 0: + getMap.put("id", "9"); + getMap.put("order", "0"); + getMap.put("name", ""+ SystemEnv.getHtmlLabelName(82857,weaver.general.ThreadVarLanguage.getLang())+""); + break; + case 1: + getMap.put("id", "8"); + getMap.put("order", "1"); + getMap.put("name", ""+ SystemEnv.getHtmlLabelName(1831,weaver.general.ThreadVarLanguage.getLang())+""); + break; + case 2: + getMap.put("id", "0"); + getMap.put("order", "2"); + getMap.put("name", ""+ SystemEnv.getHtmlLabelName(15710,weaver.general.ThreadVarLanguage.getLang())+""); + break; + case 3: + getMap.put("id", "1"); + getMap.put("order", "3"); + getMap.put("name", ""+ SystemEnv.getHtmlLabelName(15711,weaver.general.ThreadVarLanguage.getLang())+""); + break; + case 4: + getMap.put("id", "2"); + getMap.put("order", "4"); + getMap.put("name", ""+ SystemEnv.getHtmlLabelName(480,weaver.general.ThreadVarLanguage.getLang())+""); + break; + } + getMapList.add(getMap); + } + if (1 == user.getUID()) { + for (int i = 0; i < 5; i++) { + Map getMap = new HashMap(); + switch (i) { + case 0: + getMap.put("id", "3"); + getMap.put("order", "5"); + getMap.put("name", ""+ SystemEnv.getHtmlLabelName(15844,weaver.general.ThreadVarLanguage.getLang())+""); + break; + case 1: + getMap.put("id", "4"); + getMap.put("order", "6"); + getMap.put("name", ""+ SystemEnv.getHtmlLabelName(6094,weaver.general.ThreadVarLanguage.getLang())+""); + break; + case 2: + getMap.put("id", "5"); + getMap.put("order", "7"); + getMap.put("name", ""+ SystemEnv.getHtmlLabelName(6091,weaver.general.ThreadVarLanguage.getLang())+""); + break; + case 3: + getMap.put("id", "6"); + getMap.put("order", "8"); + getMap.put("name", ""+ SystemEnv.getHtmlLabelName(6092,weaver.general.ThreadVarLanguage.getLang())+""); + break; + case 4: + getMap.put("id", "7"); + getMap.put("order", "9"); + getMap.put("name", ""+ SystemEnv.getHtmlLabelName(2245,weaver.general.ThreadVarLanguage.getLang())+""); + break; + } + getMapList.add(getMap); + } + } + jo.put("datas", getMapList); + return jo; + } + + private List getV2ResourceTree(String groupid, List selectedids, String isNoAccount, User user, String sqlwhere, String virtualtype) throws Exception { + TreeNode root = new TreeNode(); + try { + RecordSet rs = new RecordSet(); + AppDetachComInfo adci = new AppDetachComInfo(); + ResourceComInfo rci = new ResourceComInfo(); + DepartmentComInfo rsDepartment = new DepartmentComInfo(); + SubCompanyComInfo scc = new SubCompanyComInfo(); + MutilResourceBrowser mrb = new MutilResourceBrowser(); + + Dao_Hrm4Ec d = null; + if (!"oracle".equals(rs.getDBType())) { + d = Dao_Hrm4EcFactory.getInstance().getDao("Dao_Hrm4EcSqlServer"); + } else { + d = Dao_Hrm4EcFactory.getInstance().getDao("Dao_Hrm4EcOracle"); + } + String fromSql = "hrmresource"; + if (Util.getIntValue(virtualtype) < -1) + fromSql = "HrmResourcevirtualview"; + String sql = "select hr.id, lastname, hr.pinyinlastname, hr.subcompanyid1, hr.jobtitle, hr.loginid, hr.account ,hr.workcode, hr.mobile" + + " from " + + fromSql + + " hr, HrmGroupMembers t2 " + + " where hr.id= userid and groupid in (" + groupid + ")"; + if (Util.getIntValue(virtualtype) < -1) + sql += " and hr.virtualtype=" + virtualtype; + + if (sqlwhere.length() > 0) { + if(sqlwhere.trim().startsWith("and id in")) + sqlwhere = sqlwhere.replaceFirst("id in", "hr.id in"); + if (sqlwhere.trim().startsWith("and")) { + sqlwhere = " " + sqlwhere; + } else { + sqlwhere = " and " + sqlwhere; + } + } + sqlwhere += " and status in(0,1,2,3) "; + if(Util.null2String(params.get("from")).equals("ResourceBrowserDecService")) { + + }else{ + if (adci.isUseAppDetach()) { + String appdetawhere = adci.getScopeSqlByHrmResourceSearch(user.getUID() + "", true, "resource_hr"); + String tempstr = (appdetawhere != null && !"".equals(appdetawhere) ? (" and " + appdetawhere) : ""); + sqlwhere += tempstr; + } + } + /* + * 执行力管理分权增加控制,未开启,查询部门(包括下级)人员,分部(包括下级)人员, + * */ + if(this.rightStr.equals("Execution:PerformanceSet") || this.rightStr.equals("Execution:ReportSet")){ + String appdetawhere = checkBlogAppLoadSub(this.rightStr); + String tempstr = (appdetawhere != null && !"".equals(appdetawhere) ? (appdetawhere) : ""); + sqlwhere += tempstr; + } + if (sqlwhere.length() > 0) + sql += sqlwhere; + String noAccountSql = ""; + if (!isNoAccount.equals("1")) { + noAccountSql = " and loginid is not null " + (rs.getDBType().equals("oracle") ? "" : " and loginid<>'' "); + } + sql += noAccountSql; + + sql += " order by t2.dsporder"; + root = d.getHrmResourceV2(root, sql, isNoAccount, selectedids); + if (null != root) { + int j = root.getChildren().size(); + for (int i = 0; i < j; i++) { + String id = root.getChildren().get(i).getId(); + String subcomid = rsDepartment.getSubcompanyid1(rci.getDepartmentID(id)); + String supsubcomid = scc.getSupsubcomid(subcomid); + root.getChildren().get(i).setDepartmentname( + rsDepartment.getDepartmentmark(rci.getDepartmentID(id))); + root.getChildren().get(i).setSubcompanyname(scc.getSubCompanyname(subcomid)); + root.getChildren().get(i).setSupsubcompanyname( + scc.getSubCompanyname(supsubcomid)); + root.getChildren().get(i).setIcon(rci.getMessagerUrls(id)); + root.getChildren().get(i).setRequestParams(rci.getUserIconInfoStr(id,user)); + root.getChildren().get(i).setJobtitlename(mrb.getJobTitlesname(id)); + if(Util.null2String(params.get("from")).equals("ResourceBrowserDecService")) { + root.getChildren().get(i).setCanClick("true"); + root.getChildren().get(i).setIsImgIcon(false); + root.getChildren().get(i).setName(rci.getLastname(id)); + } + } + } + } catch (Exception e) { + writeLog(e); + } + return root.getChildren(); + } + + private TreeNode getV2GroupTree(User user, List selectList, String isNoAccount, String sqlwhere, String showNum) throws Exception { + TreeNode root = new TreeNode(); + try { + RecordSet rs = new RecordSet(); + Dao_Hrm4Ec d = null; + if (!"oracle".equals(rs.getDBType())) { + d = Dao_Hrm4EcFactory.getInstance().getDao("Dao_Hrm4EcSqlServer"); + } else { + d = Dao_Hrm4EcFactory.getInstance().getDao("Dao_Hrm4EcOracle"); + } + + root.setId("-1"); + root.setNodeid("group_-1x"); + root.setLastname(SystemEnv.getHtmlLabelName(17620, user.getLanguage())); + root.setName(root.getLastname()); + root.setOpen("true"); + root.setType("group"); + root.setIcon("/images/treeimages/Home_wev8.gif"); + root.setCanClick("false"); + root.setDisabledCheck(true); + root.setIsParent("true"); + + // 公共组 + TreeNode node = new TreeNode(); + node.setId("-2"); + node.setNodeid("group_-2x"); + node.setLastname(SystemEnv.getHtmlLabelName(17619, user.getLanguage())); + node.setName(node.getLastname()); + node.setOpen("true"); + node.setIcon("/images/treeimages/Home_wev8.gif"); + node.setType("group"); + node.setCanClick("false"); + node.setIsPrivate("false"); + node.setDisabledCheck(true); + node = d.getV2GroupList(node, user, isNoAccount, sqlwhere, showNum); + if(node.getChildren().size()>0){ + node.setIsParent("true"); + } + root.AddChildren(node); + + // 私人组 + TreeNode prinode = new TreeNode(); + prinode.setId("-3"); + prinode.setNodeid("group_-3x"); + prinode.setLastname(SystemEnv.getHtmlLabelName(17618, user.getLanguage())); + prinode.setName(prinode.getLastname()); + prinode.setOpen("true"); + prinode.setType("group"); + prinode.setIcon("/images/treeimages/Home_wev8.gif"); + prinode.setCanClick("false"); + prinode.setIsPrivate("true"); + prinode.setDisabledCheck(true); + prinode = d.getV2ServiceList(prinode, user, isNoAccount, sqlwhere, showNum); + if(prinode.getChildren().size()>0){ + prinode.setIsParent("true"); + } + root.AddChildren(prinode); + } catch (Exception e) { + writeLog(e); + } + return root; + } + + private TreeNode getV2GroupTree(User user, List selectList, String isNoAccount, String sqlwhere,String groupName, String showNum) throws Exception { + TreeNode root = new TreeNode(); + try { + RecordSet rs = new RecordSet(); + Dao_Hrm4Ec d = null; + if (!"oracle".equals(rs.getDBType())) { + d = Dao_Hrm4EcFactory.getInstance().getDao("Dao_Hrm4EcSqlServer"); + } else { + d = Dao_Hrm4EcFactory.getInstance().getDao("Dao_Hrm4EcOracle"); + } + + root.setId("-1"); + root.setNodeid("group_-1x"); + root.setLastname(SystemEnv.getHtmlLabelName(17620, user.getLanguage())); + root.setName(root.getLastname()); + root.setOpen("true"); + root.setType("group"); + root.setIcon("/images/treeimages/Home_wev8.gif"); + root.setCanClick("false"); + + // 公共组 + TreeNode node = new TreeNode(); + node.setId("-2"); + node.setNodeid("group_-2x"); + node.setLastname(SystemEnv.getHtmlLabelName(17619, user.getLanguage())); + node.setName(node.getLastname()); + node.setOpen("true"); + node.setIcon("/images/treeimages/Home_wev8.gif"); + node.setType("group"); + node.setCanClick("false"); + node.setIsPrivate("false"); + node = d.getV2GroupList(node, user, isNoAccount, sqlwhere, groupName, showNum); + + root.AddChildren(node); + + // 私人组 + TreeNode prinode = new TreeNode(); + prinode.setId("-3"); + prinode.setNodeid("group_-3x"); + prinode.setLastname(SystemEnv.getHtmlLabelName(17618, user.getLanguage())); + prinode.setName(prinode.getLastname()); + prinode.setOpen("true"); + prinode.setType("group"); + prinode.setIcon("/images/treeimages/Home_wev8.gif"); + prinode.setCanClick("false"); + prinode.setIsPrivate("true"); + prinode = d.getV2ServiceList(prinode, user, isNoAccount, sqlwhere, groupName, showNum); + root.AddChildren(prinode); + } catch (Exception e) { + writeLog(e); + } + return root; + } + + private String getV2ResourceJson(String nodeids, List selectList, User user, String isNoAccount, String sqlwhere) throws Exception { + String[] arr_groupid = Util.TokenizerString2(nodeids, ","); + JSONArray jsonArr = new JSONArray(); + try { + RecordSet rs = new RecordSet(); + Dao_Hrm4Ec d = null; + if (!"oracle".equals(rs.getDBType())) { + d = Dao_Hrm4EcFactory.getInstance().getDao("Dao_Hrm4EcSqlServer"); + } else { + d = Dao_Hrm4EcFactory.getInstance().getDao("Dao_Hrm4EcOracle"); + } + + for (String groupid : arr_groupid) { + String nodeid = groupid; + if (groupid.equals("-1") || groupid.equals("-2") || groupid.equals("-3")) { + // 包含子节点 + if (groupid.equals("-1")) { + groupid = ""; + groupid = d.getAllGroupId(user, groupid); + } else if (groupid.equals("-2")) { + groupid = d.getPubGroupId(user, groupid); + } else if (groupid.equals("-3")) { + groupid = d.getPriGroupId(user, groupid); + } + + JSONObject jo = d.getV2Resource(sqlwhere, groupid, nodeid); + if (null != jo) { + jsonArr.add(jo); + } + } + } + } catch (Exception e) { + writeLog(e); + } + return jsonArr.toString(); + } + + private JSONArray getV2ResourceByGroupid(JSONArray jsonArr, User user, String groupid, List selectedids, String isNoAccount, String sqlwhere, String virtualtype) throws Exception { + String sql = ""; + try { + RecordSet rs = new RecordSet(); + AppDetachComInfo adci = new AppDetachComInfo(); + ResourceComInfo rci = new ResourceComInfo(); + DepartmentComInfo rsDepartment = new DepartmentComInfo(); + SubCompanyComInfo scc = new SubCompanyComInfo(); + MutilResourceBrowser mrb = new MutilResourceBrowser(); + + Dao_Hrm4Ec d = null; + if (!"oracle".equals(rs.getDBType())) { + d = Dao_Hrm4EcFactory.getInstance().getDao("Dao_Hrm4EcSqlServer"); + } else { + d = Dao_Hrm4EcFactory.getInstance().getDao("Dao_Hrm4EcOracle"); + } + // 包含子节点 + if (groupid.equals("-1")) { + groupid = ""; + groupid = d.getAllGroupId(user, groupid); + } else if (groupid.equals("-2")) { + groupid = d.getPubGroupId(user, groupid); + } else if (groupid.equals("-3")) { + groupid = d.getPriGroupId(user, groupid); + } + + String fromSql = "hrmresource"; + if (Util.getIntValue(virtualtype) < -1) + fromSql = "HrmResourcevirtualview"; + sql = "select hr.id, lastname, hr.pinyinlastname, hr.subcompanyid1, hr.jobtitle " + + " from " + + fromSql + + " hr, HrmGroupMembers t2 " + + " where hr.id= userid and groupid in (" + groupid + ")"; + if (Util.getIntValue(virtualtype) < -1) + sql += " and hr.virtualtype=" + virtualtype; + String ids = ""; + for (int i = 0; selectedids != null && i < selectedids.size(); i++) { + if (ids.length() > 0) + ids += ","; + ids += selectedids.get(i); + } + if (ids.length() > 0) + sql += " and userid not in (" + ids + ")"; + if (sqlwhere.length() > 0) { + if(sqlwhere.trim().startsWith("and id in")) + sqlwhere = sqlwhere.replaceFirst("id in", "hr.id in"); + if (sqlwhere.trim().startsWith("and")) { + sqlwhere = " " + sqlwhere; + } else { + sqlwhere = " and " + sqlwhere; + } + } + sqlwhere += " and status in(0,1,2,3) "; + if (adci.isUseAppDetach()) { + String appdetawhere = adci.getScopeSqlByHrmResourceSearch(user.getUID() + "", true, "resource_hr"); + String tempstr = (appdetawhere != null && !"".equals(appdetawhere) ? (" and " + appdetawhere) : ""); + sqlwhere += tempstr; + } + if (sqlwhere.length() > 0) + sql += sqlwhere; + + String noAccountSql = ""; + if (!isNoAccount.equals("1")) { + noAccountSql = " and loginid is not null " + (rs.getDBType().equals("oracle") ? "" : " and loginid<>'' "); + } + sql += noAccountSql; + + sql += " order by hr.dsporder"; + + /** + * 浏览按钮自定义显示字段 + */ + List resourceIds = new ArrayList(); + jsonArr = d.getV2ResList(sql, jsonArr, ids); + if (null != jsonArr && 0 < jsonArr.size()) { + for (int i = 0; i < jsonArr.size(); i++) { + JSONObject ja = jsonArr.getJSONObject(i); + ja.put("jobtitlename", mrb.getJobTitlesname(ja.getString("id"))); + ja.put("messagerurl", rci.getMessagerUrls(ja.getString("id"))); + String id = ja.getString("id"); + resourceIds.add(id); + String subcomid = rsDepartment.getSubcompanyid1(rci.getDepartmentID(id)); + String supsubcomid = scc.getSupsubcomid(subcomid); + ja.put("departmentid", rci.getDepartmentID(id)); + ja.put("departmentname", rsDepartment.getDepartmentmark(rci.getDepartmentID(id))); + ja.put("subcompanyid", subcomid); + ja.put("subcompanyname", scc.getSubCompanyname(subcomid)); + ja.put("supsubcompanyid", supsubcomid); + ja.put("supsubcompanyname", scc.getSubCompanyname(supsubcomid)); + ja.put("requestParams", rci.getUserIconInfoStr(id,user)); + } + } + Map> map = new HashMap(); + if(resourceIds.size() > 0){ + for(String resourceId : resourceIds){ + Map userInfo = getUserInfo(resourceId, user, true); + map.put(resourceId, userInfo); + } + } + for (int i = 0; i < jsonArr.size(); i++) { + JSONObject ja = jsonArr.getJSONObject(i); + String id = ja.getString("id"); + if(map.containsKey(id)) + ja.putAll(map.get(id)); + } + } catch (Exception e) { + writeLog(e); + } + return jsonArr; + } + + private List getDepartTreeList(List otl, String subId, String departmentId, String selectedids, String isNoAccount, User user, String sqlwhere) { + DepartmentComInfo rsDepartment = new DepartmentComInfo(); + AppDetachComInfo adci = new AppDetachComInfo(); + rsDepartment.setTofirstRow(); + if (departmentId.length() > 0) { + // 获取人员 + getResourceTreeList(otl, departmentId, selectedids, isNoAccount, + user, sqlwhere); + } + while (rsDepartment.next()) { + if (departmentId.equals(rsDepartment.getDepartmentid())) + continue; + String supdepid = rsDepartment.getDepartmentsupdepid(); + if (departmentId.equals("0") && supdepid.equals("")) + supdepid = "0"; + if (!(rsDepartment.getSubcompanyid1().equals(subId) && (supdepid + .equals(departmentId) || (!rsDepartment.getSubcompanyid1( + supdepid).equals(subId) && departmentId.equals("0"))))) + continue; + + String id = rsDepartment.getDepartmentid(); + String name = rsDepartment.getDepartmentmark(); + String canceled = rsDepartment.getDeparmentcanceled(); + Tree newtree = new Tree(); + newtree.setId("dept_" + id); + newtree.setPid("dept_" + supdepid); + newtree.setLastname(name); + newtree.setNocheck("Y"); + newtree.setIcon("/images/treeimages/subCopany_Colse_wev8.gif"); + if (hasChild("dept", id)) { + newtree.setIsParent("true"); + } + if (!"1".equals(canceled)) + otl.add(newtree); + } + + return otl; + } + + private List getResourceTreeList(List otl, String departmentId, String selectedids, String isNoAccount, User user, String sqlwhere) { + try { + RecordSet rs = new RecordSet(); + AppDetachComInfo adci = new AppDetachComInfo(); + ResourceComInfo rci = new ResourceComInfo(); + DepartmentComInfo rsDepartment = new DepartmentComInfo(); + SubCompanyComInfo scc = new SubCompanyComInfo(); + MutilResourceBrowser mrb = new MutilResourceBrowser(); + + Dao_Hrm4Ec d = null; + if (!"oracle".equals(rs.getDBType())) { + d = Dao_Hrm4EcFactory.getInstance().getDao("Dao_Hrm4EcSqlServer"); + } else { + d = Dao_Hrm4EcFactory.getInstance().getDao("Dao_Hrm4EcOracle"); + } + + String sql = "select hr.id, lastname, hr.pinyinlastname, hr.subcompanyid1, hr.jobtitle, loginid, account ,hr.departmentid" + + "from hrmresource hr, hrmdepartment t2 " + + "where hr.departmentid=t2.id and t2.id=" + departmentId; + if (sqlwhere.length() > 0) { + if(sqlwhere.trim().startsWith("and id in")) + sqlwhere = sqlwhere.replaceFirst("id in", "hr.id in"); + if (sqlwhere.trim().startsWith("and")) { + sqlwhere = " " + sqlwhere; + } else { + sqlwhere = " and " + sqlwhere; + } + } + sqlwhere += " and hr.status in (0,1,2,3)"; + if (adci.isUseAppDetach()) { + String appdetawhere; + appdetawhere = adci.getScopeSqlByHrmResourceSearch(user.getUID() + "", true, "resource_hr"); + String tempstr = (appdetawhere != null && !"".equals(appdetawhere) ? (" and " + appdetawhere) : ""); + sqlwhere += tempstr; + } + if (sqlwhere.length() > 0) + sql += sqlwhere; + sql += " order by hr.dsporder "; + List RSotl = d.getHrmResource(sql); + if (null != RSotl && 0 < RSotl.size()) { + for (int i = 0; i < RSotl.size(); i++) { + RSotl.get(i).setIcon(rci.getMessagerUrls(RSotl.get(i).getId())); + RSotl.get(i).setRequestParams(rci.getUserIconInfoStr(RSotl.get(i).getId(),user)); + } + } + otl.addAll(RSotl); + } catch (Exception e) { + writeLog(e); + } + return otl; + } + + /** + * 指定节点下是否有子节点 + * + * @param id 节点id + * @return boolean + * @throws Exception + */ + private boolean hasChild(String type, String id) { + boolean hasChild = false; + try { + ResourceComInfo rci = new ResourceComInfo(); + DepartmentComInfo rsDepartment = new DepartmentComInfo(); + SubCompanyComInfo scc = new SubCompanyComInfo(); + SubCompanyVirtualComInfo scvc = new SubCompanyVirtualComInfo(); + DepartmentVirtualComInfo dvci = new DepartmentVirtualComInfo(); + ResourceVirtualComInfo rvci = new ResourceVirtualComInfo(); + if (Util.getIntValue(id) < 0) { + if (type.equals("subcompany")) { + scvc.setTofirstRow(); + while (scvc.next()) { + if (scvc.getSupsubcomid().equals(id) && !"1".equals(scvc.getCompanyiscanceled())) + hasChild = true; + } + + dvci.setTofirstRow(); + while (dvci.next()) { + if (dvci.getSubcompanyid1().equals(id) && !"1".equals(dvci.getDeparmentcanceled())) { + hasChild = true; + } + } + } else if (type.equals("dept")) { + + dvci.setTofirstRow(); + while (dvci.next()) { + String str = dvci.getSubcompanyid1(id); + if (dvci.getSubcompanyid1().equals(str) && dvci.getDepartmentsupdepid().equals(id) && !"1".equals(dvci.getDeparmentcanceled())) + hasChild = true; + } + if (!hasChild) { + RecordSet rs = new RecordSet(); + rs.executeSql("select count(*) from HrmResourceVirtualView t1 where t1.status in (0,1,2,3) and t1.departmentid=" + id); + if (rs.next()) { + if (rs.getInt(1) > 0) { + hasChild = true; + } + } + } + } + } else { + if (type.equals("subcompany")) { + scc.setTofirstRow(); + while (scc.next()) { + if (scc.getSupsubcomid().equals(id) && !"1".equals(scc.getCompanyiscanceled())) + hasChild = true; + } + + rsDepartment.setTofirstRow(); + while (rsDepartment.next()) { + if (rsDepartment.getSubcompanyid1().equals(id) && !"1".equals(rsDepartment.getDeparmentcanceled())) { + hasChild = true; + } + } + } else if (type.equals("dept")) { + rsDepartment.setTofirstRow(); + while (rsDepartment.next()) { + String str = rsDepartment.getSubcompanyid1(id); + if (rsDepartment.getSubcompanyid1().equals(str) && rsDepartment.getDepartmentsupdepid().equals(id) && !"1".equals(rsDepartment.getDeparmentcanceled())) + hasChild = true; + } + if (!hasChild) { + rci.setTofirstRow(); + while (rci.next()) { + String str = rci.getDepartmentID(); + if (str.equals(id)) + hasChild = true; + } + } + } + } + } catch (Exception e) { + writeLog(e); + } + return hasChild; + } + + private Map getWrongCode(int errid, Map jo) { + jo.put("error", errid); + jo.put("status", "false"); + switch (errid) { + case 402: + jo.put("msg", ""+ SystemEnv.getHtmlLabelName(2011,weaver.general.ThreadVarLanguage.getLang())+""); + break; + case 403: + jo.put("msg", ""+ SystemEnv.getHtmlLabelName(501597,weaver.general.ThreadVarLanguage.getLang())+""); + break; + default: + jo.put("msg", ""+ SystemEnv.getHtmlLabelName(382011,weaver.general.ThreadVarLanguage.getLang())+""); + break; + } + return jo; + } + + private List getMobileTemplate(){ + List mobileShowTemplate = new ArrayList<>(); + int i = 0; + for(Map m : browserFieldConfig){ + Map c = new HashMap(); + String fieldName = String.valueOf(m.get("fieldName")); + c.put("dataIndex", fieldName + "span"); + c.put("showType", i % 2); + c.put("hide", "false"); + if(i == 0) + c.put("primary", "true"); + mobileShowTemplate.add(c); + i++; + } + return mobileShowTemplate; + } + + private List getMobileShowTemplate() { + List mobileShowTemplate = new ArrayList<>(); + Map col = null; + List colConfigs = null; + Map colRow = null; + List colRowConfigs = null; + Map cell = null; + + col = new HashMap<>(); + col.put("key", "col1"); + colConfigs = new ArrayList(); + col.put("configs", colConfigs); + colRow = new HashMap<>(); + colRow.put("key", "col1_row1"); + colRowConfigs = new ArrayList(); + colRow.put("configs", colRowConfigs); + colConfigs.add(colRow); + cell = new HashMap<>(); + cell.put("key", "lastname"); + colRowConfigs.add(cell); + + colRow = new HashMap<>(); + colRow.put("key", "col1_row2"); + colRowConfigs = new ArrayList(); + colRow.put("configs", colRowConfigs); + colConfigs.add(colRow); + cell = new HashMap<>(); + cell.put("key", "subcompanyname"); + colRowConfigs.add(cell); + mobileShowTemplate.add(col); + + col = new HashMap<>(); + col.put("key", "col2"); + colConfigs = new ArrayList(); + col.put("configs", colConfigs); + colRow = new HashMap<>(); + colRow.put("key", "col2_row1"); + colRowConfigs = new ArrayList(); + colRow.put("configs", colRowConfigs); + colConfigs.add(colRow); + cell = new HashMap<>(); + cell.put("key", "jobtitlename"); + colRowConfigs.add(cell); + + colRow = new HashMap<>(); + colRow.put("key", "col2_row2"); + colRowConfigs = new ArrayList(); + colRow.put("configs", colRowConfigs); + colConfigs.add(colRow); + cell = new HashMap<>(); + cell.put("key", "departmentname"); + colRowConfigs.add(cell); + mobileShowTemplate.add(col); + + return mobileShowTemplate; + } + + private Map getAllResourceList(Map params) { + Map jo = new HashMap<>(); + jo.put("status", false); + try { + List> lsRow = new ArrayList<>(); + Map row = new HashMap<>(); + HrmGroupTreeComInfo hrmgrpcominfo = new HrmGroupTreeComInfo(); + String[] allresourceArray = hrmgrpcominfo.getResourceAll(user, params, false); + if (allresourceArray != null && allresourceArray.length > 0) { + jo.put("status", true); + jo.put("datas", allresourceArray[0]); + if (allresourceArray[0] != null) { + jo.put("count", allresourceArray[0].split(",").length); + } + } + } catch (Exception e) { + writeLog(e); + } + return jo; + } + + private Map getResourceListByLetter(Map params) { + Map jo = new HashMap<>(); + jo.put("status", false); + String sql = ""; + RecordSet rs = new RecordSet(); + try { + List> lsRow = new ArrayList<>(); + Map row = null; + AppDetachComInfo adci = new AppDetachComInfo(); + DepartmentComInfo rsDepartment = new DepartmentComInfo(); + ResourceComInfo rci = new ResourceComInfo(); + SubCompanyComInfo scc = new SubCompanyComInfo(); + MutilResourceBrowser mrb = new MutilResourceBrowser(); + String letter = Util.null2String(params.get("letter")).toLowerCase(); + List lsLetter = Util.splitString2List(Util.null2String(params.get("letter")).toLowerCase(), ","); + String sqlwhere = Util.null2String((String) params.get("sqlwhere")); + if (StringUtils.isNotBlank(sqlwhere)) { + sqlwhere = " and " + sqlwhere; + } + + sql = " select id" + displayFieldsStr + " from hrmresource hr where status in(0,1,2,3) " + sqlwhere; + + if (letter.equals("#")) { + if (rs.getDBType().toLowerCase().equals("oracle")) { + sql += " and (lower(substr(pinyinlastname,0,1)) not in ('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z')) "; + } else { + sql += " and (lower(substring(pinyinlastname,1,1)) not in ('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z')) "; + } + } else { + String tmpSql = ""; + for (int i = 0; lsLetter != null && i < lsLetter.size(); i++) { + if (i == 0) { + sql += " and ( "; + } + if (tmpSql.length() > 0) tmpSql += " or "; + tmpSql += " pinyinlastname like '" + lsLetter.get(i) + "%' "; + } + if (tmpSql.length() > 0) { + sql += tmpSql + ")"; + } + } + if (adci.isUseAppDetach()) { + String appdetawhere = adci.getScopeSqlByHrmResourceSearch(user.getUID() + "", true, "resource_hr"); + String tempstr = (appdetawhere != null && !"".equals(appdetawhere) ? (" and " + appdetawhere) : ""); + sql += tempstr; + } + sql += " order by dsporder, pinyinlastname "; + this.writeLog("gecy getResourceListByLetter>>>" + sql); + rs.executeQuery(sql); + while (rs.next()) { + String userid = rs.getString("id"); +// String subcomid = rsDepartment.getSubcompanyid1(rci.getDepartmentID(userid)); +// String supsubcomid = scc.getSupsubcomid(subcomid); + row = new HashMap<>(); + row.put("id", userid); + for(String f : getDisplayFields()){ + row.put(f, rs.getString(f)); + } +// row.put("img", rci.getMessagerUrls(userid)); +// row.put("messagerurl", rci.getMessagerUrls(userid)); +// row.put("lastname", rci.getLastname(userid)); +// row.put("pinyinlastname", rci.getPinyinlastname(userid)); +// row.put("jobtitlename", mrb.getJobTitlesname(userid)); +// row.put("departmentid", rci.getDepartmentID(userid)); +// row.put("departmentname", rsDepartment.getDepartmentmark(rci.getDepartmentID(userid))); +// row.put("subcompanyid", subcomid); +// row.put("subcompanyname", scc.getSubCompanyname(subcomid)); +// row.put("supsubcompanyid", supsubcomid); +// row.put("supsubcompanyname", scc.getSubCompanyname(supsubcomid)); + lsRow.add(row); + } + + lsRow = EditGetMap(lsRow); + jo.put("status", true); + jo.put("datas", lsRow); + } catch (Exception e) { + writeLog(e); + } + return jo; + } + + private Map getOrgResource(Map params) { + Map result = new HashMap<>(); + String types = Util.null2String(params.get("types")); + String alllevel = Util.null2String(params.get("alllevel")).length() == 0 ? "0" : Util.null2String(params.get("alllevel")); + String isNoAccount = Util.null2String(params.get("isNoAccount")).length() == 0 ? "0" : Util.null2String(params.get("isNoAccount")); + if ("".equals(types)) + return result; + String[] typeArr = types.split(","); + List> datas = new ArrayList>(); + try { + MutilResourceBrowser mrb = new MutilResourceBrowser(); + ResourceComInfo rcomInfo = new ResourceComInfo(); + DepartmentComInfo deptComInfo = new DepartmentComInfo(); + SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo(); + String whereClause = Util.null2String(params.get("sqlwhere")); + String resourceids = ""; + + if (whereClause.length() > 0) whereClause = " and " + whereClause; + + WorkflowCommonService WorkflowCommonService = new WorkflowCommonServiceImpl(); + params.put("tableAlias","hr"); + Map dataRanage = WorkflowCommonService.getDataDefinitionDataRanageSet(params, user, 1); + if (Util.null2String(dataRanage.get("sqlWhere")).length() > 0) { + if (whereClause.length() > 0) { + if (!whereClause.trim().startsWith("and")) whereClause += "and"; + } + whereClause += Util.null2String(dataRanage.get("sqlWhere")); + } + /* + * 执行力管理分权增加控制,未开启,查询部门(包括下级)人员,分部(包括下级)人员, + * */ + if(this.rightStr.equals("Execution:PerformanceSet") || this.rightStr.equals("Execution:ReportSet")){ + String appdetawhere = checkBlogAppLoadSub(this.rightStr); + String tempstr = (appdetawhere != null && !"".equals(appdetawhere) ? (appdetawhere) : ""); + whereClause += tempstr; + } + this.writeLog("gecy getOrgResource>>>>" + whereClause + ";;" + user.getUID() + ";;" + types); + + for (String typeInfo : typeArr) { + String[] typeInfoArr = typeInfo.split("\\|"); + List records = new ArrayList<>(); + if (typeInfoArr.length > 1) { + String type = typeInfoArr[0]; + String id = typeInfoArr[1]; + if (type.equals("subcom") || type.equals("dept") || type.equals("com")) { + // 部门 + String nodeid = type + "_" + id; + if (Integer.parseInt(id) < 0) { + // 虚拟 + resourceids = mrb.getComDeptResourceVirtualIds(nodeid, alllevel, isNoAccount, user, whereClause); + } else { + resourceids = mrb.getComDeptResourceIds(nodeid, alllevel, isNoAccount, user, whereClause); + } + } else if (type.equals("group")) {// 自定义组 + resourceids = mrb.getGroupResourceIds(id, isNoAccount, user, whereClause); + } + + String[] resourceidArr = Util.TokenizerString2(resourceids, ","); + List> users = new ArrayList>(); + List ids = new ArrayList(); + for (String resourceid : resourceidArr) { + if ("".equals(Util.null2String(resourceid))) + continue; + ids.add(resourceid); + } + + if(ids.size() > 0){ + for(String resourceId : ids){ + users.add(getUserInfo(resourceId, user, true)); + } + } + + Map typeresult = new HashMap(); + typeresult.put("id", id); + typeresult.put("type", type); + typeresult.put("users", users); + typeresult.put("nodeid", type + "_" + id + "x"); + datas.add(typeresult); + } else { + if ("".equals(Util.null2String(typeInfo))) + continue; + datas.add(getUserInfo(typeInfo, user, true)); + } + } + } catch (Exception e) { + writeLog(e); + e.printStackTrace(); + } + result.put("status", true); + result.put("datas", datas); + return result; + } + + //微博单独返回人员 由微博模块维护 + private Map getBlogHrmResource(Map params) { + + Map result = new HashMap<>(); + List> users = new ArrayList>(); + + int pageSize = Util.getIntValue((String) params.get("pageSize"),10) ; + int current = Util.getIntValue((String) params.get("current"),10) ; + String conditon = StringUtils.EMPTY ; + conditon= BlogDiscussShareUtil.getShareSqlWhereForBrw(this.user.getUID()+"", (String) params.get("lastname")); + + RecordSet rs = new RecordSet(); + String sql = ""; + + if(rs.getDBType().equals("mysql")||rs.getDBType().equals("sqlserver")){ + + sql = " select id from hrmresource hr where (status =0 or status = 1 or status = 2 or status = 3) and (loginid is not null and loginid <> '') and seclevel>=0 "+conditon; + }else{ + + sql = " select id from hrmresource hr where (status =0 or status = 1 or status = 2 or status = 3) and (loginid is not null ) and seclevel>=0 "+conditon; + } + sql += " order by dsporder "; + + rs.executeQuery(sql); + writeLog("blogshare ------------ "+sql); + int count = rs.getCounts(); + + SplitPageParaBean spp = new SplitPageParaBean(); + SplitPageUtil spu = new SplitPageUtil(); + + String backfields = "id"; + spp.setBackFields(backfields); + spp.setSqlFrom("hrmresource hr"); + + if(rs.getDBType().equals("mysql")||rs.getDBType().equals("sqlserver")){ + spp.setSqlWhere(" where (status =0 or status = 1 or status = 2 or status = 3) and (loginid is not null and loginid <> '') and seclevel>=0 "+conditon); + }else{ + spp.setSqlWhere(" where (status =0 or status = 1 or status = 2 or status = 3) and (loginid is not null) and seclevel>=0 "+conditon); + } + + spp.setPrimaryKey("id"); + spp.setSqlOrderBy("dsporder"); + spu.setSpp(spp); + + rs = spu.getCurrentPageRsNew(current, pageSize); + try { + while (rs.next()) { + users.add(getUserInfo(rs.getString("id"), user, true)); + } + } catch (Exception e) { + e.printStackTrace(); + } + result.put("status", true); + result.put("datas", users); + result.put("count",count); + return result; + + } + + + //微博单独返回人员 由微博模块维护 + private Map getBlogSelectedHrmResource(Map params) { + + Map result = new HashMap<>(); + List> users = new ArrayList>(); + + + String selectIds = Util.null2String( params.get("selectids")); + + if(selectIds.equals("")){ + result.put("status", true); + result.put("datas", users); + } + + RecordSet rs = new RecordSet(); + String sql = ""; + + sql = " select id from hrmresource hr where (status =0 or status = 1 or status = 2 or status = 3) and seclevel>=0 and id in ("+selectIds+")"; + sql += " order by dsporder "; + + try { + rs.executeSql(sql); + while (rs.next()) { + users.add(getUserInfo(rs.getString(1), user, true)); + } + } catch (Exception e) { + e.printStackTrace(); + } + result.put("status", true); + result.put("datas", users); + return result; + + } + + private Map getUserInfo(String userid, ResourceComInfo rcomInfo, DepartmentComInfo deptComInfo, SubCompanyComInfo subCompanyComInfo) throws Exception { + Map userInfo = new HashMap(); + userInfo.put("id", userid); + userInfo.put("lastname", rcomInfo.getLastname(userid)); + userInfo.put("pinyinlastname", rcomInfo.getLastname(userid)); //rcomInfo.getPinyinlastname(userid) + userInfo.put("jobtitlename", MutilResourceBrowser.getJobTitlesname(userid)); + userInfo.put("icon", rcomInfo.getMessagerUrls(userid)); + userInfo.put("requestParams", rcomInfo.getUserIconInfoStr(userid,user)); + userInfo.put("type", "resource"); + userInfo.put("nodeid", "resource_" + userid + "x"); + userInfo.put("departmentid", rcomInfo.getDepartmentID(userid)); + userInfo.put("departmentname", deptComInfo.getDepartmentmark(rcomInfo.getDepartmentID(userid))); + String subcompanyid = deptComInfo.getSubcompanyid1(rcomInfo.getDepartmentID(userid)); + String parentsubcompanyid = subCompanyComInfo.getSupsubcomid(subcompanyid); + userInfo.put("subcompanyid", subcompanyid); + userInfo.put("subcompanyname", subCompanyComInfo.getSubcompanyname(subcompanyid)); + userInfo.put("supsubcompanyid", parentsubcompanyid); + userInfo.put("supsubcompanyname", subCompanyComInfo.getSubcompanyname(parentsubcompanyid)); + return userInfo; + } + + + private Map getUserInfo(String userid, User user, Boolean allFields) throws Exception{ + MutilResourceBrowser mrb = new MutilResourceBrowser(); + ResourceComInfo rcomInfo = new ResourceComInfo(); + DepartmentComInfo deptComInfo = new DepartmentComInfo(); + SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo(); + JobActivitiesComInfo jobActivitiesComInfo = new JobActivitiesComInfo(); + JobTitlesComInfo jobTitlesComInfo = new JobTitlesComInfo(); + String jobactivityId = jobTitlesComInfo.getJobactivityid(rcomInfo.getJobTitle(userid)); + PrivacyComInfo pc = new PrivacyComInfo(); + Map mapShowSets = pc.getMapShowSets(); + AccountType accountType = new AccountType(); + HrmTransMethod hrmTransMethod = new HrmTransMethod(); + EncryptFieldViewScopeConfigComInfo encryptFieldViewScopeConfigComInfo = new EncryptFieldViewScopeConfigComInfo(); + Map userInfo = new HashMap(); + userInfo.put("id", userid); + userInfo.put("lastname", rcomInfo.getLastname(userid)); + userInfo.put("pinyinlastname", rcomInfo.getLastname(userid)); //rcomInfo.getPinyinlastname(userid) + userInfo.put("jobtitlename", MutilResourceBrowser.getJobTitlesname(userid)); + userInfo.put("icon", rcomInfo.getMessagerUrls(userid)); + userInfo.put("type", "resource"); + userInfo.put("email", rcomInfo.getEmail(userid)); + userInfo.put("nodeid", "resource_" + userid + "x"); + String departmentid = rcomInfo.getDepartmentID(userid); + userInfo.put("departmentid", rcomInfo.getDepartmentID(userid)); + userInfo.put("departmentname", deptComInfo.getDepartmentmark(rcomInfo.getDepartmentID(userid))); + String subcompanyid = deptComInfo.getSubcompanyid1(rcomInfo.getDepartmentID(userid)); + String parentsubcompanyid = subCompanyComInfo.getSupsubcomid(subcompanyid); + userInfo.put("subcompanyid", subcompanyid); + userInfo.put("subcompanyname", subCompanyComInfo.getSubcompanyname(subcompanyid)); + userInfo.put("supsubcompanyid", parentsubcompanyid); + userInfo.put("supsubcompanyname", subCompanyComInfo.getSubcompanyname(parentsubcompanyid)); + userInfo.put("requestParams", rcomInfo.getUserIconInfoStr(userid,user)); + + try { + List displayKeys = new ArrayList<>(); + for (Map m : browserFieldConfig) { + String fieldName = Util.null2String(m.get("fieldName")); + String fullPath = Util.null2String(m.get("fullPath")); + String fullPathDelimiter = Util.null2String(m.get("fullPathDelimiter")); + if(fullPathDelimiter.equals("")) + fullPathDelimiter = "|"; + else + fullPathDelimiter = "" + fullPathDelimiter + ""; + String orderType = Util.null2String(m.get("orderType")); + String key = fieldName + "span"; + generateDisplayKeys(displayKeys, key, allFields); + switch (fieldName) { + case "departmentid": + String fullDeptPath = deptComInfo.getDepartmentRealPath(departmentid, fullPathDelimiter, orderType); + userInfo.put(key, fullPath.equals("1") ? fullDeptPath : deptComInfo.getDepartmentmark(departmentid)); + break; + case "subcompanyid1": + userInfo.put(key, fullPath.equals("1") ? subCompanyComInfo.getSubcompanyRealPath(subcompanyid, fullPathDelimiter, orderType) : subCompanyComInfo.getSubCompanyname(subcompanyid)); + break; + case "accounttype": + userInfo.put(key, accountType.getAccountType(rcomInfo.getAccountType(userid), user.getLanguage()+"")); + break; + case "sex": + userInfo.put(key, rcomInfo.getSexName(Util.null2String(rcomInfo.getSexs(userid)),""+user.getLanguage())); + break; + case "managerid": + userInfo.put(key, rcomInfo.getResourcename(rcomInfo.getManagerID(userid))); + break; + case "assistantid": + userInfo.put(key, rcomInfo.getResourcename(rcomInfo.getAssistantID(userid))); + break; + case "jobtitle": + userInfo.put(key, mrb.getJobTitlesname(userid)); + break; + case "status": + userInfo.put(key, ResourceComInfo.getStatusName(Util.null2String(rcomInfo.getStatus(userid)), user.getLanguage() + "")); + break; + case "jobactivity": + userInfo.put(key, Util.null2String(jobActivitiesComInfo.getJobActivitiesname(jobactivityId)));//hrmTransMethod.getJobActivitiesname("", rcomInfo.getJobTitle(userid))); + break; + case "orgid": + userInfo.put(key, deptComInfo.getAllParentDepartmentBlankNames(departmentid, subcompanyid, "|")); + break; + case "jobcall": + userInfo.put(key, Util.null2String(new JobCallComInfo().getJobCallname(rcomInfo.getJobCall(userid)))); + break; + case "jobGroupId": + String jobtitleid = rcomInfo.getJobTitle(userid) ; + String jobActivityId = new JobTitlesComInfo().getJobactivityid(jobtitleid); + String groupId = jobActivitiesComInfo.getJobgroupid(jobActivityId); + userInfo.put(key, Util.null2String(new JobGroupsComInfo().getJobGroupsname(groupId))); + break; + case "joblevel": + userInfo.put(key, Util.null2String(rcomInfo.getJoblevel(userid))); + break; + case "jobactivitydesc": + userInfo.put(key, Util.null2String(rcomInfo.getJobActivityDesc(userid))); + break; + case "workroom": + userInfo.put(key, Util.null2String(rcomInfo.getWorkroom(userid))); + break; + default: + + String value = ""; + switch(fieldName){ + case "loginid": + value = rcomInfo.getLoginID(userid); + break; + case "workcode": + value = rcomInfo.getWorkcode(userid); + break; + case "lastname": + value = rcomInfo.getLastname(userid); + break; + case "locationid": + value = rcomInfo.getLocationid(userid); + break; + case "mobile": + value = encryptFieldViewScopeConfigComInfo.fieldCanView(""+user.getUID(),"hrmresource","mobile")? EncryptConfigBiz.getDecryptData(rcomInfo.getMobile(userid)):rcomInfo.getMobile(userid); + break; + case "telephone": + value = encryptFieldViewScopeConfigComInfo.fieldCanView(""+user.getUID(),"hrmresource","telephone")? EncryptConfigBiz.getDecryptData(rcomInfo.getTelephone(userid)):rcomInfo.getTelephone(userid); + break; + case "mobilecall": + value = encryptFieldViewScopeConfigComInfo.fieldCanView(""+user.getUID(),"hrmresource","mobilecall")? EncryptConfigBiz.getDecryptData(rcomInfo.getMobileCall(userid)):rcomInfo.getMobileCall(userid); + break; + case "fax": + value = encryptFieldViewScopeConfigComInfo.fieldCanView(""+user.getUID(),"hrmresource","fax")? EncryptConfigBiz.getDecryptData(rcomInfo.getFax(userid)):rcomInfo.getFax(userid); + break; + case "email": + value = encryptFieldViewScopeConfigComInfo.fieldCanView(""+user.getUID(),"hrmresource","email")? EncryptConfigBiz.getDecryptData(rcomInfo.getEmail(userid)):rcomInfo.getEmail(userid); + break; + case "managerid": + value = rcomInfo.getManagerID(userid); + break; + case "assistantid": + value = rcomInfo.getAssistantID(userid); + break; + } + if (mapShowSets != null && mapShowSets.get(fieldName) != null) { + userInfo.put(key, pc.getSearchContent(Util.null2String(value), (userid + "+" + user.getUID() + "+" + fieldName))); + } else { + userInfo.put(key, hrmTransMethod.getDefineContent(Util.null2String(value), fieldName + ":" + user.getLanguage())); + } + break; + } + } + if(displayKeys.size() > 0) userInfo.put("displayKeys", displayKeys); + }catch (Exception e){ + e.printStackTrace(); + } + return userInfo; + } + + /** + * 加载人力浏览按钮显示列定义 + * @return + */ + private List loadDisplayColumnConfig() { + List columns = new ArrayList(); + displayFields.clear(); + displayFields.add("lastname"); + displayFields.add("pinyinlastname"); + displayFields.add("departmentid"); + displayFields.add("subcompanyid1"); + displayFields.add("workcode"); + displayFields.add("mobile"); + try { + browserFieldConfig = new BrowserDisplayFieldServiceImpl().getConfig(1); + int i = 0; + for (Map m : browserFieldConfig) { + Map c = new HashMap(); + String fieldName = String.valueOf(m.get("fieldName")); + if (!fieldName.equals("jobactivity") && !fieldName.equals("orgid") && !this.displayFields.contains(fieldName)) + displayFields.add(fieldName); + c.put("dataIndex", fieldName + "span"); + c.put("showType", i > 1 ? "0" : "1"); + c.put("hide", "false"); + columns.add(c); + i++; + } + } catch (Exception ex) { + writeLog(ex); + } + displayFieldsStr = ", " + String.join(",", getDisplayFields()); + + if(Util.null2String(params.get("from")).equals("ResourceBrowserDecService")) { + List tableHeadColumns = new ArrayList(); + tableHeadColumns.add(new ListHeadBean("id", BoolAttr.TRUE).setIsPrimarykey(BoolAttr.TRUE)); + tableHeadColumns.add(new ListHeadBean("lastname", SystemEnv.getHtmlLabelName(413, user.getLanguage()), 1, BoolAttr.TRUE)); + tableHeadColumns.add(new ListHeadBean("jobtitlename", "", 1)); + tableHeadColumns.add(new ListHeadBean("departmentname", "")); + columns = tableHeadColumns; + } + return columns; + } + + private List getDisplayFields(){ + List list = new ArrayList<>(); + for(String f : displayFields){ + if(f.toLowerCase().equals("jobgroupid") || f.toLowerCase().equals("jobactivity")){ + continue; + } + list.add(f); + } + return list; + } + + private void generateDisplayKeys(List list, String key, Boolean allFields){ + if(allFields == true || key.equals("lastnamespan") || !browserFieldFilterKeys.contains(key)) + list.add(key); + } + + private void generateRange(Map dataRanage, String virtualtype){ + try { + String sqlWhere = Util.null2String(dataRanage.get("sqlWhere")); + if (sqlWhere.length() > 0) { + SubCompanyVirtualComInfo subCompanyVirtualComInfo = new SubCompanyVirtualComInfo(); + SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo(); + DepartmentVirtualComInfo departmentVirtualComInfo = new DepartmentVirtualComInfo(); + DepartmentComInfo departmentComInfo = new DepartmentComInfo(); + + RecordSet rs = new RecordSet(); + Set subCompanyIds = new HashSet<>(); + Set departmentIds = new HashSet<>(); + Set allSubCompanyIds = new HashSet<>(); + Set allDepartmentIds = new HashSet<>(); + + String table = "HRMRESOURCEALLVIEW"; + if(Util.getIntValue(virtualtype, 1) < 0){ + table = "HRMRESOURCEVIRTUALVIEW"; + } + + String sql = "select subcompanyid1, departmentid from " + table + " where 1 = 1" + sqlWhere; + rs.executeQuery(sql); + while (rs.next()) { + String subcompanyId = Util.null2String(rs.getString("subcompanyid1")); + String departmentId = Util.null2String(rs.getString("departmentid")); + if (!"".equals(subcompanyId)) { + subCompanyIds.add(subcompanyId); + } + if (!"".equals(subcompanyId)) { + departmentIds.add(departmentId); + } + } + + Iterator iterator = subCompanyIds.iterator(); + while (iterator.hasNext()) { + String ids = ""; + String v = (String)iterator.next(); + allSubCompanyIds.add(v); + if (Integer.parseInt(v) < 0) { + ids = subCompanyVirtualComInfo.getAllSupCompany(v); + }else{ + ids = subCompanyComInfo.getAllSupCompany(v); + } + String [] idArr = Util.splitString(ids, ","); + for(String id : idArr){ + allSubCompanyIds.add(id); + } + } + + iterator = allSubCompanyIds.iterator(); + while (iterator.hasNext()) { + String v = (String)iterator.next(); + if(!"".equals(v)) + dataRanageAllSubCompanyIds.add(v); + } + if(allSubCompanyIds.size() == 0) + dataRanageAllSubCompanyIds.add(""); + + iterator = departmentIds.iterator(); + while (iterator.hasNext()) { + String ids = ""; + String v = (String)iterator.next(); + allDepartmentIds.add(v); + if (Integer.parseInt(v) < 0) { + ids = departmentVirtualComInfo.getAllSupDepartment(v); + }else{ + ids = departmentComInfo.getAllSupDepartment(v); + } + String [] idArr = Util.splitString(ids, ","); + for(String id : idArr){ + allDepartmentIds.add(id); + } + } + + iterator = allDepartmentIds.iterator(); + while (iterator.hasNext()) { + String v = (String)iterator.next(); + if(!"".equals(v)) + dataRanageAllDepartmentIds.add(v); + } + if(allDepartmentIds.size() == 0) + dataRanageAllDepartmentIds.add(""); + } + }catch (Exception ex){ + ex.printStackTrace(); + writeLog(ex); + } + } + + public void getSubCompanyTreeListByRight(int userId, String rightStr) { + ManageDetachComInfo ma = new ManageDetachComInfo(); + this.isExecutionDetach = ma.isUseExecutionManageDetach(); + CheckSubCompanyRight newCheck = new CheckSubCompanyRight(); + newCheck.setShowCanceled(false); + allSubComIds = newCheck.getSubComPathByUserRightId(userId, rightStr, 1); + subComIds = newCheck.getSubComByUserRightId(userId, rightStr); + depIds = newCheck.geDeptPathByUserRightId(userId, rightStr, 1); + if (!this.isExecutionDetach) { + //未分权 + String rightLevel = HrmUserVarify.getRightLevel(rightStr, user); + int subcompanyID = user.getUserSubCompany1(); + int departmentID = user.getUserDepartment(); + if (rightLevel.equals("2")) { + // 总部级别的,什么也不返回 + } else if (rightLevel.equals("1")) { // 分部级别的 + String subcompids = SubCompanyComInfo.getAllChildSubcompanyId(String.valueOf(subcompanyID), String.valueOf(subcompanyID)); + String[] result1 = subcompids.split(","); + this.allChildSubComIds = result1; + } else if (rightLevel.equals("0")) { // 部门级别 + String departmentids = ""; + try { + departmentids = DepartmentComInfo.getAllChildDepartId(String.valueOf(departmentID), String.valueOf(departmentID)); + } catch (Exception e) { + writeLog(e); + } + String[] result0 = departmentids.split(","); + this.allChildDeptIds = result0; + } + } + } + /** + * 生成执行力分权未开启时的角色查看分部部门id + * @param rightStr + * @return + */ + private String checkBlogAppLoadSub(String rightStr) { + String whereClause = ""; + ManageDetachComInfo ma=new ManageDetachComInfo(); + boolean isExecutionDetach = ma.isUseExecutionManageDetach(); + if (!isExecutionDetach) { + //未分权 + String rightLevel = HrmUserVarify.getRightLevel(rightStr, user); + int subcompanyID = user.getUserSubCompany1(); + int departmentID = user.getUserDepartment(); + if (rightLevel.equals("2")) { + // 总部级别的,什么也不返回 + } else if (rightLevel.equals("1")) { // 分部级别的 + String subcompids = SubCompanyComInfo.getAllChildSubcompanyId(String.valueOf(subcompanyID), String.valueOf(subcompanyID)); + whereClause += " and hr.subcompanyid1 in(" + subcompids+")"; + } else if (rightLevel.equals("0")) { // 部门级别 + String departmentids = "0"; + try { + departmentids = DepartmentComInfo.getAllChildDepartId(String.valueOf(departmentID), String.valueOf(departmentID)); + } catch (Exception e) { + writeLog(e); + } + whereClause += " and hr.departmentid in(" + departmentids+")"; + } + }else{ + //开启管理分权执行力 + CheckSubCompanyRight cscr = new CheckSubCompanyRight(); + String companyid = ""; + int[] companyids = cscr.getSubComByUserRightId(user.getUID(), rightStr, 1); + for (int i = 0; companyids != null && i < companyids.length; i++) { + companyid += "," + companyids[i]; + } + if (companyid.length() > 0) { + companyid = companyid.substring(1); + whereClause += " and ( hr.subcompanyid1 in(" + companyid + "))"; + } else { + whereClause += " and ( hr.subcompanyid1 in(0))";// 分权而且没有选择机构权限 + } + + } + return whereClause; + } + /* + * 未开启执行力分权,人员组织结构页签,查询控制 + * */ + private boolean checkBlogAppSetting(String type, String rightStr, String id) { + boolean hasRight = false; + DepartmentComInfo departmentComInfo = new DepartmentComInfo(); + if (!this.isExecutionDetach) { + String rightLevel = HrmUserVarify.getRightLevel(rightStr, user); + switch (rightLevel) { + case "0": + if (type.equals("com")) { + if (!hasRight && this.allSubComIds != null && this.allSubComIds.length > 0) { + for (int i = 0; i < allSubComIds.length; i++) { + if (id.equals(String.valueOf(allSubComIds[i]))) { + hasRight = true; + } + } + } + } else { + if (this.allChildDeptIds != null && this.allChildDeptIds.length > 0) { + for (int i = 0; i < this.allChildDeptIds.length; i++) { + if (id.equals(this.allChildDeptIds[i])) { + hasRight = true; + break; + } + } + } + } + break; + case "1": + if (type.equals("com")) { + if (this.allSubComIds != null && this.allSubComIds.length > 0) { + for (int i = 0; i < this.allSubComIds.length; i++) { + if (id.equals(String.valueOf(this.allSubComIds[i]))) { + hasRight = true; + break; + } + } + } + if (this.allChildSubComIds != null && this.allChildSubComIds.length > 0) { + for (int i = 0; i < this.allChildSubComIds.length; i++) { + if (id.equals(this.allChildSubComIds[i])) { + hasRight = true; + break; + } + } + } + } else { + String subcompanyid = departmentComInfo.getSubcompanyid1(id); + if (this.allChildSubComIds != null && this.allChildSubComIds.length > 0) { + for (int i = 0; i < this.allChildSubComIds.length; i++) { + if (subcompanyid.equals(this.allChildSubComIds[i])) { + hasRight = true; + break; + } + } + } + } + break; + case "2": + hasRight = true; + break; + default: + hasRight = true; + break; + } + } else { + if (type.equals("com")) { + if (this.allSubComIds != null && this.allSubComIds.length > 0) { + for (int i = 0; i < this.allSubComIds.length; i++) { + if (id.equals(String.valueOf(this.allSubComIds[i]))) { + hasRight = true; + break; + } + } + } + if (this.allChildSubComIds != null && this.allChildSubComIds.length > 0) { + for (int i = 0; i < this.allChildSubComIds.length; i++) { + if (id.equals(String.valueOf(this.allChildSubComIds[i]))) { + hasRight = true; + break; + } + } + } + } else { + String subcompanyid = departmentComInfo.getSubcompanyid1(id); + hasRight = false; + if (this.depIds != null && this.depIds.length > 0) { + for (int i = 0; i < depIds.length; i++) { + if (id.equals(String.valueOf(depIds[i]))) { + hasRight = true; + break; + } + } + } + if (!hasRight && this.subComIds != null && this.subComIds.length > 0) { + for (int i = 0; i < subComIds.length; i++) { + if (subcompanyid.equals(String.valueOf(subComIds[i]))) { + hasRight = true; + break; + } + } + } + if (this.allChildDeptIds != null && this.allChildDeptIds.length > 0) { + for (int i = 0; i < this.allChildDeptIds.length; i++) { + if (id.equals(String.valueOf(this.allChildDeptIds[i]))) { + hasRight = true; + break; + } + } + } + } + } + return hasRight; + } + public static void main(String[] args) { + ResourceBrowserService ResourceBrowserService = new ResourceBrowserService(); + System.out.println("aaa=" + JSONObject.toJSONString(ResourceBrowserService.getMobileShowTemplate(), SerializerFeature.DisableCircularReferenceDetect)); + } + + private Map getv2resourceBySub(Map params) { + Map jo = new HashMap<>(); + jo.put("status", false); + jo.put("type", 6); + + HrmOrgForwardBean hrmOrgForwardBean = localHrmOrgForwardBean.get(); + if (hrmOrgForwardBean != null) hrmOrgForwardBean.checkInited(true); + + try { + ResourceComInfo resourceComInfo = new ResourceComInfo(); + ResourceVirtualComInfo resourceVirtualComInfo = new ResourceVirtualComInfo(); + DepartmentVirtualComInfo departmentVirtualComInfo = new DepartmentVirtualComInfo(); + CompanyComInfo cci = new CompanyComInfo(); + SubCompanyVirtualComInfo scvc = new SubCompanyVirtualComInfo(); + SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo(); + AppDetachComInfo adci = new AppDetachComInfo(user); + + if (null == user) { + jo = getWrongCode(402, jo); + return jo; + } + String id = Util.null2String(params.get("id")); + String isNoAccount = Util.null2String(params.get("isNoAccount")); + String sqlwhere = Util.null2String(params.get("sqlwhere")); + String selectedids = Util.null2String(params.get("selectedids")); + String virtualtype = Util.null2String(params.get("virtualtype")); + String type = Util.null2String(params.get("type")); + String alllevel = Util.null2String(params.get("alllevel")); + String cmd = Util.null2String(params.get("cmd")); + + WorkflowCommonService WorkflowCommonService = new WorkflowCommonServiceImpl(); + params.put("tableAlias", "hr"); + Map dataRanage = WorkflowCommonService.getDataDefinitionDataRanageSet(params, user, 1); + String dataRanageResourceIds = Util.null2String(dataRanage.get("sqlWhere")); + if (dataRanageResourceIds.length() > 0) { + sqlwhere += " " + dataRanageResourceIds; + } + + List selectList = new ArrayList(); + if (selectedids.length() > 0) { + String[] tmp_selectedids = selectedids.split(","); + for (String selectedid : tmp_selectedids) { + selectList.add(selectedid); + } + } + String resultString = ""; + TreeNode envelope = new TreeNode(); + if (cmd.equals("getNum")) { + String nodeids = Util.null2String(params.get("nodeids")); + resultString = getResourceNumJson(nodeids, selectList, sqlwhere); + jo.put("status", true); + jo.put("datas", resultString); + } else { + if (id.equals("")) { + // 初始化 + TreeNode root = new TreeNode(); + String companyname = cci.getCompanyname("1"); + root.setLastname(companyname); + if (!"".equals(virtualtype) && !"1".equals(virtualtype)) { + root.setId(virtualtype); + root.setNodeid("com_" + virtualtype + "x"); + } else { + root.setNodeid("com_" + 1 + "x"); + root.setId("0"); + } + + root.setOpen("true"); + root.setTarget("_self"); + root.setIcon("/images/treeimages/global_wev8.gif"); + root.setType("com"); + + //添加本分部 + String subId = String.valueOf(user.getUserSubCompany1()); + String name = subCompanyComInfo.getSubCompanyname(subId); + String canceled = subCompanyComInfo.getCompanyiscanceled(subId); + if (!"".equals(virtualtype) && !"1".equals(virtualtype)) { + String deptId = resourceVirtualComInfo.getDepartmentid(virtualtype, "" + user.getUID()); + subId = departmentVirtualComInfo.getSubcompanyid1(deptId); + name = scvc.getSubCompanyname(subId); + canceled = scvc.getCompanyiscanceled(subId); + } + boolean canAdd = true; + if (subId == null || subId.equals("") || subId.equals("0")) { + jo.put("status", true); + jo.put("datas", root); + return jo; + } + + if (adci.isUseAppDetach()) { + if (adci.checkUserAppDetach(subId, "2") == 0) { + canAdd = false; + } + } + + if (!ObjtypeComparor.isSourceHasTarget(localHrmOrgForwardBean.get(), SimpleObjtypeInfo.initSubCompany(id, OrgUpOrDownTypeStyle.ORG_ALL_DOWN))) { + canAdd = false; + } + + TreeNode subCompanyNode = new TreeNode(); + subCompanyNode.setLastname(name); + subCompanyNode.setId(subId); + subCompanyNode.setNodeid("subcom_" + subId + "x"); + subCompanyNode.setPid("0"); + subCompanyNode.setIcon("/images/treeimages/Home_wev8.gif"); + subCompanyNode.setNocheck("N"); + subCompanyNode.setType("subcom"); + if (hasChild("subcompany", subId)) { + subCompanyNode.setIsParent("true"); + } + if ("1".equals(canceled)) { + canAdd = false; + } + if (canAdd) { + root.AddChildren(subCompanyNode); + } + jo.put("status", true); + jo.put("datas", root); + } else if (type.equals("subcom")) { + if (!"".equals(virtualtype) && !"1".equals(virtualtype)) { + virtualtype = scvc.getCompanyid(id); + } + + getV2SubCompanyTreeListBySub(envelope, id, virtualtype, selectList, isNoAccount, user, sqlwhere); + ArrayList lsChild = envelope.getChildren(); + + jo.put("status", true); + jo.put("datas", lsChild); + } else if (type.equals("dept")) { + String subId = ""; + if (!"".equals(virtualtype) && !"1".equals(virtualtype)) { + DepartmentVirtualComInfo DepartmentComInfo = new DepartmentVirtualComInfo(); + subId = DepartmentComInfo.getSubcompanyid1(id); + } else { + DepartmentComInfo DepartmentComInfo = new DepartmentComInfo(); + subId = DepartmentComInfo.getSubcompanyid1(id); + } + + getV2DepartTreeList(envelope, subId, id, selectList, isNoAccount, user, sqlwhere, virtualtype); + ArrayList lsChild = envelope.getChildren(); + /** + * 浏览按钮自定义显示字段 + */ + List ids = new ArrayList(); + for (TreeNode tn : lsChild) { + if (tn.getType().equals("resource")) + ids.add(tn.getId()); + } + Map> map = new HashMap(); + if (ids.size() > 0) { + for (String resourceId : ids) { + Map userInfo = getUserInfo(resourceId, user, null); + map.put(resourceId, userInfo); + } + } + JSONArray jsonArray = (JSONArray) JSONArray.toJSON(lsChild); + for (int i = 0; i < jsonArray.size(); i++) { + JSONObject jsonObject = (JSONObject) jsonArray.get(i); + String k = jsonObject.getString("id"); + String loopType = jsonObject.getString("type"); + if (map.containsKey(k) && "resource".equals(loopType)) { + jsonObject.putAll(map.get(k)); +// jsonObject.put("columnControled", true); + } + } + jo.put("status", true); + jo.put("datas", jsonArray); + } + } + + } catch (Exception e) { + writeLog(e); + } + return jo; + } + + private TreeNode getV2SubCompanyTreeListBySub(TreeNode companyTreeList, String subId, String virtualtype, List selectedids, String isNoAccount, User user, String sqlwhere) throws Exception { + getV2DepartTreeList(companyTreeList, subId, "0", selectedids, isNoAccount, user, sqlwhere, virtualtype); + AppDetachComInfo adci = new AppDetachComInfo(user); + String alllowsubcompanystr = Util.null2String(adci.getAlllowsubcompanystr()); + String alllowsubcompanyviewstr = Util.null2String(adci.getAlllowsubcompanyviewstr()); + if (null != virtualtype && !"".equals(virtualtype) && !"1".equals(virtualtype)) { + SubCompanyVirtualComInfo scvc = new SubCompanyVirtualComInfo(); + ResourceVirtualComInfo resourceVirtualComInfo = new ResourceVirtualComInfo(); + String subComId = resourceVirtualComInfo.getSubcompanyid(virtualtype, "" + user.getUID()); + if (subComId == null || subComId.equals("")) { + return companyTreeList; + } + String allShowSubComIds = ""; + try { + allShowSubComIds = scvc.getSubCompanyTreeStr(subComId); + } catch (Exception e) { + e.printStackTrace(); + } + List allShowSubComIdList = Util.TokenizerString(allShowSubComIds, ","); + if (allShowSubComIdList == null) { + allShowSubComIdList = new ArrayList(); + } + allShowSubComIdList.add(subComId); + scvc.setTofirstRow(); + while (scvc.next()) { + String id = scvc.getSubCompanyid(); + String supsubcomid = scvc.getSupsubcomid(); + String tmp_virtualtype = scvc.getCompanyid(); + if (null != virtualtype && !"".equals(virtualtype) && !"1".equals(virtualtype)) { + if (!virtualtype.equals(tmp_virtualtype)) continue; + } + + if (supsubcomid.equals("")) + supsubcomid = "0"; + if (!supsubcomid.equals(subId)) + continue; + + if (adci.isUseAppDetach()) { + if (adci.checkUserAppDetach(id, "2") == 0) { + continue; + } + } + + if (!ObjtypeComparor.isSourceHasTarget(localHrmOrgForwardBean.get(), SimpleObjtypeInfo.initSubCompany(id, OrgUpOrDownTypeStyle.ORG_ALL_DOWN))) { + continue; + } + + if (!allShowSubComIdList.contains(id)) { + continue; + } + + String name = Util.formatMultiLang(scvc.getSubCompanyname()); + String canceled = scvc.getCompanyiscanceled(); + + TreeNode subCompanyNode = new TreeNode(); + subCompanyNode.setLastname(name); + subCompanyNode.setId(id); + subCompanyNode.setNodeid("subcom_" + id + "x"); + subCompanyNode.setPid(subId); + subCompanyNode.setIcon("/images/treeimages/Home_wev8.gif"); + subCompanyNode.setNocheck("N"); + subCompanyNode.setType("subcom"); + if (hasChild("subcompany", id)) { + subCompanyNode.setIsParent("true"); + } + + if (!"1".equals(canceled)) { + companyTreeList.AddChildren(subCompanyNode); + } + } + } else { + SubCompanyComInfo scvc = new SubCompanyComInfo(); + String subComId = "" + user.getUserSubCompany1(); + String allShowSubComIds = scvc.getAllChildSubcompanyId(subComId, subComId); + List allShowSubComIdList = Util.TokenizerString(allShowSubComIds, ","); + if (allShowSubComIdList == null) { + allShowSubComIdList = new ArrayList(); + } + allShowSubComIdList.add(subComId); + scvc.setTofirstRow(); + while (scvc.next()) { + String id = scvc.getSubCompanyid(); + String supsubcomid = scvc.getSupsubcomid(); + String tmp_virtualtype = scvc.getCompanyid(); + if (null != virtualtype && !"".equals(virtualtype) + && !"1".equals(virtualtype)) { + if (!virtualtype.equals(tmp_virtualtype)) + continue; + } + + if (supsubcomid.equals("")) + supsubcomid = "0"; + if (!supsubcomid.equals(subId)) + continue; + + if (adci.isUseAppDetach()) { + if (adci.checkUserAppDetach(id, "2") == 0) { + continue; + } + } + + if (!ObjtypeComparor.isSourceHasTarget(localHrmOrgForwardBean.get(), SimpleObjtypeInfo.initSubCompany(id, OrgUpOrDownTypeStyle.ORG_ALL_DOWN))) { + continue; + } + + if (!allShowSubComIdList.contains(id)) { + continue; + } + + String name = Util.formatMultiLang(scvc.getSubCompanyname()); + String canceled = scvc.getCompanyiscanceled(); + + TreeNode subCompanyNode = new TreeNode(); + subCompanyNode.setLastname(name); + subCompanyNode.setId(id); + subCompanyNode.setNodeid("subcom_" + id + "x"); + subCompanyNode.setPid(subId); + subCompanyNode.setIcon("/images/treeimages/Home_wev8.gif"); + subCompanyNode.setNocheck("N"); + subCompanyNode.setType("subcom"); + if (hasChild("subcompany", id)) { + subCompanyNode.setIsParent("true"); + } + + if (!"1".equals(canceled)) + companyTreeList.AddChildren(subCompanyNode); + } + } + + return companyTreeList; + } +} diff --git a/src/com/api/customization/qc2988837/Util/KqCustomUtil.java b/src/com/api/customization/qc2988837/Util/KqCustomUtil.java new file mode 100644 index 0000000..8a6ef94 --- /dev/null +++ b/src/com/api/customization/qc2988837/Util/KqCustomUtil.java @@ -0,0 +1,33 @@ +package com.api.customization.qc2988837.Util; + +import com.engine.kq.log.KQLog; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; + +public class KqCustomUtil { + + /** + * 是否建模表配置不统计,不计算考勤 + * @param resourceId + * @param workDate + * @return + */ + public boolean isExclude(String resourceId,String workDate){ + KQLog kqLog = new KQLog(); + RecordSet rs = new RecordSet(); + boolean isExculde = false; + String tableName = new BaseBean().getPropValue("qc2988837","tableName"); + String resourceField = new BaseBean().getPropValue("qc2988837","resourceField"); + String fromDateField = new BaseBean().getPropValue("qc2988837","fromDateField"); + String toDateField = new BaseBean().getPropValue("qc2988837","toDateField"); + String sql = "select "+resourceField+","+fromDateField+","+toDateField+" from "+tableName+ + " where FIND_IN_SET("+resourceId+","+resourceField+") > 0 and '"+workDate+"' between "+fromDateField+" and "+toDateField; + kqLog.info("该人员当天是否不计算考勤:" + sql); + rs.executeQuery(sql); + if (rs.next()){ + isExculde = true; + } + + return isExculde; + } +} diff --git a/src/com/api/hrm/service/HrmResourceTreeService.java b/src/com/api/hrm/service/HrmResourceTreeService.java new file mode 100644 index 0000000..78aebd4 --- /dev/null +++ b/src/com/api/hrm/service/HrmResourceTreeService.java @@ -0,0 +1,149 @@ +package com.api.hrm.service; + +import com.api.hrm.bean.TreeNode; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.Util; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; +import weaver.hrm.appdetach.AppDetachComInfo; +import weaver.hrm.resource.ResourceComInfo; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class HrmResourceTreeService extends BaseBean{ + private AppDetachComInfo adci = null; + private User user = null; + private String alllevel = null;//是否显示所有下级 + private String isNoAccount = null;// 是否显示无账号人员 + public Map getHrmResourceTree(HttpServletRequest request, HttpServletResponse response) { + User user = HrmUserVarify.getUser(request, response); + TreeNode manager = new TreeNode(); + Map apidatas = new HashMap(); + Map resultDatas = new HashMap(); + try{ + adci = new AppDetachComInfo(user); + this.user = user; + String id = Util.null2String(request.getParameter("id")); + String rootid = Util.null2String(request.getParameter("rootid")); + if(id.length()>0){ + rootid = ""; + } + alllevel = Util.null2String(request.getParameter("alllevel"));//是否显示所有下级 + isNoAccount = Util.null2String(request.getParameter("isNoAccount"));// 是否显示无账号人员 + if(id.length()==0||rootid.length()>0){ + String userid = ""+user.getUID(); + String username = user.getLastname(); + if(rootid.length()>0){ + ResourceComInfo rci = new ResourceComInfo(); + userid = rootid; + username = rci.getLastname(userid); + } + manager.setId(userid); + manager.setName(username); + manager.setType("1"); + manager.setCanClick(true); + List result = getChildTreeNode(manager).getSubs(); + if(result!=null && result.size()>0){ + manager.setIsParent(true); + } + resultDatas.put("rootManager", manager); + apidatas.put("datas", resultDatas); + }else{ + manager.setId(id); + List result = getChildTreeNode(manager).getSubs(); + apidatas.put("datas", result); + } + }catch (Exception e) { + writeLog(e); + } + + return apidatas; + } + + private TreeNode getChildTreeNode(TreeNode manager){ + List childNode = null; + RecordSet rs = new RecordSet(); + String sql = ""; + String sqlwhere = ""; + try{ + childNode = new ArrayList(); + String id = manager.getId(); + + if(id.length()>0){ + //二开修改 取线长下所有组员 + sql = " select hr.id, lastname from hrmresource hr left join cus_fielddata c on hr.id=c.id and c.scope='HrmCustomFieldByInfoType' " + + " and c.scopeid=-1 left join hrmdepartmentdefined d on hr.departmentid=d.deptid where (field89="+id+" or managerid="+id+" or d.kqwy="+id+") "; + if(sqlwhere.length()>0)sqlwhere=" and " +sqlwhere; + sqlwhere+=" and hr.status in (0,1,2,3)"; + + if(!isNoAccount.equals("1")){ + sqlwhere +=" and loginid is not null "+(rs.getDBType().equals("oracle")?"":" and loginid<>'' "); + } + if(adci.isUseAppDetach()){ + String appdetawhere = adci.getScopeSqlByHrmResourceSearch(user.getUID()+"",true,"resource_hr"); + String tempstr= (appdetawhere!=null&&!"".equals(appdetawhere)?(" and " + appdetawhere):""); + sqlwhere+=tempstr; + } + if(sqlwhere.length()>0)sql+=sqlwhere; + sql += " order by hr.dsporder "; + rs.executeSql(sql); + while(rs.next()){ + TreeNode orgBean = new TreeNode(); + if(id.equals(rs.getString("id")))continue; + orgBean.setId(rs.getString("id")); + orgBean.setName(rs.getString("lastname")); + orgBean.setType("1"); + orgBean.setCanClick(true); + orgBean.setIsParent(hasChild(rs.getString("id"))); + childNode.add(orgBean); + } + } + manager.setSubs(childNode); + }catch (Exception e) { + writeLog(e); + } + return manager; + } + + private boolean hasChild(String id){ + RecordSet rs = new RecordSet(); + String sql = ""; + String sqlwhere = ""; + boolean isParent = false; + try{ + if(id.length()>0){ + //sql = "select count(1) from hrmresource hr where managerid = "+id; + sql = " select count(1) from hrmresource hr left join cus_fielddata c on hr.id=c.id and c.scope='HrmCustomFieldByInfoType' " + + " and c.scopeid=-1 left join hrmdepartmentdefined d on hr.departmentid=d.deptid where (field89="+id+" or managerid="+id+" or d.kqwy="+id+")"; + if(sqlwhere.length()>0)sqlwhere=" and " +sqlwhere; + sqlwhere+=" and hr.status in (0,1,2,3)"; + + if(!isNoAccount.equals("1")){ + sqlwhere +=" and loginid is not null "+(rs.getDBType().equals("oracle")?"":" and loginid<>'' "); + } + if(adci.isUseAppDetach()){ + String appdetawhere = adci.getScopeSqlByHrmResourceSearch(user.getUID()+"",true,"resource_hr"); + String tempstr= (appdetawhere!=null&&!"".equals(appdetawhere)?(" and " + appdetawhere):""); + sqlwhere+=tempstr; + } + if(sqlwhere.length()>0)sql+=sqlwhere; + //sql += " order by hr.dsporder "; + rs.executeSql(sql); + if(rs.next()){ + if(rs.getInt(1)>0){ + isParent = true; + } + } + } + }catch (Exception e) { + writeLog(e); + } + return isParent; + } +} diff --git a/src/com/api/hs/HsCheckApi.java b/src/com/api/hs/HsCheckApi.java new file mode 100644 index 0000000..19db50b --- /dev/null +++ b/src/com/api/hs/HsCheckApi.java @@ -0,0 +1,10 @@ +package com.api.hs; + +import com.engine.hsCheck.web.QkCheckAction; + +import javax.ws.rs.Path; + +@Path("/hshrm") +public class HsCheckApi extends QkCheckAction { + +} diff --git a/src/com/api/leshanvc/web/EntryCommitFormModeController.java b/src/com/api/leshanvc/web/EntryCommitFormModeController.java new file mode 100644 index 0000000..fda7d8f --- /dev/null +++ b/src/com/api/leshanvc/web/EntryCommitFormModeController.java @@ -0,0 +1,13 @@ +package com.api.leshanvc.web; + +import javax.ws.rs.Path; + +/** + * @Author ml + * @Date 2023/3/1 11:34 + * @Description This is description of class + * @Since version-1.0 + */ +@Path("/leshavc/formmode") +public class EntryCommitFormModeController extends com.engine.leshanvc.web.EntryCommitFormModeController { +} diff --git a/src/com/api/leshanvc/web/EntryWorkflowSaveEventAction.java b/src/com/api/leshanvc/web/EntryWorkflowSaveEventAction.java new file mode 100644 index 0000000..57c14e8 --- /dev/null +++ b/src/com/api/leshanvc/web/EntryWorkflowSaveEventAction.java @@ -0,0 +1,13 @@ +package com.api.leshanvc.web; + +import javax.ws.rs.Path; + +/** + * @Author weaver_cl + * @Description: + * @Date 2023/2/21 + * @Version V1.0 + **/ +@Path("/leshavc/entry/workflow") +public class EntryWorkflowSaveEventAction extends com.engine.leshanvc.web.EntryWorkflowSaveEventAction { +} diff --git a/src/com/api/leshanvc/web/KqWorkflowRangeLimitAction.java b/src/com/api/leshanvc/web/KqWorkflowRangeLimitAction.java new file mode 100644 index 0000000..c51ab0c --- /dev/null +++ b/src/com/api/leshanvc/web/KqWorkflowRangeLimitAction.java @@ -0,0 +1,13 @@ +package com.api.leshanvc.web; + +import javax.ws.rs.Path; + +/** + * @Author weaver_cl + * @Description: + * @Date 2023/3/3 + * @Version V1.0 + **/ +@Path("/leshavc/kq/workflow") +public class KqWorkflowRangeLimitAction extends com.engine.leshanvc.web.KqWorkflowRangeLimitAction { +} diff --git a/src/com/api/leshanvc/web/LeaverWorkflowAction.java b/src/com/api/leshanvc/web/LeaverWorkflowAction.java new file mode 100644 index 0000000..c782493 --- /dev/null +++ b/src/com/api/leshanvc/web/LeaverWorkflowAction.java @@ -0,0 +1,12 @@ +package com.api.leshanvc.web; + +import javax.ws.rs.Path; + +/** + * @author:dxfeng + * @createTime: 2023/04/19 + * @version: 1.0 + */ +@Path("/leshavc/leaver/workflow") +public class LeaverWorkflowAction extends com.engine.leshanvc.web.LeaverWorkflowAction { +} diff --git a/src/com/api/leshanvc/web/LzWorkflowManageAction.java b/src/com/api/leshanvc/web/LzWorkflowManageAction.java new file mode 100644 index 0000000..5562ae5 --- /dev/null +++ b/src/com/api/leshanvc/web/LzWorkflowManageAction.java @@ -0,0 +1,13 @@ +package com.api.leshanvc.web; + +import javax.ws.rs.Path; + +/** + * @Author ml + * @Date 2023/3/16 9:19 + * @Description This is description of class + * @Since version-1.0 + */ +@Path("/leshavc/lz/workflow") +public class LzWorkflowManageAction extends com.engine.leshanvc.web.LzWorkflowManageAction { +} diff --git a/src/com/api/leshanvc/web/ResourceCardAction.java b/src/com/api/leshanvc/web/ResourceCardAction.java new file mode 100644 index 0000000..e1d418c --- /dev/null +++ b/src/com/api/leshanvc/web/ResourceCardAction.java @@ -0,0 +1,12 @@ +package com.api.leshanvc.web; + +import javax.ws.rs.Path; + +/** + * @author:dxfeng + * @createTime: 2023/04/20 + * @version: 1.0 + */ +@Path("/leshavc/resource") +public class ResourceCardAction extends com.engine.leshanvc.web.ResourceCardAction{ +} diff --git a/src/com/api/leshanvc/web/SyncXcDataAction.java b/src/com/api/leshanvc/web/SyncXcDataAction.java new file mode 100644 index 0000000..9854fbf --- /dev/null +++ b/src/com/api/leshanvc/web/SyncXcDataAction.java @@ -0,0 +1,7 @@ +package com.api.leshanvc.web; + +import javax.ws.rs.Path; + +@Path("/leshavc/common/formmode") +public class SyncXcDataAction extends com.engine.leshanvc.web.SyncXcDataAction { +} diff --git a/src/com/api/leshanvc/web/WorkflowCheckAction.java b/src/com/api/leshanvc/web/WorkflowCheckAction.java new file mode 100644 index 0000000..313e493 --- /dev/null +++ b/src/com/api/leshanvc/web/WorkflowCheckAction.java @@ -0,0 +1,13 @@ +package com.api.leshanvc.web; + +import javax.ws.rs.Path; + +/** + * @Author weaver_cl + * @Description: + * @Date 2023/3/8 + * @Version V1.0 + **/ +@Path("/leshavc/common/workflow") +public class WorkflowCheckAction extends com.engine.leshanvc.web.WorkflowCheckAction { +} diff --git a/src/com/cloudstore/dev/api/service/Service_DevTable.java b/src/com/cloudstore/dev/api/service/Service_DevTable.java new file mode 100644 index 0000000..daf477a --- /dev/null +++ b/src/com/cloudstore/dev/api/service/Service_DevTable.java @@ -0,0 +1,3165 @@ +/* + * + * Copyright (c) 2001-2018 泛微软件. + * 泛微协同商务系统,版权所有. + * + */ +package com.cloudstore.dev.api.service; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.api.cube.service.CubeSearchService; +import com.api.cube.util.CubeSearchTransMethod; +import com.api.formmode.cache.CustomSearchComInfo; +import com.cloudstore.api.util.Util_DateTime; +import com.cloudstore.api.util.Util_Ehcache; +import com.cloudstore.dev.api.bean.*; +import com.cloudstore.dev.api.dao.Dao_Table; +import com.cloudstore.dev.api.dao.Dao_TableFactory; +import com.cloudstore.dev.api.util.TextUtil; +import com.cloudstore.dev.api.util.Util_TableMap; +import com.cloudstore.dev.api.util.Util_public; +import com.cloudstore.eccom.core.WeaCommon; +import com.cloudstore.eccom.result.WeaResultMsg; +import com.engine.common.constant.BizLogOperateType; +import com.engine.common.constant.BizLogSmallType4SysEngine; +import com.engine.common.constant.BizLogType; +import com.engine.common.entity.BizLogContext; +import com.engine.common.util.LogUtil; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.google.common.collect.Sets; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey; +import org.apache.poi.hssf.usermodel.HSSFCell; +import org.apache.poi.hssf.usermodel.HSSFRow; +import org.apache.poi.hssf.usermodel.HSSFSheet; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.openxml4j.opc.OPCPackage; +import org.apache.poi.openxml4j.opc.PackageAccess; +import org.apache.poi.poifs.crypt.EncryptionInfo; +import org.apache.poi.poifs.crypt.EncryptionMode; +import org.apache.poi.poifs.crypt.Encryptor; +import org.apache.poi.poifs.filesystem.POIFSFileSystem; +import org.apache.poi.ss.usermodel.*; +import org.apache.poi.xssf.streaming.SXSSFRow; +import org.apache.poi.xssf.streaming.SXSSFSheet; +import org.apache.poi.xssf.streaming.SXSSFWorkbook; +import weaver.common.StringUtil; +import weaver.conn.RecordSet; +import weaver.conn.constant.DBConstant; +import weaver.formmode.data.ModeDataIDUpdateSingle; +import weaver.formmode.service.CommonConstant; +import weaver.general.BaseBean; +import weaver.general.StaticObj; +import weaver.general.Util; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; +import weaver.hrm.company.DepartmentComInfo; +import weaver.interfaces.datasource.DataSource; +import weaver.rsa.security.RSA; +import weaver.security.util.SecurityMethodUtil; +import weaver.servicefiles.DataSourceXML; +import weaver.systeminfo.SystemEnv; +import weaver.systeminfo.setting.HrmUserSetting; +import weaver.systeminfo.setting.HrmUserSettingComInfo; +import weaver.systeminfo.setting.HrmUserSettingHandler; +import weaver.wechat.util.Utils; + +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import java.io.*; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Service_DevTable 表格接口 + */ +@Path("/ec/dev/table") +public class Service_DevTable { + + private static final Log logger = LogFactory.getLog(Service_DevTable.class); + + public String checkData = null; + private Dao_Table d = null; + /** + * 原部门层级划分 + */ + Map orgLevelMap; + Map orgLevelCodeMap; + + public Service_DevTable() { + try { + d = getDaoTableByPool(null); + } catch (Exception e) { + logger.error(e); + } + orgLevelMap = new HashMap<>(); + orgLevelMap.put(0, "中心"); + orgLevelMap.put(1, "部门"); + orgLevelMap.put(2, "小组"); + orgLevelMap.put(3, "线体"); + orgLevelCodeMap = new HashMap<>(); + orgLevelCodeMap.put(0, "中心编码"); + orgLevelCodeMap.put(1, "部门编码"); + orgLevelCodeMap.put(2, "小组编码"); + orgLevelCodeMap.put(3, "线体编码"); + } + + private Dao_Table getDaoTableByPool(String poolname) throws Exception { + try { + if (StringUtils.isBlank(poolname) && d != null) { + return d; + } + String dbType; + if (StringUtils.isBlank(poolname) || DataSourceXML.SYS_LOCAL_POOLNAME.equals(poolname)) { + RecordSet rs = new RecordSet(); + dbType = rs.getDBType(); + } else { + DataSource datasource = (DataSource) StaticObj.getServiceByFullname("datasource." + poolname, DataSource.class); + dbType = datasource.getType(); + } + if (isDBType(DBConstant.DB_TYPE_ORACLE, dbType)) + return Dao_TableFactory.getInstance().getDao("Dao_TableOracle"); + else if (isDBType(DBConstant.DB_TYPE_MYSQL, dbType)) + return Dao_TableFactory.getInstance().getDao("Dao_TableMysql"); + else if (isDBType(DBConstant.DB_TYPE_SQLSERVER, dbType)) + return Dao_TableFactory.getInstance().getDao("Dao_TableSqlServer"); + else if (isDBType(DBConstant.DB_TYPE_DB2, dbType)) + return Dao_TableFactory.getInstance().getDao("Dao_TableDB2"); + else if (isDBType(DBConstant.DB_TYPE_HANA, dbType)) + return Dao_TableFactory.getInstance().getDao("Dao_TableHana"); + else if (isDBType(DBConstant.DB_TYPE_POSTGRESQL, dbType)) + return Dao_TableFactory.getInstance().getDao("Dao_TablePostgresql"); + else + throw new Exception("不支持的数据库类型:" + dbType); + } catch (Exception e) { + throw new Exception("无法读取数据源,poolName:" + poolname, e); + } + } + + /** + * 判断数据库类型支持版本问题 + * + * @param dbTypeDef 标准数据库类型字符 + * @param dbType 数据库类型可以包含版本号 + * @return + */ + public boolean isDBType(String dbTypeDef, String dbType) { + if (dbType.equals("dm") || dbType.equals("st") || dbType.equals("jc") || dbType.equals("gs")) dbType = "oracle"; + if (dbType.equals("nt") || dbType.equals("ob")) dbType = "oracle"; + if (dbType.equals("pg")) dbType = "postgresql"; + if (dbType.equals("hg")) dbType = "postgresql"; + if (dbType.equals("og")) dbType = "postgresql"; + if (dbType.equals("ux")) dbType = "postgresql"; + if (dbType.equals("obmysql")) dbType = "mysql"; + return StringUtil.isNull(dbType) ? false : dbType.toLowerCase().startsWith(dbTypeDef); + } + + /** + * 1、列定义 2、数据总数 + * + * @param request + * @param response + * @param dataKey + * @return + */ + @POST + @Path("/counts") + @Produces(MediaType.TEXT_PLAIN) + public String getcounts(@Context HttpServletRequest request, + @Context HttpServletResponse response, + @FormParam("dataKey") String dataKey) { + JSONObject rspJson = new JSONObject(); + rspJson.put("status", false); + try { + + if (StringUtils.isBlank(dataKey)) { + rspJson.put("msg", "dataKey is null"); + return rspJson.toJSONString(); + } + User user = HrmUserVarify.getUser(request, response); + int languageid = user != null ? user.getLanguage() : 7; + + //解决counts接口非组件发起调用接口时找不到缓存数据问题 + Thread.sleep(100); + + String xmlString = Util_TableMap.getVal(dataKey); + if (StringUtils.isBlank(xmlString)) { + logger.info("读取dataKey为空:" + dataKey); + rspJson.put("msg", SystemEnv.getHtmlLabelName(508217, languageid)); + rspJson.put("errorCode", "005"); + return rspJson.toJSONString(); + } + + SplitPageBean bean = new SplitPageBean(xmlString, 0, "RootMap", "sql", "head"); + + // 兼容免登录业务 + String loginFree = Util.null2String(bean.getRootMap().getString("loginFree")); + if (!loginFree.equals("true") && user == null) { + rspJson.put("msg", SystemEnv.getHtmlLabelName(10004767, languageid)); + rspJson.put("errorCode", "005"); + return rspJson.toJSONString(); + } + + if (bean.getRootMap().containsKey("datasource")) { + rspJson = getMethodDatas(bean, user, rspJson, request, response); + if (rspJson.containsKey("datas")) { + rspJson.remove("datas"); + } + } else { + JSONObject sqlMap = bean.getSql(); + String poolname = bean.getSql().getString("poolname"); + rspJson.put("count", getDaoTableByPool(poolname).getDevTableCount(sqlMap)); + } + rspJson.put("status", true); + // "TimesE is :" + (System.currentTimeMillis() - times1)); + } catch (Exception e) { + logger.error(e.getMessage()); + //e.printStackTrace(); + //rspJson.put("msg", Util_public.getErrorInfoFromException(e)); + } + String result = JSON.toJSONString(rspJson); + return result; + } + + private JSONObject getMethodDatas(SplitPageBean bean, User user, JSONObject rspJson, HttpServletRequest request, HttpServletResponse response) throws Exception { + JSONObject Rootheads = bean.getRootMap(); + JSONObject sp = bean.getSql(); + JSONArray heads = bean.getHeads(); + + Map getCanMap = new HashMap(); + String tPrimaryKey = Util.null2String(sp.getString("sqlprimarykey")); + String[] primarys = primarys = tPrimaryKey.split(","); + if ("".equals(tPrimaryKey)) { + rspJson.put("errMsg", "tPrimaryKey is null!"); + } + boolean needCanMap = false; + if (Rootheads.containsKey("sourceparams")) { + getCanMap.put("fromExport", Util.null2String(bean.getSql().get("fromExport"))); + String sourceparamString = Util.null2String(Rootheads.getString("sourceparams")); + if (!"".equals(sourceparamString)) { + String[] sclist = sourceparamString.split("\\+"); + for (int i = 0; i < sclist.length; i++) { + String[] keyandvalue = sclist[i].split(":"); + if (2 == keyandvalue.length) { + getCanMap.put(keyandvalue[0], keyandvalue[1]); + } + } + } + needCanMap = true; + } + String dataSourceKey = Rootheads.getString("datasource"); + + String[] funcName = dataSourceKey.split("\\."); + String useFunName = funcName[funcName.length - 1]; + String useFun = dataSourceKey.substring(0, dataSourceKey.length() - useFunName.length() - 1); + + Class usedClass = Class.forName(useFun); + + Method useMethod1; + if (needCanMap) { + useMethod1 = usedClass.newInstance().getClass().getMethod(useFunName, User.class, Map.class, HttpServletRequest.class, HttpServletResponse.class); + } else { + useMethod1 = usedClass.newInstance().getClass().getMethod(useFunName, User.class, HttpServletRequest.class, HttpServletResponse.class); + } + List> getDatas = new ArrayList>(); + if (Rootheads.containsKey("pageBySelf")) { + // 这个逻辑是说明有分页参数,获取返回结构不一样 + Map getDatasforMap = new HashMap(); + if (needCanMap) { + getDatasforMap = (Map) useMethod1.invoke( + usedClass.newInstance(), user, getCanMap, request, + response); + } else { + getDatasforMap = (Map) useMethod1.invoke( + usedClass.newInstance(), user, request, response); + } + if (null != getDatasforMap) { + if (getDatasforMap.containsKey("dataAll")) { + rspJson.put("datas", getDatasforMap.get("dataAll")); + } + if (getDatasforMap.containsKey("recordCount")) { + rspJson.put("count", getDatasforMap.get("recordCount")); + } else { + rspJson.put("count", 0); + } + } else { + rspJson.put("count", 0); + rspJson.put("datas", new ArrayList>()); + } + + } else { + + if (needCanMap) { + getDatas = (List>) useMethod1.invoke( + usedClass.newInstance(), user, getCanMap, request, + response); + } else { + getDatas = (List>) useMethod1.invoke( + usedClass.newInstance(), user, request, response); + } + if (null != getDatas) { + rspJson.put("datas", getDatas); + rspJson.put("count", getDatas.size()); + } + } + for (int i = 0; i < getDatas.size(); i++) { + Map getData = getDatas.get(i); + for (int j = 0; j < heads.size(); j++) { + + JSONObject onceHead = heads.getJSONObject(j); + if (!getData.containsKey( + onceHead.getString("dataIndex"))) { + if ("randomFieldId".equals(onceHead.getString("dbField"))) { + getData.put(onceHead.getString("dataIndex"), getData.get(tPrimaryKey)); + } else { + getData.put(onceHead.getString("dataIndex"), getData.get(onceHead.getString("dbField"))); + } + } + } + } + ////============添加外部数据源 对randomField数据的处理 Andyzhang + if ("1".equals(Rootheads.getString("randomfieldopen"))) + for (int i = 0; i < rspJson.getJSONArray("datas").size(); i++) { + JSONObject obj = rspJson.getJSONArray("datas").getJSONObject(i); + for (int j = 0; j < heads.size(); j++) { + JSONObject onceHead = heads.getJSONObject(j); + if ("set".equals(onceHead.getString("from"))) { + obj.put(onceHead.getString("dataIndex"), obj.getString(onceHead.getString("dbField"))); + } + } + } + return rspJson; + } + + // 统一处理显示列定制 + private JSONArray getShowColHeads(SplitPageBean bean, String pageUid, + User user) { + if ("".equals(pageUid)) { + return bean.getHeads(); + } + List cols = d.getUserDefColumns(pageUid, user.getUID()); + if (cols == null || cols.isEmpty()) { + return bean.getHeads(); + } + Map headMap = Maps.newHashMap(); + Map noDataIndexMap = Maps.newHashMap(); + for (int i = 0; i < bean.getHeads().size(); i++) { + JSONObject col = (JSONObject) bean.getHeads().get(i); + col.put("orders", i); + if (StringUtils.isBlank(col.getString("dataIndex")) || headMap.containsKey(col.getString("dataIndex"))) { + noDataIndexMap.put(String.valueOf(i), col);//只是为了匹配下面方法的格式,没有实际意义。 + } else { + headMap.put(col.getString("dataIndex"), col); + } + } + + JSONArray heads = new JSONArray(); + for (UserDefCol col : cols) { + if (!headMap.containsKey(col.getDataIndex())) + continue; + JSONObject head = headMap.get(col.getDataIndex()); + //配置可以默认显示的列 Andyzhang + head.put("display", String.valueOf("0".equals(col.getDisplay()))); + if ("1".equalsIgnoreCase(head.getString("ignoreConfig"))) + head.put("display", "true"); + + if (StringUtils.isNotBlank(col.getWidth())) + head.put("oldWidth", col.getWidth()); + heads.add(head); + headMap.remove(col.getDataIndex()); + } + this.addToListByOrders(heads, headMap); + this.addToListByOrders(heads, noDataIndexMap); + return heads; + } + + /** + * 格式化輸出 + * + * @param bean + * @param data + * @param sumlist + * @param decimalFormat + * @return + */ + public Map sumTransMethod(SplitPageBean bean, Map data, String[] sumlist, String decimalFormat, String tCountcolumns) { + if (StringUtils.isNotBlank(decimalFormat)) { + String[] str = decimalFormat.split("\\|"); + int i = 0; + for (String item : sumlist) { + String format = str[i]; + String value = data.get(item); + String valueSpan = String.format(format, Util.getDoubleValue(value, 0)); + data.put(item + "span", valueSpan); + data.put(item, valueSpan); + i++; + } + } + + if ("true".equals(bean.getRootMap().getString("counttransmethod"))) + for (Object column : (List) bean.getHeads()) { + JSONObject obj = (JSONObject) column; + String name = obj.getString("dbField"); + String jsonName = obj.getString("dataIndex"); + for (String item : sumlist) { + if (item.equalsIgnoreCase(name)) { + if (obj.containsKey("transMethod") && StringUtils.isNotBlank(obj.getString("transMethod"))) { + if ("true".equals(obj.getString("display")) || "true".equals(obj.getString("transMethodForce"))) { + try { + String transMethod = obj.getString("transMethod"); + Object[] params = getParams(obj, data); + String valueSpan = doMethod(transMethod, params, obj.getString("dbField")); + data.put(jsonName + "span", valueSpan); + } catch (Exception e) { + e.printStackTrace(); + logger.error(e.getMessage()); + } + } + } + } + } + } + return data; + } + + /** + * TODO + * + * @param transMethod + * @param params + * @param defaultValue + * @return + * @throws ClassNotFoundException + * @throws InstantiationException + * @throws IllegalAccessException + * @throws NoSuchMethodException + * @throws SecurityException + * @throws IllegalArgumentException + * @throws InvocationTargetException + */ + private static String doMethod(String transMethod, Object[] params, String defaultValue) throws Exception { + if ("".equals(transMethod)) return defaultValue; + if ("com.api.cube.util.CubeSearchTransMethod.getOthers".equals(transMethod)) { + String otherpara = (String) params[1] + "+$issumcolumn$"; + return CubeSearchTransMethod.INSTANCE.getOthers((String) params[0], otherpara); + } + Object o = doMethod(transMethod, params); + return o.toString(); + } + + /** + * 获得一行数据中某个key的具体数据。处理了RecordSet与Map类型 + * + * @param data + * @param key + * @return + */ + private static String getValue(Object data, String key) { + if (data instanceof Map) { + return (String) ((Map) data).get(key); + } else if (data instanceof RecordSet) { + return ((RecordSet) data).getString(key); + } else { + return ""; + } + } + + /** + * 将transMethod方法的参数转化成某个固定格式,为了后面的处理 + * + * @param obj + * @param name + * @param rs + * @return + */ + private static JSONArray transMethodToNew(JSONObject obj, String name, Object rs) { + //String column = Util.null2String(obj.getString("dbField")); + String others = Util.null2String(obj.getString(name)); + JSONArray tmParams = new JSONArray(); + String otherArr[] = others.split("[+]"); + JSONObject tmObj1 = new JSONObject(); + tmObj1.put("type", "fixedValue"); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < otherArr.length; i++) { + + int pos = otherArr[i].toLowerCase().indexOf("column:"); + if (pos != -1) { + String tempOtherPara = otherArr[i].substring(pos + 7); + String paramString = Util.null2String(getValue(rs, tempOtherPara)); + if ("".equals(paramString)) { + sb.append(" "); + } else { + sb.append(paramString); + } + } else { + sb.append(otherArr[i]); + } + if (i != otherArr.length - 1) { + sb.append("+"); + } + } + tmObj1.put("obj", sb.toString()); + tmParams.add(tmObj1); + return tmParams; + } + + /** + * 获得transMethod方法的参数 + * + * @param obj + * @param data + * @return + */ + private static Object[] getParams(JSONObject obj, Object data) { + JSONArray tmParams = new JSONArray(); + JSONObject tmObj = new JSONObject(); + tmObj.put("type", "columns"); + tmObj.put("obj", obj.getString("dbField")); + tmParams.add(tmObj); + if (obj.containsKey("transMethodOther")) { + if (obj.get("transMethodOther") != null) + tmParams.addAll(transMethodToNew(obj, "transMethodOther", data)); + } + if (obj.containsKey("transMethodOther2")) { + if (obj.get("transMethodOther2") != null) + tmParams.addAll(transMethodToNew(obj, "transMethodOther2", data)); + } + Object[] sl = new Object[tmParams.size()]; + int i = 0; + for (Object t : (List) tmParams) { + JSONObject tObj = (JSONObject) t; + String typeStr = tObj.getString("type"); + String objStr = tObj.getString("obj"); + if (typeStr.equals("columns")) { + sl[i] = getValue(data, objStr); + } else { + sl[i] = objStr; + } + i++; + } + return sl; + } + + /** + * 执行方法 + * + * @param transMethod + * @param params + * @return + * @throws ClassNotFoundException + * @throws InstantiationException + * @throws IllegalAccessException + * @throws NoSuchMethodException + * @throws InvocationTargetException + */ + public static Object doMethod(String transMethod, Object[] params) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { + String tmArr[] = transMethod.split("\\."); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < tmArr.length - 1; i++) { + sb.append(tmArr[i]); + if (i != tmArr.length - 2) { + sb.append("."); + } + } + Class clazz = Class.forName(sb.toString()); + Object obj = clazz.newInstance(); + Class[] cl = new Class[params.length]; + for (int i = 0; i < params.length; i++) { + cl[i] = String.class; + } + + Method m1 = clazz.getDeclaredMethod(tmArr[tmArr.length - 1], cl); + return m1.invoke(obj, params); + } + + + @GET + @Path("/refresh") + @Produces(MediaType.TEXT_PLAIN) + public String refreshDatakey(@Context HttpServletRequest request, @Context HttpServletResponse response) { + JSONObject rspJson = new JSONObject(); + rspJson.put("status", true); + String dataKey = request.getParameter("dataKey"); + if (StringUtils.isBlank(dataKey)) { + rspJson.put("msg", "dataKey" + weaver.systeminfo.SystemEnv.getHtmlLabelName(385284, weaver.general.ThreadVarLanguage.getLang()) + ""); + return rspJson.toJSONString(); + } + + String xmlString = Util_TableMap.getVal(dataKey); + if (StringUtils.isBlank(xmlString)) { + User user = HrmUserVarify.getUser(request, response); + int languageid = user != null ? user.getLanguage() : 7; + rspJson.put("msg", SystemEnv.getHtmlLabelName(508217, languageid)); + rspJson.put("errorCode", "005"); + return rspJson.toJSONString(); + } else { + Util_TableMap.refreshKey(dataKey); + } + return rspJson.toJSONString(); + } + + + @POST + @Path("/datas") + @Produces(MediaType.TEXT_PLAIN) + public String datas(@Context HttpServletRequest request, + @Context HttpServletResponse response, + @FormParam("dataKey") String dataKey, + @FormParam("pageSize") String pageSize, + @FormParam("sortParams") String sortParams, + @FormParam("min") String min, @FormParam("max") String max, + @FormParam("current") String current, @FormParam("ismobile") String ismobile) { + + JSONObject rspJson = new JSONObject(); + rspJson.put("status", false); + + if (!Util_public.checkSortParams(sortParams)) { + rspJson.put("msg", "SQL Injection error"); + return rspJson.toJSONString(); + } + + try { + TimeMarker timeMarker = new TimeMarker(); + timeMarker.setMark(true); + timeMarker.markStart(); + + if (StringUtils.isBlank(dataKey)) { + rspJson.put("msg", "dataKey is null"); + return rspJson.toJSONString(); + } + User user = HrmUserVarify.getUser(request, response); + int languageid = user != null ? user.getLanguage() : 7; + + String xmlString = Util_TableMap.getVal(dataKey); + if (StringUtils.isBlank(xmlString)) { + rspJson.put("msg", SystemEnv.getHtmlLabelName(508217, languageid)); + rspJson.put("errorCode", "005"); + return rspJson.toJSONString(); + } + + String sessionId = Util_TableMap.getSessionVal(dataKey); + if (!StringUtils.equals(SessionFilter.getSessionId(), sessionId)) { + rspJson.put("msg", SystemEnv.getHtmlLabelName(388918, languageid)); + rspJson.put("errorCode", "005"); + return rspJson.toJSONString(); + } + + SplitPageBean bean = new SplitPageBean(request, dataKey, "RootMap", "operates", "head", "sql", "checkboxpopedom", "browser", "otherHeads"); + + // 校验免登录标识 + String loginFree = Util.null2String(bean.getRootMap().getString("loginFree")); + if (!loginFree.equals("true") && user == null) { + rspJson.put("msg", SystemEnv.getHtmlLabelName(10004767, languageid)); + rspJson.put("errorCode", "005"); + return rspJson.toJSONString(); + } + + Util_TableMap.refreshKey(dataKey); + + if ("1".equalsIgnoreCase(ismobile)) bean.getSql().put("ismobile", "ismobile"); + + //获取测试预览的当前操作用户 +// if (bean.getRootMap() != null && bean.getRootMap().containsKey("sourceparams")) { +// String sourceparams = (String)bean.getRootMap().get("sourceparams"); +// String datashowid = sourceparams.substring(sourceparams.indexOf(":")+1); +// +// RecordSet rs = new RecordSet(); +// rs.executeQuery("select showname from datashowset where id = ?", datashowid); +// if (rs.next()) { +// String showname = rs.getString(Util.null2String("showname")); +// String operatorId = (String)StaticObj.getInstance().getObject("browser.operatoruser." + showname); +// if (operatorId != null && operatorId.length() > 0) { +// user = User.getUser(Integer.parseInt(operatorId), 0); +// } +// } +// } + + timeMarker.mark("init Bean"); + String isPageAutoWrap = "1"; + // 加入读取折行逻辑 + if (user != null) { + HrmUserSettingComInfo userSetting = new HrmUserSettingComInfo(); + String id = userSetting.getId(user.getUID() + ""); + if ("".equals(id)) { + HrmUserSettingHandler handler = new HrmUserSettingHandler(); + HrmUserSetting setting = handler.getSetting(user.getUID()); + boolean rtxload = setting.isRtxOnload(); + String isload = "0"; + if (rtxload) { + isload = "1"; + } + d.insertUserSetting(user.getUID(), isload); + userSetting.removeHrmUserSettingComInfoCache(); + userSetting = new HrmUserSettingComInfo(); + id = userSetting.getId(user.getUID() + ""); + } + //默认折行 + isPageAutoWrap = userSetting.getIsPageAutoWrap(id); + } + + boolean flag = !"0".equals(isPageAutoWrap); + String pageAutoWrap = bean.getRootMap().getString("pageAutoWrap"); + if (StringUtils.isNotBlank(pageAutoWrap)) { + flag = "1".equals(pageAutoWrap); + } + rspJson.put("pageAutoWrap", flag); + //rspJson.put("pageAutoWrap", "1".equals(isPageAutoWrap)); + + // pageSize逻辑上移 + String paSize = ""; + String pageUId = ""; + if (null != bean.getRootMap()) { + pageUId = Util.null2String(bean.getRootMap().getString("pageUid")); + } + String tablePageSize = bean.getRootMap().getString("pagesize"); + + if (null != bean.getHeads()) { + if (user != null) bean.setHeads(getShowColHeads(bean, pageUId, user)); + bean.mergeHeads(); + } + + //调整分页规则 + if (StringUtils.isNotBlank(pageSize)) { + rspJson.put("pageSize", pageSize); + } else if (!"".equals(pageUId)) { + if (user != null) + paSize = d.getPageSize(user.getUID(), pageUId); + if (StringUtils.isBlank(paSize)) { + // 需要新增 + rspJson.put("pageSize", StringUtils.isBlank(tablePageSize) ? 10 : tablePageSize); + } else { + rspJson.put("pageSize", paSize); + } + } else { + rspJson.put("pageSize", 10); + } + + // 分页逻辑上移 + min = Util.null2String(min); + max = Util.null2String(max); + current = Util.null2String(current); + if ("".equals(max) || "".equals(min)) { + // 只要空就走以下逻辑 + if ("".equals(current)) { + min = "1"; + max = rspJson.getString("pageSize"); + } else { + int minInt = (Integer.valueOf(current) - 1) * Integer.valueOf(rspJson.getString("pageSize")) + 1; + int maxInt = minInt + Integer.valueOf(rspJson.getString("pageSize")) - 1; + min = minInt + ""; + max = maxInt + ""; + } + } + + timeMarker.mark("get current user and count page "); + List> mssl = new ArrayList>(); + + if (bean.getRootMap().containsKey("datasource")) { + // 说明不需要拼接sql,直接从接口获取数据 + // 支持方法中直接分页 + mssl = getDataFromDatasource(request, response, sortParams, min, max, timeMarker, rspJson, bean, user, ismobile); + + + rspJson.put("datas", mssl); + rspJson.put("columns", bean.getHeads()); + rspJson.put("ops", bean.getOperates()); + + } else { + String poolname = bean.getSql().getString("poolname"); + // 加入分页逻辑 + //根据pageUId 查询 mode_customsearch 里的相关信息,是否需要置顶,以及置顶条件,然后给需要置顶的表,修改表结构添加isTop 字段,用于排序。 + if (pageUId.startsWith("mode_customsearch:")) { + CustomSearchComInfo customSearchComInfo = new CustomSearchComInfo(); + int custom_id = Util.getIntValue(Util.null2String(pageUId.substring(pageUId.indexOf(":") + 1, pageUId.length())), 0); + if (custom_id != 0) { + String dataShowType = customSearchComInfo.getDatashowtype(custom_id + ""); + Map otherparam = new HashMap<>(); + otherparam.put("user", user); + if (!dataShowType.equals("2")) { + getCompleteSql(pageUId, bean, otherparam);//添加密级判断,以及数据置顶逻辑 + } + } + } + + JSONObject jsonObject = bean.getSql(); + if ("excel".equals(request.getParameter("displayType")) && !jsonObject.containsKey("wrapclose")) { //查询 excel 换行 + jsonObject.put("wrapclose", "1"); + } + + mssl = getDaoTableByPool(poolname).getDevTableDatas(jsonObject, bean.getHeads(), min, max, sortParams, bean.getBroList(), timeMarker); + // 需要判断是否包含字段密级字段(seclevel) 目前参数不支持 快速判断(分页最大值为100,最差情况也就是遍历一百次) +// AddSeclevelUtil addSeclevelUtil = new AddSeclevelUtil(); +// HashMap otherparam = new HashMap<>(); +// addSeclevelUtil.getSecLevelItems(mssl,user,otherparam); + + timeMarker.mark("read data from datasource"); + if (pageUId.startsWith("mode_customsearch:")) { + CubeSearchTransMethod.clearCache(pageUId); + } + // 加入查询分页数量 + //logger.info("heads:"+ JSON.toJSONString( bean.getHeads())); + + rspJson.put("columns", bean.getHeads()); + rspJson.put("ops", bean.getOperates()); + rspJson.put("datas", mssl); + rspJson.put("isSts", false); + // 加入以前的合并同类给出合计值功能 + if (bean.getSql().containsKey("sumColumns")) { + // 说明存在合计参数 + String[] sumlist = Util.null2String(bean.getSql().getString("sumColumns")).split(","); + List sumDecryptList = Util.TokenizerString(bean.getSql().getString("sumDecryptColumns"), ","); + String tCountcolumns = Util.null2String(bean.getSql().getString("countcolumnsdbtype")); + String decimalFormat = Util.null2String(bean.getSql().getString("decimalFormat")); + Map sumMap = new HashMap(); + for (int i = 0; i < sumlist.length; i++) { + if (sumDecryptList.indexOf(sumlist[i]) > -1) { + sumMap.put(sumlist[i].trim(), "****"); + sumMap.put(sumlist[i].trim() + "span", "****"); + continue; + } + Double thissum = 0.00; + Double sumspan = null; + for (int j = 0; j < mssl.size(); j++) { + if (Util_public.isThousandsField(sumlist[i], tCountcolumns)) { + String str = mssl.get(j).get(sumlist[i].trim()); + if (StringUtils.isNotEmpty(str)) str = str.replace(",", ""); + thissum += Util.getDoubleValue(str, 0); + } else + thissum += Util.getDoubleValue(mssl.get(j).get(sumlist[i].trim()), 0); + //span不进行转换后统计列计算 andyzhang + //当页合计 + + } + sumMap.put(sumlist[i].trim(), Util_public.parseString(thissum)); + sumMap.put(sumlist[i].trim() + "span", Util_public.parseString(thissum)); + } + + sumMap = sumTransMethod(bean, sumMap, sumlist, decimalFormat, tCountcolumns); + + Map allSumMap = new HashMap(); + allSumMap = getDaoTableByPool(poolname).getSqlSum(bean.getSql(), sumlist, allSumMap); + // 如果存在sumValues,说明这个值在取tableString时已经计算好了。针对需要transMethod配置显示数据的场景。 + // 格式: key:value+key2:value2 + if (bean.getSql().containsKey("sumValues")) { + String[] sumValues = Util.null2String(bean.getSql().getString("sumValues")).split("\\+"); + for (int i = 0; i < sumValues.length; i++) { + String[] sumValue = sumValues[i].split(":"); + //allSumMap.put(sumValue[0].trim(), Util.getDoubleValue(sumValue[1].trim(), 0)); + allSumMap.put(sumValue[0].trim(), sumValue[1].trim()); + } + } + + allSumMap = sumTransMethod(bean, allSumMap, sumlist, decimalFormat, tCountcolumns); + //decimalFormat="%.0f|%.2f|%.2f|%.0f|"; + + rspJson.put("isSts", true); + rspJson.put("stsData", sumMap); + rspJson.put("stsAllData", allSumMap); + timeMarker.mark("sum data"); + } + } + boolean haveCheck = false; + if (bean.getCheckboxList().size() > 0) { + JSONObject checkboxFirst = (JSONObject) bean.getCheckboxList().get(0); + haveCheck = checkboxFirst.getString("id") != null; + } + rspJson.put("haveCheck", haveCheck); + rspJson.put("status", true); + + // 暂时来说,这里向rspJson里放入了browser,columns,datas,还没有抽出来。 + bean.outputByBrowser(rspJson, mssl); + timeMarker.mark("do browser"); + rspJson.put("rootMap", bean.getRootMap()); + // result = JSON.toJSONString(rspJson); + + // "AAATimesF is :" + (System.currentTimeMillis() - startTime)); + timeMarker.markEnd(); + if (timeMarker.isMark()) { + rspJson.put("timeJson", timeMarker.toTimeCostJSON()); + } + + rspJson.put("expandOperate", 0); + + //移动端信息 + if (bean.getRootMap().containsKey("mobileshowtype")) + rspJson.put("mobileshowtype", bean.getRootMap().getString("mobileshowtype")); + + if (bean.getRootMap().containsKey("rowstylefield")) + rspJson.put("rowstylefield", bean.getRootMap().getString("rowstylefield")); + + if (bean.getRootMap().containsKey("mobileshowtemplate")) { + String str = bean.getRootMap().getString("mobileshowtemplate"); + if (StringUtil.isNotNull(str)) { + SplitMobileTemplateBean tempBean = Util_public.getMobileTemplateExt(str); + rspJson.put("mobileshowtemplate", tempBean); + } + } + + } catch (Exception e) { + logger.error(e.getMessage()); + e.printStackTrace(); + //rspJson.put("msg", Util_public.getErrorInfoFromException(e)); + rspJson.put("msg", "error"); + } + + return rspJson.toJSONString(); + } + + + private List> getDataFromDatasource(HttpServletRequest request, HttpServletResponse response, + String sortParams, String min, + String max, TimeMarker timeMarker, JSONObject rspJson, + SplitPageBean bean, User user, String ismobile) throws Exception { + List> mssl = Lists.newArrayList(); + request.setAttribute("min", min); + request.setAttribute("max", max); + request.setAttribute("pageSize", rspJson.getString("pageSize")); + request.setAttribute("sortParams", sortParams); + String tPrimaryKey = Util.null2String(bean.getSql().getString("sqlprimarykey")); + rspJson = getMethodDatas(bean, user, rspJson, request, response); + if (timeMarker != null) { + timeMarker.mark("read data from dataSource"); + } + + List> getDatas = Lists.newArrayList(); + if (rspJson.containsKey("datas")) { + getDatas = (List>) rspJson.get("datas"); + } + int minInt = 0; + int maxInt = getDatas.size(); + if (!bean.getRootMap().containsKey("pageBySelf")) { + minInt = Integer.valueOf(min) - 1; + maxInt = Integer.valueOf(max); + if (minInt < 0) { + minInt = 0; + } + if (maxInt > getDatas.size()) + maxInt = getDatas.size(); + } + for (int i = minInt; i < maxInt; i++) { + Map getData = getDatas.get(i); + for (Object obj : (List) bean.getHeads()) { + JSONObject column = (JSONObject) obj; + //加入对base64的支持功能 andyzhang + if (column.containsKey("isBase64") && column.getString("isBase64").equals("1")) { + String jsonName = column.getString("dataIndex"); + String value = getData.get(jsonName); + value = TextUtil.toBase64ForMultilang(value); + /*if (Util.isEnableMultiLang()) {//weainput多语言需要在前面加上base_标识 + value=TextUtil.toBase64ForMultilang(value); + }else { + value=Util_public.base64Encode(value); + }*/ + getData.put(jsonName, value); + } + if (column.containsKey("transMethod") && column.containsKey("display")) + if ("true".equals(column.getString("display")) || "true".equals(column.getString("transMethodForce"))) { + String jsonName = column.getString("dataIndex"); + String transvalue = Util_public.doTransMethod(column, getData); + + if ("1".equalsIgnoreCase(ismobile)) { + if (StringUtils.isNotBlank(transvalue)) + transvalue = Util_public.deletcLink(transvalue); + } + getData.put(jsonName + "span", transvalue); + } + if (StringUtils.isNotBlank(tPrimaryKey)) { + getData.put("randomFieldId", getData.get(tPrimaryKey)); + } + } + mssl.add(getData); + } + + if (timeMarker != null) { + timeMarker.mark("do transmethod in dataSource"); + } + return mssl; + } + + // 测试用获取 xmlString以及oracle和sql拼好的语句 + @GET + @Path("/getxml") + @Produces(MediaType.TEXT_PLAIN) + public String datas(@Context HttpServletRequest request, @Context HttpServletResponse response) { + // long startTime = System.currentTimeMillis(); + String dataKey = Util.null2String(request.getParameter("dataKey")); + JSONObject jo = new JSONObject(); + jo.put("status", false); + try { + if (!"".equals(dataKey)) { + //AndyZhang 解决IP地址切换的导致的数据获取不到问题 + String xmlString = Util.null2String(Util_TableMap.getVal(dataKey)); + if (!"".equals(xmlString)) { + jo.put("xmlString", xmlString); + SplitPageBean bean = new SplitPageBean(request, dataKey, "head", "sql"); + String sortParams = Util.null2String(request.getParameter("sortParams")); + RecordSet rs = new RecordSet(); + String sql = getDevTableSql(bean.getSql(), bean.getHeads(), sortParams, rs.getDBType()); + jo.put("sql", sql); + jo.put("status", true); + } else { + jo.put("msg", "xmlString " + weaver.systeminfo.SystemEnv.getHtmlLabelName(18622, weaver.general.ThreadVarLanguage.getLang()) + ""); + } + } else { + jo.put("msg", "dataKey " + weaver.systeminfo.SystemEnv.getHtmlLabelName(18622, weaver.general.ThreadVarLanguage.getLang()) + ""); + } + } catch (Exception e) { + logger.error(e); + //e.printStackTrace(); + jo.put("msg", Util_public.getErrorInfoFromException(e)); + } + return jo.toString(); + } + + public String getTableSqlByKey(HttpServletRequest request, String dataKey) throws Exception { + // String dataKey = Util.null2String(request.getParameter("dataKey")); + if (null == dataKey || "".equals(dataKey) + || !Util_TableMap.containsKey(dataKey)) + return ""; + SplitPageBean bean = new SplitPageBean(request, dataKey, "head", "sql"); + RecordSet rs = new RecordSet(); + String dbtype = "oracle".equalsIgnoreCase(rs.getDBType()) ? "oracle" : "sqlserver"; + return getDevTableSql(bean.getSql(), bean.getHeads(), "", dbtype); + } + + public String getTableSqlByKeyNoOrder(HttpServletRequest request, String dataKey) throws Exception { + // String dataKey = Util.null2String(request.getParameter("dataKey")); + if (null == dataKey || "".equals(dataKey) + || !Util_TableMap.containsKey(dataKey)) + return ""; + SplitPageBean bean = new SplitPageBean(request, dataKey, "head", "sql"); + RecordSet rs = new RecordSet(); + String dbtype = "oracle".equalsIgnoreCase(rs.getDBType()) ? "oracle" : "sqlserver"; + return getDevTableSqlNoOrder(bean.getSql(), bean.getHeads(), "", dbtype); + } + + private String getDevTableSqlNoOrder(JSONObject sqlObj, JSONArray heads, + String sortParams, String type) { + + String tFields = Util.null2String(sqlObj.getString("backfields")); + String tFrom = Util.toSqlForSplitPage(Util.null2String(sqlObj + .getString("sqlform"))); + String tWhere = Util.toSqlForSplitPage(Util.null2String(sqlObj + .getString("sqlwhere"))); + String tOrder = Util.null2String(sqlObj.getString("sqlorderby")); + String tOrderWay = Util.null2String(sqlObj.getString("sqlsortway")); + String tDistinct = Util.null2String(sqlObj.getString("sqlisdistinct")); + + StringBuilder sb = new StringBuilder(); + + sb.append(" select " + ("true".equals(tDistinct) ? "distinct " : "") + + tFields); + sb.append(" "); + if (!tFrom.startsWith("from")) + sb.append("from"); + sb.append(" ").append(tFrom); + sb.append(" "); + if (!tWhere.startsWith("where") && !"".equals(tWhere)) + sb.append(" where"); + sb.append(" ").append(tWhere); + if (!"".equals(tOrder)) + sb.append(" order by ").append(tOrder); + + return sb.toString(); + } + + private String getDevTableSql(JSONObject sqlObj, JSONArray heads, + String sortParams, String type) { + String tFields = Util.null2String(sqlObj.getString("backfields")); + String tFrom = Util.toSqlForSplitPage(Util.null2String(sqlObj + .getString("sqlform"))); + String tWhere = Util.toSqlForSplitPage(Util.null2String(sqlObj + .getString("sqlwhere"))); + String tOrder = Util.null2String(sqlObj.getString("sqlorderby")); + String tOrderWay = Util.null2String(sqlObj.getString("sqlsortway")); + String tDistinct = Util.null2String(sqlObj.getString("sqlisdistinct")); + + StringBuilder sb = new StringBuilder(); + + sb.append(" select " + ("true".equals(tDistinct) ? "distinct " : "") + + tFields); + sb.append(" "); + if (!tFrom.startsWith("from")) + sb.append("from"); + sb.append(" ").append(tFrom); + sb.append(" "); + if (!tWhere.startsWith("where") && !"".equals(tWhere)) + sb.append(" where"); + sb.append(" ").append(tWhere); + if (!"".equals(tOrder)) + sb.append(" order by ").append(tOrder); + if (!"".equals(tOrderWay)) + sb.append(" ").append(tOrderWay); + + return sb.toString(); + } + + /** + * 分页函数接口 + * + * @param request 请求对象 + * @param response 回复对象 + * @param dataKey tableString 键 + * @param min 开始行号 + * @param pageSize 分页大小 + * @param max 末尾行号 + * @return + */ + @POST + @Path("/pageSize") + @Produces(MediaType.TEXT_PLAIN) + public String datas(@Context HttpServletRequest request, + @Context HttpServletResponse response, + @FormParam("dataKey") String dataKey, @FormParam("min") String min, + @FormParam("pageSize") String pageSize, + @FormParam("max") String max) { + long startTime = System.currentTimeMillis(); + String result = ""; + JSONObject rspJson = new JSONObject(); + rspJson.put("status", false); + String pageUid = ""; + User user = HrmUserVarify.getUser(request, response); + String xmlString = Util_TableMap.getVal(dataKey); + + if (StringUtils.isBlank(xmlString)) { + int languageid = user != null ? user.getLanguage() : 7; + rspJson.put("msg", SystemEnv.getHtmlLabelName(508217, languageid)); + rspJson.put("errorCode", "005"); + return rspJson.toJSONString(); + } + + try { + SplitPageBean bean = new SplitPageBean(request, dataKey, "RootMap"); + pageUid = Util.null2String(bean.getRootMap().getString("pageUid")); + } catch (Exception e) { + logger.error(e); + e.printStackTrace(); + //rspJson.put("msg", Util_public.getErrorInfoFromException(e)); + } + if (StringUtils.isBlank(pageUid)) { + if (rspJson.get("msg") == null) { + rspJson.put("msg", "pageUid" + weaver.systeminfo.SystemEnv.getHtmlLabelName(18622, weaver.general.ThreadVarLanguage.getLang()) + ""); + } + return rspJson.toJSONString(); + } + + if (user == null) { + rspJson.put("msg", "user" + weaver.systeminfo.SystemEnv.getHtmlLabelName(18622, weaver.general.ThreadVarLanguage.getLang()) + ""); + + return rspJson.toJSONString(); + } + //加入查询分页数量 + min = Util.null2String(min); + max = Util.null2String(max); + pageSize = Util.null2String(pageSize); + if (!"".equals(pageUid)) { + int usedPageSize = 10; + if (!"".equals(pageSize)) { + usedPageSize = Integer.valueOf(pageSize); + } else if (!"".equals(min) && !"".equals(max)) { + usedPageSize = (Integer.valueOf(max) - Integer.valueOf(min)) + 1; + } + + String paSize = d.getPageSize(user.getUID(), pageUid); + if ("".equals(paSize)) { + // 需要新增 + d.insertPageSize(user.getUID(), pageUid, usedPageSize); + } else if (usedPageSize != Integer.valueOf(paSize)) { + // 需要修改 + d.updatePageSize(user.getUID(), pageUid, usedPageSize); + } + rspJson.put("pageSize", usedPageSize); + rspJson.put("status", true); + } else { + rspJson.put("errMsg", "pageUid" + weaver.systeminfo.SystemEnv.getHtmlLabelName(18622, weaver.general.ThreadVarLanguage.getLang()) + ""); + } + result = JSON.toJSONString(rspJson); + return result; + } + + /** + * 安全性检查 + * + * @param data + * @return + */ + public JSONObject checkJson(JSONObject data) { + if (Objects.isNull(checkData)) { + BaseBean bb = new BaseBean(); + checkData = Util.null2String(bb.getPropValue("weaver_new_session", "checkdata")); + } + + if ("0".equals(checkData)) return data; + + Map map = new HashMap<>(); + + //自行修复报错 + Iterator it = data.entrySet().iterator(); + while (it.hasNext()) { + Map.Entry entry = (Map.Entry) it.next(); + map.put(entry.getKey(), entry.getValue()); + } + + for (Map.Entry entry : map.entrySet()) { + String value = Util.null2String(entry.getValue()); + value = SecurityMethodUtil.checkSql(value); + value = SecurityMethodUtil.clearKeywordFromConditon(value); + entry.setValue(value); + } + return data; + } + + + /** + * 获取选择框的状态列表 + * + * @param request 请求 + * @param response 响应 + * @param dataKey 键值 + * @param checkId 编号 + * @param randomDatas + * @return + */ + @POST + @Path("/checks") + @Produces(MediaType.TEXT_PLAIN) + public String checks(@Context HttpServletRequest request, + @Context HttpServletResponse response, + @FormParam("dataKey") String dataKey, @FormParam("checkId") String checkId, + @FormParam("randomDatas") String randomDatas) { + JSONObject rspJson = new JSONObject(); + /*防止html注入 + if(StringUtils.isNotBlank(randomDatas)) + randomDatas=randomDatas.replaceAll("[\\>\\<]", ""); + */ + JSONArray rdJson = JSON.parseArray(randomDatas); + try { + if (StringUtils.isBlank(dataKey)) { + rspJson.put("msg", "dataKey is null"); + //rspJson.put("errorCode", "005"); + rspJson.put("status", false); + return rspJson.toJSONString(); + } + + User user = HrmUserVarify.getUser(request, response); + + String xmlString = Util_TableMap.getVal(dataKey); + if (StringUtils.isBlank(xmlString)) { + int languageid = user != null ? user.getLanguage() : 7; + rspJson.put("msg", SystemEnv.getHtmlLabelName(508217, languageid)); + rspJson.put("errorCode", "005"); + return rspJson.toJSONString(); + } + + List getList = new ArrayList(); + SplitPageBean bean = new SplitPageBean(request, dataKey, "RootMap", "operates", "head", "checkboxpopedom", "otherHeads"); + + // 校验免登录标识 + String loginFree = Util.null2String(bean.getRootMap().getString("loginFree")); + if (!loginFree.equals("true") && user == null) { + int languageid = user != null ? user.getLanguage() : 7; + rspJson.put("msg", SystemEnv.getHtmlLabelName(10004767, languageid)); + rspJson.put("errorCode", "005"); + return rspJson.toJSONString(); + } + + bean.mergeHeads(); + + JSONObject popdom = bean.getOperates().size() > 0 ? bean.getOperates().getJSONObject(0) : null; + String opTransmethod = popdom != null ? Utils.null2String(popdom.getString("transmethod")) : ""; + JSONObject checkbox = bean.getCheckBox(checkId); + String showmethod = Util.null2String(checkbox.getString("showmethod")); + for (int i = 0; i < rdJson.size(); i++) { + JSONObject newRd = new JSONObject(); + JSONObject rd = rdJson.getJSONObject(i); + rd = checkJson(rd); + JSONArray tmParams = transMethodToNew(checkbox, "popedompara", rd, bean.getHeads()); + String opValue = ""; + String value = ""; + try { + // "tmParams:"+tmParams.toJSONString()); + if ("".equals(showmethod) || "true".equals(showmethod)) + value = "true"; + else if ("false".equals(showmethod)) + value = "false"; + else //检查参数安全 andyzhang 2019-12-23 + //value = SecurityMethodUtil.textXssClean(doMethod(rd, showmethod, tmParams, "", bean.getHeads())); + value = doMethod(rd, showmethod, tmParams, "", bean.getHeads()); + + if ("".equals(opTransmethod) || "true".equals(opTransmethod)) + newRd.put("randomFieldOp", "true"); + else if ("false".equals(opTransmethod)) + newRd.put("randomFieldOp", "false"); + else { + JSONArray opParams = new JSONArray(); + JSONObject tmObj = new JSONObject(); + tmObj.put("type", "fixedValue"); + tmObj.put("obj", rd.getString("randomFieldId") == null ? 0 + : rd.getString("randomFieldId")); + opParams.add(tmObj); + + opParams.addAll(transMethodToNew(popdom, "otherpara", rd, bean.getHeads())); + opParams.addAll(transMethodToNew(popdom, "otherpara2", rd, bean.getHeads())); + opValue = doMethod(rd, opTransmethod, opParams, "", bean.getHeads()); + for (int j = 1; j < bean.getOperates().size(); j++) { + JSONObject op = bean.getOperates().getJSONObject(j); + JSONArray rfop = transMethodToNew(op, "otherpara", rd, bean.getHeads()); + // l.write("checks rfop :" + rfop.toString()); + newRd.put("randomFieldOpPara" + op.getString("index"), rfop); + } + newRd.put("randomFieldOp", opValue); + } + + } catch (Exception e) { + e.printStackTrace(); + } + newRd.put("randomFieldCk", value); + newRd.put("randomFieldId", rd.getString("randomFieldId")); + // "opValue:"+opValue); + // l.write("checks out try newRd :" + newRd.toString()); + rdJson.set(i, newRd); + } + } catch (Exception e) { + logger.error("checks 错误:" + e.getMessage()); + rspJson.put("msg", e.getMessage()); + e.printStackTrace(); + //rspJson.put("msg", Util_public.getErrorInfoFromException(e)); + } + // return JSON.toJSONString(rspJson); + //l.writeLog(JSON.toJSONString(rspJson)); + rspJson.put("status", true); + rspJson.put("datas", rdJson); + return JSON.toJSONString(rspJson); + } + + + /** + * 读取待选列 + * + * @param request + * @param response + * @return + */ + @GET + @Path("/showCol") + @Produces(MediaType.TEXT_PLAIN) + public String getshowCol(@Context HttpServletRequest request, + @Context HttpServletResponse response) { + JSONObject rspJson = new JSONObject(); + String dataKey = Util.null2String(request.getParameter("dataKey")); + rspJson.put("status", false); + if (StringUtils.isBlank(dataKey)) { + rspJson.put("errMsg", "dataKey " + weaver.systeminfo.SystemEnv.getHtmlLabelName(18622, weaver.general.ThreadVarLanguage.getLang()) + ""); + return rspJson.toJSONString(); + } + try { + SplitPageBean bean = new SplitPageBean(request, dataKey, "RootMap", "head"); + String pageUid = ""; + if (null != bean.getRootMap()) { + pageUid = Util.null2String(bean.getRootMap().getString("pageUid")); + } + if (StringUtils.isBlank(pageUid)) { + rspJson.put("errMsg", "pageUid" + weaver.systeminfo.SystemEnv.getHtmlLabelName(18622, weaver.general.ThreadVarLanguage.getLang()) + ""); + return rspJson.toJSONString(); + } + // 获得当前用户的定制列 + User user = HrmUserVarify.getUser(request, response); + + if (user == null) { + rspJson.put("errMsg", "user" + weaver.systeminfo.SystemEnv.getHtmlLabelName(18622, weaver.general.ThreadVarLanguage.getLang()) + ""); + return rspJson.toJSONString(); + } + + List userDefCols = d.getUserDefColumns(pageUid, user.getUID()); + JSONArray unchoosedColumns = bean.getUnchoosedColumns(); + JSONArray choosedColumns = bean.getChoosedColumns(); + + // 用户如果有定制列,则按用户的定义处理 + // 但如果用户配置的定制列已不存在,或者有不在配置列中的,则按当前配置的处理 + if (userDefCols != null && !userDefCols.isEmpty()) { + JSONArray defUnchoose = new JSONArray();//用户自定义的未选列 + JSONArray defChoosed = new JSONArray();//用户自定义的已选列 + // 将默认的待选已选转为Map,增加orders属性 + Map unchooseMap = Maps.newHashMap(); + Map choosedMap = Maps.newHashMap(); + for (int i = 0; i < unchoosedColumns.size(); i++) { + JSONObject col = (JSONObject) unchoosedColumns.get(i); + col.put("orders", i); + unchooseMap.put(col.getString("dataIndex"), col); + } + for (int i = 0; i < choosedColumns.size(); i++) { + JSONObject col = (JSONObject) choosedColumns.get(i); + col.put("orders", i); + choosedMap.put(col.getString("dataIndex"), col); + } + // 按用户配置的定制列来组装数据 + for (UserDefCol defCol : userDefCols) { + String dataIndex = defCol.getDataIndex(); + JSONObject col = unchooseMap.get(dataIndex); + unchooseMap.remove(dataIndex); + if (col == null) { + col = choosedMap.get(dataIndex); + choosedMap.remove(dataIndex); + } + if (col == null) { + continue; + } + col.put("display", defCol.getDisplay()); + col.put("orders", defCol.getOrders()); + if ("0".equals(defCol.getDisplay())) { + defChoosed.add(col); + } else { + defUnchoose.add(col); + } + } + // 对于不在用户配置内的,按它们的配置位置加入到列表中 + if (!unchooseMap.isEmpty()) { + addToListByOrders(defUnchoose, unchooseMap); + } + if (!choosedMap.isEmpty()) { + addToListByOrders(defChoosed, choosedMap); + } + unchoosedColumns = defUnchoose; + choosedColumns = defChoosed; + } + + rspJson.put("destdatas", choosedColumns); + rspJson.put("srcdatas", unchoosedColumns); + rspJson.put("currentPage", "1"); + rspJson.put("totalPage", "1"); + rspJson.put("status", true); + + } catch (Exception e) { + logger.error(e); + //e.printStackTrace(); + //rspJson.put("msg", Util_public.getErrorInfoFromException(e)); + return rspJson.toJSONString(); + } + return JSON.toJSONString(rspJson); + } + + private class OrderCompare implements Comparable { + JSONObject jsonObject; + + public OrderCompare(JSONObject jsonObject) { + this.jsonObject = jsonObject; + } + + private int getOrders() { + return jsonObject.getIntValue("orders"); + } + + @Override + public int compareTo(OrderCompare o) { + return Integer.valueOf(this.getOrders()).compareTo(Integer.valueOf(o.getOrders())); + } + } + + /** + * 将map中的value按顺序(orders属性)加入到前面的list中。 + * + * @param array + * @param map + */ + private void addToListByOrders(JSONArray array, Map map) { + List list = Lists.newArrayList(); + for (JSONObject jo : map.values()) { + list.add(new OrderCompare(jo)); + } + Collections.sort(list); + for (OrderCompare o : list) { + int index = o.getOrders(); + if (index < array.size()) { + array.add(index, o.jsonObject); + } else { + array.add(o.jsonObject); + } + } + } + + /** + * 保存已选列 + * + * @param request + * @param response + * @param dataKey + * @param systemIds + * @return + */ + @POST + @Path("/showCol") + @Produces(MediaType.TEXT_PLAIN) + public String postshowCol(@Context HttpServletRequest request, + @Context HttpServletResponse response, + @FormParam("dataKey") String dataKey, + @FormParam("systemIds") String systemIds, + @FormParam("widths") String widths) { + JSONObject rspJson = new JSONObject(); + rspJson.put("status", false); + if (StringUtils.isBlank(dataKey)) { + rspJson.put("errMsg", "dataKey " + weaver.systeminfo.SystemEnv.getHtmlLabelName(18622, weaver.general.ThreadVarLanguage.getLang()) + ""); + return rspJson.toJSONString(); + } + try { + SplitPageBean bean = new SplitPageBean(request, dataKey, "RootMap", "head"); + String pageUid = ""; + if (null != bean.getRootMap()) { + pageUid = Util.null2String(bean.getRootMap().getString("pageUid")); + } + if (StringUtils.isBlank(pageUid)) { + rspJson.put("errMsg", "pageUid" + weaver.systeminfo.SystemEnv.getHtmlLabelName(18622, weaver.general.ThreadVarLanguage.getLang()) + ""); + return rspJson.toJSONString(); + } + + User user = HrmUserVarify.getUser(request, response); + + if (user == null) { + rspJson.put("errMsg", "user" + weaver.systeminfo.SystemEnv.getHtmlLabelName(18622, weaver.general.ThreadVarLanguage.getLang()) + ""); + return rspJson.toJSONString(); + } + + if (StringUtils.isBlank(systemIds)) { + boolean result = d.clearShowCol(pageUid, user.getUID()); + rspJson.put("status", result); + } else { + String[] dataIndexArr = Util.null2String(systemIds).split(","); + String[] widthIndexArr = Util.null2String(widths).split(","); + + if (StringUtils.isNotBlank(widths)) + widthIndexArr = Util.null2String(widths).split(","); + + List choosedDefCols = Lists.newArrayList();//已选列 + List unchoosedDefCols = Lists.newArrayList();//待选列 + // 处理传入的已选列 + Set dataIndexSet = Sets.newHashSet(); + for (int i = 0; i < dataIndexArr.length; i++) { + String dataIndex = dataIndexArr[i]; + dataIndexSet.add(dataIndex); + + String widthNew = ""; + if (StringUtils.isNotBlank(widths)) widthNew = widthIndexArr[i]; + //int orders = i;//排序改为在下面处理,因为还有不参与列定制配置的需求。 + UserDefCol col = new UserDefCol(dataIndex, user.getUID(), pageUid, "0"/*0为显示,1为不显示*/, 0, widthNew); + choosedDefCols.add(col); + } + // 将tableString中不在传入列内的处理为待选列 + int orders = 0; + for (int i = 0; i < bean.getChoosedColumns().size(); i++) { + JSONObject col = (JSONObject) bean.getChoosedColumns().get(i); + if (dataIndexSet.contains(col.getString("dataIndex"))) { + continue; + } + if ("false".equals(col.getString("customCol"))) { + // 处理不参与列定制配置的列 + int order = Util.getIntValue(col.getString("_index"), 0); + UserDefCol defCol = new UserDefCol(col.getString("dataIndex"), user.getUID(), pageUid, "0", order, ""); + if (order >= choosedDefCols.size()) { + choosedDefCols.add(defCol); + } else { + choosedDefCols.add(order, defCol); + } + } else { + orders++; + UserDefCol defCol = new UserDefCol(col.getString("dataIndex"), user.getUID(), pageUid, "1", orders, ""); + unchoosedDefCols.add(defCol); + } + } + for (int i = 0; i < bean.getUnchoosedColumns().size(); i++) { + JSONObject col = (JSONObject) bean.getUnchoosedColumns().get(i); + if (dataIndexSet.contains(col.getString("dataIndex"))) { + continue; + } + orders++; + UserDefCol defCol = new UserDefCol(col.getString("dataIndex"), user.getUID(), pageUid, "1", orders, ""); + unchoosedDefCols.add(defCol); + } + // 处理已选列的顺序 + for (int i = 0; i < choosedDefCols.size(); i++) { + UserDefCol col = choosedDefCols.get(i); + col.setOrders(i); + } + d.clearShowCol(pageUid, user.getUID()); + d.insertShowCol(choosedDefCols, unchoosedDefCols); + rspJson.put("status", true); + } + + } catch (Exception e) { + logger.error(e); + //e.printStackTrace(); + //rspJson.put("msg", Util_public.getErrorInfoFromException(e)); + return rspJson.toJSONString(); + } + return JSON.toJSONString(rspJson); + } + + public static String delHTMLTag(String htmlStr) { + String regEx_script = "]*?>[\\s\\S]*?<\\/script>"; // 定义script的正则表达式 + String regEx_style = "]*?>[\\s\\S]*?<\\/style>"; // 定义style的正则表达式 + String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式 + if (StringUtils.isEmpty(htmlStr)) return htmlStr; + Pattern p_script = Pattern.compile(regEx_script, + Pattern.CASE_INSENSITIVE); + Matcher m_script = p_script.matcher(htmlStr); + htmlStr = m_script.replaceAll(""); // 过滤script标签 + + Pattern p_style = Pattern + .compile(regEx_style, Pattern.CASE_INSENSITIVE); + Matcher m_style = p_style.matcher(htmlStr); + htmlStr = m_style.replaceAll(""); // 过滤style标签 + + Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE); + Matcher m_html = p_html.matcher(htmlStr); + htmlStr = m_html.replaceAll(""); // 过滤html标签 + + return htmlStr.trim(); // 返回文本字符串 + } + + + private JSONObject getJSONObject(String field, JSONArray heads) { + for (Object head : (List) heads) { + JSONObject obj = (JSONObject) head; + String fieldName = obj.getString("dbField"); + if (field.equalsIgnoreCase(fieldName)) { + return obj; + } + ; + } + return null; + } + + public JSONArray getExportFields(String fields, JSONArray heads) { + if (StringUtils.isNotBlank(fields)) { + String[] field_list = fields.split(","); + JSONArray newHeads = new JSONArray(); + + List list = Arrays.asList(field_list); + for (Object head : (List) heads) { + JSONObject obj = (JSONObject) head; + obj.put("display", "false"); + String fieldName = obj.getString("dbField"); + if (list.contains(fieldName)) { + obj.put("display", "true"); + } + ; + } + + for (String item : field_list) { + JSONObject obj = getJSONObject(item, heads); + if (obj != null) { + obj.put("display", "true"); + newHeads.add(obj); + } + } + return newHeads; + } else + return heads; + + } + + public boolean getUserExportConfig(int userId) { + BaseBean bean = new BaseBean(); + String status = bean.getPropValue("weaver_export_config", "status"); + status = StringUtils.isBlank(status) ? "0" : status; + if ("0".equals(status)) return true; + String userList = bean.getPropValue("weaver_export_config", "user"); + String deptList = bean.getPropValue("weaver_export_config", "dept"); + if (StringUtils.isNotEmpty(userList)) { + String[] list = userList.split(","); + for (String item : list) { + if (String.valueOf(userId).equalsIgnoreCase(item)) + return true; + } + } + + if (StringUtils.isNotEmpty(deptList)) { + String[] list = deptList.split(","); + String where = ""; + for (String item : list) { + where = StringUtils.isEmpty(where) ? item : where + "," + item; + } + RecordSet rs = new RecordSet(); + rs.executeQuery("select id from HrmResource where departmentid in (" + where + ") and id =?", userId); + return rs.getCounts() > 0; + } + return false; + + } + + /** + * 清除Excel临时文件 + * + * @param request + * @param response + * @return + */ + @GET + @Path("/cleartemp") + @Produces(MediaType.TEXT_PLAIN) + public String cleartemp(@Context HttpServletRequest request, @Context HttpServletResponse response) { + String fileName = request.getParameter("filename"); + WeaResultMsg result = new WeaResultMsg(true); + + if (StringUtils.isBlank(fileName) || fileName.contains("..")) { + return result.fail("file name error").toString(); + } + + String path = request.getSession().getServletContext().getRealPath("cloudstore/system/tmpFile/" + fileName); + + File file = new File(path); + + if (file.exists()) { + try { + file.delete(); + return result.success("ok").toString(); + } catch (Exception ex) { + return result.success(ex.getMessage()).toString(); + } + } + return result.success("" + weaver.systeminfo.SystemEnv.getHtmlLabelName(391241, weaver.general.ThreadVarLanguage.getLang()) + "").toString(); + } + + /** + * 下载文件并且自动删除文件 + * + * @param request + * @param response + * @throws IOException + */ + @GET + @Path("/downfiledata") + @Produces(MediaType.TEXT_PLAIN) + public String downloadExcel(@Context HttpServletRequest request, @Context HttpServletResponse response) + throws IOException { + WeaResultMsg result = new WeaResultMsg(false); + + String fileName = request.getParameter("filename"); + + if (!SecurityMethodUtil.isValidPath(fileName)) { + return result.fail("file name error").toString(); + } + + String reName = request.getParameter("rename"); + if (StringUtils.isNotBlank(reName)) + reName = URLDecoder.decode(reName, "utf-8"); + String path = request.getSession().getServletContext().getRealPath("filesystem/cloudstore/system/tmpFile/" + fileName); + + response.reset(); + //response.setCharacterEncoding("UTF-8"); + logger.info("开始导出文件:" + fileName); + logger.info("文件名:" + reName); + File file = new File(path); + if (!file.exists()) + return result.fail("" + weaver.systeminfo.SystemEnv.getHtmlLabelName(10004787, weaver.general.ThreadVarLanguage.getLang()) + "" + fileName).toString(); + + response.setContentType("application/vnd.ms-excel;charset=ISO-8859-1"); + //response.setContentType("application/octet-stream"); + + String agent = request.getHeader("User-Agent"); + + if (StringUtils.isNotBlank(reName)) { + //response.addHeader("Content-Disposition","attachment;filename=" +reName); + if ((agent.contains("Firefox") || agent.contains(" Chrome") || agent.contains("Safari")) && !agent.contains("Edge")) { + response.setHeader("content-disposition", "attachment; filename*=UTF-8''" + URLEncoder.encode(reName.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""), "UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")")); + } else { + response.setHeader("content-disposition", "attachment; filename=\"" + + URLEncoder.encode(reName.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""), "UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")") + "\""); + } + } else + response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(), "utf-8")); + + InputStream in = new FileInputStream(file); + response.setHeader("Content-Length", String.valueOf(in.available())); + logger.info("文件长度:" + in.available()); + OutputStream out = response.getOutputStream(); + int size = 0; + int len = 0; + byte[] buffer = new byte[1024]; + while ((len = in.read(buffer)) > 0) { + out.write(buffer, 0, len); + size = size + len; + } + logger.info("文件长度写出:" + size); + in.close(); + out.flush(); + out.close(); + file.deleteOnExit(); + file.delete(); + return ""; + } + + + @POST + @Path("/export") + @Produces(MediaType.TEXT_PLAIN) + public String export(@Context HttpServletRequest request, + @Context HttpServletResponse response, + @FormParam("dataKey") String dataKey, + @FormParam("filetype") String filetype, @FormParam("filename") String filename, + @FormParam("fields") String fields, @FormParam("min") String min, @FormParam("max") String max, + @FormParam("htmlfields") String htmlfields, @FormParam("sharepassword") String sharepassword) { + /*if (StringUtils.isNotBlank(filename)) { + try { + filename = URLDecoder.decode(filename, "utf-8"); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + }*/ + JSONObject rspJson = new JSONObject(); + + if (StringUtils.isBlank(filetype)) { + filetype = "xlsx"; + } else if (!StringUtils.equalsAny(filetype, "xlsx", "xls")) { + rspJson.put("msg", "file type error"); + rspJson.put("errorCode", "005"); + return rspJson.toJSONString(); + } + + if (!SecurityMethodUtil.isValidPath(filename)) { + rspJson.put("msg", "file name error"); + rspJson.put("errorCode", "005"); + return rspJson.toJSONString(); + } + + String xmlString = Util_TableMap.getVal(dataKey); + if (StringUtils.isBlank(xmlString)) { + rspJson.put("msg", "" + weaver.systeminfo.SystemEnv.getHtmlLabelName(10004788, weaver.general.ThreadVarLanguage.getLang()) + ""); + rspJson.put("errorCode", "005"); + rspJson.put("dataKey", dataKey); + return rspJson.toJSONString(); + } + String pageUId = ""; + String maxOccurs = "0"; + boolean status = true; + try { + SplitPageBean bean = new SplitPageBean(request, dataKey, "RootMap", "head", "sql"); + User user = HrmUserVarify.getUser(request, response); + + pageUId = bean.getRootMap().getString("pageUid"); + + logger.info("pageUid=======>> " + pageUId); + String exportRight = bean.getRootMap().getString("exportRight"); + String rootFileName = bean.getRootMap().getString("fileName"); + + //Map maxMap=new HashMap<>(); + if (Objects.nonNull(pageUId)) maxOccurs = Util_Ehcache.getInstance().getLockStr(pageUId); + + if (Util.getIntValue(maxOccurs, 0) > 3) { + logger.info("限制下载并发:" + maxOccurs); + rspJson.put("msg", SystemEnv.getHtmlLabelName(522074, user.getLanguage())); + rspJson.put("errorCode", "005"); + rspJson.put("dataKey", dataKey); + return rspJson.toJSONString(); + } else { + if (Objects.nonNull(pageUId)) { + maxOccurs = String.valueOf(Util.getIntValue(Util_Ehcache.getInstance().getLockStr(pageUId), 0) + 1); + Util_Ehcache.getInstance().putLock(pageUId, maxOccurs); + logger.info("限制下载并发:" + maxOccurs); + } + } + + String isEncryptShare = Util.null2String(bean.getRootMap().getString("isEncryptShare")); + if (isEncryptShare.equals("1") && StringUtils.isBlank(sharepassword)) { + if (Objects.nonNull(pageUId)) logger.info("加密绕过:" + pageUId); + rspJson.put("msg", SystemEnv.getHtmlLabelName(382663, user.getLanguage())); + rspJson.put("errorCode", "005"); + rspJson.put("dataKey", dataKey); + return rspJson.toJSONString(); + } + + //andyzhang 判断权限在导出 + if (StringUtils.isNotBlank(exportRight)) + if (!HrmUserVarify.checkUserRight(Util.null2String(exportRight), user)) { + rspJson.put("noright", true); + rspJson.put("status", status); + if (Objects.nonNull(pageUId)) { + maxOccurs = String.valueOf(Util.getIntValue(Util_TableMap.getValWithEh(pageUId), 0) - 1); + Util_TableMap.setObjValWithEh(pageUId, maxOccurs); + } + return rspJson.toJSONString(); + } + //andyzhang 根据配置导出 + if (null != bean.getHeads() && Objects.nonNull(pageUId)) { + if (user != null) bean.setHeads(getShowColHeads(bean, pageUId, user)); + bean.mergeHeads(); + } + + JSONArray heads = bean.getHeads(); + if (StringUtils.isNotBlank(fields)) + heads = getExportFields(fields, bean.getHeads()); + // 汉桑二开:导出设置 直接上级选择登录名,选项值变更为 编号+登录名 + // 找到直接上级所在的列 + for (int i = 0; i < heads.size(); i++) { + JSONObject item = heads.getJSONObject(i); + if ("3".equalsIgnoreCase(item.getString("transMethodOther"))) { + int managerIdIndex = heads.indexOf(item); + heads.remove(managerIdIndex); + + JSONObject headMap = new JSONObject(); + headMap.put("orderkey","managerCode"); + headMap.put("_index",30); + headMap.put("display", "true"); + headMap.put("dbField","managerid"); + headMap.put("fromExport","1"); + headMap.put("title", "直接上级编号"); + headMap.put("labelid","15709"); + headMap.put("transMethod","weaver.hrm.resource.ResourceComInfo.filterResourcename"); + headMap.put("dataIndex", "managerCode"); + headMap.put("orders", 30); + headMap.put("oldWidth", "10%"); + headMap.put("tablename","hrmresource"); + headMap.put("transMethodOther", "1"); + heads.add(managerIdIndex, headMap); + heads.add(managerIdIndex+1,item); + break; + } + } + + List> mssl = null; + bean.getSql().put("fromExport", "1"); + + String filetypestr = "." + filetype; + + String fileNameRadom = (rootFileName != null ? rootFileName : "table") + Util_DateTime.getNowDateTimeStr() + + Util_public.createGuid() + filetypestr; + HttpSession session = request.getSession(true); + File f = new File(session.getServletContext().getRealPath("filesystem/cloudstore/system/tmpFile/")); + if (!f.exists()) { + f.mkdirs(); + } + + String url = session.getServletContext().getRealPath("filesystem/cloudstore/system/tmpFile/" + fileNameRadom); + String realUrl = "filesystem/cloudstore/system/tmpFile/" + fileNameRadom; + + if (StringUtils.isBlank(fields) && user != null && Objects.nonNull(pageUId)) + heads = getShowColHeads(bean, pageUId, user); + + String languageId = "7"; + if (user != null) + languageId = String.valueOf(user.getLanguage()); + + Workbook workbook = null; + FileOutputStream fOut = new FileOutputStream(url); + + // 先限制结束位置为第 100万 条 + // int end = Integer.MAX_VALUE; + int end = 1000000; + int start = 0; + // 步长 + final int STEP_SIZE = 5000; + // 当前max值 + int temMax = STEP_SIZE; + int temMin = 1; + // 如果用户设置了min、max + if (StringUtils.isNotBlank(min)) { + start = Integer.parseInt(min); + temMin = start; + temMax = temMin + STEP_SIZE; + } + if (StringUtils.isNotBlank(max)) { + end = Integer.parseInt(max); + temMax = Math.min(end, temMax); + } + boolean isEXCEL2003 = "xls".equalsIgnoreCase(filetype); + if (isEXCEL2003) { + // excel 单sheet页最多65535行,限定最大行数。 + end = Math.min(start + 65530, end); + } + // 标记当前操作是不是 向excel中追加 + boolean isAddRow = false; + TimeMarker timeMarker = new TimeMarker(); + timeMarker.setMark(true); + timeMarker.markStart(); + while (true) { + // 从数据库查询数据 + if (bean.getRootMap().containsKey("datasource")) { + mssl = getDataFromDatasource(request, response, null, String.valueOf(temMin), String.valueOf(temMax), null, rspJson, bean, user, ""); + } else { + String poolname = bean.getSql().getString("poolname"); + mssl = getDaoTableByPool(poolname).getDevTableDatas(bean.getSql(), heads, String.valueOf(temMin), + String.valueOf(temMax), "", new ArrayList(), new TimeMarker()); + } + /* + * 汉桑通讯录导出二开, + * 部门全路径导出时,不展示> + * 一级命名“中心”、二级命名“部门”、三级命名“小组”、四级命名“线体” + */ + ExportFieldIndex fieldIndex = new ExportFieldIndex(); + for (Map item : mssl) { + if (StringUtils.isNotBlank(item.get("managerid"))){ + item.put("managerCode",item.get("managerid")); + } + String departmentIdSpan = item.get("departmentidspan"); + if (StringUtils.isBlank(departmentIdSpan)) { + continue; + } + String[] departmentArrays = departmentIdSpan.split(">"); + fieldIndex.setMaxDepartment(Math.max(fieldIndex.getMaxDepartment(), departmentArrays.length)); + for (int i = 0; i < departmentArrays.length; i++) { + item.put("departmentidspan_" + i, departmentArrays[i]); + } + /* + *通讯录导出表头调整 + *中心编码、中心、部门编码、部门、小组编码、小组、线体编码、线体 + */ + String departmentId = item.get("departmentid"); + List departmentCodeList = new ArrayList<>(); + DepartmentComInfo departmentComInfo = new DepartmentComInfo(); + departmentCodeList.add(departmentComInfo.getDepartmentCode(departmentId)); + String allSupDepartment = departmentComInfo.getAllSupDepartment(departmentId); + String[] split = allSupDepartment.split(","); + for (String s : split) { + departmentCodeList.add(0, departmentComInfo.getDepartmentCode(s)); + } + + for (int i = 0; i < departmentCodeList.size(); i++) { + item.put("departmentcodespan_" + i, departmentCodeList.get(i)); + + } + + } + // 部门由>分隔,标识为部门全路径导出 + if (fieldIndex.getMaxDepartment() > 1) { + // 找到部门所在的列 + for (int i = 0; i < heads.size(); i++) { + JSONObject item = heads.getJSONObject(i); + if ("departmentid".equalsIgnoreCase(item.getString("dataIndex"))) { + fieldIndex.setDepartmentHeader(item); + } + } + + // 处理分隔后的部门表头信息 + int departmentIndex = heads.indexOf(fieldIndex.getDepartmentHeader()); + heads.remove(departmentIndex); + AtomicInteger atomicInteger = new AtomicInteger(0); + for (int i = 0; i < fieldIndex.getMaxDepartment(); i++) { + JSONObject headMap = new JSONObject(); + headMap.put("dataIndex", "departmentidspan_" + i); + headMap.put("title", orgLevelMap.get(i)); + headMap.put("display", "true"); + heads.add(departmentIndex + i + atomicInteger.get(), headMap); + + JSONObject headCodeMap = new JSONObject(); + headCodeMap.put("dataIndex", "departmentcodespan_" + i); + headCodeMap.put("title", orgLevelCodeMap.get(i)); + headCodeMap.put("display", "true"); + heads.add(departmentIndex + i + atomicInteger.getAndIncrement(), headCodeMap); + } + } + + timeMarker.mark("get data from database " + temMax); + if (StringUtils.isNotBlank(htmlfields)) + Util_public.replaceHtml(heads, mssl, htmlfields); + + // 处理追加 + if (isEXCEL2003) { + if (isAddRow) { + workbook = addRowExcel2003(workbook, heads, mssl, languageId); + } else { + workbook = exportExcel2003(heads, mssl, languageId, filename); + isAddRow = true; + } + } else { + if (isAddRow) { + workbook = addRowExcel2007(workbook, heads, mssl, languageId); + } else { + workbook = exportExcel2007(heads, mssl, languageId, filename); + isAddRow = true; + } + } + timeMarker.mark("add data to file " + temMax); + // 移动窗口 + temMin += STEP_SIZE; + temMax = Math.min(end, temMax + STEP_SIZE); + // 如果查询结果 mssl 的长度小于步长,说明已经到数据末尾。 + if (mssl.size() < STEP_SIZE || temMin > temMax) { + break; + } + + } + + workbook.write(fOut); + fOut.flush(); + + fOut.getFD().sync(); + fOut.close(); + + if (StringUtils.isNotBlank(sharepassword)) { + + RSA rsa = new RSA(); + sharepassword = rsa.decrypt(request, sharepassword); + + if ("xls".equalsIgnoreCase(filetype)) { + Biff8EncryptionKey.setCurrentUserPassword(sharepassword); + POIFSFileSystem fs = new POIFSFileSystem(new File(url), true); + HSSFWorkbook hwb = new HSSFWorkbook(fs.getRoot(), true); + FileOutputStream out = new FileOutputStream(url); + hwb.write(out); + hwb.close(); + out.close(); + Biff8EncryptionKey.setCurrentUserPassword(null); + + } else { + + POIFSFileSystem fs = new POIFSFileSystem(); + EncryptionInfo info = new EncryptionInfo(EncryptionMode.standard); + Encryptor enc = info.getEncryptor(); + //设置密码 + enc.confirmPassword(sharepassword); + OPCPackage opc = OPCPackage.open(new File(url), PackageAccess.READ_WRITE); + OutputStream os = enc.getDataStream(fs); + opc.save(os); + opc.close(); + os.close(); + //把加密后的文件写回到流 + FileOutputStream fos = new FileOutputStream(url); + fs.writeFilesystem(fos); + fs.close(); + fos.close(); + + } + } + + String rename = ""; + if (StringUtils.isNotBlank(filename)) + rename = URLEncoder.encode(URLEncoder.encode(filename + "." + filetype, "utf-8"), "utf-8"); + rspJson.put("size", mssl.size()); + rspJson.put("url", "/api/ec/dev/table/downfiledata?filename=" + fileNameRadom + "&rename=" + rename); + // } + + timeMarker.mark("deal with file"); + //加入导出日志 + BizLogContext bizLogContext = new BizLogContext(); + bizLogContext.setLogType(BizLogType.SYSTEM); + bizLogContext.setDateObject(new Date()); + if (user != null) + bizLogContext.setUserid(user.getUID()); + String pageId = Util.null2String(bean.getRootMap().getString("pageId")); + bizLogContext.setTargetId(pageId); + bizLogContext.setLogSmallType(BizLogSmallType4SysEngine.SYSTEM_ENGINE_EXPORT); + if ("Hrm:resourceSearchResultByManager".equals(pageId) || "Hrm:resourceSearchResult".equals(pageId)) { + bizLogContext.setTargetName("~`~`7 导出人员Excel日志`~`8 Export personnel excel log`~`9 導出人員Excel日誌`~`~"); + bizLogContext.setLogType(BizLogType.HRM); + } else + bizLogContext.setTargetName("" + weaver.systeminfo.SystemEnv.getHtmlLabelName(382051, weaver.general.ThreadVarLanguage.getLang()) + ""); + if (user != null) + bizLogContext.setUsertype(Util.getIntValue(user.getLogintype())); + bizLogContext.setOperateType(BizLogOperateType.SELECT); + //bizLogContext.setParams(request.getParameterMap()); + bizLogContext.setClientIp(Util.null2String(Util.getIpAddr(request))); + bizLogContext.setDesc(xmlString); + //l.writeLog(bizLogContext.toString()); + saveLog(bizLogContext); + //标记导出日志时间 + timeMarker.mark("deal with log"); + timeMarker.markEnd(); + rspJson.put("timeMark", timeMarker.toTimeCostJSON()); + } catch (Exception e) { + logger.error(e.getMessage()); + e.printStackTrace(); + status = false; + rspJson.put("url", ""); + rspJson.put("err", e.getMessage()); + if (Objects.nonNull(pageUId)) Util_Ehcache.getInstance().putLock(pageUId, "0"); + } + rspJson.put("status", status); + if (Objects.nonNull(pageUId)) { + maxOccurs = String.valueOf(Util.getIntValue(Util_Ehcache.getInstance().getLockStr(pageUId), 0) - 1); + Util_Ehcache.getInstance().putLock(pageUId, maxOccurs); + } + logger.info("限制下载并发归位:" + maxOccurs); + + + return rspJson.toJSONString(); + } + + + public void downExcel(String fileName, String filetype, Workbook workbook, HttpServletRequest request, HttpServletResponse response) { + try { + fileName = fileName + "." + filetype; + String agent = request.getHeader("User-Agent"); + + if ((agent.contains("Firefox") || agent.contains(" Chrome") || agent.contains("Safari")) && !agent.contains("Edge")) { + response.setHeader("content-disposition", "attachment; filename*=UTF-8''" + URLEncoder.encode(fileName.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""), "UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")")); + } else { + response.setHeader("content-disposition", "attachment; filename=\"" + + URLEncoder.encode(fileName.replaceAll("<", "").replaceAll(">", "").replaceAll("<", "").replaceAll(">", ""), "UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "(").replaceAll("%29", ")") + "\""); + } + + + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + workbook.write(bout); + logger.info(fileName + ":" + bout.toByteArray().length); + ServletOutputStream out = response.getOutputStream(); + response.setContentType("application/vnd.ms-excel;charset=ISO-8859-1"); + response.setHeader("Content-Length", String.valueOf(bout.toByteArray().length)); + //解决某些操作系统环境下载打不开的问题 + bout.writeTo(out); + out.flush(); + out.close(); + } catch (Exception ex) { + ex.printStackTrace(); + } + + } + + public String doMethod(Map mss, String tm, JSONArray tmp, String value) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException { + if ("".equals(tm)) return value; + String tmArr[] = tm.split("\\."); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < tmArr.length - 1; i++) { + sb.append(tmArr[i]); + if (i != tmArr.length - 2) { + sb.append("."); + } + } + Class clazz = Class.forName(sb.toString()); + Object obj = clazz.newInstance(); + //List cl = new ArrayList(); + Class[] cl = new Class[tmp.size()]; + Object[] sl = new Object[tmp.size()]; + int i = 0; + for (Object t : (List) tmp) { + JSONObject tObj = (JSONObject) t; + String typeStr = tObj.getString("type"); + String objStr = tObj.getString("obj"); + if (typeStr.equals("columns")) { + sl[i] = mss.get(objStr); + } else { + sl[i] = objStr; + } + cl[i] = String.class; + i++; + } + Method m1 = clazz.getDeclaredMethod(tmArr[tmArr.length - 1], cl); + Object o = m1.invoke(obj, sl); + return o.toString(); + } + + public void setCell(HSSFRow r, int n, String value, String type, HSSFWorkbook workbook, CellStyle DatecellStyle, + CellStyle NumbercellStyle, CellStyle StrcellStyle, String languageId) { + HSSFCell cell = r.createCell((short) n); + value = Util.null2String(value); + if (null != type && !"".equals(type)) { + // / "type is not null :" + type); + if (type.indexOf("number") > -1) { + cell.setCellStyle(NumbercellStyle); + cell.setCellValue(value); + } else if ("date".equals(type)) { + cell.setCellStyle(DatecellStyle); + cell.setCellValue(value); + } else { + cell.setCellType(CellType.STRING); + cell.setCellStyle(StrcellStyle); + value = Util.formatMultiLang(value, languageId); + cell.setCellValue(value); + } + } else { + cell.setCellType(CellType.STRING); + cell.setCellStyle(StrcellStyle); + value = Util.formatMultiLang(value, languageId); + //AndyZhang 加入时区转换功能 + value = Util_public.transformTimeZone(value); + cell.setCellValue(value); + } + + } + + public JSONArray transMethodToNew(JSONObject obj, String name, JSONObject mss, JSONArray heads) { + + String others = Util.null2String(obj.getString(name)); + JSONArray tmParams = new JSONArray(); + String otherArr[] = others.split("[+]"); + JSONObject tmObj1 = new JSONObject(); + tmObj1.put("type", "fixedValue"); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < otherArr.length; i++) { + + int pos = otherArr[i].toLowerCase().indexOf("column:"); + if (pos != -1) { + String tempOtherPara = otherArr[i].substring(pos + 7); + String paramString = Util.null2String(mss.get(getRealKey(heads, tempOtherPara))); + if ("".equals(paramString)) { + sb.append(" "); + } else { + sb.append(paramString); + } + } else { + sb.append(otherArr[i]); + } + if (i != otherArr.length - 1) { + sb.append("+"); + } + } + tmObj1.put("obj", sb.toString()); + if (!"".equals(tmObj1.getString("obj"))) { + tmParams.add(tmObj1); + } + return tmParams; + } + + public String doMethod(JSONObject mss, String tm, JSONArray tmp, String value, JSONArray heads) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException { + Object o = null; + + if (tm == null || "".equals(tm)) return value; + String tmArr[] = tm.split("\\."); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < tmArr.length - 1; i++) { + sb.append(tmArr[i]); + if (i != tmArr.length - 2) { + sb.append("."); + } + } + Class clazz = Class.forName(sb.toString()); + Object obj = clazz.newInstance(); + Class[] cl = new Class[tmp.size()]; + Object[] sl = new Object[tmp.size()]; + int i = 0; + for (Object t : (List) tmp) { + JSONObject tObj = (JSONObject) t; + String typeStr = tObj.getString("type"); + String objStr = tObj.getString("obj"); + if (typeStr.equals("columns")) { + sl[i] = mss.get(getRealKey(heads, objStr)); + } else { + sl[i] = objStr; + } + cl[i] = String.class; + i++; + } + Method m1 = clazz.getDeclaredMethod(tmArr[tmArr.length - 1], cl); + o = m1.invoke(obj, sl); + + return o.toString(); + } + + /** + * from='set' + * + * @param heads + * @param rdField + * @return + */ + public String getRealKey(JSONArray heads, String rdField) { + String value = ""; + for (int i = 0; i < heads.size() && "".equals(value); i++) { + JSONObject obj = heads.getJSONObject(i); + if (rdField.equals(obj.getString("dbField")) && "set".equals(obj.getString("from"))) { + value = obj.getString("dataIndex"); + } + } + return value; + } + + + /** + * 清除待办列 + * + * @param request + * @param response + * @param pageUid + * @return + */ + @GET + @Path("/clearShowCol") + @Produces(MediaType.TEXT_PLAIN) + public String clearShowCol(@Context HttpServletRequest request, + @Context HttpServletResponse response, + @QueryParam("pageUid") String pageUid) { + User user = HrmUserVarify.getUser(request, response); + JSONObject rspJson = new JSONObject(); + if (user == null) { + rspJson.put("errMsg", "user " + weaver.systeminfo.SystemEnv.getHtmlLabelName(18622, weaver.general.ThreadVarLanguage.getLang()) + ""); + return rspJson.toJSONString(); + } + if (1 == user.getUID()) { + if (StringUtils.isBlank(pageUid)) { + rspJson.put("error", 1); + rspJson.put("msg", "" + weaver.systeminfo.SystemEnv.getHtmlLabelName(83869, weaver.general.ThreadVarLanguage.getLang()) + "pageUid"); + } else { + try { + if ("all".equals(pageUid)) { + d.clearShowCol(null); + } else { + d.clearShowCol(pageUid); + } + rspJson.put("error", 0); + rspJson.put("msg", "" + weaver.systeminfo.SystemEnv.getHtmlLabelName(311, weaver.general.ThreadVarLanguage.getLang()) + "pageUid" + weaver.systeminfo.SystemEnv.getHtmlLabelName(24358, weaver.general.ThreadVarLanguage.getLang()) + " " + pageUid + " " + weaver.systeminfo.SystemEnv.getHtmlLabelName(10004789, weaver.general.ThreadVarLanguage.getLang()) + ""); + } catch (Exception e) { + rspJson.put("error", 1); + logger.error(e); + //e.printStackTrace(); + //rspJson.put("msg", "处理出错,报错信息为:"+Util_public.getErrorInfoFromException(e)); + } + } + } else { + rspJson.put("error", 1); + rspJson.put("msg", "" + weaver.systeminfo.SystemEnv.getHtmlLabelName(10004790, weaver.general.ThreadVarLanguage.getLang()) + "sysadmin" + weaver.systeminfo.SystemEnv.getHtmlLabelName(24533, weaver.general.ThreadVarLanguage.getLang()) + ""); + } + return rspJson.toJSONString(); + } + + public Workbook exportExcel2003(JSONArray heads, List> mssl, String languageId, String filename) { + HSSFWorkbook workbook = new HSSFWorkbook(); + HSSFSheet sheet = workbook.createSheet(); + workbook.setSheetName(0, StringUtils.isNotBlank(filename) ? filename : "datas"); + HSSFRow row = sheet.createRow((short) 0); + + CellStyle DatecellStyle = workbook.createCellStyle(); + DataFormat DateCSformat = workbook.createDataFormat(); + DatecellStyle.setDataFormat(DateCSformat.getFormat("yyyy-mm-dd")); + + CellStyle NumbercellStyle = workbook.createCellStyle(); + DataFormat NumberCSformat = workbook.createDataFormat(); + NumbercellStyle.setDataFormat(NumberCSformat.getFormat("#,##0.00")); + + CellStyle StrcellStyle = workbook.createCellStyle(); + DataFormat format = workbook.createDataFormat(); + StrcellStyle.setDataFormat(format.getFormat("@")); + + int col = 0; + for (Object head : (List) heads) { + JSONObject obj = (JSONObject) head; + if (!"false".equals(obj.getString("display"))) { + this.setCell(row, col++, obj.getString("title"), "", workbook, DatecellStyle, NumbercellStyle, StrcellStyle, languageId); + } + } + int rowNum = 1; + + for (int i = 0; i < mssl.size(); i++) { + row = sheet.createRow((short) rowNum++); + col = 0; + Map mss = mssl.get(i); + //logger.info("mss is :" + JSON.toJSONString(mss)); + for (Object head : (List) heads) { + JSONObject obj = (JSONObject) head; + + if (!"false".equals(obj.getString("display"))) { + if (obj.containsKey("transMethod")) { + String name = obj.getString("dataIndex"); + String value = mss.get(name); + //String valueSpan = delHTMLTag("".equals(mss.get(name + "span")) ? value : mss.get(name + "span")); + //直接送转换数据 + String valueSpan = delHTMLTag(mss.get(name + "span")); + this.setCell(row, col++, valueSpan, obj.getString("exportType"), workbook, DatecellStyle, NumbercellStyle, StrcellStyle, languageId); + } else { + this.setCell(row, col++, delHTMLTag(mss.get(obj.getString("dataIndex"))), obj.getString("exportType"), workbook, DatecellStyle, NumbercellStyle, StrcellStyle, languageId); + } + } + + } + } + return workbook; + } + + /** + * excel2003 追加行 + * + * @param wb + * @param heads + * @param mssl + * @param languageId + * @return + */ + public Workbook addRowExcel2003(Workbook wb, JSONArray heads, List> mssl, String languageId) { + HSSFWorkbook workbook; + if (wb instanceof HSSFWorkbook) { + workbook = (HSSFWorkbook) wb; + } else { + return wb; + } + + HSSFSheet sheet = workbook.getSheetAt(0); + + CellStyle DatecellStyle = workbook.createCellStyle(); + DataFormat DateCSformat = workbook.createDataFormat(); + DatecellStyle.setDataFormat(DateCSformat.getFormat("yyyy-mm-dd")); + + CellStyle NumbercellStyle = workbook.createCellStyle(); + DataFormat NumberCSformat = workbook.createDataFormat(); + NumbercellStyle.setDataFormat(NumberCSformat.getFormat("#,##0.00")); + + CellStyle StrcellStyle = workbook.createCellStyle(); + DataFormat format = workbook.createDataFormat(); + StrcellStyle.setDataFormat(format.getFormat("@")); + + int col = 0; + int rowNum = sheet.getLastRowNum() + 1; + HSSFRow row = null; + + for (int i = 0; i < mssl.size(); i++) { + row = sheet.createRow(rowNum++); + col = 0; + Map mss = mssl.get(i); + //logger.info("mss is :" + JSON.toJSONString(mss)); + for (Object head : (List) heads) { + JSONObject obj = (JSONObject) head; + + if (!"false".equals(obj.getString("display"))) { + if (obj.containsKey("transMethod")) { + String name = obj.getString("dataIndex"); + String value = mss.get(name); + //直接送转换数据 + String valueSpan = delHTMLTag(mss.get(name + "span")); + this.setCell(row, col++, valueSpan, obj.getString("exportType"), workbook, DatecellStyle, NumbercellStyle, StrcellStyle, languageId); + } else { + this.setCell(row, col++, delHTMLTag(mss.get(obj.getString("dataIndex"))), obj.getString("exportType"), workbook, DatecellStyle, NumbercellStyle, StrcellStyle, languageId); + } + } + + } + } + return workbook; + } + + public Workbook exportExcel2007(JSONArray heads, List> mssl, String languageId, String filename) { + SXSSFWorkbook workbook = new SXSSFWorkbook(); + + SXSSFSheet sheet = workbook.createSheet(); + workbook.setSheetName(0, StringUtils.isNotBlank(filename) ? filename : "datas"); + SXSSFRow row = sheet.createRow(0); + + CellStyle DatecellStyle = workbook.createCellStyle(); + DataFormat DateCSformat = workbook.createDataFormat(); + DatecellStyle.setDataFormat(DateCSformat.getFormat("yyyy-mm-dd")); + + CellStyle NumbercellStyle = workbook.createCellStyle(); + DataFormat NumberCSformat = workbook.createDataFormat(); + NumbercellStyle.setDataFormat(NumberCSformat.getFormat("#,##0.00")); + + CellStyle StrcellStyle = workbook.createCellStyle(); + DataFormat format = workbook.createDataFormat(); + StrcellStyle.setDataFormat(format.getFormat("@")); + + int col = 0; + for (Object head : (List) heads) { + JSONObject obj = (JSONObject) head; + if (!"false".equals(obj.getString("display"))) { + this.setCell(row, col++, obj.getString("title"), "", workbook, DatecellStyle, NumbercellStyle, StrcellStyle, languageId); + } + } + int rowNum = 1; + // " start transmethod "); + for (int i = 0; i < mssl.size(); i++) { + row = sheet.createRow(rowNum++); + col = 0; + Map mss = mssl.get(i); + //logger.info("mss is :" + JSON.toJSONString(mss)); + for (Object head : (List) heads) { + JSONObject obj = (JSONObject) head; + + if (!"false".equals(obj.getString("display"))) { + if (obj.containsKey("transMethod")) { + String name = obj.getString("dataIndex"); + String value = mss.get(name); + + //String valueSpan = delHTMLTag("".equals(mss.get(name + "span")) ? value : mss.get(name + "span")); + //直接送转换数据 + String valueSpan = delHTMLTag(mss.get(name + "span")); + this.setCell(row, col++, valueSpan, obj.getString("exportType"), workbook, DatecellStyle, NumbercellStyle, StrcellStyle, languageId); + } else { + String name = obj.getString("dataIndex"); + String value = mss.get(name); + this.setCell(row, col++, delHTMLTag(value), obj.getString("exportType"), workbook, DatecellStyle, NumbercellStyle, StrcellStyle, languageId); + } + } + } + } + return workbook; + } + + /** + * exce2007 追加行 + * + * @param wb + * @param heads + * @param mssl + * @param languageId + * @return + */ + public Workbook addRowExcel2007(Workbook wb, JSONArray heads, List> mssl, String languageId) { + SXSSFWorkbook workbook; + if (wb instanceof SXSSFWorkbook) { + workbook = (SXSSFWorkbook) wb; + } else { + return wb; + } + + SXSSFSheet sheet = workbook.getSheetAt(0); + + CellStyle DatecellStyle = workbook.createCellStyle(); + DataFormat DateCSformat = workbook.createDataFormat(); + DatecellStyle.setDataFormat(DateCSformat.getFormat("yyyy-mm-dd")); + + CellStyle NumbercellStyle = workbook.createCellStyle(); + DataFormat NumberCSformat = workbook.createDataFormat(); + NumbercellStyle.setDataFormat(NumberCSformat.getFormat("#,##0.00")); + + CellStyle StrcellStyle = workbook.createCellStyle(); + DataFormat format = workbook.createDataFormat(); + StrcellStyle.setDataFormat(format.getFormat("@")); + + int col = 0; + int rowNum = sheet.getLastRowNum() + 1; + SXSSFRow row = null; + + for (int i = 0; i < mssl.size(); i++) { + row = sheet.createRow(rowNum++); + col = 0; + Map mss = mssl.get(i); + for (Object head : (List) heads) { + JSONObject obj = (JSONObject) head; + + if (!"false".equals(obj.getString("display"))) { + if (obj.containsKey("transMethod")) { + String name = obj.getString("dataIndex"); + String value = mss.get(name); + + //直接送转换数据 + String valueSpan = delHTMLTag(mss.get(name + "span")); + this.setCell(row, col++, valueSpan, obj.getString("exportType"), workbook, DatecellStyle, NumbercellStyle, StrcellStyle, languageId); + } else { + String name = obj.getString("dataIndex"); + String value = mss.get(name); + this.setCell(row, col++, delHTMLTag(value), obj.getString("exportType"), workbook, DatecellStyle, NumbercellStyle, StrcellStyle, languageId); + } + } + } + } + return workbook; + } + + public void setCell(Row r, int n, String value, String type, Workbook workbook, CellStyle DatecellStyle, + CellStyle NumbercellStyle, CellStyle StrcellStyle, String languageId) { + Cell cell = r.createCell(n); + value = Util.null2String(value); + if (null != type && !"".equals(type)) { + if (type.indexOf("number") > -1) { + cell.setCellStyle(NumbercellStyle); + cell.setCellValue(value); + } else if ("date".equals(type)) { + + cell.setCellStyle(DatecellStyle); + cell.setCellValue(value); + } else { + cell.setCellStyle(StrcellStyle); + value = Util.formatMultiLang(value, languageId); + cell.setCellValue(value); + } + } else { + // "type is null "); + cell.setCellStyle(StrcellStyle); + value = Util.formatMultiLang(value, languageId); + //AndyZhang 加入时区转换功能 + value = Util_public.transformTimeZone(value); + cell.setCellValue(value); + } + } + + public void saveLog(BizLogContext bizLogContext) { + LogUtil.writeBizLog(bizLogContext); + } + + /** + * 设置默认用户的自定义字段数据 + * + * @param request + * @param response + * @return + * @throws IOException + */ + @GET + @Path("/syndefcols") + @Produces(MediaType.TEXT_PLAIN) + public String synchronizationColsDef(@Context HttpServletRequest request, @Context HttpServletResponse response) throws IOException { + + String pageuid = request.getParameter("pageuid"); + String systemIds = request.getParameter("systemIds"); + String systemIdsHide = request.getParameter("systemIdsHide"); + return synchronizationCols(request, response, "", "0", pageuid, systemIds, systemIdsHide); + } + + /** + * #1063683 + * 概述:显示列定制增加更改默认显示列及同步显示列定制功能 + * + * @param request + * @param response + * @return + * @throws IOException + */ + @GET + @Path("/syncols") + @Produces(MediaType.TEXT_PLAIN) + public String syncCols(@Context HttpServletRequest request, @Context HttpServletResponse response) throws IOException { + WeaResultMsg result = new WeaResultMsg(false); + User user = HrmUserVarify.getUser(request, response); + String dataKey = request.getParameter("dataKey"); + String sOrgType = request.getParameter("orgType"); + OrgType orgType = OrgType.valueOf(sOrgType); + String orgId = request.getParameter("orgId"); + int def = Util.getIntValue(request.getParameter("def"), 0); + String pageuid = ""; + String systemIds = request.getParameter("systemIds"); + String systemIdsHide = request.getParameter("systemIdsHide"); + + + if (!StringUtils.isEmpty(dataKey)) { + try { + SplitPageBean bean = new SplitPageBean(request, dataKey, "RootMap", "head"); + if (null != bean.getRootMap()) + pageuid = Util.null2String(bean.getRootMap().getString("pageUid")); + + if (StringUtils.isEmpty(pageuid)) + return result.fail("" + weaver.systeminfo.SystemEnv.getHtmlLabelName(10004769, weaver.general.ThreadVarLanguage.getLang()) + "pageuid").toString(); + + if (user == null) { + result.fail("user" + weaver.systeminfo.SystemEnv.getHtmlLabelName(18622, weaver.general.ThreadVarLanguage.getLang()) + ""); + return result.toString(); + } + + List userDefCols = d.getUserDefColumns(pageuid, user.getUID()); + JSONArray unchoosedColumns = bean.getUnchoosedColumns(); + JSONArray choosedColumns = bean.getChoosedColumns(); + + if (userDefCols != null && !userDefCols.isEmpty()) { + JSONArray defUnchoose = new JSONArray();//用户自定义的未选列 + JSONArray defChoosed = new JSONArray();//用户自定义的已选列 + // 将默认的待选已选转为Map,增加orders属性 + Map unchooseMap = Maps.newHashMap(); + Map choosedMap = Maps.newHashMap(); + for (int i = 0; i < unchoosedColumns.size(); i++) { + JSONObject col = (JSONObject) unchoosedColumns.get(i); + col.put("orders", i); + unchooseMap.put(col.getString("dataIndex"), col); + } + for (int i = 0; i < choosedColumns.size(); i++) { + JSONObject col = (JSONObject) choosedColumns.get(i); + col.put("orders", i); + choosedMap.put(col.getString("dataIndex"), col); + } + // 按用户配置的定制列来组装数据 + for (UserDefCol defCol : userDefCols) { + String dataIndex = defCol.getDataIndex(); + JSONObject col = unchooseMap.get(dataIndex); + unchooseMap.remove(dataIndex); + if (col == null) { + col = choosedMap.get(dataIndex); + choosedMap.remove(dataIndex); + } + if (col == null) { + continue; + } + col.put("display", defCol.getDisplay()); + col.put("orders", defCol.getOrders()); + if ("0".equals(defCol.getDisplay())) { + defChoosed.add(col); + } else { + defUnchoose.add(col); + } + } + // 对于不在用户配置内的,按它们的配置位置加入到列表中 + if (!unchooseMap.isEmpty()) { + addToListByOrders(defUnchoose, unchooseMap); + } + if (!choosedMap.isEmpty()) { + addToListByOrders(defChoosed, choosedMap); + } + unchoosedColumns = defUnchoose; + choosedColumns = defChoosed; + } + + BizLogContext bizLogContext = new BizLogContext(); + //加入导出日志 + bizLogContext.setLogType(BizLogType.SYSTEM); + bizLogContext.setDateObject(new Date()); + if (user != null) { + bizLogContext.setUserid(user.getUID()); + bizLogContext.setUsertype(Util.getIntValue(user.getLogintype())); + } + bizLogContext.setLogSmallType(BizLogSmallType4SysEngine.SYSTEM_ENGINE_EXPORT); + bizLogContext.setOperateType(BizLogOperateType.ADD); + bizLogContext.setClientIp(Util.null2String(Util.getIpAddr(request))); + + List choosedDefCols = new ArrayList<>(); + List unchoosedDefCols = new ArrayList<>(); + + for (int i = 0; i < choosedColumns.size(); i++) { + JSONObject col = (JSONObject) choosedColumns.get(i); + UserDefCol udc = new UserDefCol(); + + udc.setDataIndex(col.getString("dataIndex")); + udc.setDisplay(col.getString("dataIndex")); + udc.setOrders(col.getInteger("orders")); + udc.setPageUid(col.getString("pageUid")); + udc.setWidth(col.getString("width")); + udc.setUserId(user.getUID()); + choosedDefCols.add(udc); + } + + for (int i = 0; i < unchoosedColumns.size(); i++) { + JSONObject col = (JSONObject) unchoosedColumns.get(i); + UserDefCol udc = new UserDefCol(); + + udc.setDataIndex(col.getString("dataIndex")); + udc.setDisplay(col.getString("dataIndex")); + udc.setOrders(col.getInteger("orders")); + udc.setPageUid(col.getString("pageUid")); + udc.setWidth(col.getString("width")); + udc.setUserId(user.getUID()); + unchoosedDefCols.add(udc); + } + + logger.info("choosedDefCols:" + JSON.toJSONString(choosedDefCols)); + logger.info("unchoosedDefCols:" + JSON.toJSONString(unchoosedDefCols)); + logger.info("orgType:" + orgType); + logger.info("orgId:" + orgId); + d.synCols(bizLogContext, choosedDefCols, unchoosedDefCols, orgType, orgId, def); + + } catch (Exception ex) { + logger.error(ex.getMessage()); + return result.fail(ex.toString()).toString(); + } + + + } + + + return result.success().toString(); + } + + /** + * 同步自定义字段到任意用户 + * + * @param request + * @param response + * @return + * @throws IOException + */ + @GET + @Path("/syncols") + @Produces(MediaType.TEXT_PLAIN) + public String synchronizationCols(@Context HttpServletRequest request, @Context HttpServletResponse response) throws IOException { + String dataKey = request.getParameter("dataKey"); + String userlist = request.getParameter("userlist"); + String pageuid = request.getParameter("pageuid"); + String systemIds = request.getParameter("systemIds"); + String systemIdsHide = request.getParameter("systemIdsHide"); + return synchronizationCols(request, response, dataKey, userlist, pageuid, systemIds, systemIdsHide); + } + + /** + * 同步自定义字段到任意用户 + * + * @param request + * @param response + * @param dataKey + * @param userlist + * @param pageuid + * @param systemIds + * @param systemIdsHide + * @return + * @throws IOException + */ + public String synchronizationCols(HttpServletRequest request, HttpServletResponse response, String dataKey, String userlist, + String pageuid, String systemIds, String systemIdsHide) throws IOException { + WeaResultMsg result = new WeaResultMsg(false); + + if (!StringUtils.isEmpty(dataKey)) { + try { + SplitPageBean bean = new SplitPageBean(request, dataKey, "RootMap", "head"); + if (null != bean.getRootMap()) { + pageuid = Util.null2String(bean.getRootMap().getString("pageUid")); + } + + if (StringUtils.isEmpty(pageuid)) + return result.fail("" + weaver.systeminfo.SystemEnv.getHtmlLabelName(10004769, weaver.general.ThreadVarLanguage.getLang()) + "pageuid").toString(); + + User user = HrmUserVarify.getUser(request, response); + if (user == null) { + result.fail("user" + weaver.systeminfo.SystemEnv.getHtmlLabelName(18622, weaver.general.ThreadVarLanguage.getLang()) + ""); + return result.toString(); + } + + List userDefCols = d.getUserDefColumns(pageuid, user.getUID()); + JSONArray unchoosedColumns = bean.getUnchoosedColumns(); + JSONArray choosedColumns = bean.getChoosedColumns(); + + if (userDefCols != null && !userDefCols.isEmpty()) { + JSONArray defUnchoose = new JSONArray();//用户自定义的未选列 + JSONArray defChoosed = new JSONArray();//用户自定义的已选列 + // 将默认的待选已选转为Map,增加orders属性 + Map unchooseMap = Maps.newHashMap(); + Map choosedMap = Maps.newHashMap(); + for (int i = 0; i < unchoosedColumns.size(); i++) { + JSONObject col = (JSONObject) unchoosedColumns.get(i); + col.put("orders", i); + unchooseMap.put(col.getString("dataIndex"), col); + } + for (int i = 0; i < choosedColumns.size(); i++) { + JSONObject col = (JSONObject) choosedColumns.get(i); + col.put("orders", i); + choosedMap.put(col.getString("dataIndex"), col); + } + // 按用户配置的定制列来组装数据 + for (UserDefCol defCol : userDefCols) { + String dataIndex = defCol.getDataIndex(); + JSONObject col = unchooseMap.get(dataIndex); + unchooseMap.remove(dataIndex); + if (col == null) { + col = choosedMap.get(dataIndex); + choosedMap.remove(dataIndex); + } + if (col == null) { + continue; + } + col.put("display", defCol.getDisplay()); + col.put("orders", defCol.getOrders()); + if ("0".equals(defCol.getDisplay())) { + defChoosed.add(col); + } else { + defUnchoose.add(col); + } + } + // 对于不在用户配置内的,按它们的配置位置加入到列表中 + if (!unchooseMap.isEmpty()) { + addToListByOrders(defUnchoose, unchooseMap); + } + if (!choosedMap.isEmpty()) { + addToListByOrders(defChoosed, choosedMap); + } + unchoosedColumns = defUnchoose; + choosedColumns = defChoosed; + } + + String sqlWhere = ""; + String sqlWhereDelete = ""; + ArrayList params = new ArrayList<>(); + + if (!StringUtils.isEmpty(userlist)) { + sqlWhereDelete = WeaCommon.createWhereInSQL(userlist, params); + sqlWhere = " where id in " + WeaCommon.createWhereInSQL(userlist, params); + } + + ArrayList paramsWhere = new ArrayList<>(); + paramsWhere.add(pageuid); + RecordSet rs = new RecordSet(); + rs.executeUpdate("delete from cloudstore_defcol where pageuid=? " + (StringUtils.isEmpty(userlist) ? "" : " and userid in"), paramsWhere); + + for (int i = 0; i < choosedColumns.size(); i++) { + JSONObject obj = choosedColumns.getJSONObject(i); + String dataIndex = obj.get("dbField").toString(); + ArrayList paramsReal = new ArrayList<>(); + paramsReal.add(pageuid); + paramsReal.add(i); + paramsReal.add(dataIndex); + paramsReal.addAll(params); + String sql = " Insert into cloudstore_defcol(userid,sysid,pageuid,orders,display,dataindex,width) " + + " select id,'',?,?,0,?,'' from HrmResource " + sqlWhere; + rs.executeUpdate(sql, paramsReal); + } + + for (int i = 0; i < unchoosedColumns.size(); i++) { + JSONObject obj = unchoosedColumns.getJSONObject(i); + String dataIndex = obj.get("dbField").toString(); + + ArrayList paramsReal = new ArrayList<>(); + paramsReal.add(pageuid); + paramsReal.add(i); + paramsReal.add(dataIndex); + paramsReal.addAll(params); + + String sql = " Insert into cloudstore_defcol(userid,sysid,pageuid,orders,display,dataindex,width) " + + " select id,'',?,?,1,?,'' from HrmResource " + sqlWhere; + rs.executeUpdate(sql, paramsReal); + } + } catch (Exception ex) { + logger.error(ex.getMessage()); + return result.fail(ex.toString()).toString(); + } + } else { + if (StringUtils.isEmpty(pageuid)) + return result.fail("" + weaver.systeminfo.SystemEnv.getHtmlLabelName(10004769, weaver.general.ThreadVarLanguage.getLang()) + "pageuid").toString(); + if (StringUtils.isEmpty(systemIds)) + return result.fail("" + weaver.systeminfo.SystemEnv.getHtmlLabelName(10004769, weaver.general.ThreadVarLanguage.getLang()) + "systemIds").toString(); + if (StringUtils.isEmpty(systemIdsHide)) + return result.fail("" + weaver.systeminfo.SystemEnv.getHtmlLabelName(10004769, weaver.general.ThreadVarLanguage.getLang()) + "systemIdsHide").toString(); + + RecordSet rs = new RecordSet(); + rs.executeUpdate("delete from cloudstore_defcol where pageuid=?", pageuid); + + String[] dataIndexArr = Util.null2String(systemIds).split(","); + String[] dataIndexArrHide = Util.null2String(systemIdsHide).split(","); + + String sqlWhere = ""; + ArrayList params = new ArrayList<>(); + + if (!StringUtils.isEmpty(userlist)) + sqlWhere = " where id in " + WeaCommon.createWhereInSQL(userlist, params); + + int i = 0; + for (String dataIndex : dataIndexArr) { + ArrayList paramsReal = new ArrayList<>(); + paramsReal.add(pageuid); + paramsReal.add(++i); + paramsReal.add(dataIndex); + paramsReal.addAll(params); + + String sql = " Insert into cloudstore_defcol(userid,sysid,pageuid,orders,display,dataindex,width) " + + " select id,'',?,?,0,?,'' from HrmResource " + sqlWhere; + rs.executeUpdate(sql, paramsReal); + } + for (String dataIndex : dataIndexArrHide) { + ArrayList paramsReal = new ArrayList<>(); + paramsReal.add(pageuid); + paramsReal.add(++i); + paramsReal.add(dataIndex); + paramsReal.addAll(params); + + String sql = " Insert into cloudstore_defcol(userid,sysid,pageuid,orders,display,dataindex,width) " + + " select id,'',?,?,1,?,'' from HrmResource " + sqlWhere; + rs.executeUpdate(sql, paramsReal); + } + } + result.success(); + return result.toString(); + } + + + public SplitPageBean getCompleteSql(String pageUId, SplitPageBean bean, Map params) { + + Date date = new Date(); + SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd"); + String curDate = sdf.format(date); + JSONObject sqlObj = bean.getSql(); + + String defaultsqltop = ""; + String detailTable = ""; + String relationCondition = " "; + String formid = ""; + CubeSearchService cubeSearchService = new CubeSearchService();//原先用来处理sql动态参数的,暂时不考虑先保留代码 + //获取mode_customsearch id + int id = Util.getIntValue(Util.null2String(pageUId.substring(pageUId.indexOf(":") + 1, pageUId.length())), 0); + //置顶标识 + int enabledtop = 0; + int modeid = 0; + //设定排序的表的过滤条件 + String sqlwhere = ""; + String tOrder = Util.null2String(sqlObj.getString("sqlorderby"));//bean 里面的排序语句,如果当前表在mode_customsearch设置了置顶条件,那么需要将置顶条件字段拼接在前面 + String sqlFrom = Util.null2String(sqlObj.getString("sqlform")); + String beanSqlWhere = Util.null2String(sqlObj.getString("sqlwhere")); + if (!("".equals(sqlFrom))) { + //获取表名 + String tableName = sqlFrom.substring(4, sqlFrom.indexOf("t1")).trim(); + if (id != 0) { + String topColumn = "mode_top_" + id; + //查询 mode_customsearch 表里面的信息,enabledtop defaultsqltop + String sqlForModeCustomsearch = "select enabledtop,defaultsqltop,detailtable,modeid,formid from mode_customsearch where id = " + id; + + RecordSet rs = new RecordSet(); + rs.execute(sqlForModeCustomsearch); + while (rs.next()) { + enabledtop = Util.getIntValue(Util.null2String(rs.getString("enabledtop"), "0")); + // sqlwhere = Util.null2String(rs.getString("defaultsqltop"),""); + defaultsqltop = Util.null2String(rs.getString("defaultsqltop"), ""); + String temp = Util.null2String(rs.getString("detailtable")); + detailTable = !"".equals(temp) ? "," + temp + " d1 " : ""; + relationCondition = !"".equals(temp) ? " and t1.id = d1.mainid " : " "; + modeid = Util.getIntValue(Util.null2String(rs.getString("modeid"), "0")); + bean.getSql().put("modeid", modeid); + params.put("modeId", modeid); + formid = Util.null2String(rs.getString("formid")); + } + + if (!weaver.formmode.virtualform.VirtualFormHandler.isVirtualForm(formid)) { + ModeDataIDUpdateSingle.INSTANCE.updateModifyInfo(tableName); + } + //添加密级处理 +// AddSeclevelUtil addSeclevelUtil = new AddSeclevelUtil(); +// String secLevelSqlWhere = addSeclevelUtil.getBrowserOrSearchSecLevelSqlWhere(params); +// if(!"".equals(secLevelSqlWhere)){ +// beanSqlWhere+= secLevelSqlWhere; +// sqlObj.put("sqlwhere",beanSqlWhere); +// } + + + if (enabledtop == 1) { + //查询设置表单的表 存不存在标记置顶的字段 + try { + String sqlGetTopCol = "select id, " + topColumn + " from " + tableName + " where 1=2 "; + rs.execute(sqlGetTopCol); + if ("".equals(rs.getExceptionMsg())) {//rs对象内部处理了异常,只能根据msg 来判断是否有异常,先保留try catch + String nullFun = CommonConstant.DB_ISNULL_FUN; + tOrder = !"".equals(tOrder) ? nullFun + "(t1." + topColumn + ",0) desc," + tOrder : nullFun + "(t1." + topColumn + ",0) desc"; + bean.getSql().put("topColumn", "mode_top_" + id); + bean.getSql().put("sqlorderby", tOrder); + + if (!"".equals(defaultsqltop)) { + //查询出当天满足条件的(当天数据量较小) + if (defaultsqltop.indexOf("d1.") == -1) { + detailTable = ""; + relationCondition = ""; + } + + String sqlGetCurData = " select t1.id from " + tableName + " t1 " + detailTable + " where t1.modedatacreatedate='" + curDate + "' and " + defaultsqltop + relationCondition + " and t1.formmodeid =" + modeid + " and t1." + topColumn + " is null "; + rs.executeQuery(sqlGetCurData); + int dataId = 0; + if ("".equals(rs.getExceptionMsg())) { + while (rs.next()) { + dataId = Util.getIntValue(rs.getString("id"), 0); + String sqlUpdateDayData = " update " + tableName + " set " + topColumn + "=1 where id=" + dataId; + rs.execute(sqlUpdateDayData); + } + } + + } + } + } catch (Exception e) { + //打印日志,列不存在 + } + } + } + } + return bean; + } + + class ExportFieldIndex { + private Integer maxDepartment = 0; + + private Object departmentHeader; + + + public Integer getMaxDepartment() { + return maxDepartment; + } + + public void setMaxDepartment(Integer maxDepartment) { + this.maxDepartment = maxDepartment; + } + + public Object getDepartmentHeader() { + return departmentHeader; + } + + public void setDepartmentHeader(Object departmentHeader) { + this.departmentHeader = departmentHeader; + } + } + +} \ No newline at end of file diff --git a/src/com/customization/leshanvc/HsGetOutWorkDurationCmd.java b/src/com/customization/leshanvc/HsGetOutWorkDurationCmd.java new file mode 100644 index 0000000..f04a7ea --- /dev/null +++ b/src/com/customization/leshanvc/HsGetOutWorkDurationCmd.java @@ -0,0 +1,40 @@ +package com.customization.leshanvc; + +import com.engine.core.cfg.annotation.CommandDynamicProxy; +import com.engine.core.interceptor.AbstractCommandProxy; +import com.engine.core.interceptor.Command; +import com.engine.kq.biz.KQExitRulesBiz; +import com.engine.kq.cmd.attendanceEvent.GetOutWorkDurationCmd; +import org.apache.commons.lang.StringUtils; +import weaver.general.BaseBean; +import weaver.general.Util; +import weaver.interfaces.leshanvc.workflow.util.ConvertDurationUtil; + +import java.util.Map; + +/** + * @author:dxfeng + * @createTime: 2023/02/17 + * @version: 1.0 + */ +@CommandDynamicProxy(target = GetOutWorkDurationCmd.class, desc = "公出流程时间计算按照半小时为最小单位") +public class HsGetOutWorkDurationCmd extends AbstractCommandProxy> { + @Override + public Map execute(Command> targetCommand) { + + String minimumUnit = KQExitRulesBiz.getMinimumUnit(); + Map resultMap = nextExecute(targetCommand); + // 半小时 + if ("3".equals(minimumUnit)) { + String duration = Util.null2String(resultMap.get("duration")); + if (StringUtils.isNotBlank(duration)) { + try { + resultMap.put("duration", ConvertDurationUtil.handelHalfHour(duration)); + } catch (NumberFormatException e) { + new BaseBean().writeLog(e); + } + } + } + return resultMap; + } +} diff --git a/src/com/customization/leshanvc/HsGetTravelRulesFormCmd.java b/src/com/customization/leshanvc/HsGetTravelRulesFormCmd.java new file mode 100644 index 0000000..ae24941 --- /dev/null +++ b/src/com/customization/leshanvc/HsGetTravelRulesFormCmd.java @@ -0,0 +1,30 @@ +package com.customization.leshanvc; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.engine.core.cfg.annotation.CommandDynamicProxy; +import com.engine.core.interceptor.AbstractCommandProxy; +import com.engine.core.interceptor.Command; +import com.engine.kq.cmd.attendanceEvent.GetOutWorkDurationCmd; +import com.engine.kq.cmd.travelrules.GetTravelRulesFormCmd; + +import java.util.List; +import java.util.Map; + +/** + * @author:dxfeng + * @createTime: 2023/02/17 + * @version: 1.0 + */ +@CommandDynamicProxy(target = GetTravelRulesFormCmd.class, desc = "公出流程时间计算按照半小时为最小单位") +public class HsGetTravelRulesFormCmd extends AbstractCommandProxy> { + @Override + public Map execute(Command> targetCommand) { + GetTravelRulesFormCmd getTravelRulesFormCmd = (GetTravelRulesFormCmd) targetCommand; + Map result = nextExecute(targetCommand); + List minimumUnit = (List) result.get("exit_minimumUnit"); + minimumUnit.set(2, minimumUnit.get(2).replace("1分钟", "半小时")); + return result; + } +} diff --git a/src/com/engine/cube/cmd/app/GetBatchImportInfo.java b/src/com/engine/cube/cmd/app/GetBatchImportInfo.java new file mode 100644 index 0000000..d4c2ad8 --- /dev/null +++ b/src/com/engine/cube/cmd/app/GetBatchImportInfo.java @@ -0,0 +1,855 @@ +package com.engine.cube.cmd.app; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.api.formmode.cache.ModeFormFieldEncryptComInfo; +import com.cloudstore.dev.api.util.Util_TableMap; +import com.engine.common.biz.AbstractCommonCommand; +import com.engine.common.entity.BizLogContext; +import com.engine.common.entity.EncryptFieldEntity; +import com.engine.core.interceptor.CommandContext; +import com.engine.cube.biz.CardFormHelper; +import com.engine.cube.biz.DetachHelper; +import com.engine.encrypt.biz.EncryptFieldConfigComInfo; +import com.engine.cube.util.AddSeclevelUtil; +import com.weaver.formmodel.util.StringHelper; +import weaver.conn.RecordSet; +import weaver.conn.constant.DBConstant; +import weaver.formmode.cache.StringCacheMap; +import weaver.formmode.excel.ExcelCacheUtil; +import weaver.formmode.excel.ExpExcelUtil; +import weaver.formmode.excel.ImpExcelServer; +import weaver.formmode.service.AppInfoService; +import weaver.formmode.service.FormInfoService; +import weaver.formmode.service.ModelInfoService; +import weaver.formmode.setup.ModeRightInfo; +import weaver.general.Util; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; +import weaver.systeminfo.SystemEnv; + +import java.util.*; + + +public class GetBatchImportInfo extends AbstractCommonCommand> { + + private static String hostaddr = ""; + + public GetBatchImportInfo(Map params, User user) { + this.params = params; + this.user = user; + } + + @Override + public BizLogContext getLogContext() { + return null; + } + + @Override + public Map execute(CommandContext commandContext) { + Map result = new HashMap(); + String modeid = Util.null2String(this.params.get("modeid")); + boolean BatchImportRight = false; + ModeRightInfo modeRightInfo = new ModeRightInfo(); + modeRightInfo.setModeId(Util.getIntValue(modeid)); + modeRightInfo.setUser(user); + modeRightInfo.setType(4); + BatchImportRight = modeRightInfo.checkUserRight(4); + if (!BatchImportRight) { + BatchImportRight = HrmUserVarify.checkUserRight("ModeSetting:All", user); + } + if(!BatchImportRight){ + result.put("status", false); + result.put("errorCode","no-right"); + result.put("error",SystemEnv.getHtmlLabelName(2011,user.getLanguage()));//没有权限 + result.put("noRight", true); + return result; + } + String operation = Util.null2String(this.params.get("operation")); + String customId = Util.null2String(this.params.get("customid")); + String isSinglePage = Util.null2String(this.params.get("isSinglePage"));//单页模式用于前端用户导入 + int sourcetype = 0; + if(!"1".equals(isSinglePage)){ + sourcetype = 1; + } + + int modelId = Util.getIntValue(modeid); + int appId = Util.getIntValue(Util.null2String(this.params.get("appid")));//当前所选应用id + + ModelInfoService modelInfoService = new ModelInfoService(); + AppInfoService appInfoService = new AppInfoService(); + Map data = new HashMap(); + if(modelId>0){ + data = modelInfoService.getModelInfoById(modelId); + } + if(modelId>0&&data.size()==0){ + throw new RuntimeException("no data was found"); + } + + int modetype = Util.getIntValue(Util.null2String(data.get("modetype")),0); + int formid = Util.getIntValue(Util.null2String(data.get("formid")),0); + String modename = Util.null2String(data.get("modename")); + if(modelId==0){ + modetype = appId; + } + int tempId = modetype; + if(tempId==0){ + tempId = appId; + } + String maintablename =""; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery("select tablename from workflow_bill where id = ?",formid); + if(recordSet.next()){ + maintablename = recordSet.getString("tablename"); + } + String userRightStr = "ModeSetting:All"; + Map appInfo = appInfoService.getAppInfoById(tempId); + boolean isUseFmManageDetach=DetachHelper.modeDetachIsOpen(); + int subCompanyId = Util.getIntValue(Util.null2String(data.get("subCompanyId")),-1); + if(subCompanyId==-1){ + subCompanyId = Util.getIntValue(Util.null2String(appInfo.get("subcompanyid")),-1); + } + int operatelevel = DetachHelper.getUserDeatchOperateLevel(user, subCompanyId, userRightStr); + //判断模块是否开启分级保护 + AddSeclevelUtil addSeclevelUtil = new AddSeclevelUtil(); + boolean isOpenClassprotect = false; + Map params = new HashMap<>(); + params.put("modeid", modeid); + isOpenClassprotect = addSeclevelUtil.modeOpenClassProtect(params); + String fmdetachable = isUseFmManageDetach?"1":"0"; + if(operation.equals("getImpStatus")){ + JSONObject impStatus = new JSONObject(); + String tempkey = Util.null2String(this.params.get("tempkey")); + String key = user.getUID()+"_"+modeid+"_"+tempkey; + Object obj = ExpExcelUtil.getObject("modeimp_"+key); + Map cacheMap = null; + if(obj!=null){ + cacheMap = (Map) obj; + } + int step = 0; + if(cacheMap!=null&&cacheMap.containsKey("msg")){ + int s = 1; + String msg = Util.null2String(cacheMap.get("msg")); + String status = Util.null2String(cacheMap.get("status")); + step = Util.getIntValue(Util.null2String(cacheMap.get("step"))); + String impaddr = Util.null2String(cacheMap.get("impaddr")); + String starttimeStr = Util.null2String(cacheMap.get("starttime")); + String endtimeStr = Util.null2String(cacheMap.get("endtime")); + String searchid = Util.null2String(cacheMap.get("searchid")); + String errorflag = Util.null2String(cacheMap.get("errorflag")); + if(!"".equals(starttimeStr)&&!"".equals(endtimeStr)){ + long starttime = Long.parseLong(starttimeStr); + long endtime= Long.parseLong(endtimeStr); + if(starttime>endtime){//还未结束 + ImpExcelServer.putMessage("status", key, "0"); + if(step==6){ + step = 0; + msg = ""; + s = 0; + ImpExcelServer.putMessage("step", key, "0"); + } + } + } + String errmsg = ""; + String time = ""; + if(status.equals("-1")){ + errmsg = Util.null2String(cacheMap.get("errmsg")); + time = Util.null2String(cacheMap.get("time")); + if(!StringHelper.isEmpty(errmsg)){ + errmsg = errmsg.replace("\\n","
"); + } + } + impStatus.put("s",s); + impStatus.put("msg",msg); + impStatus.put("status",status); + impStatus.put("errmsg",errmsg); + impStatus.put("time",time); + impStatus.put("step",step); + impStatus.put("impaddr", impaddr); + impStatus.put("searchid", searchid); + impStatus.put("errorflag", errorflag); + impStatus.put("modeid", modeid); + }else{ + impStatus.put("s",0); + impStatus.put("size",cacheMap==null?0:cacheMap.size()); + } + hostaddr = ExcelCacheUtil.getHostaddr(); + result.put("hostaddr", hostaddr); + result.put("impStatus", impStatus); +// try { +// if(step>3){//主表数据执行后就删除临时表,序列删除,触发器删除 +// RecordSet rs = new RecordSet(); +// rs.execute("delete from M_"+modeid+"_"+user.getUID()); +// rs.writeLog("GetBatchImportInfo-step="+step); +// String dbType = rs.getDBType(); +//// if(DBConstant.DB_TYPE_ORACLE.equals(dbType)){ +//// rs.execute("DROP SEQUENCE M_"+modeid+"_"+user.getUID()+"_id"); +//// rs.execute("DROP TRIGGER M_"+modeid+"_"+user.getUID()+"_Trigger"); +//// } +// } +// } catch (Exception e) { +// e.printStackTrace(); +// } + return result; + }else if(operation.equals("stopImport")){ + String tempkey = Util.null2String(this.params.get("tempkey")); + String key = user.getUID()+"_"+modeid+"_"+tempkey+"_cancel"; + StringCacheMap.put(key, key); + hostaddr = ExcelCacheUtil.getHostaddr(); + result.put("hostaddr", hostaddr); + return result; + }else if(operation.equals("getBatchImportLogList")){ + String startdate = Util.null2String(this.params.get("startdate")); + String enddate = Util.null2String(this.params.get("enddate")); + String operator = Util.null2String(this.params.get("operator")); + String operatetype = Util.null2String(this.params.get("operatetype")); + + String SqlWhere = " where a.modeid='"+modeid+"' " ; + if(!startdate.isEmpty()){ + SqlWhere += " and optdatetime >= '"+startdate+" 00:00:00'"; + } + if(!enddate.isEmpty()){ + SqlWhere += " and optdatetime <= '"+enddate+" 23:59:59 '"; + } + if(!operator.isEmpty()){ + SqlWhere += " and operator = '"+operator+"'"; + } + if(!operatetype.isEmpty()){ + SqlWhere += " and operatetype = '"+operatetype+"'"; + } + + String perpage = "10"; + String backFields = " a.id,a.id optid,a.modeid,a.operatetype,a.ipaddress,a.operator,a.optdatetime,a.addrow,a.updaterow,a.delrow,a.failurerow,a.adddetailrow,a.deldetailrow,a.backupremark,a.backindex"; + String sqlFrom = " from mode_batchimp_log a "; + String pageUid = "modeList_12345678"; + String orderby = " a.optdatetime desc "; + String tableString=""+ + ""+ + ""+ + ""+ + //操作人 + ""+ + //操作类型 + ""+ + ""+ + //操作日期 + ""+ + //增加 + ""+ + //删除 + ""+ + //更新 + ""+ + //失败 + ""+ + //增加明细 + ""+ + //删除明细 + ""+ + ""; + if (operatelevel>=2) {//如果拥有完全控制权限 + //下载导入的文件 + tableString+=""; + //备注 + tableString+=""; + } + tableString+= + ""+ + "
"; + Map apidatas = new HashMap(); + String sessionkey = pageUid + "_" + Util.getEncrypt(Util.getRandom()); + Util_TableMap.setVal(sessionkey, tableString); + apidatas.put("sessionkey", sessionkey); + return apidatas; + } + if("getTemplate".equals(operation)){ + JSONArray templateFields = new JSONArray(); + FormInfoService formInfoService = new FormInfoService(); + formInfoService.setUser(user); + net.sf.json.JSONObject resultObj = formInfoService.getAllFieldByImport(Util.getIntValue(modeid),formid); + + String maintable1 = resultObj.getString("maintable"); + net.sf.json.JSONArray tables = resultObj.getJSONArray("tables"); + for(int i=0;i0) { + String sql = "select note from mode_excelField where id="+validateid; + RecordSet.execute(sql); + if (RecordSet.next()) { + note = RecordSet.getString("note"); + } + } + batchImportValidate.put("note", note); + + String sqlwhere = " and modeid="+StringHelper.empty2Null(modeid)+" and formid="+formid+" and ( fieldid in ('-1000','-1001','-1002') or exists (select 1 from workflow_billfield b where b.billid="+formid+" and b.id=a.fieldid) )"; + String sql2 = "select a.fieldid from mode_import_template a where 1=1 "+sqlwhere+" order by a.dsporder,a.fieldid "; + rs2.execute(sql2);//设置的字段 + int count = rs2.getCounts(); + sqlwhere = ""; + if(count>0){ + sqlwhere = " and exists (select 1 from mode_import_template c where c.fieldid=a.id and c.modeid="+StringHelper.empty2Null(modeid)+" and c.formid="+formid+" )"; + } + + //----------------选择框字段-------------------- + String sql = ""; + if(count>0){ + sql = "select * from (select a.id,a.viewtype,a.detailtable,b.indexdesc,a.fieldname from workflow_billfield a, htmllabelindex b " + + " where a.billid="+formid+" and fieldhtmltype=5 and type<>2 and b.id=a.fieldlabel "+sqlwhere+") t"; + }else{ + sql="select * from (select a.id,a.viewtype,a.detailtable,b.indexdesc ,c.needExcel,a.fieldname from workflow_billfield a, htmllabelindex b, ModeFormFieldExtend c where c.needExcel = 1 and a.billid=c.formId " + +"and a.id=c.fieldId and a.billid="+formid+" and fieldhtmltype=5 and type<>2 and b.id=a.fieldlabel " + + " union " + + " select a.id,a.viewtype,a.detailtable,c.indexdesc,1 as needExcel, a.fieldname from workflow_billfield a ,HtmlLabelindex c where " + +"a.billid="+formid+" and c.id=a.fieldlabel and fieldhtmltype=5 and type<>2 and not exists (select 1 from ModeFormFieldExtend b where b.formid=a.billid and b.formid="+formid+" and b.fieldId=a.id)" + + ") t"; + } + sql += " ORDER BY viewtype,detailtable,id "; + JSONArray selectFields = new JSONArray(); + batchImportValidate.put("selectFields", selectFields); + rs.execute(sql); + while(rs.next()){ + JSONObject temp = new JSONObject(); + String fieldid = rs.getString("id"); + String fieldlabel = rs.getString("indexdesc"); + String detailtable = rs.getString("detailtable"); + String fieldname = rs.getString("fieldname"); + if(isOpenClassprotect){ + if("seclevel".equals(fieldname.toLowerCase())){ + continue; + } + } + if(!detailtable.equals("")){ + fieldlabel = fieldlabel + "("+ SystemEnv.getHtmlLabelName(126218, user.getLanguage())+CardFormHelper.getNumOfDetailTableName(detailtable)+")"; + } + if(StringHelper.isEmpty(detailtable)){ + detailtable = "maintable"; + } + temp.put("key",fieldid); + temp.put("showname",fieldlabel); + temp.put("detailtable",detailtable); + selectFields.add(temp); + } + + + //选择项目 + JSONObject selectOption = new JSONObject(); + batchImportValidate.put("selectOption", selectOption); + sql = "select a.fieldid,a.selectvalue,a.selectname from workflow_SelectItem a,workflow_billfield b " + + " where a.fieldid=b.id AND b.fieldhtmltype=5 AND b.billid="+formid+" ORDER BY b.viewtype,a.fieldid,a.listorder"; + rs.execute(sql); + while(rs.next()){ + String fieldid = rs.getString("fieldid"); + String selectvalue = rs.getString("selectvalue"); + String selectname = rs.getString("selectname"); + JSONArray options = null; + if(selectOption.containsKey(fieldid)){ + options = selectOption.getJSONArray(fieldid); + }else{ + options = new JSONArray(); + selectOption.put(fieldid, options); + } + JSONObject obj = new JSONObject(); + obj.put("key", selectvalue); + obj.put("showname", selectname); + options.add(obj); + } + + //-------已经设置的列表------------ + JSONArray validateFieldDetail = new JSONArray(); + batchImportValidate.put("validateFieldDetail", validateFieldDetail); + if(validateid>0){ + sql = "select * from mode_excelFieldDetail where mainid="+validateid; + if(count==0){ + sql+=" and (selectids in(select a.id from workflow_billfield a, htmllabelindex b, ModeFormFieldExtend c where c.needExcel = 1 and a.billid=c.formId " + +"and a.id=c.fieldId and a.billid="+formid+" and fieldhtmltype=5 and b.id=a.fieldlabel union select a.id from workflow_billfield a ,HtmlLabelindex c where " + +"a.billid="+formid+" and c.id=a.fieldlabel and fieldhtmltype=5 and not exists (select 1 from ModeFormFieldExtend b where b.formid=a.billid and b.formid="+formid+" and b.fieldId=a.id) )" + + " or (selectids is null or selectids='')) "; + } + sql += " order by id "; + RecordSet.execute(sql); + while(RecordSet.next()){ + String id = RecordSet.getString("id"); + String fieldid = RecordSet.getString("fieldid"); + String selectid = Util.null2String(RecordSet.getString("selectids")); + String selectvalue = Util.null2String(RecordSet.getString("selectvalue")); + + JSONObject obj = new JSONObject(); + obj.put("key", id); + obj.put("selectid", selectid); + obj.put("selectvalue", selectvalue); + obj.put("fieldid", fieldid); + validateFieldDetail.add(obj); + } + } + + //如果没有数据默认添加一行 + if(validateFieldDetail.size()==0){ + JSONObject obj = new JSONObject(); + obj.put("key", "new_"+new Date().getTime()); + obj.put("selectid", ""); + obj.put("selectvalue", ""); + obj.put("fieldid", ""); + validateFieldDetail.add(obj); + } + + //----------------每个表的字段----------------------- + JSONObject tableFields = new JSONObject(); + batchImportValidate.put("tableFields", tableFields); + + Listlist=new ArrayList(); + String selectid = ""; + + String fieldsql = ""; + if(count==0){ + fieldsql = "select b.id,b.detailtable,c.indexdesc from htmllabelindex c,workflow_billfield b left join ModeFormFieldExtend a " + + " on b.id=a.fieldId where (needExcel !=0 or needExcel is null) and c.id=b.fieldlabel and b.billid="+formid; + }else{ + fieldsql = "select b.*,c.indexdesc from htmllabelindex c,workflow_billfield b join mode_import_template a " + + " on b.id=a.fieldId and modeid='"+modeid+"' and formid='"+formid+"' where c.id=b.fieldlabel and b.billid="+formid; + } + rs.executeQuery(fieldsql); + List tableList = new ArrayList(); + while(rs.next()){ + ////QC 364486 表单建模,设置为多语言,批量导入,导入必填字段,选择必填字段,乱码 + String indexdesc =Util.formatMultiLang(Util.null2String(rs.getString("indexdesc")), user.getLanguage()+""); + String fieldid = Util.null2String(rs.getString("id")); + String detailtable = Util.null2String(rs.getString("detailtable")); + if(!detailtable.equals("")){ + indexdesc += "("+ SystemEnv.getHtmlLabelName(126218, user.getLanguage()) +CardFormHelper.getNumOfDetailTableName(detailtable)+")"; + } + if(StringHelper.isEmpty(detailtable)){ + detailtable = "maintable"; + } + JSONArray fieldids = null; + if(tableFields.containsKey(detailtable)){ + fieldids = tableFields.getJSONArray(detailtable); + }else{ + fieldids = new JSONArray(); + tableFields.put(detailtable,fieldids); + tableList.add(detailtable); + } + JSONObject obj = new JSONObject(); + obj.put("key", fieldid); + obj.put("showname", indexdesc); + + fieldids.add(obj); + } + batchImportValidate.put("tableList",tableList); + result.put("batchImportValidate", batchImportValidate); + result.put("fmdetachable", fmdetachable); + result.put("operatelevel", operatelevel); + return result; + }else if(operation.equals("checkImp")){ + JSONObject jsonObj = ExpExcelUtil.checkCanImpExcel(user,modeid); + result.putAll(jsonObj); + result.put("fmdetachable", fmdetachable); + result.put("operatelevel", operatelevel); + return result; + }else{ + //-----获取基本信息 + RecordSet rs = new RecordSet(); + String needfav = ""; + String needhelp = ""; + + int rightLevel = -1;//无权限 + + ModeRightInfo ModeRightInfo = new ModeRightInfo(); + int type = 4;//批量导入权限 + boolean isRight = false; + boolean isALLRight = false; + if (type == 4) {//监控权限判断 + ModeRightInfo.setModeId(modelId); + ModeRightInfo.setType(type); + ModeRightInfo.setUser(user); + isRight = ModeRightInfo.checkUserRight(type); + if (!isRight) { + isALLRight = HrmUserVarify.checkUserRight(userRightStr, user); + if (!isALLRight) { + result.put("isRight", false); + result.put("rightLevel", -1); + result.put("fmdetachable", fmdetachable); + result.put("operatelevel", operatelevel); + + JSONObject batchImportInfo = new JSONObject(); + batchImportInfo.put("modename", modename); + batchImportInfo.put("isRight", isRight); + batchImportInfo.put("formid", formid); + batchImportInfo.put("modeid", modeid); + result.put("batchImportInfo", batchImportInfo); + + return result; + } + } + } + + + List importTypes = ModeRightInfo.checkUserImportType(); + /*if (importTypes.size() == 0) { + if (isALLRight) { + importTypes.add(0); + } + }*/ + + JSONArray importTypeOption = new JSONArray(); + //根据后台设置的导入类型 这里做一个限制 + if ( importTypes.contains(1) || user.getUID()==1 ||isALLRight) { + JSONObject obj = new JSONObject(); + obj.put("key", "1"); + obj.put("showname", SystemEnv.getHtmlLabelName(31259, user.getLanguage())); + importTypeOption.add(obj); + } + if (importTypes.contains(3) || user.getUID()==1 || isALLRight) { + JSONObject obj = new JSONObject(); + obj.put("key", "3"); + obj.put("showname", SystemEnv.getHtmlLabelName(17744, user.getLanguage())); + importTypeOption.add(obj); + } + if ( importTypes.contains(2)) { + JSONObject obj = new JSONObject(); + obj.put("key", "2"); + obj.put("showname", SystemEnv.getHtmlLabelName(517042, user.getLanguage())); + importTypeOption.add(obj); + } + + + //-------------- + + String sql = ""; + String interfacepath = ""; + String fieldtranspath = ""; + String importorder = ""; + String isuse = ""; + String validateid = ""; + String keyfield = ""; + int fieldDetailCount = 0; + String templateTitle = ""; + String fieldtransTitle = ""; + int isHaveTemplate = 0; + boolean isHaveFieldtrans=false;//是否存在导入转换接口 + if (modelId>0) { + String templateSql = "select 1 from mode_import_template a where modeid=" + modeid + " and formid=" + formid + " and (exists(select 1 from workflow_billfield b where b.billid=" + formid + " and b.id=a.fieldid) or a.fieldid in(-1000,-1001,-1002)) "; + rs.execute(templateSql); + if (rs.getCounts() > 0) { + isHaveTemplate = 1; + } + } + //获取接口路径等信息 + sql = "select * from mode_DataBatchImport where modeid=" + modeid; + rs.execute(sql); + if (rs.next()) { + interfacepath = rs.getString("interfacepath"); + keyfield = rs.getString("keyfield"); + fieldtranspath = rs.getString("fieldtranspath"); + importorder = rs.getString("importorder"); + isuse = rs.getString("isuse"); + validateid = Util.null2String(rs.getString("validateid")); + if (!validateid.equals("")) { + sql = "select COUNT(a.id) as num from mode_excelFieldDetail a,mode_excelField b where a.mainid=b.id and b.modeid=" + modeid; + rs.execute(sql); + if (rs.next()) { + fieldDetailCount = rs.getInt("num"); + } + } + } + + + if (sourcetype == 1 && operatelevel > 0) { + if(isHaveTemplate==1){//编辑模板 + templateTitle = SystemEnv.getHtmlLabelName(28052, user.getLanguage()); + }else{//设置模板 + templateTitle = SystemEnv.getHtmlLabelName(503155, user.getLanguage()); + } + if(isHaveFieldtrans){//编辑字段 + fieldtransTitle = SystemEnv.getHtmlLabelName(15449, user.getLanguage()); + }else{//设置字段 + fieldtransTitle = SystemEnv.getHtmlLabelName(504193, user.getLanguage()); + } + } + + JSONArray keyFieldOption = new JSONArray(); + JSONObject obj = new JSONObject(); + obj.put("key", ""); + obj.put("showname", ""); + keyFieldOption.add(obj); + if (importTypes.size() == 0 || importTypes.contains(3) || importTypes.contains(0)|| user.getUID()==1 || isALLRight) { + String sql1 = ""; + if(isHaveTemplate==1){ + sql1 = " select 1 from mode_import_template c where c.fieldid=-1000 and c.modeid="+modeid+" and c.formid="+formid+" "; + }else{ + sql1 = "select 1 from ModeFormFieldExtend where fieldid=-1000 and needExcel=1 and formid="+formid+" "; + } + rs.execute(sql1); + if(rs.getCounts()>0){//显示数据id时,才显示此选项 + obj = new JSONObject(); + obj.put("key", "dataid"); + obj.put("showname", SystemEnv.getHtmlLabelName(81287, user.getLanguage())); + keyFieldOption.add(obj); + } + } + + String sqlwhere = ""; + if(isHaveTemplate==1){ + sqlwhere = " and exists (select 1 from mode_import_template c where c.fieldid=a.id and c.modeid="+modeid+" and c.formid="+formid+" )"; + sql = "select a.id,a.fieldname,a.fieldlabel from workflow_billfield a where " + + "billid="+formid +" and (fieldhtmltype<>2 and fieldhtmltype<>6 and fieldhtmltype<> 7) " + +sqlwhere+ " and viewtype=0 order by dsporder,id"; + }else{ + sql = "select a.id,a.fieldname,b.needExcel,a.fieldlabel from workflow_billfield a, ModeFormFieldExtend b where b.formid=a.billid and " + +"b.formid="+formid+" and b.needExcel=1 and (fieldhtmltype<>2 and fieldhtmltype<>6 and fieldhtmltype<> 7) and viewtype=0 union " + +"select a.id,a.fieldname,1 as needExcel,a.fieldlabel from workflow_billfield a where a.billid="+formid+" " + +"and (fieldhtmltype<>2 and fieldhtmltype<>6 and fieldhtmltype<> 7) and a.viewtype=0 and not exists (select 1 from ModeFormFieldExtend b where b.formid=a.billid and b.formid="+formid+" and b.fieldId=a.id) "; + } + rs.execute(sql); + ModeFormFieldEncryptComInfo modeFormFieldEncryptComInfo=new ModeFormFieldEncryptComInfo(); + while (rs.next()) { + String fieldid=rs.getString("id"); + String fieldname = rs.getString("fieldname"); + if(isOpenClassprotect){ + if("seclevel".equals(fieldname.toLowerCase())){ + continue; + } + } + String labelname = SystemEnv.getHtmlLabelName(Util.getIntValue(rs.getString("fieldlabel")), user.getLanguage()); + EncryptFieldEntity encryptFieldEntity = new EncryptFieldConfigComInfo().getFieldEncryptConfig(maintablename, fieldname); + String isencrypt = modeFormFieldEncryptComInfo.getIsencrypt(fieldid); + if(encryptFieldEntity != null && ("1".equals(encryptFieldEntity.getDesensitization()) || "1".equals(encryptFieldEntity.getIsEncrypt()))) { + isencrypt = "1";//前端不能选择加密字段 + } + obj = new JSONObject(); + obj.put("key", fieldname); + obj.put("showname", labelname); + obj.put("isencrypt", isencrypt ); + keyFieldOption.add(obj); + } + + if( (operatelevel < 1 && !isRight)){ + rightLevel = 0;//只读权限 + }else if(operatelevel>=0){ + rightLevel = operatelevel; + } + + JSONObject batchImportInfo = new JSONObject(); + batchImportInfo.put("importTypeOption", importTypeOption); + batchImportInfo.put("modename", modename); + batchImportInfo.put("templateTitle", templateTitle); + batchImportInfo.put("fieldtransTitle", fieldtransTitle); + batchImportInfo.put("isHaveFieldtrans", isHaveFieldtrans); + batchImportInfo.put("fieldtranspath", fieldtranspath); + batchImportInfo.put("isRight", isRight); + batchImportInfo.put("importorder", importorder); + batchImportInfo.put("interfacepath", interfacepath); + batchImportInfo.put("isuse", isuse); + batchImportInfo.put("validateid", validateid); + batchImportInfo.put("fieldDetailCount", fieldDetailCount); + batchImportInfo.put("keyFieldOption", keyFieldOption); + batchImportInfo.put("excelid", ""); + batchImportInfo.put("formid", formid); + batchImportInfo.put("isHaveTemplate", isHaveTemplate); + batchImportInfo.put("modeid", modeid); + RecordSet appRs= new RecordSet(); + appRs.executeQuery("select * from HrmOrganizationShowSet"); + String applyToModel = ""; //是否全路径 + while (appRs.next()){ + applyToModel = Util.null2String(appRs.getString("applyToModel")); + } + String windowTitle = ""; + if(null != customId&& !customId.equals("")){ + RecordSet titileRs = new RecordSet(); + titileRs.executeQuery("select customname from mode_customsearch where id = ?",customId); + if(titileRs.next()){ + windowTitle = Util.null2String(titileRs.getString("customname")); + } + } + JSONArray arr = new JSONArray(); + if (!"".equals(keyfield)) { + String [] keyfields = keyfield.split("\\|"); + for (int i = 0; i < keyfields.length; i++) { + arr.add( keyfields[i]); + } + } + batchImportInfo.put("keyfield", arr); + + //qc656609获取应用图标信息 + String geticonsql = "select icon,iconcolor,iconbg from modetreefield where id=(select modetype from modeinfo where id="+modeid+")"; + JSONObject iconInfo = new JSONObject(); + String icon = "";//图标 + String iconcolor = "";//图标颜色 + String iconbg = "";//图标背景颜色 + rs.execute(geticonsql); + if(rs.next()){ + icon = rs.getString("icon"); + iconcolor = rs.getString("iconcolor"); + iconbg = rs.getString("iconbg"); + } + iconInfo.put("icon", icon); + iconInfo.put("iconcolor", iconcolor); + iconInfo.put("iconbg", iconbg); + + result.put("windowTitle", windowTitle); + result.put("applyToModel", applyToModel); + result.put("rightLevel", rightLevel); + result.put("isRight", isRight); + result.put("batchImportInfo", batchImportInfo); + result.put("modeid", modeid); + result.put("operatelevel", operatelevel); + result.put("fmdetachable", fmdetachable); + result.put("iconInfo", iconInfo); + return result; + } + } + + /** + * 获取导入转换接口字段设置 + * @param modeid + * @param formid + * @return + */ + private JSONArray getFieldTrans(String modeid, int formid) { + JSONArray array = new JSONArray(); + RecordSet rs = new RecordSet(); + String sql = "select fieldid from mode_import_fieldtrans a where modeid=? and formid=? and (exists(select 1 from workflow_billfield b where b.billid=? and b.id=a.fieldid) or a.fieldid in(-1000,-1001,-1002)) "; + rs.executeQuery(sql, modeid,formid,formid); + List fieldTrans = new ArrayList(); + while (rs.next()) { + String fieldid=Util.null2String(rs.getString("fieldid")); + fieldTrans.add(fieldid); + } + List tables = new ArrayList(); + String maintablename=""; + sql="select * from (select 'main' tabletype,tablename,0 as orderid from workflow_bill where id=? union select 'detail' tabletype,tablename,orderid from Workflow_billdetailtable where billid=? ) t order by orderid"; + rs.executeQuery(sql, formid,formid); + while (rs.next()) { + String tablename=Util.null2String(rs.getString("tablename")); + String tabletype=Util.null2String(rs.getString("tabletype")); + if ("main".equals(tabletype)) { + maintablename=tablename; + } + tables.add(tablename); + } + sql="select fieldid,w.fieldname,info.labelname fieldlabelname,w.detailtable,w.viewtype from mode_import_template t left join workflow_billfield w on w.id=t.fieldid left join htmllabelinfo info on info.indexid=w.fieldlabel and info.languageid=? where t.modeid=? and t.formid=? order by t.fieldid"; + rs.executeQuery(sql, user.getLanguage(),modeid,formid); + if (rs.getCounts()<=0) {//如果没有设置字段,则以表达中的导入字段为准 + sql=" select fieldid ,'' fieldname,'' fieldlabelname,'' detailtable,0 viewtype from modeformfieldextend where formid=? and needexcel=1 and fieldid in (-1000,-1001,-1002) "; + sql+=" union all select w.id fieldid,w.fieldname,info.labelname fieldlabelname,w.detailtable,w.viewtype from workflow_billfield w left join htmllabelinfo info on info.indexid=w.fieldlabel and info.languageid=? where billid=? and w.fieldhtmltype not in (6,7) and id not in (select fieldid from modeformfieldextend where needexcel=0 and formid=?)"; + rs.executeQuery(sql,formid, user.getLanguage(),formid,formid); + } + Map infomap = new HashMap(); + while (rs.next()) { + String fieldid = Util.null2String(rs.getString("fieldid")); + String fieldname = Util.null2String(rs.getString("fieldname")); + String fieldlabelname = Util.null2String(rs.getString("fieldlabelname")); + String detailtable = Util.null2String(rs.getString("detailtable")); + String viewtype = Util.null2String(rs.getString("viewtype")); + String temptablename=maintablename; + if ("1".equals(viewtype)) {//明细表 + temptablename=detailtable; + } + if ("-1000".equals(fieldid)) {//数据id + fieldname="id"; + fieldlabelname=SystemEnv.getHtmlLabelName(81287,user.getLanguage()); + }else if ("-1001".equals(fieldid)) { + fieldname="modedatacreater"; + fieldlabelname=SystemEnv.getHtmlLabelName(382643,user.getLanguage()); + }else if ("-1002".equals(fieldid)) { + fieldname="modedatacreatedate"; + fieldlabelname=SystemEnv.getHtmlLabelName(126848,user.getLanguage()); + } + JSONArray tablemap; + if (infomap.containsKey(temptablename)) { + tablemap=infomap.get(temptablename); + }else { + tablemap=new JSONArray(); + infomap.put(temptablename, tablemap); + } + JSONObject obj = new JSONObject(); + obj.put("fieldid", fieldid); + obj.put("key", fieldid); + obj.put("fieldlabelname", fieldlabelname); + obj.put("fieldname", fieldname); + obj.put("ischeck", fieldTrans.contains(fieldid)?"1":"0"); + tablemap.add(obj); + } + for (int i = 0; i < tables.size(); i++) { + String tablename = tables.get(i); + JSONObject tableObj = new JSONObject(); + String tablenamelabel = ""; + if(i==0){//主表 + tablenamelabel = SystemEnv.getHtmlLabelName(21778,user.getLanguage()); + }else{ + String index = tablename.replace(maintablename+"_dt", ""); + tablenamelabel = SystemEnv.getHtmlLabelName(17463,user.getLanguage())+index; + } + tableObj.put("index", i); + tableObj.put("tablename", tablename); + tableObj.put("tablenamelabel", tablenamelabel); + JSONArray fieldArray = infomap.get(tablename); + if (fieldArray==null) { + fieldArray=new JSONArray(); + } + tableObj.put("fieldArray", fieldArray); + array.add(tableObj); + } + return array; + } + + + +} \ No newline at end of file diff --git a/src/com/engine/cube/cmd/card/LayoutFieldAttrExcute.java b/src/com/engine/cube/cmd/card/LayoutFieldAttrExcute.java new file mode 100644 index 0000000..c1a7eb7 --- /dev/null +++ b/src/com/engine/cube/cmd/card/LayoutFieldAttrExcute.java @@ -0,0 +1,663 @@ +package com.engine.cube.cmd.card; + +import com.alibaba.fastjson.JSONArray; +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.cube.biz.CardHelper; +import com.engine.cube.biz.DataHelper; +import com.engine.cube.entity.CardEntity; +import com.weaver.formmodel.util.DateHelper; +import com.weaver.formmodel.util.StringHelper; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.TimeUtil; +import weaver.general.Util; +import weaver.hrm.User; +import weaver.hrm.company.DepartmentComInfo; +import weaver.hrm.report.schedulediff.HrmScheduleDiffUtil; +import weaver.hrm.resource.ResourceComInfo; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class LayoutFieldAttrExcute extends AbstractCommonCommand> { + private final DataHelper dataHelper; + private CardEntity card; + + public LayoutFieldAttrExcute(Map stringObjectMap, User user) { + this.params = stringObjectMap; + this.user = user; + this.dataHelper = new DataHelper(user); + } + + @Override + public BizLogContext getLogContext() { + return null; + } + + @Override + public Map execute(CommandContext commandContext) { + Map result = new HashMap(); + JSONObject datas = new JSONObject(); + this.card = CardHelper.initBaseCardEntity(params); + String triggerStr = Util.null2String(this.params.get("trigger")); + JSONObject trigger = JSONObject.parseObject(triggerStr); + if(trigger == null || trigger.isEmpty()) { + return result; + } + RecordSet rs = new RecordSet(); + rs.executeQuery(" select fieldid, attrcontent, caltype, othertype, transtype, datasource" + + " from modefieldattr where layoutid = ? and caltype <> '5' ", card.getLayoutId()); + while(rs.next()) { + String attrcontent = Util.null2String(rs.getString(2)).trim(); + //attrcontent = attrcontent.replaceAll("\\$currentdate\\$", "\\$date\\$"+ DateHelper.getCurrentDate()+"\\$date\\$"); + attrcontent = attrcontent.replaceAll("\\$currentdept\\$", user.getUserDepartment()+""); + attrcontent = attrcontent.replaceAll("\\$currentuser\\$", user.getUID()+""); + attrcontent = attrcontent.replaceAll("\\$billid\\$", Util.null2String(this.card.getBillId())); + attrcontent = attrcontent.replaceAll("\\$dataid\\$", Util.null2String(this.card.getBillId())); + attrcontent = attrcontent.replaceAll("\\$modeid\\$", Util.null2String(this.card.getModeId())); + attrcontent = attrcontent.replaceAll("\\$formid\\$", Util.null2String(this.card.getFormId())); + Pattern pat = Pattern.compile("\\$([-]?\\d+)\\$"); + Matcher mat = pat.matcher(attrcontent); + List fields = new ArrayList(); + boolean hasFind = false; + JSONArray triggerDatas = null; + while(mat.find()){ + String field = mat.group(); + field = field.replaceAll("\\$", ""); + String fieldStr = "field"+field; + if(trigger.containsKey(fieldStr)) { + hasFind = true; + if(triggerDatas==null){ + triggerDatas = trigger.getJSONArray(fieldStr); + }else{ + triggerDatas.addAll(trigger.getJSONArray(fieldStr)); + } + } + } + if(hasFind && triggerDatas != null && !triggerDatas.isEmpty()) { + String caltype = Util.null2String(rs.getString(3)); + String fieldid = "field"+Util.null2String(rs.getString(1)).toLowerCase(); + String datasource = Util.null2String(rs.getString("datasource")); + if(datasource.isEmpty()) { + datasource = null; + } + JSONArray tempArr = new JSONArray(); + if(datas.containsKey(caltype)){ + tempArr = (JSONArray) datas.get(caltype); + } + int othretype = Util.getIntValue(rs.getString(4)); + if("1".equals(caltype)||"0".equals(caltype)) { + tempArr.addAll(this.doFieldSql(fieldid, attrcontent, triggerDatas, datasource)); + } else if("2".equals(caltype)) { + tempArr.addAll(this.doFieldMath(fieldid, attrcontent, triggerDatas)); + } else if("3".equals(caltype)) { + tempArr.addAll(this.doDateTimeCal(fieldid, attrcontent, triggerDatas, othretype )); + } else { + tempArr.addAll(this.doOtherAttr(fieldid, attrcontent, triggerDatas)); + } + datas.put(caltype, tempArr); + } + } + result.put("datas", datas); + return result; + } + private JSONArray doOtherAttr(String fieldid, String attrcontent, JSONArray triggerDatas){ + JSONArray result = new JSONArray(); + + int size = triggerDatas.size(); + for(int i = 0; i -1 || execSql.toUpperCase().indexOf("UPDATE") > -1 + || execSql.toUpperCase().indexOf("DROP") > -1 || execSql.toUpperCase().indexOf("TRUNCATE") > -1 + || execSql.toUpperCase().indexOf("DELETE") > -1 || execSql.toUpperCase().indexOf("EXEC") > -1 + || execSql.toUpperCase().indexOf("CALL") > -1 ){ + return result; + } + execSql = execSql.substring(index + 12); + index = execSql.lastIndexOf("\")"); + if (index > -1) { + execSql = execSql.substring(0, index); + execSql = execSql.trim(); + } + + Pattern pat = Pattern.compile("\\$([-]?\\d+)\\$"); + Matcher mat = pat.matcher(attrcontent); + List paramNames = new ArrayList(); + List fieldArr = new ArrayList(); + while(mat.find()){ + try{ + String field = mat.group(); + String fid = field.replaceAll("\\$", ""); + paramNames.add("field"+fid); + fieldArr.add(field); + //execSql = Util.replaceString(execSql, field, " ? "); + //execSql = execSql.replaceAll( "\\$"+fid+"\\$", " ? "); + }catch(Exception e){ + e.printStackTrace(); + } + } + + RecordSet rs = new RecordSet(); + + int size = triggerDatas.size(); + for(int i = 0; i 1){ + dataHelper.addValue(data, fieldid, rs.getString(2)); + } else { + dataHelper.addValue(data, fieldid, rs.getString(1)); + } + } + dataHelper.dealData(data, new String[]{fieldid}); + + } + //if(data.isEmpty()) { + // data.put(fieldid, ""); + //} + if(triggerData.containsKey("index")) { + data.put("index", triggerData.get("index")); + } + result.add(data); + } + return result; + } + private JSONArray doDateTimeCal(String fieldid, String attrcontent, JSONArray triggerDatas, int othertype) { + JSONArray result = new JSONArray(); + int size = triggerDatas.size(); + for(int i=0;i -1) { + int index0 = datecontent_tmp.indexOf("$", index + 1); + String field1 = datecontent_tmp.substring(index + 1, index0); + String mark_t = datecontent_tmp.substring(0, index).trim(); + if ("+".equals(mark_t)) { + retDateContent += ("+"); + } else if ("-".equals(mark_t)) { + retDateContent += ("-"); + } + + if (("datetime").equals(field1)) { + retDateContent += "$datetime$"; + } else if ("currentdate".equals(field1)) { + retDateContent += "$date$"+ DateHelper.getCurrentDate()+"$date$"; + } else if ("currentdatetime".equals(field1)) { + retDateContent += "$currentdatetime$"+ DateHelper.getCurDateTime()+"$currentdatetime$"; + } else { + String fieldtypeStr = ""; + String htmltype = dataHelper.getFieldHtmlType("field"+field1); + String detailtype = dataHelper.getFieldType("field"+field1); + + boolean isdate = "3".equals(htmltype)&&"2".equals(detailtype); + boolean istime = "3".equals(htmltype)&&"19".equals(detailtype); + boolean isinput = !isdate&&!istime; + if (isinput == true) { + fieldtypeStr = "$input$"; + } else if (isdate == true) { + fieldtypeStr = "$date$"; + } else if (istime == true) { + fieldtypeStr = "$time$"; + } + + + retDateContent += (fieldtypeStr + triggerData.getString("field"+field1) + fieldtypeStr) ; + } + datecontent_tmp = datecontent_tmp.substring(index0 + 1); + index = datecontent_tmp.indexOf("$"); + } + + // 最后结尾如果有数据,要特殊处理 + String[] tailStr = datecontent_tmp.split(""); + Pattern pa = Pattern.compile("\\d{1}"); + if (tailStr != null) { + int ishead = -1; + for (int j = 0; j < tailStr.length; j++) { + String s = tailStr[j].trim(); + Matcher matcher = pa.matcher(s); + if ("+".equals(s)) { + if (ishead == 0) { + retDateContent += "$input$"; + } + retDateContent += ("+"); + ishead = 1; + } else if ("-".equals(s)) { + if (ishead == 0) { + retDateContent += "$input$"; + } + retDateContent += ("-"); + ishead = 1; + } else if (matcher.find()) { + if (ishead == 1) { + retDateContent += ("$input$" + s); + ishead = 0; + } else { + retDateContent += s; + } + } + } + if (ishead == 0) { + retDateContent += "$input$\""; + } + } + + String datecontent = retDateContent; + + String key = ""; + String fromdate = ""; + String fromtime = ""; + String todate = ""; + String totime = ""; + String tempCalStr = ""; + int inputDate = -1; + int setDataCx = 0;//赋值次数 + String tempDateTime = ""; + double tempDouble = 0; + boolean isDateTimeCal = false; + int index0 = datecontent.indexOf("$"); + + while(index0 > -1){ + String calStr = ""; + int index1 = datecontent.indexOf("$", index0+1); + String espStr = datecontent.substring(index0+1, index1);//数据类型标识。date日期、time时间、input数字 + datecontent = datecontent.substring(index1+1); + if("datetime".equals(espStr)){ + //datecontent = datecontent.substring(index1+espStr.length()+1); + isDateTimeCal = true; + }else{ + int index2 = datecontent.indexOf("$"+espStr+"$");//找这个标签的下一次出现的地方 + String data0 = datecontent.substring(0, index2);//标识中的值 + if("date".equalsIgnoreCase(espStr)){ + if("".equals(fromdate)){ + fromdate = data0; + setDataCx += 1; + }else{ + todate = data0; + if(isDateTimeCal == false){ + setDataCx += 2; + } + } + }else if("time".equalsIgnoreCase(espStr)){ + if("".equals(fromtime)){ + fromtime = data0; + }else{ + totime = data0; + if(isDateTimeCal == true){ + setDataCx += 2; + } + } + }else if("currentdatetime".equalsIgnoreCase(espStr)){ + String[] split = data0.split(" "); + if (split.length==2) { + if("".equals(fromdate)){ + fromdate = split[0]; + fromtime=split[1]; + setDataCx += 1; + }else{ + todate = split[0]; + totime=split[1]; + if(isDateTimeCal == true){ + setDataCx += 2; + } + } + } + }else if("input".equalsIgnoreCase(espStr)){ + inputDate = Util.getIntValue(data0, 0); + setDataCx += 5; + } + try{ + if(setDataCx==3 || setDataCx==6 || setDataCx==5){//3:日期[合并时间]与日期[合并时间]计算;6:日期[合并]时间与数字计算;5:做过日期计算又做与数字的计算 + if(setDataCx == 3){ + tempDouble = Util.getDoubleValue(getDateTimeCal(fromdate, fromtime, todate, totime, isDateTimeCal, othertype, tempCalStr)); + key = ""+tempDouble; + /*if(tempDouble<0){ + key = null; + }*/ + inputDate = Util.getIntValue(key); + fromdate = ""; + fromtime = ""; + todate = ""; + todate = ""; + }else if(setDataCx == 6){ + tempDateTime = getDateTimeInputCal(fromdate, fromtime, inputDate, isDateTimeCal, othertype, tempCalStr); + key = tempDateTime; + }else if(setDataCx == 5){ + if("+".equalsIgnoreCase(tempCalStr)){ + tempDouble = tempDouble + inputDate; + }else{ + tempDouble = tempDouble - inputDate; + } + key = ""+tempDouble; + } + setDataCx = 0; + } + }catch(Exception e){ + e.printStackTrace(); + setDataCx = 0; + } + int index3 = datecontent.indexOf("$", index2+espStr.length()+2);// + if(index3 > -1){ + calStr = datecontent.substring(index2+espStr.length()+2, index3); + if(!"".equals(calStr.trim())){ + tempCalStr = calStr; + } + } + datecontent = datecontent.substring(index2+espStr.length()+2); + } + index0 = datecontent.indexOf("$"); + } + JSONObject result = new JSONObject(); + result.put(fieldid, key); + return result; + } + /** + * 日期[合并时间]字段与数字的计算,返回日期[合并]时间 + * isDateTimeCal:石否合并日期时间 + * othertype:0:不排除非工作日(自然日期计算),使用总部一般工作时间;1:排除非工作日。 + * tempCalStr:加法还是减法。默认为加法 + */ + public String getDateTimeInputCal(String fromdate, String fromtime, int inputData, boolean isDateTimeCal, int othertype, String tempCalStr){ + String retStr = ""; + if("".equals(fromdate)){ + return retStr; + } + try{ + if(inputData==0 && isDateTimeCal==true){ + retStr = fromdate + " " + fromtime; + return retStr; + } + if("-".equals(tempCalStr)){ + inputData = inputData * (-1); + tempCalStr = "+"; + } + if((inputData==1 || inputData==0) && isDateTimeCal==false){ + retStr = fromdate; + return retStr; + } + if(inputData >= 0){ + inputData = inputData - 1; + }else{ + inputData = inputData; + } + if("".equals(fromtime)){ + isDateTimeCal = false; + } + if(othertype == 0){ + if(isDateTimeCal == false){ + retStr = TimeUtil.dateAdd(fromdate, inputData); + }else{ + retStr = TimeUtil.timeAdd(fromdate+" "+((fromtime + ":00").substring(0, 8)), inputData*24*3600); + } + }else{ + //如果考虑排除工作日,时间暂时无法参与计算 + int addtype = 0; + if("-".equals(tempCalStr)){ + addtype = 0; + }else{ + addtype = 1; + } + if(inputData<0){ + inputData = inputData * (-1); + if(addtype == 1){ + addtype = 0; + }else{ + addtype = 1; + //inputData = inputData * (-1); + } + } + retStr = getNextWorkDate(fromdate, inputData, user, addtype);//无法获取人员信息,当前操作者未必就是正确的分部,所以用总部的 + if(isDateTimeCal == true){ + retStr = retStr + " " + fromtime; + } + } + }catch(Exception e){ + new BaseBean().writeLog(e); + } + return retStr; + } + /** + * 通过日期,分部,天数,返回指定天数后(前)的日期,排除工作日 + * addtype:1,days天数之后;0,days天数之前 + */ + public String getNextWorkDate(String fromdate, int days, User user, int addtype){ + String retStr = ""; + try{ + //writeLog("fromdate = " + fromdate); + //writeLog("days = " + days); + //writeLog("addtype = " + addtype); + HrmScheduleDiffUtil hrmScheduleDiffUtil = new HrmScheduleDiffUtil(); + hrmScheduleDiffUtil.setUser(user); + String nextDate_t = fromdate; + int day0 = 1; + if(addtype == 1){ + day0 = 1; + }else{ + day0 = -1; + } + int index = 0; + for(int cx=0; cx= (long)0){ + retStr = ""+(Util.getDoubleValue((""+TimeUtil.timeInterval(todate+" "+totime, fromdate +" "+ fromtime)))/3600/24); + }else{ + retStr = ""+(Util.getDoubleValue((""+TimeUtil.timeInterval(todate+" "+totime, fromdate +" "+ fromtime)))/3600/24); + } + }else{ + if(TimeUtil.dateInterval(todate, fromdate) >= (long)0){ + retStr = ""+(TimeUtil.dateInterval(todate, fromdate) + 1); + }else{ + retStr = ""+(TimeUtil.dateInterval(todate, fromdate)); + } + } + }else{ + HrmScheduleDiffUtil hrmScheduleDiffUtil = new HrmScheduleDiffUtil(); + hrmScheduleDiffUtil.setUser(user); + ResourceComInfo resourceComInfo = new ResourceComInfo(); + DepartmentComInfo departmentComInfo = new DepartmentComInfo(); + int departmentId = Util.getIntValue(resourceComInfo.getDepartmentID(""+user.getUID())); + int subCompanyId = Util.getIntValue(departmentComInfo.getSubcompanyid1(""+departmentId)); + //做减法,要把数据倒过来 + long firstCal = 0; + if(isDateTimeCal == true){ + firstCal = TimeUtil.timeInterval(todate+" "+totime, fromdate+" "+fromtime);//前小后大返回大于0的数 + }else{ + firstCal = TimeUtil.dateInterval(todate, fromdate); + } + //下面的那个方法,必须前面参数的日期在后面参数的日期之前,比如,2012-02-01---2012-03-01,得到的值大于0 + if(totime.length() == 8){ + totime = totime.substring(0, 5); + } + if(fromtime.length() == 8){ + fromtime = fromtime.substring(0, 5); + } + if(firstCal >= (long)0){ + String a = hrmScheduleDiffUtil.getTotalWorkingDays(todate, totime, fromdate, fromtime, subCompanyId); + if(!"".equals(a)){ + a = ""+(Util.getFloatValue(a)); + }else{ + a = ""+0; + } + retStr = a; + }else{ + String b = hrmScheduleDiffUtil.getTotalWorkingDays(fromdate, fromtime, todate, totime, subCompanyId); + if(!"".equals(totime)){ + b = ""+(Util.getFloatValue(b)); + }else{ + b = ""+(Util.getFloatValue(b) - 1); + } + retStr = "-" + b; + } + } + }else{ + } + if(!"".equals(retStr) && retStr.indexOf(".")>-1){ + //处理一分钟的特殊情况 + if(retStr.equals("6.944444444444445E-4")){ + retStr = "0.001388888888888889"; + } + retStr = retStr + "00000"; + retStr = retStr.substring(0, retStr.indexOf(".")+5); + } + }catch(Exception e){ + new BaseBean().writeLog(e); + } + return retStr; + } + private JSONArray doFieldMath(String fieldid, String attrcontent, JSONArray triggerDatas){ + JSONArray result = new JSONArray(); + Pattern pat = Pattern.compile("\\$([-]?\\d+)\\$"); + int index = attrcontent.indexOf("doFieldMath(\""); + String attrcontentTemp=null; + if (index > -1) { + attrcontentTemp = attrcontent.substring(index + 13); + index = attrcontentTemp.lastIndexOf("\")"); + if (index > -1) { + attrcontentTemp = attrcontentTemp.substring(0, index); + } + + int size = triggerDatas.size(); + for(int i = 0; i + * 处理方式: + * 1、拟稿表单增加“登记时间”(必填),“附件”(必填)、是否初婚(必填); + * 2、开发:满足 员工自助更新流程办结时,更新员工婚假余额。 + * 条件:流程上自助信息类型选择“婚姻状况” + * 在职期间登记结婚的(登记日期与入职日期判断),初婚15天,再婚3天,自动更新员工假期余额中 + * + * @author wangj + * @version 1.00版本 + * @Date 2023/9/4 + */ + +public class UpdateMarriageLeaveBalance implements Action { + @Override + public String execute(RequestInfo requestInfo) { + + Map mainnInfo = new HashMap(1000); + Property[] property = requestInfo.getMainTableInfo().getProperty(); + for (int i = 0; i < property.length; i++) { + mainnInfo.put(property[i].getName().toLowerCase(), Util.null2String(property[i].getValue())); + } + //自助信息类型 + String zzxxlx = Util.null2String(mainnInfo.get("zzxxlx")); + //婚姻状况 + String hyzk = Util.null2String(mainnInfo.get("hyzk")); + + try { + + + //已婚 + if ("1".equals(zzxxlx) && "1".equals(hyzk)) { + int days = 0; + //是否初婚 + String sfch = Util.null2String(mainnInfo.get("sfch")); + //登记日期 + String djrq = Util.null2String(mainnInfo.get("djrq")); + //申请人 + String sqr = Util.null2String(mainnInfo.get("sqr")); + //入职日期 + String rzrq = getRzrq(sqr); + + //判断结婚登记日期在入职期间的 + boolean flag = compareDateLessEquation(rzrq, djrq); + if (flag) { + if ("1".equals(sfch)) { + //再婚3天 + days = 3; + } else { + //0 或 空默认初婚 15天 + days = 15; + } + if (days > 0) { + updateLeaveBalance(sqr, days); + } + } + + } + + } catch (Exception e) { + requestInfo.getRequestManager().setMessagecontent("接口异常:"+e.getMessage()); + return Action.FAILURE_AND_CONTINUE; + } + return Action.SUCCESS; + } + + /** + * @Description: 比较日期小于等于 + * @Param: + * @return: + * @Author: wangj + */ + private boolean compareDateLessEquation(String start, String end) { + boolean flag = false; + if ("".equals(start) || "".equals(end)) { + return false; + } + Date sdate = DateUtil.parseDate(start, "yyyy-MM-dd"); + Date edate = DateUtil.parseDate(end, "yyyy-MM-dd"); + if (sdate.getTime() < edate.getTime()) { + flag = true; + } + return flag; + } + + private String getRzrq(String id) { + String date = ""; + RecordSet rs = new RecordSet(); + String sql = "select workcode,lastname,companystartdate from hrmresource where id = ?"; + rs.executeQuery(sql, id); + while (rs.next()) { + date = Util.null2String(rs.getString("companystartdate")); + } + return date; + } + + private void updateLeaveBalance(String sqr, int days) { + String sql = "select count(1) as sl from kq_balanceofleave where leaveRulesId = 32 and resourceid = ?"; + RecordSet rs = new RecordSet(); + int count = 0; + rs.executeQuery(sql,sqr); + while (rs.next()){ + count = Util.getIntValue(rs.getString("sl")); + } + + String year = DateUtil.getCurrentTime("yyyy"); + + if(count > 0){ + sql = "update kq_balanceofleave set leaveRulesId = ?, resourceId = ?, belongYear = ?, baseAmount = ?, extraAmount = ?, usedAmount = ?, baseAmount2 = ?, extraAmount2 = ?, usedAmount2 = ?, status = ?,tiaoxiuamount = ?,isDelete = ? where resourceid = ? and leaveRulesId = ?"; + rs.executeUpdate(sql,"32",sqr,year,days,"0","0","0","0","0","0","0","0",sqr,"32"); + }else{ + sql = "insert into kq_balanceofleave (leaveRulesId, resourceId, belongYear, baseAmount, extraAmount, usedAmount, baseAmount2, extraAmount2, usedAmount2, status,tiaoxiuamount) values (?,?,?,?,?,?,?,?,?,?,?)"; + rs.executeUpdate(sql,"32",sqr,year,days,"0","0","0","0","0","0","0"); + } + + } +} diff --git a/src/com/engine/hansang/job/CountOvertimeWorkersJob.java b/src/com/engine/hansang/job/CountOvertimeWorkersJob.java new file mode 100644 index 0000000..4406b42 --- /dev/null +++ b/src/com/engine/hansang/job/CountOvertimeWorkersJob.java @@ -0,0 +1,268 @@ +package com.engine.hansang.job; + +import c.u.d.c.gh; +import com.alibaba.fastjson.JSONObject; +import com.engine.kq.util.KQDurationCalculatorUtil; +import com.time.util.DateUtil; +import org.apache.tools.ant.types.selectors.modifiedselector.Cache; +import org.htmlparser.tags.TableRow; +import weaver.conn.RecordSet; +import weaver.conn.RecordSetTrans; +import weaver.formmode.setup.ModeRightInfo; +import weaver.general.BaseBean; +import weaver.general.Util; +import weaver.interfaces.schedule.BaseCronJob; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.text.DecimalFormat; +import java.util.*; + +/** + * 统计加班时间超过80%的人员信息 + * + * @author wangj + * @version 1.00版本 + * @Date 2023/9/7 + */ + +public class CountOvertimeWorkersJob extends BaseCronJob { + private static DecimalFormat df = new DecimalFormat("0.00"); + + @Override + public void execute() { + Map jbmap = new HashMap<>(1000); + String date = DateUtil.getCurrentTime("yyyy-MM"); + String start = date + "-01"; + String end = getLastDayByMonth(); + + Map flowData = getFlowOverTimeDataNew(start, end); + + RecordSet rs = new RecordSet(); + //1、查询当月的加班时长限制 + String sql = "select bm,gw,zjj,dyljjbcexs from uf_jbfjsp where dyljjbcexs is not null"; + rs.execute(sql); + while (rs.next()) { + String bm = Util.null2String(rs.getString("bm")); + String gw = Util.null2String(rs.getString("gw")); + String zjj = Util.null2String(rs.getString("zjj")); + String dyljjbcexs = Util.null2String(rs.getString("dyljjbcexs")); + String str = bm + "-" + gw + "-" + zjj; + jbmap.put(str, dyljjbcexs); + } + + String formmodeid = ""; + rs.execute("select k.id from modeinfo k inner join workflow_bill l on formid = l.id where l.tablename = 'uf_gwjbsxtz'"); + if (rs.next()) { + formmodeid = Util.null2String(rs.getString("id")); + } + + rs.execute("delete from uf_gwjbsxtz where yf = '" + date + "'"); + + //2、获取全部人员信息,查询人员的加班时长总计(当月) + sql = "select a.id,a.workcode,a.lastname,a.departmentid,a.jobtitle,a.managerid,b.field35 as zjj,b.field102 as xnfz,b.field36 as xzsx,c.field118 as cbzxmc from hrmresource a left join cus_fielddata b on a.id = b.id left join cus_fielddata c on a.id = c.id where b.scope = 'HrmCustomFieldByInfoType' and b.scopeid = '-1' and c.scope = 'HrmCustomFieldByInfoType' and c.scopeid = '3'"; + rs.execute(sql); + while (rs.next()) { + String id = Util.null2String(rs.getString("id")); + String workcode = Util.null2String(rs.getString("workcode")); + String lastname = Util.null2String(rs.getString("lastname")); + String departmentid = Util.null2String(rs.getString("departmentid")); + String jobtitle = Util.null2String(rs.getString("jobtitle")); + String managerid = Util.null2String(rs.getString("managerid")); + String zjj = Util.null2String(rs.getString("zjj")); + String xnfz = Util.null2String(rs.getString("xnfz")); + String xzsx = Util.null2String(rs.getString("xzsx")); + String cbzxmc = Util.null2String(rs.getString("cbzxmc")); + + Map deptm = getDepartmentManager(departmentid); + String bmjl = Util.null2String(deptm.get("bmjl")); + String bmzj = Util.null2String(deptm.get("bmzj")); + String bmzg = Util.null2String(deptm.get("bmzg")); + + String limithour = Util.null2String(jbmap.get(departmentid + "-" + jobtitle + "-" + zjj)); + + if ("".equals(limithour)) { + continue; + } + + //获取人员当月的加班总计(小时) + String overHours = getOverTimeByUserId(id, flowData); + + BigDecimal a = new BigDecimal(overHours); + BigDecimal b = new BigDecimal(limithour); + BigDecimal c = a.divide(b, 2, RoundingMode.HALF_UP); + String bl = c.toString(); + + //更新数据到岗位加班上限台账建模表 + insertData(workcode, id, departmentid, jobtitle, xzsx, cbzxmc, xnfz, managerid, limithour, overHours, date, formmodeid, bl, bmjl, bmzj, bmzg); + + } + } + + private Map getDepartmentManager(String deptid) { + Map map = new HashMap<>(100); + String bmjl = "0"; + String bmzj = "0"; + String bmzg = "0"; + String sql = "select bmjl,bmzj,bmzg from hrmdepartmentdefined where deptid = ?"; + RecordSet rs = new RecordSet(); + rs.executeQuery(sql, deptid); + while (rs.next()) { + bmjl = Util.null2String(rs.getString("bmjl")); + bmzj = Util.null2String(rs.getString("bmzj")); + bmzg = Util.null2String(rs.getString("bmzg")); + } + map.put("bmjl", bmjl); + map.put("bmzj", bmzj); + map.put("bmzg", bmzg); + + return map; + } + + private void insertData(String gh, String xm, String bm, String gw, String xzzx, String cbzx, String xnfz, String zjld, String dyjbsx, String dyljjbsc, String yf, String formmodeid, String bl, String bmjl, String bmzj, String bmzg) { + RecordSetTrans rst = new RecordSetTrans(); + + String modedatacreater = "1"; + String modedatacreatertype = "0"; + + String createdate = DateUtil.getCurrentTime("yyyy-MM-dd"); + String createtime = DateUtil.getCurrentTime("HH:mm:ss"); + + String modeuuid = UUID.randomUUID().toString(); + rst.setAutoCommit(false); + try { + String sql = " insert into uf_gwjbsxtz(gh,xm,bm,gw,xzzx,cbzx,xnfz,zjld,dyjbsx,dyljjbsc,yf,bl,bmjl,bmzj,bmzg,formmodeid,modedatacreater,modedatacreatertype,modeuuid,modedatacreatedate,modedatacreatetime) " + + "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + rst.executeUpdate(sql, gh, xm, bm, gw, xzzx, cbzx, xnfz, zjld, dyjbsx, dyljjbsc, yf, bl, bmjl, bmzj, bmzg, formmodeid, modedatacreater, modedatacreatertype, modeuuid, createdate, createtime); + } catch (Exception e) { + e.getMessage(); + } + + rst.commit(); + int dataId = getDataIdByUUID(modeuuid); + ModeRightInfo modeRightInfo = new ModeRightInfo(); + modeRightInfo.editModeDataShare(1, Integer.parseInt(formmodeid), dataId); + + } + + /** + * 根据uuid获取建模的数据id,常用于建模的权限重构 + * + * @param uuid modeUuid + * @return dataId + */ + public static int getDataIdByUUID(String uuid) { + RecordSet rs = new RecordSet(); + int dataid = -1; + String sql = "select id uf_gwjbsxtz where modeuuid = ?"; + if (rs.executeQuery(sql, uuid) && rs.next()) { + dataid = Util.getIntValue(rs.getString(1)); + } + return dataid; + } + + /** + * 获取实际加班数据,包括流程,打卡生成的 + * + * @return + */ + public Map getFlowOverTimeDataNew(String start, String end) { + Map datas = new HashMap<>(); + ; + RecordSet rs = new RecordSet(); + String 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 >='" + start + "' and belongdate <='" + end + "' group by resourceid,changeType,paidLeaveEnable"; + rs.execute(sql); + try { + 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"); + + value = Util.getDoubleValue(KQDurationCalculatorUtil.getDurationRound(value / (60.0) + "")); + + 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, df.format(tmpVal)); + } else { + datas.put(key, df.format(value)); + } + } + } catch (Exception e) { + new BaseBean().writeLog(e); + } + return datas; + } + + /** + * 获取人员加班时间总计 + * + * @param id + * @param flowData + * @return + */ + private String getOverTimeByUserId(String id, Map flowData) { + String fieldValue = ""; + 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)); + + if ("".equals(fieldValue)) { + fieldValue = "0.00"; + } + return fieldValue; + } + + /** + * 获取当月最后一天 + * + * @return + */ + private String getLastDayByMonth() { + // 指定日期 + Date date = new Date(); + + // 获取指定日期所在月份的最后一天 + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); + Date lastDayOfMonth = calendar.getTime(); + + String dates = DateUtil.formatDate(lastDayOfMonth, "yyyy-MM-dd"); + return dates; + } + + +} diff --git a/src/com/engine/hansang/job/UpdateHrmLastNameJob.java b/src/com/engine/hansang/job/UpdateHrmLastNameJob.java new file mode 100644 index 0000000..bdf2911 --- /dev/null +++ b/src/com/engine/hansang/job/UpdateHrmLastNameJob.java @@ -0,0 +1,78 @@ +package com.engine.hansang.job; + +import com.time.util.DateUtil; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.interfaces.schedule.BaseCronJob; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; + +/** + * 更新人员lastname字段信息 + * + * 开发需求: + * 1、定时任务执行,lastname值改为:工号-姓名 + * 2、离职日期有值时,lastname值改为:工号-姓名(R)。离职日期字段field82,工作信息中 + * + * @author wangj + * @version 1.00版本 + * @Date 2023/9/4 + */ + +public class UpdateHrmLastNameJob extends BaseCronJob { + @Override + public void execute() { + String date = DateUtil.getCurrentTime("yyyy-MM-dd"); + RecordSet rs = new RecordSet(); + String sql = "select a.id,workcode,lastname,field82 as lzrq from hrmresource a left join cus_fielddata b on a.id = b.id where b.scope = 'HrmCustomFieldByInfoType' and scopeid = 3"; + + rs.execute(sql); + while (rs.next()){ + String newLastname = ""; + String id = Util.null2String(rs.getString("id")); + String workcode = Util.null2String(rs.getString("workcode")); + String lastname = Util.null2String(rs.getString("lastname")); + String lzrq = Util.null2String(rs.getString("lzrq")); + + if(lastname.contains("-")){ + String[] lastnameArr = lastname.split("-"); + lastname = lastnameArr[lastnameArr.length-1]; + lastname = lastname.replaceAll("\\(R\\)",""); + } + newLastname = workcode+"-"+lastname; + if(!"".equals(lzrq)){ + //当前日期>=离职日期的吧 + boolean flag = compareDate(lzrq,date); + if(flag){ + newLastname = newLastname+"(R)"; + } + } + updateLastName(id,newLastname); + } + + } + + private void updateLastName(String id,String lastname){ + RecordSet rs = new RecordSet(); + String sql = "update hrmresource set lastname = ? where id = ?"; + rs.executeUpdate(sql,lastname,id); + } + + //比较时间大小 + public static boolean compareDate(String start, String end) { + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); + try { + Date date1 = simpleDateFormat.parse(start); + Date date2 = simpleDateFormat.parse(end); + if (date1.getTime() <= date2.getTime()) { + return true; + } + } catch (ParseException e) { + throw new RuntimeException(e); + } + return false; + } + +} diff --git a/src/com/engine/hrm/cmd/codeseting/RegenerateCodeCmd.java b/src/com/engine/hrm/cmd/codeseting/RegenerateCodeCmd.java new file mode 100644 index 0000000..cb650ba --- /dev/null +++ b/src/com/engine/hrm/cmd/codeseting/RegenerateCodeCmd.java @@ -0,0 +1,61 @@ +package com.engine.hrm.cmd.codeseting; + +import com.engine.common.biz.AbstractCommonCommand; +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.integration.util.StringUtils; +import weaver.general.Util; +import weaver.hrm.User; +import weaver.hrm.company.DepartmentComInfo; +import weaver.hrm.resource.ResourceComInfo; + +import java.util.HashMap; +import java.util.Map; + +public class RegenerateCodeCmd extends AbstractCommonCommand> { + + public RegenerateCodeCmd(Map params, User user) { + this.params = params; + this.user = user; + } + + @Override + public BizLogContext getLogContext() { + return null; + } + + @Override + public Map execute(CommandContext commandContext) { + Map apidata = new HashMap<>(); + try { + DepartmentComInfo departmentComInfo = new DepartmentComInfo(); + ResourceComInfo resourceComInfo = new ResourceComInfo(); + String serialtype = Util.null2String(params.get("serialtype")); + String subcompanyid = Util.null2String(params.get("subcompanyid")); + String deptid = Util.null2String(params.get("departmentid")); + String jobtitlesid = Util.null2String(params.get("jobtitlesid")); + String userid = Util.null2String(params.get("userid")); + + switch (RuleCodeType.getByValue(serialtype)) { + case DEPARTMENT: + if (StringUtils.isEmpty(subcompanyid)) subcompanyid = departmentComInfo.getSubcompanyid1(deptid); + break; + case USER: + if (StringUtils.isEmpty(subcompanyid)) subcompanyid = resourceComInfo.getSubCompanyID(userid); + if (StringUtils.isEmpty(deptid)) deptid = resourceComInfo.getDepartmentID(userid); + if (StringUtils.isEmpty(jobtitlesid)) jobtitlesid = resourceComInfo.getJobTitle(userid); + break; + } + + String code = CodeRuleManager.getCodeRuleManager().generateRuleCode(Enum.valueOf(RuleCodeType.class, serialtype), subcompanyid, deptid, jobtitlesid, null); + apidata.put("code", code); + } catch (Exception e) { + writeLog(e); + apidata.put("api_status", false); + apidata.put("api_errormsg", e.getMessage()); + } + return apidata; + } +} diff --git a/src/com/engine/hsCheck/cmd/CheckCmd.java b/src/com/engine/hsCheck/cmd/CheckCmd.java new file mode 100644 index 0000000..3ad0f42 --- /dev/null +++ b/src/com/engine/hsCheck/cmd/CheckCmd.java @@ -0,0 +1,231 @@ +package com.engine.hsCheck.cmd; + +import com.engine.common.biz.AbstractCommonCommand; +import com.engine.common.entity.BizLogContext; +import com.engine.core.interceptor.CommandContext; +import org.apache.commons.lang3.StringUtils; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.Util; + +import java.util.HashMap; +import java.util.Map; + +public class CheckCmd extends AbstractCommonCommand> { + + public CheckCmd(Map params) { + this.params = params; + } + + @Override + public BizLogContext getLogContext() { + return null; + } + + @Override + public Map execute(CommandContext commandContext) { + RecordSet rs = new RecordSet(); + BaseBean bb = new BaseBean(); + Map apimap = new HashMap(); + try { + String workflowId = Util.null2String(params.get("workflowId")); + String resourceId = Util.null2String(params.get("resourceId")); + String fromDate = Util.null2String(params.get("fromDate")); + String fromTime = Util.null2String(params.get("fromTime")); + String toDate = Util.null2String(params.get("toDate")); + String toTime = Util.null2String(params.get("toTime")); + + String st = fromDate + " " + fromTime; + String ed = toDate + " " + toTime; + int _tmpRq = 0; + String msg = ""; + + if ("105".equals(workflowId)) { + rs.execute("select wr.requestid,wr.requestname from formtable_main_20_dt1 a,formtable_main_20 b ,workflow_requestbase wr " + + "where b.requestId =wr.REQUESTID and b.id=a.mainid and a.resourceId=" + resourceId + " and wr.CURRENTNODETYPE >0 and " + + " ((CONCAT(fromDate ,' ',fromTime) < '" + st + "' and '" + st + "' < CONCAT(toDate ,' ',toTime) ) or (CONCAT(fromDate ,' ',fromTime) < '" + ed + "' and '"+ed+"' < CONCAT(toDate ,' ',toTime)) or (CONCAT(fromDate ,' ',fromTime) > '" + st + "' and '"+ed+"' > CONCAT(toDate ,' ',toTime)) )" + + " " + + " "); + bb.writeLog("select wr.requestid,wr.requestname from formtable_main_20_dt1 a,formtable_main_20 b ,workflow_requestbase wr " + + "where b.requestId =wr.REQUESTID and b.id=a.mainid and a.resourceId=" + resourceId + " and wr.CURRENTNODETYPE >0 and " + + " ((CONCAT(fromDate ,' ',fromTime) < '" + st + "' and '" + st + "' < CONCAT(toDate ,' ',toTime) ) or (CONCAT(fromDate ,' ',fromTime) < '" + ed + "' and '"+ed+"' < CONCAT(toDate ,' ',toTime)) or (CONCAT(fromDate ,' ',fromTime) > '" + st + "' and '"+ed+"' > CONCAT(toDate ,' ',toTime)))" + + " " + + " "); + rs.next(); + String reqid = rs.getString("requestid"); + _tmpRq = Util.getIntValue(reqid); + msg = Util.null2String(rs.getString("requestname")); + if(StringUtils.isNotBlank(reqid)){ + boolean checkBack = checkLeaveBack(reqid,st,ed); + if(!checkBack){ + _tmpRq = 0; + } + } + }else if("50".equals(workflowId)){ + rs.execute("select wr.requestid,wr.requestname from formtable_main_74 b ,workflow_requestbase wr " + + "where b.requestId =wr.REQUESTID and b.resourceId=" + resourceId + " and wr.CURRENTNODETYPE >0 and " + + " ((CONCAT(fromDate ,' ',fromTime) < '" + st + "' and '" + st + "' < CONCAT(toDate ,' ',toTime) ) or (CONCAT(fromDate ,' ',fromTime) < '" + ed + "' and '"+ed+"' < CONCAT(toDate ,' ',toTime)) or (CONCAT(fromDate ,' ',fromTime) > '" + st + "' and '"+ed+"' > CONCAT(toDate ,' ',toTime)) )" + + " " + + " "); + bb.writeLog("select wr.requestid,wr.requestname from formtable_main_74 b ,workflow_requestbase wr " + + "where b.requestId =wr.REQUESTID and b.resourceId=" + resourceId + " and wr.CURRENTNODETYPE >0 and " + + " ((CONCAT(fromDate ,' ',fromTime) < '" + st + "' and '" + st + "' < CONCAT(toDate ,' ',toTime) ) or (CONCAT(fromDate ,' ',fromTime) < '" + ed + "' and '"+ed+"' < CONCAT(toDate ,' ',toTime)) or (CONCAT(fromDate ,' ',fromTime) > '" + st + "' and '"+ed+"' > CONCAT(toDate ,' ',toTime)) )" + + " " + + " "); + rs.next(); + String reqid = rs.getString("requestid"); + _tmpRq = Util.getIntValue(reqid); + msg = Util.null2String(rs.getString("requestname")); + if(StringUtils.isNotBlank(reqid)){ + boolean checkBack = checkLeaveBack(reqid,st,ed); + if(!checkBack){ + _tmpRq = 0; + } + } + }else if("75".equals(workflowId)) { + rs.execute("select wr.requestid,wr.requestname from formtable_main_76_dt1 a,formtable_main_76 b ,workflow_requestbase wr " + + "where b.requestId =wr.REQUESTID and b.id=a.mainid and a.jbry=" + resourceId + " and wr.CURRENTNODETYPE >0 and " + + " ((CONCAT(ksrq ,' ',kssj) < '" + st + "' and '" + st + "' < CONCAT(jsrq ,' ',jssj) ) or (CONCAT(ksrq ,' ',kssj) < '" + ed + "' and '"+ed+"' < CONCAT(jsrq ,' ',jssj)) or (CONCAT(ksrq ,' ',kssj) > '" + st + "' and '"+ed+"' > CONCAT(jsrq ,' ',jssj)))" + + " " + + " "); + bb.writeLog("select wr.requestid,wr.requestname from formtable_main_76_dt1 a,formtable_main_76 b ,workflow_requestbase wr " + + "where b.requestId =wr.REQUESTID and b.id=a.mainid and a.jbry=" + resourceId + " and wr.CURRENTNODETYPE >0 and " + + " ((CONCAT(ksrq ,' ',kssj) < '" + st + "' and '" + st + "' < CONCAT(jsrq ,' ',jssj) ) or (CONCAT(ksrq ,' ',kssj) < '" + ed + "' and '"+ed+"' < CONCAT(jsrq ,' ',jssj)) or (CONCAT(ksrq ,' ',kssj) > '" + st + "' and '"+ed+"' > CONCAT(jsrq ,' ',jssj)))" + + " " + + " "); + rs.next(); + _tmpRq = Util.getIntValue(rs.getString("requestid")); + msg = Util.null2String(rs.getString("requestname")); + }else if("76".equals(workflowId)||"88".equals(workflowId)){ + rs.execute("select wr.requestid,wr.requestname from formtable_main_75 b ,workflow_requestbase wr " + + "where b.requestId =wr.REQUESTID and b.resourceId=" + resourceId + " and wr.CURRENTNODETYPE >0 and " + + " ((CONCAT(fromDate ,' ',fromTime) < '" + st + "' and '" + st + "' < CONCAT(toDate ,' ',toTime) ) or (CONCAT(fromDate ,' ',fromTime) < '" + ed + "' and '"+ed+"' < CONCAT(toDate ,' ',toTime)) or (CONCAT(fromDate ,' ',fromTime) > '" + st + "' and '"+ed+"' > CONCAT(toDate ,' ',toTime)))" + + " " + + " "); + bb.writeLog("select wr.requestid,wr.requestname from formtable_main_75 b ,workflow_requestbase wr " + + "where b.requestId =wr.REQUESTID and b.resourceId=" + resourceId + " and wr.CURRENTNODETYPE >0 and " + + " ((CONCAT(fromDate ,' ',fromTime) < '" + st + "' and '" + st + "' < CONCAT(toDate ,' ',toTime) ) or (CONCAT(fromDate ,' ',fromTime) < '" + ed + "' and '"+ed+"' < CONCAT(toDate ,' ',toTime)) or (CONCAT(fromDate ,' ',fromTime) > '" + st + "' and '"+ed+"' > CONCAT(toDate ,' ',toTime)))" + + " " + + " "); + rs.next(); + _tmpRq = Util.getIntValue(rs.getString("requestid")); + msg = Util.null2String(rs.getString("requestname")); + }else if("77".equals(workflowId)){ + rs.execute("select wr.requestid,wr.requestname from formtable_main_77 b ,workflow_requestbase wr " + + "where b.requestId =wr.REQUESTID and b.resourceId=" + resourceId + " and wr.CURRENTNODETYPE >0 and " + + " ((CONCAT(fromDate ,' ',fromTime) < '" + st + "' and '" + st + "' < CONCAT(toDate ,' ',toTime) ) or (CONCAT(fromDate ,' ',fromTime) < '" + ed + "' and '"+ed+"' < CONCAT(toDate ,' ',toTime)) or (CONCAT(fromDate ,' ',fromTime) > '" + st + "' and '"+ed+"' > CONCAT(toDate ,' ',toTime)))" + + " " + + " "); + bb.writeLog("select wr.requestid,wr.requestname from formtable_main_77 b ,workflow_requestbase wr " + + "where b.requestId =wr.REQUESTID and b.resourceId=" + resourceId + " and wr.CURRENTNODETYPE >0 and " + + " ((CONCAT(fromDate ,' ',fromTime) < '" + st + "' and '" + st + "' < CONCAT(toDate ,' ',toTime) ) or (CONCAT(fromDate ,' ',fromTime) < '" + ed + "' and '"+ed+"' < CONCAT(toDate ,' ',toTime)) or (CONCAT(fromDate ,' ',fromTime) > '" + st + "' and '"+ed+"' > CONCAT(toDate ,' ',toTime)))" + + " " + + " "); + rs.next(); + _tmpRq = Util.getIntValue(rs.getString("requestid")); + msg = Util.null2String(rs.getString("requestname")); + }else if("51".equals(workflowId)){ + rs.execute("select wr.requestid,wr.requestname from formtable_main_77 b ,workflow_requestbase wr " + + "where b.requestId =wr.REQUESTID and b.resourceId=" + resourceId + " and wr.CURRENTNODETYPE >0 and " + + " ((CONCAT(fromDate ,' ',fromTime) < '" + st + "' and '" + st + "' < CONCAT(toDate ,' ',toTime) ) or (CONCAT(fromDate ,' ',fromTime) < '" + ed + "' and '"+ed+"' < CONCAT(toDate ,' ',toTime)) or (CONCAT(fromDate ,' ',fromTime) > '" + st + "' and '"+ed+"' > CONCAT(toDate ,' ',toTime)))" + + " " + + " "); + bb.writeLog("select wr.requestid,wr.requestname from formtable_main_77 b ,workflow_requestbase wr " + + "where b.requestId =wr.REQUESTID and b.resourceId=" + resourceId + " and wr.CURRENTNODETYPE >0 and " + + " ((CONCAT(fromDate ,' ',fromTime) < '" + st + "' and '" + st + "' < CONCAT(toDate ,' ',toTime) ) or (CONCAT(fromDate ,' ',fromTime) < '" + ed + "' and '"+ed+"' < CONCAT(toDate ,' ',toTime)) or (CONCAT(fromDate ,' ',fromTime) > '" + st + "' and '"+ed+"' > CONCAT(toDate ,' ',toTime)))" + + " " + + " "); + rs.next(); + _tmpRq = Util.getIntValue(rs.getString("requestid")); + msg = Util.null2String(rs.getString("requestname")); + }else if("78".equals(workflowId)){ + rs.execute("select wr.requestid,wr.requestname from formtable_main_78 b ,workflow_requestbase wr " + + "where b.requestId =wr.REQUESTID and b.resourceId=" + resourceId + " and wr.CURRENTNODETYPE >0 and " + + " ((CONCAT(fromDate ,' ',fromTime) < '" + st + "' and '" + st + "' < CONCAT(toDate ,' ',toTime) ) or (CONCAT(fromDate ,' ',fromTime) < '" + ed + "' and '"+ed+"' < CONCAT(toDate ,' ',toTime)) or (CONCAT(fromDate ,' ',fromTime) > '" + st + "' and '"+ed+"' > CONCAT(toDate ,' ',toTime)))" + + " " + + " "); + bb.writeLog("select wr.requestid,wr.requestname from formtable_main_78 b ,workflow_requestbase wr " + + "where b.requestId =wr.REQUESTID and b.resourceId=" + resourceId + " and wr.CURRENTNODETYPE >0 and " + + " ((CONCAT(fromDate ,' ',fromTime) < '" + st + "' and '" + st + "' < CONCAT(toDate ,' ',toTime) ) or (CONCAT(fromDate ,' ',fromTime) < '" + ed + "' and '"+ed+"' < CONCAT(toDate ,' ',toTime)) or (CONCAT(fromDate ,' ',fromTime) > '" + st + "' and '"+ed+"' > CONCAT(toDate ,' ',toTime)))" + + " " + + " "); + rs.next(); + _tmpRq = Util.getIntValue(rs.getString("requestid")); + msg = Util.null2String(rs.getString("requestname")); + }else if("55".equals(workflowId)){ + rs.execute("select wr.requestid,wr.requestname from formtable_main_78 b ,workflow_requestbase wr " + + "where b.requestId =wr.REQUESTID and b.resourceId=" + resourceId + " and wr.CURRENTNODETYPE >0 and " + + " ((CONCAT(fromDate ,' ',fromTime) < '" + st + "' and '" + st + "' < CONCAT(toDate ,' ',toTime) ) or (CONCAT(fromDate ,' ',fromTime) < '" + ed + "' and '"+ed+"' < CONCAT(toDate ,' ',toTime)) or (CONCAT(fromDate ,' ',fromTime) > '" + st + "' and '"+ed+"' > CONCAT(toDate ,' ',toTime)))" + + " " + + " "); + bb.writeLog("select wr.requestid,wr.requestname from formtable_main_78 b ,workflow_requestbase wr " + + "where b.requestId =wr.REQUESTID and b.resourceId=" + resourceId + " and wr.CURRENTNODETYPE >0 and " + + " ((CONCAT(fromDate ,' ',fromTime) < '" + st + "' and '" + st + "' < CONCAT(toDate ,' ',toTime) ) or (CONCAT(fromDate ,' ',fromTime) < '" + ed + "' and '"+ed+"' < CONCAT(toDate ,' ',toTime)) or (CONCAT(fromDate ,' ',fromTime) > '" + st + "' and '"+ed+"' > CONCAT(toDate ,' ',toTime)))" + + " " + + " "); + rs.next(); + _tmpRq = Util.getIntValue(rs.getString("requestid")); + msg = Util.null2String(rs.getString("requestname")); + }else if("80".equals(workflowId)){ + rs.execute("select wr.requestid,wr.requestname from formtable_main_80 b ,workflow_requestbase wr " + + "where b.requestId =wr.REQUESTID and b.resourceId=" + resourceId + " and wr.CURRENTNODETYPE >0 and " + + " ((CONCAT(fromDate ,' ',fromTime) < '" + st + "' and '" + st + "' < CONCAT(toDate ,' ',toTime) ) or (CONCAT(fromDate ,' ',fromTime) < '" + ed + "' and '"+ed+"' < CONCAT(toDate ,' ',toTime)) or (CONCAT(fromDate ,' ',fromTime) > '" + st + "' and '"+ed+"' > CONCAT(toDate ,' ',toTime)))" + + " " + + " "); + bb.writeLog("select wr.requestid,wr.requestname from formtable_main_80 b ,workflow_requestbase wr " + + "where b.requestId =wr.REQUESTID and b.resourceId=" + resourceId + " and wr.CURRENTNODETYPE >0 and " + + " ((CONCAT(fromDate ,' ',fromTime) < '" + st + "' and '" + st + "' < CONCAT(toDate ,' ',toTime) ) or (CONCAT(fromDate ,' ',fromTime) < '" + ed + "' and '"+ed+"' < CONCAT(toDate ,' ',toTime)) or (CONCAT(fromDate ,' ',fromTime) > '" + st + "' and '"+ed+"' > CONCAT(toDate ,' ',toTime)))" + + " " + + " "); + rs.next(); + _tmpRq = Util.getIntValue(rs.getString("requestid")); + msg = Util.null2String(rs.getString("requestname")); + }else if("52".equals(workflowId)){ + rs.execute("select wr.requestid,wr.requestname from formtable_main_80 b ,workflow_requestbase wr " + + "where b.requestId =wr.REQUESTID and b.resourceId=" + resourceId + " and wr.CURRENTNODETYPE >0 and " + + " ((CONCAT(fromDate ,' ',fromTime) < '" + st + "' and '" + st + "' < CONCAT(toDate ,' ',toTime) ) or (CONCAT(fromDate ,' ',fromTime) < '" + ed + "' and '"+ed+"' < CONCAT(toDate ,' ',toTime)) or (CONCAT(fromDate ,' ',fromTime) > '" + st + "' and '"+ed+"' > CONCAT(toDate ,' ',toTime)))" + + " " + + " "); + bb.writeLog("select wr.requestid,wr.requestname from formtable_main_80 b ,workflow_requestbase wr " + + "where b.requestId =wr.REQUESTID and b.resourceId=" + resourceId + " and wr.CURRENTNODETYPE >0 and " + + " ((CONCAT(fromDate ,' ',fromTime) < '" + st + "' and '" + st + "' < CONCAT(toDate ,' ',toTime) ) or (CONCAT(fromDate ,' ',fromTime) < '" + ed + "' and '"+ed+"' < CONCAT(toDate ,' ',toTime)) or (CONCAT(fromDate ,' ',fromTime) > '" + st + "' and '"+ed+"' > CONCAT(toDate ,' ',toTime)))" + + " " + + " "); + rs.next(); + _tmpRq = Util.getIntValue(rs.getString("requestid")); + msg = Util.null2String(rs.getString("requestname")); + } + + + if (_tmpRq > 0) { + apimap.put("status",1); + apimap.put("hsmsg","时间与流程"+msg+"存在重复,请重新提交!"); + }else{ + apimap.put("status",0); + apimap.put("hsmsg",""); + } + + }catch (Exception e){ + apimap.put("status",1); + apimap.put("hsmsg",e.toString()); + } + return apimap; + } + + /** + * 判断 + * @param requestId + * @return + */ + public static Boolean checkLeaveBack(String requestId,String startDate,String endDate){ + RecordSet rs = new RecordSet(); + Boolean back = false; + String sql = "select workflowid from kq_flow_split_leave where leavebackrequestid is null and belongdate >= '"+startDate+"' and belongdate <= '"+endDate+"' and requestid = "+requestId; + rs.executeQuery(sql); + if(rs.getCounts()>0){ + //该请假流程存在未退假的日期 + back = true; + } + return back; + } +} diff --git a/src/com/engine/hsCheck/service/CheckService.java b/src/com/engine/hsCheck/service/CheckService.java new file mode 100644 index 0000000..1003cbd --- /dev/null +++ b/src/com/engine/hsCheck/service/CheckService.java @@ -0,0 +1,19 @@ +package com.engine.hsCheck.service; + + +import java.util.Map; + +/** + * TODO + * + * @Description + * @Author matrix + * @Date 2023/9/12 23:57 + **/ +public interface CheckService { + + Map check(Map paramMap); + + Map kqFormatByMode(Map paramMap); + +} diff --git a/src/com/engine/hsCheck/service/impl/CheckServiceImpl.java b/src/com/engine/hsCheck/service/impl/CheckServiceImpl.java new file mode 100644 index 0000000..4df3303 --- /dev/null +++ b/src/com/engine/hsCheck/service/impl/CheckServiceImpl.java @@ -0,0 +1,578 @@ +package com.engine.hsCheck.service.impl; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.engine.common.util.ServiceUtil; +import com.engine.core.impl.Service; +import com.engine.hsCheck.cmd.CheckCmd; +import com.engine.hsCheck.service.CheckService; +import com.engine.kq.biz.KQReportBiz; +import com.engine.kq.service.KQReportService; +import com.engine.kq.service.impl.KQReportServiceImpl; +import org.apache.commons.lang3.StringUtils; +import weaver.common.DateUtil; +import weaver.conn.BatchRecordSet; +import weaver.conn.RecordSet; +import weaver.formmode.setup.ModeRightInfo; +import weaver.general.BaseBean; +import weaver.general.TimeUtil; +import weaver.general.Util; +import weaver.hrm.User; +import weaver.systeminfo.SystemEnv; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.*; + +/** + * TODO + * + * @Description + * @Author matrix + * @Date 2023/9/12 23:57 + **/ +public class CheckServiceImpl extends Service implements CheckService { + + + static String dateFormat = "yyyy-MM-dd"; + static SimpleDateFormat format = new SimpleDateFormat(dateFormat); + + @Override + public Map check(Map params) { + return commandExecutor.execute(new CheckCmd(params)); + } + + private KQReportService getService(User user) { + return (KQReportService) ServiceUtil.getService(KQReportServiceImpl.class, user); + } + + /** + * 建模台账重新格式化考勤 + * @param params + * @return + */ + @Override + public Map kqFormatByMode(Map params) { + Map resutl = new HashMap(); + BaseBean bb = new BaseBean(); + bb.writeLog("kqFormatByMode ==>"); + try{ + String userId = Util.null2String(params.get("userId")); + String deptId = Util.null2String(params.get("deptId")); + String fromDateOri = Util.null2String(params.get("fromDate")); + String toDateOri = Util.null2String(params.get("toDate")); + Map paramsMain = new HashMap(); + Map paramsNew = new HashMap(); + paramsNew.put("pageIndex",0); + paramsNew.put("typeselect","3"); + paramsNew.put("viewScope","2"); + if(StringUtils.isNotBlank(userId)){ + paramsNew.put("resourceId",userId); + } + if(StringUtils.isNotBlank(deptId)){ + paramsNew.put("departmentId",deptId); + } + if(StringUtils.isNotBlank(fromDateOri)){ + paramsNew.put("fromDate",fromDateOri); + } + if(StringUtils.isNotBlank(toDateOri)){ + paramsNew.put("toDate",toDateOri); + } + paramsNew.put("status","9"); + paramsNew.put("isNoAccount","1"); + paramsNew.put("attendanceSerial",""); + User userLcc = new User(1); + paramsMain.put("data",JSONObject.toJSONString(paramsNew)); + Map apidatasF = new HashMap(); + apidatasF = getService(userLcc).formatReport(paramsMain, userLcc); + bb.writeLog("apidatasF:"+JSONObject.toJSONString(apidatasF)); + + //格式化结束重新获取考勤汇总表数据 + String fromDate = fromDateOri.substring(0,7)+"-01"; + String toDateRl = fromDateOri.substring(0,7)+"-31"; + String toDateSet = fromDateOri.substring(0,7); + String toDate = getLastDayOfMonth(toDateSet); + + Map apidatas = new HashMap(); + Map paramsN = new HashMap(); + paramsN.put("reportType","month"); + Map paramsData = new HashMap(); + paramsData.put("pageIndex",0); + paramsData.put("typeselect","6"); + paramsData.put("viewScope","0"); + paramsData.put("status","9"); + paramsData.put("isNoAccount","1"); + paramsData.put("attendanceSerial",""); + if(StringUtils.isNotBlank(userId)){ + paramsData.put("resourceId",userId); + } + if(StringUtils.isNotBlank(deptId)){ + paramsData.put("departmentId",deptId); + } + paramsData.put("fromDate",fromDate); + paramsData.put("toDate",toDate); + paramsN.put("data",JSONObject.toJSONString(paramsData)); + apidatas = getService(userLcc).getKQReport(paramsN, userLcc); + // bb.writeLog("apidatas:"+JSONObject.toJSONString(apidatas)); + JSONArray jsonArray = JSON.parseArray(Util.null2String(JSONObject.toJSONString(apidatas.get("datas")))); + bb.writeLog("jsonArray:"+JSONObject.toJSONString(jsonArray)); + for (Iterator iterator = jsonArray.iterator(); iterator.hasNext(); ) { + List> lsParams = new ArrayList<>(); + List> lsDelParams = new ArrayList<>(); + JSONObject next = (JSONObject) iterator.next(); + //人员id + String resourceId = next.getString("resourceId"); + //编号 + String workcode = next.getString("workcode"); + //岗位 + String jobtitleId = next.getString("jobtitleId"); + //部门编码 + String deptcode = next.getString("deptcode"); + //上级部门 + String supdept = next.getString("supdept"); + //部门 + String departmentId = next.getString("departmentId"); + //新增属性 + String ofr08name = next.getString("ofr08name"); + //直\间接 + String ofr07name = next.getString("ofr07name"); + //应出勤天数 + String workdays = next.getString("workdays"); + //应工作时长 + String workmins = next.getString("workmins"); + //实际出勤天数 + String attendancedays = next.getString("attendancedays"); + //实际工作时长 + String attendanceMins = next.getString("attendanceMins"); + //迟到次数 + String beLate = next.getString("beLate"); + //迟到时长 + String beLateMins = next.getString("beLateMins"); + //严重迟到 + String graveBeLate = next.getString("graveBeLate"); + //严重迟到时长 + String graveBeLateMins = next.getString("graveBeLateMins"); + //早退 + String leaveEearly = next.getString("leaveEearly"); + //早退时长 + String leaveEarlyMins = next.getString("leaveEarlyMins"); + //严重早退 + String graveLeaveEarly = next.getString("graveLeaveEarly"); + //严重早退时长 + String graveLeaveEarlyMins = next.getString("graveLeaveEarlyMins"); + //缺勤 + String absenteeism = next.getString("absenteeism"); + //缺勤时长 + String absenteeismMins = next.getString("absenteeismMins"); + //漏签 + String forgotCheck = next.getString("forgotCheck"); + //午餐次数 + String wucancishu = next.getString("wucancishu"); + //晚餐次数 + String jiabancishu = next.getString("jiabancishu"); + //午餐次数含夜班 + String jiabancishuYb = next.getString("jiabancishuYb"); + //晚餐次数含夜班 + String wucancishuYb = next.getString("wucancishuYb"); + //夜班次数 + String ybcs = next.getString("ybcs"); + //法定年假 + String fdnj = next.getString("leaveType_-6"); + //带薪病假 + String dxbj = next.getString("leaveType_4"); + //调休平时加班 + String txpsjb = next.getString("leaveType_5"); + //产假 + String cj = next.getString("leaveType_8"); + //陪产假 + String pcj = next.getString("leaveType_9"); + //福利年假 + String flnj = next.getString("leaveType_13"); + //小产假 + String xcj = next.getString("leaveType_14"); + //产检假 + String cjj = next.getString("leaveType_15"); + //调休周末加班 + String txzmjb = next.getString("leaveType_16"); + //产假刨妇产顺延 + String cjpfc = next.getString("leaveType_17"); + //产假多胞胎顺延 + String cjdbtsy = next.getString("leaveType_18"); + //三八节福利假 + String sbjflj = next.getString("leaveType_19"); + //特殊公出 + String tsgc = next.getString("leaveType_20"); + //放工假 + String fgj = next.getString("leaveType_21"); + //工伤假 + String gsj = next.getString("leaveType_22"); + //事假 + String sj = next.getString("leaveType_26"); + //病假 + String bj = next.getString("leaveType_27"); + //婚假 + String hj = next.getString("leaveType_32"); + //哺乳假 + String brj = next.getString("leaveType_34"); + //丧假 + String sangj = next.getString("leaveType_35"); + //育儿假 + String yrj = next.getString("leaveType_36"); + //独生子女护理假 + String dsznhlj = next.getString("leaveType_37"); + //工作日加班不关联调休 + String gzrjbno = next.getString("workingDayOvertime_nonleave"); + //工作日加班关联调休 + String gzrjb = next.getString("workingDayOvertime_4leave"); + //休息日加班不关联调休 + String xxrjbno = next.getString("restDayOvertime_nonleave"); + //休息日加班关联调休 + String xxrjb = next.getString("restDayOvertime_4leave"); + //节假日加班不关联调休 + String jjrjbno = next.getString("holidayOvertime_nonleave"); + //节假日加班关联调休 + String jjrjb = next.getString("holidayOvertime_4leave"); + //加班汇总 + String jbhz = next.getString("overtimeTotal"); + //出差 + String cc = next.getString("businessLeave"); + //公出 + String gc = next.getString("officialBusiness"); + + + bb.writeLog("userId:"+resourceId+"workdays:"+workdays); + KQReportBiz kqReportBiz = new KQReportBiz(); + Map detialDatas = kqReportBiz.getDetialDatasOnlyTime(resourceId, fromDate, toDateRl, userLcc); + Map detialOvtimeDatas = kqReportBiz.getDetialOvtimeData(resourceId, fromDate, toDateRl); + List data = new ArrayList<>(); + String today = DateUtil.getCurrentDate(); + bb.writeLog("detialDatas:"+JSONObject.toJSONString(detialDatas)+"detialOvtimeDatas:"+JSONObject.toJSONString(detialOvtimeDatas)); + List all = new ArrayList<>(); + all.add(fromDate); + List back = days(fromDate,toDateRl); + all.addAll(back); + all.add(toDateRl); + for(String date:all){ + if (DateUtil.compDate(today, date) > 0) { + data.add(""); + } else { + if (detialDatas.get(resourceId + "|" + date) != null) { + double atttime = Util.getDoubleValue((String) detialDatas.get(resourceId + "|" + date),0); + bb.writeLog("date:"+date+"atttime:"+atttime); + if(detialOvtimeDatas.get(resourceId + "|" + date) !=null ){ + atttime += (double) detialOvtimeDatas.get(resourceId + "|" + date); + bb.writeLog("atttimeNew:"+atttime); + } + data.add(atttime); + } else { + data.add(SystemEnv.getHtmlLabelName(26593, userLcc.getLanguage())); + } + } + } + bb.writeLog("dataText:"+JSONObject.toJSONString(data)); + List par = new ArrayList<>(); + List parDel = new ArrayList<>(); + par.add(resourceId); + par.add(workcode); + par.add(jobtitleId); + par.add(deptcode); + par.add(supdept); + par.add(departmentId); + par.add(ofr08name); + par.add(ofr07name); + par.add(workdays); + par.add(workmins); + par.add(attendancedays); + par.add(attendanceMins); + par.add(beLate); + par.add(beLateMins); + par.add(graveBeLate); + par.add(graveBeLateMins); + par.add(leaveEearly); + par.add(leaveEarlyMins); + par.add(graveLeaveEarly); + par.add(graveLeaveEarlyMins); + par.add(absenteeism); + par.add(absenteeismMins); + par.add(forgotCheck); + par.add(wucancishu); + par.add(jiabancishu); + par.add(jiabancishuYb); + par.add(wucancishuYb); + par.add(ybcs); + par.add(fdnj); + par.add(dxbj); + par.add(txpsjb); + par.add(cj); + par.add(pcj); + par.add(flnj); + par.add(xcj); + par.add(cjj); + par.add(txzmjb); + par.add(cjpfc); + par.add(cjdbtsy); + par.add(sbjflj); + par.add(tsgc); + par.add(fgj); + par.add(gsj); + par.add(sj); + par.add(bj); + par.add(hj); + par.add(brj); + par.add(sangj); + par.add(yrj); + par.add(dsznhlj); + par.add(gzrjbno); + par.add(xxrjbno); + par.add(jjrjbno); + par.add(gzrjb); + par.add(xxrjb); + par.add(jjrjb); + par.add(jbhz); + par.add(cc); + par.add(gc); + //年月 + String ny = fromDate.substring(0,7); + par.add(ny); + //入职日期 + String rzrq = findRzrq(resourceId); + //转正日期 + String zzrq = getField18(resourceId); + //离职日期 + String lzrq = getField82(resourceId); + par.add(rzrq); + par.add(zzrq); + par.add(lzrq); + //人员状态 + String ryzt = getStatus(resourceId); + par.add(ryzt); + //考勤月 + String kqy = ny+"-01"; + par.add(kqy); + //日历 + for (int i = 0; i < all.size(); i++) { + par.add(data.get(i)); + } + + + parDel.add(resourceId); + parDel.add(ny); + lsDelParams.add(parDel); + + BatchRecordSet bRs = new BatchRecordSet(); + bb.writeLog("开始同步数据"); + bb.writeLog("lsDelParams:"+JSON.toJSONString(lsDelParams)); + + String sql = ""; + //删除本次同步数据 + sql = " delete from uf_kqhzbx where xm = ? and ny = ?"; + bRs.executeBatchSql(sql, lsDelParams); + + int modeid = getFormModeIdByCubeName("uf_kqhzbx"); + SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd"); + SimpleDateFormat sdfTime = new SimpleDateFormat("HH:mm:ss"); + String modedatacreatedate = sdfDate.format(new java.util.Date()); + String modedatacreatetime = sdfTime.format(new Date()); + + par.add(modeid); + par.add(resourceId); + par.add("0"); + par.add(modedatacreatedate); + par.add(modedatacreatetime); + lsParams.add(par); + + sql = " insert into uf_kqhzbx (xm, bh, gw, bmbm, sjbm, bm, xzzx, zjj, ycqtst, ygzscxs, " + + "sjcqtst,sjgzscxs,cdc,cdscxs,yzcdc,yzcdscxs,ztc,ztscxs,yzztc,yzztscxs," + + "qqc,qqscxs,lqc,wuccsc,wanccsc,wuccshybc,wanccshybc,ybcsc,fdnjxs,flnjxs," + + "sjxs,dxbjt,bjt,hjt,sjt,xcjt,cjjt,pcjt,dxpsjbxs,dxzmjbxs," + + "brjxs,cjt,cjpfcsyt,cjdbtsyt,sbjfljt,tsgct,fgjxs,gsjt,yejt,dsznhljt," + + "bgldxgzrjbxs,bgldxxxrjbxs,bgldxjjrjbxs,gldxgzrjbxs,gldxxxrjbxs,gldxjjrjbxs,jbzjxs,cct,gcxs," + + "ny,rzrq,zzrq,lzrq,ryzt,kqy,h1,h2,h3,h4,h5,h6," + + "h7,h8,h9,h10,h11,h12,h13,h14,h15,h16," + + "h17,h18,h19,h20,h21,h22,h23,h24,h25,h26," + + "h27,h28,h29,h30,h31,FORMMODEID,MODEDATACREATER,MODEDATACREATERTYPE,MODEDATACREATEDATE,MODEDATACREATETIME) " + + " values(?,?,?,?,?,?,?,?,?,?," + + "?,?,?,?,?,?,?,?,?,?," + + "?,?,?,?,?,?,?,?,?,?," + + "?,?,?,?,?,?,?,?,?,?," + + "?,?,?,?,?,?,?,?,?,?," + + "?,?,?,?,?,?,?,?,?," + + "?,?,?,?,?,?,?,?,?,?,?,?," + + "?,?,?,?,?,?,?,?,?,?," + + "?,?,?,?,?,?,?,?,?,?," + + "?,?,?,?,?,?,?,?,?,?)"; + bRs.executeBatchSql(sql,lsParams); + + String idNew = ""; + RecordSet findNew = new RecordSet(); + String sqlFindnew ="select Id from uf_kqhzbx where xm = "+resourceId+" and ny = '"+ny+"' order by" + + " modedatacreatedate desc,modedatacreatetime desc"; + findNew.execute(sqlFindnew); + bb.writeLog("findSqlNew:"+sqlFindnew); + if (findNew.next()){ + idNew = weaver.general.Util.null2String(findNew.getString("id")); + } + bb.writeLog("idNew:"+idNew); + // 权限重构 + int dataId = Integer.valueOf(idNew); + ModeRightInfo modeRightInfo = new ModeRightInfo(); + modeRightInfo.editModeDataShare(Integer.valueOf(resourceId), modeid, dataId); + } + + resutl.put("code","200"); + resutl.put("msg","格式化成功"); + }catch (Exception e) { + bb.writeLog("kqFormatByMode Exception: "+e); + resutl.put("code","500"); + resutl.put("msg","接口异常:"+e.getMessage()); + return resutl; + } + return resutl; + } + + + /** + * 获取人员状态 + * @param userid + * @return + */ + private static String getStatus(String userid){ + RecordSet rs = new RecordSet(); + String sql = "select status from hrmresource where id = "+userid; + rs.executeQuery(sql); + String status = ""; + if (rs.next()){ + status = Util.null2String(rs.getString("status")); + } + return status; + } + + /** + * 根据建模表名获取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"); + } + + /** + * 找到人员入职日期 + * + * @return + */ + public static String findRzrq(String jbr) { + RecordSet rs = new RecordSet(); + String sql = "select id,companystartdate from hrmresource where id ="+jbr; + rs.executeQuery(sql); + String companystartdate = ""; + if (rs.next()) { + companystartdate = Util.null2String(rs.getString("companystartdate")); + } + return companystartdate; + } + + /** + * 获取转正日期 + * @param userid + * @return + */ + private static String getField18(String userid){ + RecordSet rs = new RecordSet(); + String sql = "select field18 from cus_fielddata where id = "+userid+" and scope = 'HrmCustomFieldByInfoType' and scopeid = 3"; + rs.executeQuery(sql); + String field18 = ""; + if (rs.next()){ + field18 = Util.null2String(rs.getString("field18")); + } + return field18; + } + + /** + * 获取离职日期 + * @param userid + * @return + */ + private static String getField82(String userid){ + RecordSet rs = new RecordSet(); + String sql = "select field82 from cus_fielddata where id = "+userid+" and scope = 'HrmCustomFieldByInfoType' and scopeid = 3"; + rs.executeQuery(sql); + String field82 = ""; + if (rs.next()){ + field82 = Util.null2String(rs.getString("field82")); + } + return field82; + } + + /** + * 获取两个日期之间所有的日期 + * @param date1 + * @param date2 + * @return + */ + public static ArrayList days(String date1, String date2) { + ArrayList L = new ArrayList(); + if (date1.equals(date2)) { + System.out.println("两个日期相等!"); + return L; + } + + String tmp; + if (date1.compareTo(date2) > 0) { // 确保 date1的日期不晚于date2 + tmp = date1; + date1 = date2; + date2 = tmp; + } + + tmp = format.format(str2Date(date1).getTime() + 3600 * 24 * 1000); + + int num = 0; + while (tmp.compareTo(date2) < 0) { + L.add(tmp); + num++; + tmp = format.format(str2Date(tmp).getTime() + 3600 * 24 * 1000); + } + + if (num == 0) + System.out.println("两个日期相邻!"); + return L; + } + + private static Date str2Date(String str) { + if (str == null) + return null; + + try { + return format.parse(str); + } catch (ParseException e) { + e.printStackTrace(); + } + return null; + } + + /** + * 获取指定月份最后一天 + * @param yearMonth + * @return + */ + public static String getLastDayOfMonth(String yearMonth){ + int year = Integer.parseInt(yearMonth.split("-")[0]);//年 + int month = Integer.parseInt(yearMonth.split("-")[1]); //月 + Calendar cal = Calendar.getInstance(); + cal.set(Calendar.YEAR, year); + cal.set(Calendar.MONTH, month); //设置当前月的上一个月 + int lastDay = cal.getMinimum(Calendar.DATE); //获取月份中的最小值,即第一天// 设置日历中月份的最大天数 + cal.set(Calendar.DAY_OF_MONTH, lastDay-1); //上月的第一天减去1就是当月的最后一天// 格式化日期 + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + return sdf.format(cal.getTime()); + } + +} diff --git a/src/com/engine/hsCheck/web/QkCheckAction.java b/src/com/engine/hsCheck/web/QkCheckAction.java new file mode 100644 index 0000000..51c971f --- /dev/null +++ b/src/com/engine/hsCheck/web/QkCheckAction.java @@ -0,0 +1,101 @@ +package com.engine.hsCheck.web; + +import com.alibaba.fastjson.JSONObject; +import com.engine.common.util.ParamUtil; +import com.engine.common.util.ServiceUtil; +import com.engine.hsCheck.service.CheckService; +import com.engine.hsCheck.service.impl.CheckServiceImpl; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.Util; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import java.util.HashMap; +import java.util.Map; + +public class QkCheckAction { + + + public CheckService getService(){ + return (CheckService) ServiceUtil.getService(CheckServiceImpl.class); + } + + @POST + @Path("/check") + @Produces(MediaType.TEXT_PLAIN) + public String doGetPurchaseReq1(@Context HttpServletRequest request, @Context HttpServletResponse response){ + + Map apidatas = new HashMap(); + BaseBean bb = new BaseBean(); + try { + apidatas.putAll(getService().check(ParamUtil.request2Map(request))); + } catch (Exception e) { + e.printStackTrace(); +// apidatas.put("api_status", false); +// apidatas.put("api_errormsg", "catch exception : " + e.getMessage()); + } + return JSONObject.toJSONString(apidatas); + } + + + /** + * 建模台账重新格式化考勤 + * @param request + * @param response + * @return + */ + @GET + @Path("/kqFormatByMode") + @Produces({MediaType.TEXT_PLAIN}) + public String kqFormatByMode(@Context HttpServletRequest request, @Context HttpServletResponse response) { + Map apidatas = new HashMap(); + try{ + apidatas.putAll(getService().kqFormatByMode(ParamUtil.request2Map(request))); + }catch (Exception e) { + e.printStackTrace(); + apidatas.put("code","500"); + apidatas.put("msg","fail"); + } + return JSONObject.toJSONString(apidatas); + } + + /** + * 获取人员信息 + * @param request + * @param response + * @return + */ + @GET + @Path("/getPersonInfo") + @Produces({MediaType.TEXT_PLAIN}) + public String getPersonInfo(@Context HttpServletRequest request, @Context HttpServletResponse response) { + Map apidatas = new HashMap(); + try{ + RecordSet rs = new RecordSet(); + Map params = ParamUtil.request2Map(request); + String userid = Util.null2String(params.get("userid")); + String xb = ""; + String zt = ""; + String sql = "select sex,status from HrmResource where id = ?"; + rs.executeQuery(sql,userid); + if(rs.next()){ + xb = Util.null2String(rs.getString("sex")); + zt = Util.null2String(rs.getString("status")); + } + apidatas.put("code","200"); + apidatas.put("xb",xb); + apidatas.put("zt",zt); + }catch (Exception e) { + e.printStackTrace(); + apidatas.put("code","500"); + apidatas.put("msg","fail"); + } + return JSONObject.toJSONString(apidatas); + } + + +} diff --git a/src/com/engine/kq/biz/KQAttFlowSetBiz.java b/src/com/engine/kq/biz/KQAttFlowSetBiz.java new file mode 100644 index 0000000..1eafcf4 --- /dev/null +++ b/src/com/engine/kq/biz/KQAttFlowSetBiz.java @@ -0,0 +1,1131 @@ +package com.engine.kq.biz; + +import com.api.hrm.util.PageUidFactory; +import com.cloudstore.dev.api.util.Util_TableMap; +import com.engine.hrm.util.HrmUtil; +import com.engine.kq.enums.KqSplitFlowTypeEnum; +import com.engine.kq.enums.OverTimeComputingModeEnum; +import com.engine.kq.log.KQLog; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.TimeUtil; +import weaver.general.Util; +import weaver.hrm.User; +import weaver.systeminfo.SystemEnv; + +import java.util.*; + +/** + * 考勤流程 设置类 + */ +public class KQAttFlowSetBiz { + + private KQLog kqLog = new KQLog(); + + public String getFieldInfo(Map attSetMap){ + String unionSql = ""; + if(attSetMap.isEmpty()){ + return ""; + } + String[][] fieldsRefect = KQAttFlowFieldsSetBiz.fieldsRefect; + String[] leavebackMainFields = KQAttFlowFieldsSetBiz.leavebackMainFields; + String[] cardMainFields = KQAttFlowFieldsSetBiz.cardMainFields; + String[] processchangeMainFields = KQAttFlowFieldsSetBiz.processchangeMainFields; + + String prefiex = "detail_"; + String mainPrefix = "a"; + String detailPrefix = "b"; + String allPrefix = "c"; + + String attId = Util.null2String(attSetMap.get("attId")); + int kqtype = Util.getIntValue(Util.null2String(attSetMap.get("kqtype")),0); + String usedetail = Util.null2String(attSetMap.get("usedetail")); + String tablename = Util.null2String(attSetMap.get("tablename")); + tablename = tablename+" "+mainPrefix; + String detailtablename = Util.null2String(attSetMap.get("detailtablename")); + detailtablename = detailtablename+" "+detailPrefix; + + String custome_sql = Util.null2String(attSetMap.get("custome_sql")); + + if(attId.length() > 0){ + String backfields = ""; + Map fieldidMap = new HashMap<>(); + Map fieldnameMap = new HashMap<>(); + Map backfieldMap = new HashMap<>(); + RecordSet rs = new RecordSet(); + String dbtype = rs.getDBType(); + String sql = "select a.field003 fieldid,a.field004 fieldname,b.field002 wffieldname from kq_att_proc_relation a left join kq_att_proc_fields b on a.field002=b.id where a.field001 = ? "; + rs.executeQuery(sql, attId); + while(rs.next()){ + String fieldid = Util.null2String(rs.getString("fieldid")); + String fieldname = Util.null2String(rs.getString("fieldname")); + String wffieldname = Util.null2String(rs.getString("wffieldname")); + if(Util.getIntValue(fieldid,0) <= 0){ + kqLog.info("getFieldInfo:考勤流程字段对应有误 :fieldid is null: :attId:"+attId); + break; + } + if("1".equalsIgnoreCase(usedetail)){ + if(KqSplitFlowTypeEnum.CARD.getFlowtype() == kqtype || KqSplitFlowTypeEnum.LEAVEBACK.getFlowtype() == kqtype + || KqSplitFlowTypeEnum.PROCESSCHANGE.getFlowtype() == kqtype){ + }else{ + if(wffieldname.indexOf(prefiex) > -1){ + wffieldname = wffieldname.substring(prefiex.length()); + }else{ + kqLog.info("getFieldInfo:考勤流程字段对应有误 :usedetail wffieldname is error: :attId:"+attId); +// break; + } + } + } + String backfield = ""; + fieldidMap.put(wffieldname, fieldid); + fieldnameMap.put(wffieldname, fieldname); + if(KqSplitFlowTypeEnum.LEAVEBACK.getFlowtype() == kqtype){ + if(Arrays.asList(leavebackMainFields).contains(wffieldname)){ + backfield = mainPrefix+"."+fieldname +" as "+wffieldname; + }else{ + backfield = detailPrefix+"."+fieldname +" as "+wffieldname; + } + }else if(KqSplitFlowTypeEnum.CARD.getFlowtype() == kqtype){ + if(Arrays.asList(cardMainFields).contains(wffieldname)){ + backfield = mainPrefix+"."+fieldname +" as "+wffieldname; + }else{ + if("detail_signtype".equalsIgnoreCase(wffieldname)){ + if("mysql".equalsIgnoreCase(dbtype)){ + backfield = "CAST("+detailPrefix+"."+fieldname +" as SIGNED) as "+wffieldname; + }else { + backfield = "cast("+detailPrefix+"."+fieldname +" as int) as "+wffieldname; + } + }else{ + backfield = detailPrefix+"."+fieldname +" as "+wffieldname; + } + } + }else if(KqSplitFlowTypeEnum.PROCESSCHANGE.getFlowtype() == kqtype){ + if(Arrays.asList(processchangeMainFields).contains(wffieldname)){ + backfield = mainPrefix+"."+fieldname +" as "+wffieldname; + }else{ + backfield = detailPrefix+"."+fieldname +" as "+wffieldname; + } + }else{ + if("1".equalsIgnoreCase(usedetail)){ + if(KqSplitFlowTypeEnum.EVECTION.getFlowtype() == kqtype && "companion".equalsIgnoreCase(wffieldname)){ + if("oracle".equalsIgnoreCase(dbtype)||"postgresql".equalsIgnoreCase(dbtype)){ + backfield = "to_char("+detailPrefix+"."+fieldname +") as "+wffieldname; + }else if("mysql".equalsIgnoreCase(dbtype)){ + backfield = "CONVERT("+detailPrefix+"."+fieldname +", char ) as "+wffieldname; + }else { + backfield = "cast("+detailPrefix+"."+fieldname +" as varchar(max) ) as "+wffieldname; + } + }else{ + backfield = detailPrefix+"."+fieldname +" as "+wffieldname; + } + }else{ + if(KqSplitFlowTypeEnum.EVECTION.getFlowtype() == kqtype && "companion".equalsIgnoreCase(wffieldname)){ + if("oracle".equalsIgnoreCase(dbtype)||"postgresql".equalsIgnoreCase(dbtype)){ + backfield = "to_char("+mainPrefix+"."+fieldname +") as "+wffieldname; + }else if("mysql".equalsIgnoreCase(dbtype)){ + backfield = "CONVERT("+mainPrefix+"."+fieldname +", char ) as "+wffieldname; + }else { + backfield = "cast("+mainPrefix+"."+fieldname +" as varchar(max) ) as "+wffieldname; + } + }else{ + backfield = mainPrefix+"."+fieldname +" as "+wffieldname; + } + } + } + if(!"".equalsIgnoreCase(wffieldname)){ + backfieldMap.put(wffieldname, backfield); + } + } + if(backfieldMap.isEmpty()){ + kqLog.info("getFieldInfo:考勤流程表字段对应為空 :attId:"+attId+":kqtype:"+kqtype); + return ""; + } + //TODO 这里需要改 + boolean isReflect = true; + String[] fieldsType = fieldsRefect[kqtype]; + for(int i = 0 ;i < fieldsType.length ;i++){ + String backfield = Util.null2String(backfieldMap.get(fieldsType[i])); + if(backfield.length() > 0){ + backfields += ","+backfieldMap.get(fieldsType[i]); + }else{ + kqLog.info("getFieldInfo:考勤流程表字段对应未找到 :attId:"+attId+":kqtype:"+kqtype+":fieldsType[i]:"+fieldsType[i]); + if(fieldsType[i].indexOf("duration") > -1){ + backfields += ", 0 as "+fieldsType[i]; + }else{ + backfields += ", '' as "+fieldsType[i]; + } + } + } + if(backfields.length() > 0){ + backfields = backfields.substring(1); + backfields += ","+mainPrefix+".requestid "; + } + if(KqSplitFlowTypeEnum.SHIFT.getFlowtype() == kqtype || KqSplitFlowTypeEnum.LEAVEBACK.getFlowtype() == kqtype + || KqSplitFlowTypeEnum.CARD.getFlowtype() == kqtype || KqSplitFlowTypeEnum.PROCESSCHANGE.getFlowtype() == kqtype){ + if(KqSplitFlowTypeEnum.SHIFT.getFlowtype() == kqtype){ + unionSql = "select "+backfields+" from "+detailtablename; + }else{ + unionSql = "select "+backfields+" from "+tablename+" left join "+detailtablename+" on "+mainPrefix+".id = "+detailPrefix+".mainid" ; + if(KqSplitFlowTypeEnum.CARD.getFlowtype() == kqtype){ + unionSql = "select "+allPrefix+".* from ("+ "select "+backfields+" from "+tablename+" left join "+detailtablename+" on "+mainPrefix+".id = "+detailPrefix+".mainid" +") "+allPrefix+" where ("+custome_sql+")"; + } + } + }else{ + if("1".equalsIgnoreCase(usedetail)){ + unionSql = "select "+backfields+" from "+detailtablename+" left join "+tablename+" on "+mainPrefix+".id = "+detailPrefix+".mainid" ; + }else{ + unionSql = "select "+backfields+" from "+tablename; + } + } + } + return unionSql; + } + + /** + * + * @param kqtype + * @param user + * @param isMyKQ 是否来自我的考勤 + * @param params + * @return + */ + public String getFieldInfoByKQType(String kqtype, User user, String isMyKQ, + Map params){ + String workflowid =Util.null2String(params.get("workflowid")); + String custome_sql =Util.null2String(params.get("custome_sql")); + RecordSet rs = new RecordSet(); + List formids = new ArrayList<>(); + String unionSqls = ""; + String sql = "select * from kq_att_proc_set where field006= ?"; + if(workflowid.length() > 0 && Util.getIntValue(workflowid) > 0){ + sql += " and field001 = ? "; + rs.executeQuery(sql,kqtype,workflowid); + }else{ + rs.executeQuery(sql,kqtype); + } + while(rs.next()){ + Map attSetMap = new HashMap<>(); + String formid = Util.null2s(rs.getString("field002"),""); + String field005 = Util.null2s(rs.getString("field005"),""); + if(field005.equals("0")){ + continue; + } + //TODO 这里需要改 如果一个表单被多个表单使用的情况 +// if(formid.length() == 0){ +// continue; +// } +// if(formids.contains(formid)){ +// continue; +// }else{ +// formids.add(formid); +// } + String attId = Util.null2String(rs.getString("id")); + String usedetail = Util.null2String(rs.getString("usedetail")); + String tablename = Util.null2String(rs.getString("tablename")); + String detailtablename = Util.null2String(rs.getString("detailtablename")); + attSetMap.put("attId", attId); + attSetMap.put("kqtype", kqtype); + attSetMap.put("usedetail", usedetail); + attSetMap.put("tablename", tablename); + attSetMap.put("detailtablename", detailtablename); + attSetMap.put("custome_sql", custome_sql); + if("1".equalsIgnoreCase(usedetail)){ + if("".equalsIgnoreCase(detailtablename)){ + kqLog.info("getFieldInfoByKQType:考勤流程明细表单不存在 :attId:"+attId+":kqtype:"+kqtype); + continue; + } + }else { + if("".equalsIgnoreCase(tablename)){ + kqLog.info("getFieldInfoByKQType:考勤流程主表表单不存在 :attId:"+attId+":kqtype:"+kqtype); + continue; + } + } + String fieldSql = getFieldInfo(attSetMap); + + if(fieldSql.length() > 0){ + if(unionSqls.length() > 0){ + unionSqls += " union all "+ fieldSql; + }else{ + unionSqls += fieldSql; + } + } + } + + if(unionSqls.length() > 0){ + + String unionsql = ""; + if("1".equalsIgnoreCase(isMyKQ)){ + String hrmSql = " select * from hrmresource a where 1=1 "; + unionSqls = " select distinct u.*,w.currentnodetype,w.status as flowstatus,w.workflowid ,w.requestid as req_requestid,w.requestname,a.managerid,a.managerstr,a.loginid,a.subcompanyid1 as asubcompanyid1,a.departmentid as adepartmentid,a.lastname from (" +unionSqls+") u left join Workflow_Requestbase w on u.requestid = w.requestid left join ("+hrmSql+") a on u.resourceid = a.id "; + }else{ + String rightSql = new KQReportBiz().getReportRight("1",""+user.getUID(),"a"); + String hrmSql = " select * from hrmresource a where 1=1 "+rightSql; + unionSqls = " select distinct u.*,w.currentnodetype,w.status as flowstatus,w.workflowid ,w.requestid as req_requestid,w.requestname,a.managerid,a.managerstr,a.loginid,a.subcompanyid1 as asubcompanyid1,a.departmentid as adepartmentid,a.lastname from (" +unionSqls+") u left join Workflow_Requestbase w on u.requestid = w.requestid left join ("+hrmSql+") a on u.resourceid = a.id "; + } + + } + return unionSqls; + } + + /** + * 拼接流程查询sql + * @param params + * @return + */ + public Map getFLowSql(Map params, User user){ + RecordSet rs = new RecordSet(); + Map sqlMap = new HashMap<>(); + + String tabkey = Util.null2String(params.get("tabKey")); + int kqtype = Util.getIntValue(Util.null2String(params.get("kqtype")),-1); + String resourceId = Util.null2String(params.get("resourceId")); + String subCompanyId = Util.null2String(params.get("subCompanyId")); + String departmentId = Util.null2String(params.get("departmentId")); + + String keyWord = Util.null2String(params.get("keyWord")); + String fromDate = Util.null2String(params.get("fromDate")); + String toDate = Util.null2String(params.get("toDate")); + String typeselect =Util.null2String(params.get("typeselect")); + String requestId =Util.null2String(params.get("requestId")); + String viewScope = Util.null2String(params.get("viewScope")); + String allLevel = Util.null2String(params.get("allLevel")); + String isNoAccount = Util.null2String(params.get("isNoAccount")); + + String isMyKQ = Util.null2String(params.get("isMyKQ")); + String not_start_node = Util.null2String(params.get("not_start_node")); + String not_requestId =Util.null2String(params.get("not_requestId")); + String custome_sql =Util.null2String(params.get("custome_sql")); + String workflowid =Util.null2String(params.get("workflowid")); + + String fromSql = " "; + //req_requestid 表示只显示Workflow_Requestbase里有的数据 + String sqlWhere = " where 1=1 and req_requestid > 0 "; + + 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"); + } + } + + boolean isFinished = false; + if("1".equalsIgnoreCase(tabkey)){ + //已归档 + isFinished = true; + } + //不区分归档不归档 查所有 + boolean isAll = false; + if("3".equalsIgnoreCase(tabkey)){ + isAll = true; + } + if(kqtype > -1){ + if(isFinished){ + fromSql = getFinishedByKQType(""+kqtype,fromDate,toDate,user,isMyKQ); + }else { + fromSql = getFieldInfoByKQType(""+kqtype,user,isMyKQ,params); + } + } + if(fromSql.length() == 0){ + return sqlMap; + }else{ + fromSql = "from ("+fromSql+") f "; + } + + if(kqtype == 0){ + String newleavetype = Util.null2String(params.get("newleavetype")); + if(newleavetype.length() > 0){ + sqlWhere += " and newleavetype= "+newleavetype; + } + } + + if (keyWord.length() > 0){ + sqlWhere += " and lastname = "+keyWord; + } + + if(resourceId.length() > 0){ + sqlWhere += " and resourceId in("+resourceId+")"; + } + + if(subCompanyId.length()>0){ + sqlWhere +=" and asubcompanyid1 in("+subCompanyId+") "; + } + + if(departmentId.length()>0){ + sqlWhere +=" and adepartmentid in("+departmentId+") "; + } + + if(requestId.length() > 0){ + sqlWhere += " and requestId ="+requestId+""; + } + + if(not_requestId.length() > 0){ + sqlWhere += " and requestId not in("+not_requestId+")"; + } + + if(viewScope.equals("4")){//我的下属 + if(allLevel.equals("1")){//所有下属 + sqlWhere+=" and managerstr like '%,"+user.getUID()+",%'"; + }else{ + sqlWhere+=" and managerid="+user.getUID();//直接下属 + } + } + if (!"1".equals(isNoAccount)) { + sqlWhere += " and loginid is not null "+(rs.getDBType().equals("oracle")?"":" and loginid<>'' "); + } + + if(!isFinished){ + if (fromDate.length() > 0 && toDate.length() > 0){ + sqlWhere += " and ( fromDate between '"+fromDate+"' and '"+toDate+"' or toDate between '"+fromDate+"' and '"+toDate+"' " + + " or '"+fromDate+"' between fromDate and toDate or '"+toDate+"' between fromDate and toDate) "; + } + } + + if(isFinished){ + sqlWhere += " and (currentnodetype = '3') "; + }else{ + if(!isAll){ + sqlWhere += " and (currentnodetype is null or currentnodetype != '3') "; + } + } + if("1".equalsIgnoreCase(not_start_node)){ + sqlWhere += " and (currentnodetype != '0') "; + } + if(workflowid.length() > 0){ + sqlWhere += " and workflowid= "+workflowid; + } + if(custome_sql.length() > 0){ + sqlWhere += " and ("+custome_sql+") "; + } + if("1".equalsIgnoreCase(isMyKQ)){ + }else{ + String rightSql = new KQReportBiz().getReportRight("1",""+user.getUID(),"a"); + String hrmSql = " select id from hrmresource a where 1=1 "+rightSql; + sqlWhere += " and resourceId in("+hrmSql+")"; + } + kqLog.info("buildFlowSetTableString"+kqtype+":流程明细sql输出下:fromSql:"+fromSql); + kqLog.info("buildFlowSetTableString"+kqtype+":流程明细sql输出下:sqlWhere:"+sqlWhere); + sqlMap.put("from", fromSql); + sqlMap.put("where", sqlWhere); + return sqlMap; + } + + + /** + * 获取归档后的考勤流程数据 + * @param kqtype + * @param fromDate + * @param toDate + * @param user + * @param isMyKQ 是否来自我的考勤 + * @return + */ + private String getFinishedByKQType(String kqtype, String fromDate, String toDate, User user, + String isMyKQ) { + boolean isLeave = false; + boolean isEvection = false; + boolean isOut = false; + String tableName = ""; + String fields = " distinct requestid,resourceid as resourceId,subcompanyid,departmentid,newleavetype,fromdatedb as fromDate,fromtimedb as fromTime,todatedb as toDate,totimedb as toTime,durationdb,durationrule,SUM(duration) as duration "; + switch (kqtype){ + case "0": + isLeave= true; + tableName = KqSplitFlowTypeEnum.LEAVE.getTablename(); + fields += ",belongdate "; + break; + case "1": + isEvection= true; + tableName = KqSplitFlowTypeEnum.EVECTION.getTablename(); + fields += ",belongdate "; + break; + case "2": + isOut= true; + tableName = KqSplitFlowTypeEnum.OUT.getTablename(); + break; + case "3": + tableName = KqSplitFlowTypeEnum.OVERTIME.getTablename(); + //二开查询增加归属日期字段 2023年09月12日09:48:39 + fields += ",belongdate "; + break; + default: + break; + } + if(tableName.length() == 0){ + kqLog.info("getFinishedByKQType:获取归档的考勤流程出问题了:kqtype:"+kqtype); + return ""; + } + if(isLeave){ + String back_table_name= KqSplitFlowTypeEnum.LEAVEBACK.getTablename(); + String table_name= KqSplitFlowTypeEnum.LEAVE.getTablename(); + String backSql = "select sum(duration) from "+back_table_name+" where "+back_table_name+".leavebackrequestid="+table_name+".requestid and "+back_table_name+".newleavetype="+table_name+".newleavetype and "+back_table_name+".resourceid="+table_name+".resourceid "; + if(fromDate.length() > 0 && toDate.length() > 0){ + if("1".equalsIgnoreCase(isMyKQ)){ + backSql += " and belongdate between'"+fromDate+"' and '"+toDate+"'"; + }else{ + backSql += " and belongdate between'"+fromDate+"' and '"+toDate+"'"; + } + + } + fields = " distinct requestid,resourceid as resourceId,subcompanyid,departmentid,newleavetype,fromdatedb as fromDate,fromtimedb as fromTime,todatedb as toDate,totimedb as toTime,durationdb,durationrule,SUM(duration) as duration," + + "("+backSql+") as backduraion,belongdate "; + } + + String baseSql = " select "+fields+" from "+tableName+" where tablenamedb is not null and (status is null or status != 1) "; + if(fromDate.length() > 0 && toDate.length() > 0){ + if("1".equalsIgnoreCase(isMyKQ)){ + baseSql += " and belongdate between'"+fromDate+"' and '"+toDate+"'"; + }else{ + baseSql += " and belongdate between'"+fromDate+"' and '"+toDate+"'"; + } + } + + //二开增加belongdate + if("0".equals(kqtype) || "1".equals(kqtype) || "2".equals(kqtype)){ + baseSql += " GROUP BY requestid,resourceid,subcompanyid,departmentid,newleavetype,fromdatedb,fromtimedb,todatedb,totimedb,durationdb,durationrule,belongdate "; + }else{ + baseSql += " GROUP BY requestid,resourceid,subcompanyid,departmentid,newleavetype,fromdatedb,fromtimedb,todatedb,totimedb,durationdb,durationrule "; + } + + String unionsql = " select u.*,w.currentnodetype,w.requestname,w.requestid as req_requestid,w.status as flowstatus,w.workflowid,a.managerid,a.managerstr,a.loginid,a.subcompanyid1 as asubcompanyid1,a.departmentid as adepartmentid,a.lastname from ("+baseSql+") u left join Workflow_Requestbase w on u.requestid = w.requestid left join hrmresource a on u.resourceid = a.id "; + return unionsql; + } + + /** + * 考勤报表明细 + * @param params + * @param user + * @return + */ + public String buildFlowSetTableString(Map params, User user){ + int kqtype = Util.getIntValue(Util.null2String(params.get("kqtype")),-1); + String isMyKQ = Util.null2String(params.get("isMyKQ")); + if(!"1".equalsIgnoreCase(isMyKQ)){ + if(kqtype == 3){ + String tabkey = Util.null2String(params.get("tabKey")); + //加班的单独走一个列表显示 + if(OverTimeComputingModeEnum.FLOW.getComputingMode().equalsIgnoreCase(tabkey)){ + return buildTableString4OvertimeFlow(params,user); + }else if(OverTimeComputingModeEnum.FLOW2CARD.getComputingMode().equalsIgnoreCase(tabkey)){ + return buildTableString4OvertimeFlow2Card(params,user); + }else if(OverTimeComputingModeEnum.CARD.getComputingMode().equalsIgnoreCase(tabkey)){ + return buildTableString4OvertimeCard(params,user); + }else if(OverTimeComputingModeEnum.FLOWINCARD.getComputingMode().equalsIgnoreCase(tabkey)){ + return buildTableString4OvertimeFlowInCard(params,user); + } + } + } + + String backfields = " * "; + String fromSql = ""; + String sqlWhere = ""; + String tableString = ""; + String tabletype="none"; + String orderby = " resourceId,fromDate "; + boolean isFinished = false; + String tabkey = Util.null2String(params.get("tabKey")); + if("1".equalsIgnoreCase(tabkey)){ + //已归档 + isFinished = true; + } + String typeselect =Util.null2String(params.get("typeselect")); + String fromDate = Util.null2String(params.get("fromDate")); + String toDate = Util.null2String(params.get("toDate")); + + //在这里生成sql语句 + Map sqlMap = getFLowSql(params,user); + if(sqlMap.isEmpty()){ + //给个默认表 比如请假表,因为表结构都是一样的 + String tableName = KqSplitFlowTypeEnum.LEAVE.getTablename(); + fromSql = tableName; + sqlWhere = " where 1=2 "; + }else{ + fromSql = Util.null2String(sqlMap.get("from")); + sqlWhere = Util.null2String(sqlMap.get("where")); + } + + String fromTimePram = kqtype+"+0+"+user.getLanguage()+"+column:newLeaveType"; + if(isFinished){ + fromTimePram = kqtype+"+0+"+user.getLanguage()+"+column:newLeaveType"+"+column:durationrule"; + } + String toTimePram = kqtype+"+1+"+user.getLanguage()+"+column:newLeaveType"; + if(isFinished){ + toTimePram = kqtype+"+1+"+user.getLanguage()+"+column:newLeaveType"+"+column:durationrule"; + } + + String otherPram = kqtype+"+column:durationrule+"+user.getLanguage(); + if(kqtype == 0){ + otherPram +="+column:newLeaveType+column:requestid+column:backduraion"; + } + + int languageId = user.getLanguage(); + + // #1475814-概述:满足考勤报分部部门显示及导出时显示全路径需求 + String transMethodString = HrmUtil.getKqDepartmentTransMethod(); + + String pageUid = "cb9b9b02-a34c-4468-b871-08167bcaeb6c"; + + tableString =" "+ +// " "+ + " "+ + " "; + tableString += " "; + tableString += " "; + tableString += " "; + tableString += " "; + + tableString += " "; + tableString += " "; + tableString += " "; + if(kqtype == 0){ + tableString += " "; + } + tableString += " "; + if(isFinished){ + tableString += " "; + } + tableString +=" "+ + "
"; + String sessionkey = pageUid + "_" + Util.getEncrypt(Util.getRandom()); + Util_TableMap.setVal(sessionkey, tableString); + return sessionkey; + } + + + /** + * 流程 生成加班明细 + * @param params + * @param user + * @return + */ + public String buildTableString4OvertimeFlow(Map params, User user){ + String dbType = new RecordSet().getDBType(); + String orgindbtype = new RecordSet().getOrgindbtype(); + String backfields = " * "; + String fromDate = Util.null2String(params.get("fromDate")); + String toDate = Util.null2String(params.get("toDate")); + String typeselect =Util.null2String(params.get("typeselect")); + String belongdateWhere = ""; + 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"); + } + } + + if (fromDate.length() > 0 && toDate.length() > 0){ + belongdateWhere += " and ( belongdate between '"+fromDate+"' and '"+toDate+"' or belongdate between '"+fromDate+"' and '"+toDate+"' " + + " or '"+fromDate+"' between belongdate and belongdate or '"+toDate+"' between belongdate and belongdate) "; + } + + String overtimeTable = ""; + + if("oracle".equalsIgnoreCase(dbType)){ + overtimeTable = " select requestid,resourceid,fromdatedb fromdate,fromtimedb fromtime,todatedb todate,totimedb totime,computingmode,paidLeaveEnable,expiringdate,durationrule,to_char(sum(duration_min)) duration_min from kq_flow_overtime where computingmode=1 "+(belongdateWhere.length() == 0 ? "" : belongdateWhere)+" group by requestid,resourceid,fromdatedb,fromtimedb,todatedb,totimedb,computingmode,paidLeaveEnable,expiringdate,durationrule "; + if("jc".equalsIgnoreCase(orgindbtype)){ + overtimeTable = " select requestid,resourceid,fromdatedb fromdate,fromtimedb fromtime,todatedb todate,totimedb totime,computingmode,paidLeaveEnable,expiringdate,durationrule,to_char(sum(cast(duration_min as NUMERIC))) duration_min from kq_flow_overtime where computingmode=1 "+(belongdateWhere.length() == 0 ? "" : belongdateWhere)+" group by requestid,resourceid,fromdatedb,fromtimedb,todatedb,totimedb,computingmode,paidLeaveEnable,expiringdate,durationrule "; + } + }else if("postgresql".equalsIgnoreCase(dbType)){ + overtimeTable = " select requestid,resourceid,fromdatedb fromdate,fromtimedb fromtime,todatedb todate,totimedb totime,computingmode,paidLeaveEnable,expiringdate,durationrule,sum(cast(duration_min as NUMERIC)) duration_min from kq_flow_overtime where computingmode=1 "+(belongdateWhere.length() == 0 ? "" : belongdateWhere)+" group by requestid,resourceid,fromdatedb,fromtimedb,todatedb,totimedb,computingmode,paidLeaveEnable,expiringdate,durationrule "; + }else if("mysql".equalsIgnoreCase(dbType)) { + overtimeTable = " select requestid,resourceid,fromdatedb fromdate,fromtimedb fromtime,todatedb todate,totimedb totime,computingmode,paidLeaveEnable,expiringdate,durationrule,CONVERT (sum(duration_min), CHAR ) duration_min from kq_flow_overtime where computingmode=1 " + (belongdateWhere.length() == 0 ? "" : belongdateWhere) + " group by requestid,resourceid,fromdatedb,fromtimedb,todatedb,totimedb,computingmode,paidLeaveEnable,expiringdate,durationrule "; + }else{ + overtimeTable = " select requestid,resourceid,fromdatedb fromdate,fromtimedb fromtime,todatedb todate,totimedb totime,computingmode,paidLeaveEnable,expiringdate,durationrule,convert(varchar,sum(cast(duration_min as NUMERIC))) duration_min from kq_flow_overtime where computingmode=1 "+(belongdateWhere.length() == 0 ? "" : belongdateWhere)+" group by requestid,resourceid,fromdatedb,fromtimedb,todatedb,totimedb,computingmode,paidLeaveEnable,expiringdate,durationrule "; + } + String fromSql = " (select b.lastname,b.loginid,b.subcompanyid1,b.departmentid,b.jobtitle,b.managerid,b.managerstr,a.* from ("+overtimeTable+") a left join hrmresource b on a.resourceid = b.id) f "; + String sqlWhere = " 1=1 "; + String tableString = ""; + String tabletype="none"; + String orderby = " computingmode "; + + String tabkey = Util.null2String(params.get("tabKey")); + int kqtype = Util.getIntValue(Util.null2String(params.get("kqtype")),-1); + String resourceId = Util.null2String(params.get("resourceId")); + String subCompanyId = Util.null2String(params.get("subCompanyId")); + String departmentId = Util.null2String(params.get("departmentId")); + + //来自我的考勤,resourceid为空时,默认取当前用户的id + String source =Util.null2String(params.get("source")); + if(source.equals("isMyKq")){ + if(resourceId.equals("")){ + resourceId = user.getUID()+""; + } + } + kqLog.info(">>>>>>source:"+source+">>>>>resourceId:"+resourceId); + + String keyWord = Util.null2String(params.get("keyWord")); + String requestId =Util.null2String(params.get("requestId")); + String viewScope = Util.null2String(params.get("viewScope")); + String allLevel = Util.null2String(params.get("allLevel")); + String isNoAccount = Util.null2String(params.get("isNoAccount")); + + String isMyKQ = Util.null2String(params.get("isMyKQ")); + + boolean isFinished = false; + if("1".equalsIgnoreCase(tabkey)){ + //已归档 + isFinished = true; + } + + if (keyWord.length() > 0){ + sqlWhere += " and lastname = "+keyWord; + } + + if(resourceId.length() > 0){ + sqlWhere += " and resourceId in("+resourceId+")"; + } + + if(subCompanyId.length()>0){ + sqlWhere +=" and subcompanyid1 in("+subCompanyId+") "; + } + + if(departmentId.length()>0){ + sqlWhere +=" and departmentid in("+departmentId+") "; + } + + if(viewScope.equals("4")){//我的下属 + if(allLevel.equals("1")){//所有下属 + sqlWhere+=" and managerstr like '%,"+user.getUID()+",%'"; + }else{ + sqlWhere+=" and managerid="+user.getUID();//直接下属 + } + } + if (!"1".equals(isNoAccount)) { + sqlWhere += " and loginid is not null "+(new RecordSet().getDBType().equals("oracle")?"":" and loginid<>'' "); + } + + String rightSql = new KQReportBiz().getReportRight("1",""+user.getUID(),"aa"); + String hrmSql = " select id from hrmresource aa where 1=1 "+rightSql; + if (null != rightSql && rightSql.length()>0) { + sqlWhere += " and resourceId in("+hrmSql+")"; + } + +// if (fromDate.length() > 0 && toDate.length() > 0){ +// sqlWhere += " and ( fromDate between '"+fromDate+"' and '"+toDate+"' or toDate between '"+fromDate+"' and '"+toDate+"' " +// + " or '"+fromDate+"' between fromDate and toDate or '"+toDate+"' between fromDate and toDate) "; +// } + String otherPram = user.getLanguage()+""; + + String fromTimePram = kqtype+"+0+"+user.getLanguage()+"++column:durationrule"; + String toTimePram = kqtype+"+1+"+user.getLanguage()+"++column:durationrule"; + + // #1475814-概述:满足考勤报分部部门显示及导出时显示全路径需求 + String transMethodString = HrmUtil.getKqDepartmentTransMethod(); + + String pageUid = PageUidFactory.getHrmPageUid("KQ_OvertimeTotal_Detail_Flow"); + String sql = "backfields>>>>"+backfields+">>>fromSql>>>"+fromSql+">>>sqlWhere>>>"+sqlWhere; + new BaseBean().writeLog("sql>>>>>>>>>"+sql); + tableString =" "+ + " "+ + " "; + tableString += " "; + tableString += " "; + tableString += " "; + tableString += " "; + tableString += " "; + tableString += " "; + tableString += " "; + tableString += " "; + tableString += " "; + tableString +=" "+ + "
"; + String sessionkey = pageUid + "_" + Util.getEncrypt(Util.getRandom()); + Util_TableMap.setVal(sessionkey, tableString); + return sessionkey; + } + + /** + * 打卡+流程 生成加班明细 + * @param params + * @param user + */ + private String buildTableString4OvertimeFlow2Card(Map params, User user) { + String backfields = " * "; + String fromDate = Util.null2String(params.get("fromDate")); + String toDate = Util.null2String(params.get("toDate")); + String typeselect =Util.null2String(params.get("typeselect")); + String belongdateWhere = ""; + 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"); + } + } + + if (fromDate.length() > 0 && toDate.length() > 0){ + belongdateWhere += " and ( belongdate between '"+fromDate+"' and '"+toDate+"' or belongdate between '"+fromDate+"' and '"+toDate+"' " + + " or '"+fromDate+"' between belongdate and belongdate or '"+toDate+"' between belongdate and belongdate) "; + } + String overtimeTable = " select requestid,resourceid,fromdate,fromtime,todate,totime,fromdatedb,fromtimedb,todatedb,totimedb,computingmode,paidLeaveEnable,expiringdate,duration_min,durationrule from kq_flow_overtime where computingmode = 2 "+(belongdateWhere.length() == 0 ? "" :belongdateWhere); + + String fromSql = " (select b.lastname,b.loginid,b.subcompanyid1,b.departmentid,b.jobtitle,b.managerid,b.managerstr,a.* from ("+overtimeTable+") a left join hrmresource b on a.resourceid = b.id) f "; + String sqlWhere = " 1=1 "; + String tableString = ""; + String tabletype="none"; + String orderby = " computingmode "; + + String tabkey = Util.null2String(params.get("tabKey")); + int kqtype = Util.getIntValue(Util.null2String(params.get("kqtype")),-1); + String resourceId = Util.null2String(params.get("resourceId")); + String subCompanyId = Util.null2String(params.get("subCompanyId")); + String departmentId = Util.null2String(params.get("departmentId")); + + //来自我的考勤,resourceid为空时,默认取当前用户的id + String source =Util.null2String(params.get("source")); + if(source.equals("isMyKq")){ + if(resourceId.equals("")){ + resourceId = user.getUID()+""; + } + } + + String keyWord = Util.null2String(params.get("keyWord")); + String requestId =Util.null2String(params.get("requestId")); + String viewScope = Util.null2String(params.get("viewScope")); + String allLevel = Util.null2String(params.get("allLevel")); + String isNoAccount = Util.null2String(params.get("isNoAccount")); + + String isMyKQ = Util.null2String(params.get("isMyKQ")); + + boolean isFinished = false; + if("1".equalsIgnoreCase(tabkey)){ + //已归档 + isFinished = true; + } + + if (keyWord.length() > 0){ + sqlWhere += " and lastname = "+keyWord; + } + + if(resourceId.length() > 0){ + sqlWhere += " and resourceId in("+resourceId+")"; + } + + if(subCompanyId.length()>0){ + sqlWhere +=" and subcompanyid1 in("+subCompanyId+") "; + } + + if(departmentId.length()>0){ + sqlWhere +=" and departmentid in("+departmentId+") "; + } + + if(viewScope.equals("4")){//我的下属 + if(allLevel.equals("1")){//所有下属 + sqlWhere+=" and managerstr like '%,"+user.getUID()+",%'"; + }else{ + sqlWhere+=" and managerid="+user.getUID();//直接下属 + } + } + if (!"1".equals(isNoAccount)) { + sqlWhere += " and loginid is not null "+(new RecordSet().getDBType().equals("oracle")?"":" and loginid<>'' "); + } + + String rightSql = new KQReportBiz().getReportRight("1",""+user.getUID(),"aa"); + String hrmSql = " select id from hrmresource aa where 1=1 "+rightSql; + if (null != rightSql && rightSql.length()>0) { + sqlWhere += " and resourceId in("+hrmSql+")"; + } + + kqLog.info("buildTableString4OvertimeFlow2Card>>>>>>backfields:"+backfields+">>>>>fromSql:"+fromSql + +">>>>>sqlWhere:"+sqlWhere); + String otherPram = user.getLanguage()+""; + String timePram = "column:fromtimedb+column:todatedb+column:totimedb"; + String fromTimePram = kqtype+"+0+"+user.getLanguage()+"++column:durationrule"; + String toTimePram = kqtype+"+1+"+user.getLanguage()+"++column:durationrule"; + + // #1475814-概述:满足考勤报分部部门显示及导出时显示全路径需求 + String transMethodString = HrmUtil.getKqDepartmentTransMethod(); + + String pageUid = PageUidFactory.getHrmPageUid("KQ_OvertimeTotal_Detail_Flow2Card"); + + tableString =" "+ + " "+ + " "; + tableString += " "; + tableString += " "; + tableString += " "; + tableString += " "; + tableString += " "; + tableString += " "; + tableString += " "; + tableString += " "; + tableString += " "; + tableString += " "; + tableString +=" "+ + "
"; + String sessionkey = pageUid + "_" + Util.getEncrypt(Util.getRandom()); + Util_TableMap.setVal(sessionkey, tableString); + return sessionkey; + } + + /** + * 打卡 生成加班明细 + * @param params + * @param user + */ + private String buildTableString4OvertimeCard(Map params, User user) { + String backfields = " * "; + String fromDate = Util.null2String(params.get("fromDate")); + String toDate = Util.null2String(params.get("toDate")); + String typeselect =Util.null2String(params.get("typeselect")); + String belongdateWhere = ""; + 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"); + } + } + + if (fromDate.length() > 0 && toDate.length() > 0){ + belongdateWhere += " and ( belongdate between '"+fromDate+"' and '"+toDate+"' or belongdate between '"+fromDate+"' and '"+toDate+"' " + + " or '"+fromDate+"' between belongdate and belongdate or '"+toDate+"' between belongdate and belongdate) "; + } + String overtimeTable = " select requestid,resourceid,fromdate,fromtime,todate,totime,computingmode,paidLeaveEnable,expiringdate,duration_min from kq_flow_overtime where computingmode = 3 "+(belongdateWhere.length() == 0 ? "" : belongdateWhere); + + String fromSql = " (select b.lastname,b.loginid,b.subcompanyid1,b.departmentid,b.jobtitle,b.managerid,b.managerstr,a.* from ("+overtimeTable+") a left join hrmresource b on a.resourceid = b.id) f "; + String sqlWhere = " 1=1 "; + String tableString = ""; + String tabletype="none"; + String orderby = " computingmode "; + + String tabkey = Util.null2String(params.get("tabKey")); + int kqtype = Util.getIntValue(Util.null2String(params.get("kqtype")),-1); + String resourceId = Util.null2String(params.get("resourceId")); + String subCompanyId = Util.null2String(params.get("subCompanyId")); + String departmentId = Util.null2String(params.get("departmentId")); + + //来自我的考勤,resourceid为空时,默认取当前用户的id + String source =Util.null2String(params.get("source")); + if(source.equals("isMyKq")){ + if(resourceId.equals("")){ + resourceId = user.getUID()+""; + } + } + kqLog.info(">>>>>>source:"+source+">>>>>resourceId:"+resourceId); + + String keyWord = Util.null2String(params.get("keyWord")); + String requestId =Util.null2String(params.get("requestId")); + String viewScope = Util.null2String(params.get("viewScope")); + String allLevel = Util.null2String(params.get("allLevel")); + String isNoAccount = Util.null2String(params.get("isNoAccount")); + + String isMyKQ = Util.null2String(params.get("isMyKQ")); + + boolean isFinished = false; + if("1".equalsIgnoreCase(tabkey)){ + //已归档 + isFinished = true; + } + + if (keyWord.length() > 0){ + sqlWhere += " and lastname = "+keyWord; + } + + if(resourceId.length() > 0){ + sqlWhere += " and resourceId in("+resourceId+")"; + } + + if(subCompanyId.length()>0){ + sqlWhere +=" and subcompanyid1 in("+subCompanyId+") "; + } + + if(departmentId.length()>0){ + sqlWhere +=" and departmentid in("+departmentId+") "; + } + + if(viewScope.equals("4")){//我的下属 + if(allLevel.equals("1")){//所有下属 + sqlWhere+=" and managerstr like '%,"+user.getUID()+",%'"; + }else{ + sqlWhere+=" and managerid="+user.getUID();//直接下属 + } + } + if (!"1".equals(isNoAccount)) { + sqlWhere += " and loginid is not null "+(new RecordSet().getDBType().equals("oracle")?"":" and loginid<>'' "); + } + String rightSql = new KQReportBiz().getReportRight("1",""+user.getUID(),"aa"); + String hrmSql = " select id from hrmresource aa where 1=1 "+rightSql; + if (null != rightSql && rightSql.length()>0) { + sqlWhere += " and resourceId in("+hrmSql+")"; + } + +// if (fromDate.length() > 0 && toDate.length() > 0){ +// sqlWhere += " and ( fromDate between '"+fromDate+"' and '"+toDate+"' or toDate between '"+fromDate+"' and '"+toDate+"' " +// + " or '"+fromDate+"' between fromDate and toDate or '"+toDate+"' between fromDate and toDate) "; +// } + String otherPram = user.getLanguage()+""; + + // #1475814-概述:满足考勤报分部部门显示及导出时显示全路径需求 + String transMethodString = HrmUtil.getKqDepartmentTransMethod(); + + String pageUid = PageUidFactory.getHrmPageUid("KQ_OvertimeTotal_Detail_Card"); + + tableString =" "+ + " "+ + " "; + tableString += " "; + tableString += " "; + tableString += " "; + tableString += " "; + tableString += " "; + tableString += " "; + tableString += " "; + tableString += " "; + tableString += " "; + tableString +=" "+ + "
"; + String sessionkey = pageUid + "_" + Util.getEncrypt(Util.getRandom()); + Util_TableMap.setVal(sessionkey, tableString); + return sessionkey; + } + + /** + * 打卡+流程 取交集 生成加班明细 + * @param params + * @param user + */ + private String buildTableString4OvertimeFlowInCard(Map params, User user) { + String backfields = " * "; + String fromDate = Util.null2String(params.get("fromDate")); + String toDate = Util.null2String(params.get("toDate")); + String typeselect =Util.null2String(params.get("typeselect")); + String belongdateWhere = ""; + 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"); + } + } + + if (fromDate.length() > 0 && toDate.length() > 0){ + belongdateWhere += " and ( belongdate between '"+fromDate+"' and '"+toDate+"' or belongdate between '"+fromDate+"' and '"+toDate+"' " + + " or '"+fromDate+"' between belongdate and belongdate or '"+toDate+"' between belongdate and belongdate) "; + } + String overtimeTable = " select requestid,resourceid,fromdate,fromtime,todate,totime,fromdatedb,fromtimedb,todatedb,totimedb,computingmode,paidLeaveEnable,expiringdate,duration_min,durationrule from kq_flow_overtime where computingmode = 4 "+(belongdateWhere.length() == 0 ? "" :belongdateWhere); + + String fromSql = " (select b.lastname,b.loginid,b.subcompanyid1,b.departmentid,b.jobtitle,b.managerid,b.managerstr,a.* from ("+overtimeTable+") a left join hrmresource b on a.resourceid = b.id) f "; + String sqlWhere = " 1=1 "; + String tableString = ""; + String tabletype="none"; + String orderby = " computingmode "; + + String tabkey = Util.null2String(params.get("tabKey")); + int kqtype = Util.getIntValue(Util.null2String(params.get("kqtype")),-1); + String resourceId = Util.null2String(params.get("resourceId")); + String subCompanyId = Util.null2String(params.get("subCompanyId")); + String departmentId = Util.null2String(params.get("departmentId")); + + //来自我的考勤,resourceid为空时,默认取当前用户的id + String source =Util.null2String(params.get("source")); + if(source.equals("isMyKq")){ + if(resourceId.equals("")){ + resourceId = user.getUID()+""; + } + } + + String keyWord = Util.null2String(params.get("keyWord")); + String requestId =Util.null2String(params.get("requestId")); + String viewScope = Util.null2String(params.get("viewScope")); + String allLevel = Util.null2String(params.get("allLevel")); + String isNoAccount = Util.null2String(params.get("isNoAccount")); + + String isMyKQ = Util.null2String(params.get("isMyKQ")); + + boolean isFinished = false; + if("1".equalsIgnoreCase(tabkey)){ + //已归档 + isFinished = true; + } + + if (keyWord.length() > 0){ + sqlWhere += " and lastname = "+keyWord; + } + + if(resourceId.length() > 0){ + sqlWhere += " and resourceId in("+resourceId+")"; + } + + if(subCompanyId.length()>0){ + sqlWhere +=" and subcompanyid1 in("+subCompanyId+") "; + } + + if(departmentId.length()>0){ + sqlWhere +=" and departmentid in("+departmentId+") "; + } + + if(viewScope.equals("4")){//我的下属 + if(allLevel.equals("1")){//所有下属 + sqlWhere+=" and managerstr like '%,"+user.getUID()+",%'"; + }else{ + sqlWhere+=" and managerid="+user.getUID();//直接下属 + } + } + if (!"1".equals(isNoAccount)) { + sqlWhere += " and loginid is not null "+(new RecordSet().getDBType().equals("oracle")?"":" and loginid<>'' "); + } + + String rightSql = new KQReportBiz().getReportRight("1",""+user.getUID(),"aa"); + String hrmSql = " select id from hrmresource aa where 1=1 "+rightSql; + if (null != rightSql && rightSql.length()>0) { + sqlWhere += " and resourceId in("+hrmSql+")"; + } + + kqLog.info("KQ_OvertimeTotal_Detail_FlowInCard>>>>>>backfields:"+backfields+">>>>>fromSql:"+fromSql + +">>>>>sqlWhere:"+sqlWhere); + String otherPram = user.getLanguage()+""; + String timePram = "column:fromtime+column:todate+column:totime"; + String fromTimePram = kqtype+"+0+"+user.getLanguage()+"++column:durationrule"; + String toTimePram = kqtype+"+1+"+user.getLanguage()+"++column:durationrule"; + + // #1475814-概述:满足考勤报分部部门显示及导出时显示全路径需求 + String transMethodString = HrmUtil.getKqDepartmentTransMethod(); + + String pageUid = PageUidFactory.getHrmPageUid("KQ_OvertimeTotal_Detail_FlowInCard"); + + tableString =" "+ + " "+ + " "; + tableString += " "; + tableString += " "; + tableString += " "; + tableString += " "; + tableString += " "; + tableString += " "; + tableString += " "; + tableString += " "; + tableString += " "; + tableString += " "; + tableString +=" "+ + "
"; + String sessionkey = pageUid + "_" + Util.getEncrypt(Util.getRandom()); + Util_TableMap.setVal(sessionkey, tableString); + return sessionkey; + } +} diff --git a/src/com/engine/kq/biz/KQBalanceOfLeaveBiz.java b/src/com/engine/kq/biz/KQBalanceOfLeaveBiz.java new file mode 100644 index 0000000..81cb3fe --- /dev/null +++ b/src/com/engine/kq/biz/KQBalanceOfLeaveBiz.java @@ -0,0 +1,4233 @@ +package com.engine.kq.biz; + +import com.alibaba.fastjson.JSONObject; +import com.engine.kq.entity.KQBalanceOfLeaveEntity; +import com.engine.kq.entity.KQOvertimeRulesDetailEntity; +import com.engine.kq.entity.KQUsageHistoryEntity; +import com.engine.kq.log.KQLog; +import com.engine.kq.util.UtilKQHS; +import com.engine.kq.wfset.bean.OvertimeBalanceTimeBean; +import com.google.common.collect.Maps; +import java.time.format.DateTimeFormatter; +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.TimeUtil; +import weaver.general.Util; +import weaver.hrm.User; +import weaver.hrm.resource.ResourceComInfo; +import weaver.systeminfo.SystemEnv; +import weaver.hrm.moduledetach.ManageDetachComInfo; +import java.math.BigDecimal; +import weaver.hrm.company.SubCompanyComInfo; +import java.math.RoundingMode; +import java.text.SimpleDateFormat; +import java.time.*; +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); + + boolean isLastYearChildcareLeave = false; + //判断查询年份是否是小孩出生日期的第三年 + if ("36".equals(ruleId)) { + isLastYearChildcareLeave = UtilKQHS.isLastYearChildcareLeave(resourceId, searchYear); + } + + /**********************************************************************************************************/ + + //假期类型缓存类 + KQLeaveRulesComInfo rulesComInfo = new KQLeaveRulesComInfo(); + //是否启用假期余额:0-未开启、1-开启 + int balanceEnable = Util.getIntValue(rulesComInfo.getBalanceEnable(ruleId), 0); + + /**********************************************************************************************************/ + + //人员缓存类 + ResourceComInfo resourceComInfo = new ResourceComInfo(); + //分部ID + String subCompanyId = resourceComInfo.getSubCompanyID(resourceId); + + /**********************************************************************************************************/ + + //假期规则缓存类 + KQLeaveRulesDetailComInfo detailComInfo = new KQLeaveRulesDetailComInfo(); + //余额发放方式:1-手动发放、2-按司龄自动发放、3-按工龄自动发放、4-每年自动发放固定天数、5-加班时长自动计入余额、6-按司龄+工龄自动发放 + int distributionMode = Util.getIntValue(detailComInfo.getDistributionMode(ruleId, subCompanyId), 1); + // + int decimalDigit = Util.getIntValue(detailComInfo.getDecimalDigit(ruleId, subCompanyId), 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 || distributionMode == 9 || distributionMode == 10) { + restAmount = getRestAmountByDis5(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"));//额外的假期时长 + + if ("36".equals(ruleId)) { + //根据释放规则获取已释放的天数/小时数 + baseAmount = getCanUseAmountChildcareLeave(resourceId, ruleId, belongYear, baseAmount, "", date, isLastYearChildcareLeave); + } else { + //根据释放规则获取已释放的天数/小时数 + 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 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)); + + /*********************************************************************************/ + + //获取此假期类型下,该人员所在分部对应的假期规则 + KQLeaveRulesDetailComInfo detailComInfo = new KQLeaveRulesDetailComInfo(); + //余额发放方式 + int distributionMode = Util.getIntValue(detailComInfo.getDistributionMode(ruleId, subCompanyId), 1); + //释放规则:0-不限制、1-按天释放、2-按月释放 + int releaseRule = Util.getIntValue(detailComInfo.getReleaseRule(ruleId, subCompanyId), 0); + //小数位数 + int decimalDigit = Util.getIntValue(detailComInfo.getDecimalDigit(ruleId, subCompanyId), 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(); + } + + //37:独生子女护理假 + if("37".equals(ruleId)){ + String canUseAmountStr = UtilKQHS.handleAmount(canUseAmount.toPlainString(),baseAmount.toPlainString()); + canUseAmount = new BigDecimal(canUseAmountStr); + } + + return canUseAmount; + } + + /** + * 育儿假专用---------------36 + * 获取指定人员的指定假期类型的指定年份在指定日期的可用余额(假期基数*释放比例) + * + * @param resourceId 指定的人员ID + * @param ruleId 指定的假期类型ID(对应于数据库表kq_leaveRules的主键ID) + * @param belongYear 指定的所属年份(格式yyyy) + * @param baseAmount 假期基数 + * @param legalOrWelfare 是计算[法定年假]还是计算[福利年假]:legal-法定年假、welfare-福利年假 + * @param date 指定日期(获取的就是此日期的假期可用余额) + * @return + */ + public static BigDecimal getCanUseAmountChildcareLeave(String resourceId, String ruleId, String belongYear, BigDecimal baseAmount, String legalOrWelfare, String date, boolean isLastYearChildcareLeave) { + BaseBean bb = new BaseBean(); + bb.writeLog("--getCanUseAmountChildcareLeave-resourceId-:"+resourceId); + BigDecimal canUseAmount = new BigDecimal("0"); + try { + //人员缓存类 + ResourceComInfo resourceComInfo = new ResourceComInfo(); + //分部ID + String subCompanyId = resourceComInfo.getSubCompanyID(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 = null; + bb.writeLog("--getCanUseAmountChildcareLeave-="+resourceId+"=isLastYearChildcareLeave-:"+isLastYearChildcareLeave); + + if (isLastYearChildcareLeave) { + String childcareLeaveDateStr = UtilKQHS.getLastDateChildcareLeave(resourceId, date); + bb.writeLog("--getCanUseAmountChildcareLeave-="+resourceId+"=childcareLeaveDateStr-:"+childcareLeaveDateStr); + //判断当前日期 大于 育儿三周岁日期 返回0.0 + boolean flag = UtilKQHS.compareDate(childcareLeaveDateStr,date); + if(flag){ + return new BigDecimal("0"); + } + + Calendar childcareLeaveDate = DateUtil.getCalendar(childcareLeaveDateStr); + actualMaximum = new BigDecimal("" + childcareLeaveDate.get(Calendar.DAY_OF_YEAR)); + } else { + actualMaximum = new BigDecimal("" + searchDate.getActualMaximum(Calendar.DAY_OF_YEAR)); + } + bb.writeLog("--getCanUseAmountChildcareLeave-="+resourceId+"=actualMaximum-:"+actualMaximum); + //指定日期是那年的第几天 + BigDecimal dayOfYear = new BigDecimal("" + searchDate.get(Calendar.DAY_OF_YEAR)); + //指定日期是那年的第几月 + BigDecimal monthOfYear = new BigDecimal("" + (searchDate.get(Calendar.MONTH) + 1)); + + /*********************************************************************************/ + + //获取此假期类型下,该人员所在分部对应的假期规则 + KQLeaveRulesDetailComInfo detailComInfo = new KQLeaveRulesDetailComInfo(); + //余额发放方式 + int distributionMode = Util.getIntValue(detailComInfo.getDistributionMode(ruleId, subCompanyId), 1); + //释放规则:0-不限制、1-按天释放、2-按月释放 + int releaseRule = Util.getIntValue(detailComInfo.getReleaseRule(ruleId, subCompanyId), 0); + //小数位数 + int decimalDigit = Util.getIntValue(detailComInfo.getDecimalDigit(ruleId, subCompanyId), 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); + } + } + bb.writeLog("--getCanUseAmountChildcareLeave-decimalDigit-"+decimalDigit); + + + /****************************************************************************************/ + + /* 释放规则 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(); + } + //36:育儿假 37:独生子女护理假 + if("36".equals(ruleId) || "37".equals(ruleId)){ + String canUseAmountStr = UtilKQHS.handleAmount(canUseAmount.toPlainString(),baseAmount.toPlainString()); + canUseAmount = new BigDecimal(canUseAmountStr); + } + + + 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); + + //假期规则缓存类 + KQLeaveRulesDetailComInfo detailComInfo = new KQLeaveRulesDetailComInfo(); + //有效期规则:0-不限制、1-按自然年失效、2-按入职日期起12个月、3-自定义次年失效日期、4-按天数失效、5-按季度失效、6-按月数失效 + int validityRule = Util.getIntValue(detailComInfo.getValidityRule(ruleId, subcompanyId), 0); + //自定义有效天数([validityRule=4]时有效) + int effectiveDays = Util.getIntValue(detailComInfo.getEffectiveDays(ruleId, subcompanyId), 0); + //自定义有效月数([validityRule=6]时有效) + int effectiveMonths = Util.getIntValue(detailComInfo.getEffectiveMonths(ruleId, subcompanyId), 0); + //自定义次年失效的月份([validityRule=3]时有效) + String expirationMonth = detailComInfo.getExpirationMonth(ruleId, subcompanyId); + //自定义次年失效的日期([validityRule=3]时有效) + String expirationDay = detailComInfo.getExpirationDay(ruleId, subcompanyId); + //允许延长有效期:0--不允许、1--允许 + int extensionEnable = Util.getIntValue(detailComInfo.getExtensionEnable(ruleId, subcompanyId), 0); + //允许延长的有效天数 + int extendedDays = Util.getIntValue(detailComInfo.getExtendedDays(ruleId, subcompanyId)); + //获取当前日期 + 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); + //假期规则缓存类 + KQLeaveRulesDetailComInfo detailComInfo = new KQLeaveRulesDetailComInfo(); + //有效期规则:0-不限制、1-按自然年失效、2-按入职日期起12个月、3-自定义次年失效日期、4-按天数失效、5-按季度失效、6-按月数失效 + int validityRule = Util.getIntValue(detailComInfo.getValidityRule(ruleId, subcompanyId), 0); + //自定义有效天数([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 <= 2) { + 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); + } + if (!KQLeaveRulesBiz.isTiaoXiu(ruleId)) { + 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); + //日期类型: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); + + /****************************************************************************************************************/ + //根据日期类型判断使用规则 + int distributionMode = 5; + if(changeType == 2){ + distributionMode = 9; + }else if(changeType == 3){ + distributionMode = 10; + } + + + //假期类型的缓存类 + KQLeaveRulesComInfo rulesComInfo = new KQLeaveRulesComInfo(); + //[调休]的假期类型的ID + String leaveRulesId = ""; + //找到[调休]的假期类型ID + rulesComInfo.setTofirstRow(); + while (rulesComInfo.next()) { + //if (KQLeaveRulesBiz.isTiaoXiu(rulesComInfo.getId())) { + // if("1".equals(rulesComInfo.getIsEnable())){ + // leaveRulesId = rulesComInfo.getId(); + // break; + // } + //} + //时间 2023-04-18 自定义调休规则 9:工作日、10:休息日 + if (KQLeaveRulesBiz.isTiaoXiuByMode(rulesComInfo.getId(),distributionMode)) { + if("1".equals(rulesComInfo.getIsEnable())){ + leaveRulesId = rulesComInfo.getId(); + break; + } + } + } + //[调休]的假期类型的最小请假单位: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)); + //保留几位小数 + int decimalDigit = Util.getIntValue(detailComInfo.getDecimalDigit(leaveRulesId, subCompanyId), 2); + + /*如果没有设置调休的假期类型,则直接退出方法*/ + 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"); + } + + 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); + 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); + 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); + 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); + 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); + 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); + 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; + } + + /** + * 按加班的时间段设置转调休时长 + * @param date + * @param leaveRulesId + * @param resourceId + * @param belongYear + * @param expirationDate + * @param fromCardOrFlow + * @param ruleDetailid + * @param overtimeBalanceTimeBean + * @param list_index + * @param minimumUnit + * @param _hoursToDay + * @param overtimeLogMap + * @param timepoint_key + * @return + */ + 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 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; + } + /*插入调休时长*/ + 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) " + + "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + flag = recordSet.executeUpdate(sql, leaveRulesId, resourceId, _belongYear, _belongMonth, 0, extraAmount, 0, 0, 0, 0, 0, expirationDate, date, fromCardOrFlow.equals("0") ? "3" : "4", 0); + 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; + } + + /** + * 按加班时长范围设置转调休时长 + * @param date + * @param leaveRulesId + * @param resourceId + * @param belongYear + * @param expirationDate + * @param fromCardOrFlow + * @param ruleDetailid + * @param min_durationOfOvertime + * @param minimumUnit + * @param _hoursToDay + * @return + */ + 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 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"; + } + /*插入调休时长*/ + 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) " + + "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + flag = recordSet.executeUpdate(sql, leaveRulesId, resourceId, _belongYear, _belongMonth, 0, extraAmount, 0, 0, 0, 0, 0, expirationDate, date, fromCardOrFlow.equals("0") ? "3" : "4", 0); + 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; + } + + /** + * 按加班时长比例转调休时长 + * @param kqOvertimeRulesDetailEntity + * @param _durationOfOvertime + * @param date + * @param leaveRulesId + * @param resourceId + * @param belongYear + * @param expirationDate + * @param fromCardOrFlow + * @return + */ + private static Map save_paidLeaveEnableDefaultType1( + KQOvertimeRulesDetailEntity kqOvertimeRulesDetailEntity, + BigDecimal _durationOfOvertime, String date, String leaveRulesId, String resourceId, + String belongYear, String expirationDate, String fromCardOrFlow) { + 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"; + } + /*插入调休时长*/ + 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) " + + "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + flag = recordSet.executeUpdate(sql, leaveRulesId, resourceId, _belongYear, _belongMonth, 0, extraAmount, 0, 0, 0, 0, 0, expirationDate, date, fromCardOrFlow.equals("0") ? "3" : "4", 0); + 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(); + //[调休]的假期类型的ID + String leaveRulesId = ""; + //找到[调休]的假期类型ID + rulesComInfo.setTofirstRow(); + while (rulesComInfo.next()) { + if (KQLeaveRulesBiz.isTiaoXiu(rulesComInfo.getId())) { + 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=? where id=?"; + result = recordSet.executeUpdate(sql, durationOfLeave.setScale(5, RoundingMode.HALF_UP).doubleValue(), 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; + } + + /** + * 累加已用的假期时长 + * + * @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 { + /*获取当前日期,当前时间*/ + 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); + + /****************************************************************************************************************/ + + //假期类型缓存类 + 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)); + //扣减优先级:1-法定年假、2-福利年假 + int priority = Util.getIntValue(detailComInfo.getPriority(ruleId, subcompanyId), 1); + + /****************************************************************************************************************/ + + //如果请假开始日期为空,默认取请假日期 + fromDateDb = date; + + //员工假期余额变更记录 + 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) { + 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 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 belongYear asc,expirationDate asc,id asc "; + } + } + recordSet.executeQuery(sql); + int total = recordSet.getCounts(); + int index = 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) { + continue; + } + //基数 + 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) { + continue; + } + } else { + if (baseAmount.add(extraAmount).add(tiaoxiuAmount).subtract(usedAmount).doubleValue() <= 0) { + continue; + } + } + + //员工假期余额使用记录 + 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) + " where id=" + id; + updateList.add(updateSql); + + usageHistoryEntity.setNewUsedAmount(newUsedAmount); + usageHistoryEntity.setBalanceOfLeaveId(id); + 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) + " where id=" + id; + updateList.add(updateSql); + + usageHistoryEntity.setNewUsedAmount(newUsedAmount); + usageHistoryEntity.setNewUsedAmount2(newUsedAmount2); + usageHistoryEntity.setBalanceOfLeaveId(id); + 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) + " where id=" + id; + updateList.add(updateSql); + + usageHistoryEntity.setNewUsedAmount(newUsedAmount); + usageHistoryEntity.setNewUsedAmount2(newUsedAmount2); + usageHistoryEntity.setBalanceOfLeaveId(id); + 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) + " 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) + " 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) + " where id=" + id; + updateList.add(updateSql); + + usageHistoryEntity.setNewUsedAmount2(newUsedAmount2); + usageHistoryEntity.setNewUsedAmount(newUsedAmount); + usageHistoryEntity.setBalanceOfLeaveId(id); + 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) + " where id=" + id; + updateList.add(updateSql); + + usageHistoryEntity.setNewUsedAmount2(newUsedAmount2); + usageHistoryEntity.setNewUsedAmount(newUsedAmount); + usageHistoryEntity.setBalanceOfLeaveId(id); + 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) + " 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); + /*该假期剩余假期余额不足以扣减,记录错误日志,退出方法*/ + 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) + " where id=" + id; + updateList.add(updateSql); + + usageHistoryEntity.setNewUsedAmount(newUsedAmount); + usageHistoryEntity.setBalanceOfLeaveId(id); + break; + } + if (temp.doubleValue() >= 0) { + String newUsedAmount = usedAmount.add(_duration).setScale(5, RoundingMode.HALF_UP).toPlainString(); + String updateSql = "update kq_balanceOfLeave set usedAmount=" + (newUsedAmount) + " where id=" + id; + updateList.add(updateSql); + + usageHistoryEntity.setNewUsedAmount(newUsedAmount); + usageHistoryEntity.setBalanceOfLeaveId(id); + 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) + " where id=" + id; + updateList.add(updateSql); + + usageHistoryEntity.setNewUsedAmount(newUsedAmount); + usageHistoryEntity.setBalanceOfLeaveId(id); + continue; + } + } + } + + logger.info("requestId:"+requestId+"::updateList:"+updateList); + /*SQL操作批处理*/ + for (int i = 0; i < updateList.size(); i++) { + flag = recordSet.executeUpdate(updateList.get(i)); + 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) { + 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(); + //分部 + String subcompanyId = resourceComInfo.getSubCompanyID(resourceId); + + /****************************************************************************************************************/ + logger.info("reduceUsedAmount:resourceId:"+resourceId+":fromdatedb:"+date+":newLeaveType:"+ruleId+":duration:"+duration+":requestid:"+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)); + //扣减优先级:1-法定年假、2-福利年假 + int priority = Util.getIntValue(detailComInfo.getDistributionMode(ruleId, subcompanyId)); + + /****************************************************************************************************************/ + + logger.info("reduceUsedAmount:distributionMode:"+distributionMode+":priority:"+priority); + + //员工假期余额变更记录 + KQUsageHistoryEntity usageHistoryEntity = new KQUsageHistoryEntity(); + + List usageHistoryEntityList = new ArrayList(); + + 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(distributionMode == 5){ + 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 + " 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 + " 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 + " 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 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 + " 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 + " 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 + " 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 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 + " 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 + " 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 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)); + 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 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 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); + sql += " and " + Util.getSubINClause(allRightSubComIds, "subCompanyId1", "in"); + } + 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")); + /*获取人员的相关信息 end*/ + + /*获取人员所属分部对应的假期规则 start*/ + rulesDetailId = detailComInfo.getId(ruleId, subCompanyId); + distributionMode = Util.getIntValue(detailComInfo.getDistributionMode(ruleId, subCompanyId), 1); + legalKey = Util.getIntValue(detailComInfo.getLegalKey(ruleId, subCompanyId), 0); + welfareKey = Util.getIntValue(detailComInfo.getWelfareKey(ruleId, subCompanyId), 1); + annualAmount = Util.getDoubleValue(detailComInfo.getAnnualAmount(ruleId, subCompanyId), 0.00); + calcMethod = Util.getIntValue(detailComInfo.getCalcMethod(ruleId, subCompanyId), 0); + convertMode = Util.getIntValue(detailComInfo.getConvertMode(ruleId, subCompanyId), 0); + decimalDigit = Util.getIntValue(detailComInfo.getDecimalDigit(ruleId, subCompanyId), 2); + excludeSubAccount = Util.getIntValue(detailComInfo.getExcludeSubAccount(ruleId, subCompanyId), 1); + beforeFormal = Util.getIntValue(detailComInfo.getBeforeFormal(ruleId, subCompanyId), 1); + /*获取人员所属分部对应的假期规则 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); + //封装参数 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) { + Map baseAmountMaps = getBaseAmountByDis8(params); + baseAmount = (Double) baseAmountMaps.get("baseAmount"); + addOrUpdate = (boolean) baseAmountMaps.get("addOrUpdate"); + expirationDate = (String) baseAmountMaps.get("expirationDate"); + belongYearNew = (String) baseAmountMaps.get("belongYearNew"); + if(addOrUpdate&&!belongYearNew.equals("")){ + belongYear = belongYearNew; + } + } + + 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) { + //但是如果假期基数、额外、已休都是0,允许重新计算 + if (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; + } + } + } + if(addOrUpdate){ + if (currentDate.compareTo(expirationDate) != 0) { + 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.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 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 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)); + //余额发放方式 + int distributionMode = Util.getIntValue(detailComInfo.getDistributionMode(ruleId, subCompanyId), 1); + //年假基数计算方式: + // 0-假期基数发放日期和假期基数变动日期均为每年的01月01号(但是假期基数是结合 司龄/工龄 变化前后的值按天数比例折算出来的)、 + // 1-假期基数发放日期和假期基数变动日期均为每年的01月01号、 + // 2-假期基数发放日期发放日期为每年的01月01号,假期基数的变动日期为每年的 入职日期/参加工作日期 + int calcMethod = Util.getIntValue(detailComInfo.getCalcMethod(ruleId, subCompanyId), 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 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)); + //余额发放方式 + int distributionMode = Util.getIntValue(detailComInfo.getDistributionMode(ruleId, subCompanyId), 1); + //年假基数计算方式: + // 0-假期基数发放日期和假期基数变动日期均为每年的01月01号(但是假期基数是结合 司龄/工龄 变化前后的值按天数比例折算出来的)、 + // 1-假期基数发放日期和假期基数变动日期均为每年的01月01号、 + // 2-假期基数发放日期发放日期为每年的01月01号,假期基数的变动日期为每年的 入职日期/参加工作日期 + int calcMethod = Util.getIntValue(detailComInfo.getCalcMethod(ruleId, subCompanyId), 1); + // + int legalKey = Util.getIntValue(detailComInfo.getLegalKey(ruleId, subCompanyId), 0); + // + int welfareKey = Util.getIntValue(detailComInfo.getWelfareKey(ruleId, subCompanyId), 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(companyStartDate.substring(4).compareTo(workStartDate.substring(4)) <= 0){ + ageLimitChangeDatetemp = belongYear + workStartDate.substring(4); + }else{ + ageLimitChangeDatetemp = belongYear + companyStartDate.substring(4); + } + } + 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 currentYear = currentDate.substring(0, 4); + //批处理年份 + String belongYear = Util.null2String(params.get("belongYear")); + String belongYearNew = ""; + //当[distributionMode]=[8-每年发放固定天数]时有效 + double annualAmount = Util.getDoubleValue("" + params.get("annualAmount"), 0); + + 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; + + /* + * 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<=2){ + baseAmount = new BigDecimal("" + annualAmount); + }else{ + baseAmount = new BigDecimal("0"); + } +//第二个孩子的情况 + if(!expirationDate.equals("")&& belongYear.compareTo(expirationDate.substring(0, 4)) == 0){ + if(baseAmountReleaseDate.compareTo(expirationDate) > 0){ + if(date4CalcAmount.compareTo(expirationDate) > 0&&date4CalcAmount.compareTo(baseAmountReleaseDate) < 0){ + belongYearNew = (Util.getIntValue(belongYear) - 1) + ""; + addOrUpdate = true; + expirationDateNew = date4CalcAmount; + continue; + }else if(date4CalcAmount.compareTo(expirationDate) <= 0){ + baseAmount = new BigDecimal("0"); + continue; + } + }else{ + if(date4CalcAmount.compareTo(expirationDate) > 0){ + break; + }else{ + baseAmount = new BigDecimal("0"); + continue; + } + } + } + + expirationDate = (Util.getIntValue(yearOfBirth) + 3) + dateOfBirth.substring(4); + + if(ageLimit>=0&&ageLimit<=2){ + }else{ + baseAmount = new BigDecimal("0"); + continue; + } + + //批处理日期>=假期基数释放日期--出生日期 + if (date4CalcAmount.compareTo(baseAmountReleaseDate) >= 0) { + } else { + baseAmount = new BigDecimal("0"); + } + break; + } + + + 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; + } + + /** + * 获取调休的余额 + * + * @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; + } + + /** + * 插入或者更新员工假期余额 + * + * @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); + + String insertSql = "insert into kq_balanceOfLeave(leaveRulesId,resourceId,belongYear,baseAmount,extraAmount,usedAmount,baseAmount2,extraAmount2,usedAmount2) " + + "values(?,?,?,?,?,?,?,?,?)"; + List insertList = new ArrayList(); + List insertParamList = new ArrayList(); + String updateSql = "update kq_balanceOfLeave set leaveRulesId=?,resourceId=?,belongYear=?,baseAmount=?,baseAmount2=? where id=?"; + String updateSql2 ="update kq_balanceOfLeave set leaveRulesId=?,resourceId=?,belongYear=?,baseAmount=?,baseAmount2=?,usedAmount=?,extraAmount=? 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()); + 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(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 + */ + private 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; + } + + +} diff --git a/src/com/engine/kq/biz/KQClearFormatPoolJob.java b/src/com/engine/kq/biz/KQClearFormatPoolJob.java new file mode 100644 index 0000000..6a204d9 --- /dev/null +++ b/src/com/engine/kq/biz/KQClearFormatPoolJob.java @@ -0,0 +1,19 @@ +package com.engine.kq.biz; + +import com.engine.kq.log.KQLog; +import weaver.interfaces.schedule.BaseCronJob; + +public class KQClearFormatPoolJob extends BaseCronJob { + private KQLog kqLog = new KQLog(); + @Override + public void execute() { + kqLog.info("begin do KQClearFormatPoolJob invoke ..."); + try { + KQFormatBiz kqFormatBiz = new KQFormatBiz(); + kqFormatBiz.clearFormatPool(); + kqLog.info("end do KQClearFormatPoolJob invoke ..."); + } catch (Exception e) { + kqLog.info(e); + } + } +} diff --git a/src/com/engine/kq/biz/KQFlowActiontBiz.java b/src/com/engine/kq/biz/KQFlowActiontBiz.java new file mode 100644 index 0000000..070c1ab --- /dev/null +++ b/src/com/engine/kq/biz/KQFlowActiontBiz.java @@ -0,0 +1,913 @@ +package com.engine.kq.biz; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.engine.kq.biz.chain.duration.WorkDayUnitSplitChain; +import com.engine.kq.biz.chain.duration.WorkDurationChain; +import com.engine.kq.biz.chain.duration.WorkHalfUnitSplitChain; +import com.engine.kq.biz.chain.duration.WorkHourUnitSplitChain; +import com.engine.kq.biz.chain.duration.WorkWholeUnitSplitChain; +import com.engine.kq.biz.chain.shiftinfo.ShiftInfoBean; +import com.engine.kq.entity.TimeScopeEntity; +import com.engine.kq.entity.WorkTimeEntity; +import com.engine.kq.enums.DurationTypeEnum; +import com.engine.kq.enums.KqSplitFlowTypeEnum; +import com.engine.kq.log.KQLog; +import com.engine.kq.wfset.attendance.manager.HrmAttProcSetManager; +import com.engine.kq.wfset.bean.SplitBean; +import com.engine.kq.wfset.util.KQFlowCardUtil; +import com.engine.kq.wfset.util.KQFlowEvectionUtil; +import com.engine.kq.wfset.util.KQFlowLeaveBackUtil; +import com.engine.kq.wfset.util.KQFlowLeaveUtil; +import com.engine.kq.wfset.util.KQFlowOtherUtil; +import com.engine.kq.wfset.util.KQFlowOutUtil; +import com.engine.kq.wfset.util.KQFlowOvertimeUtil; +import com.engine.kq.wfset.util.KQFlowProcessChangeUtil; +import com.engine.kq.wfset.util.KQFlowShiftUtil; +import com.engine.kq.wfset.util.KQFlowUtil; +import com.engine.kq.wfset.util.SplitActionUtil; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.Util; +import weaver.hrm.resource.ResourceComInfo; + +/** + * 考勤流程action相关数据处理类 + */ +public class KQFlowActiontBiz { + public KQLog kqLog = new KQLog(); + + /** + * 强制收回操作 + * @param requestId + */ + public void handleDel(int requestId) { + RecordSet rs = new RecordSet(); + try { + String updateFreezeSql = "update KQ_ATT_VACATION set status=2 where requestId=? "; + boolean isUpdate = rs.executeUpdate(updateFreezeSql,requestId); + }catch (Exception e){ + e.printStackTrace(); + rs.writeLog("handleDrawBack:删除action报错:"+e.getMessage()); + } + } + /** + * 强制收回操作 + * @param requestId + * @param workflowId + */ + public void handleDrawBack(int requestId, int workflowId) { + kqLog.writeLog("handleDrawBack:进入 强制收回:requestId:"+requestId+":workflowId:"+workflowId); + + RecordSet rs = new RecordSet(); + try { + String updateFreezeSql = "update KQ_ATT_VACATION set status=2 where requestId=? and workflowId = ? "; + boolean isUpdate = rs.executeUpdate(updateFreezeSql,requestId,workflowId); + kqLog.writeLog("handleDrawBack:强制收回isUpdate:"+isUpdate+":updateFreezeSql:"+updateFreezeSql+":requestId:"+requestId+":workflowId:"+workflowId); + }catch (Exception e){ + e.printStackTrace(); + kqLog.writeLog("handleDrawBack:强制收回action报错:"+e.getMessage()); + } + } + + /** + * 强制归档操作 + * @param requestId + * @param workflowId + */ + public void handleforceOver(int requestId, int workflowId) { + RecordSet rs = new RecordSet(); + try { + if(!KQSettingsBiz.isforceflow_attend()){ + return ; + } + 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")); + kqLog.info("handleforceOver:proc_set_id:"+proc_set_id+":kqtype:"+kqtype+":requestId:"+requestId); + Map map = new HashMap(); + if(requestId > 0){ + map.put("requestId", "and t.requestId = " + requestId); + } + Map result = handleKQFlowAction(proc_set_id,usedetails,requestId,kqtype,workflowId,true,false,map); + if(!result.isEmpty()){ + kqLog.info("handleforceOver:强制归档action失败:requestId:"+requestId+":workflowId:"+workflowId+":proc_set_id:"+proc_set_id); + } + } + }catch (Exception e){ + e.printStackTrace(); + kqLog.info("handleforceOver:强制归档action报错:"+e.getMessage()); + } + } + + public Map handleKQFlowAction(String proc_set_id, String usedetails, int requestId, int kqtype, + int workflowId,boolean isForce,boolean isUpgrade,Map map) throws Exception{ + Map result = new HashMap<>(); + ResourceComInfo rci = new ResourceComInfo(); + List splitBeans = new ArrayList(); + + DateTimeFormatter datetimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); + //生成处理的sql + Map sqlMap = handleSql(proc_set_id, usedetails, requestId,kqtype,map); + if(sqlMap != null && !sqlMap.isEmpty()){ + KqSplitFlowTypeEnum flowTypeEnum = null; + if(kqtype == KqSplitFlowTypeEnum.LEAVE.getFlowtype()){ + KQFlowLeaveUtil kqFlowLeaveUtil = new KQFlowLeaveUtil(); + result=kqFlowLeaveUtil.handleKQLeaveAction(sqlMap,splitBeans,datetimeFormatter,workflowId,requestId,rci); + flowTypeEnum = KqSplitFlowTypeEnum.LEAVE; + }else if(kqtype == KqSplitFlowTypeEnum.EVECTION.getFlowtype()){ + KQFlowEvectionUtil kqFlowEvectionUtil = new KQFlowEvectionUtil(); + result=kqFlowEvectionUtil.handleKQEvectionAction(sqlMap,splitBeans,datetimeFormatter,workflowId,requestId,rci); + flowTypeEnum = KqSplitFlowTypeEnum.EVECTION; + }else if(kqtype == KqSplitFlowTypeEnum.OUT.getFlowtype()){ + KQFlowOutUtil kqFlowOutUtil = new KQFlowOutUtil(); + result=kqFlowOutUtil.handleKQOutAction(sqlMap,splitBeans,datetimeFormatter,workflowId,requestId,rci); + flowTypeEnum = KqSplitFlowTypeEnum.OUT; + }else if(kqtype == KqSplitFlowTypeEnum.OVERTIME.getFlowtype()){ + KQFlowOvertimeUtil kqFlowOvertimeUtil = new KQFlowOvertimeUtil(); + result=kqFlowOvertimeUtil.handleKQOvertimeAction(sqlMap,splitBeans,datetimeFormatter,workflowId,requestId,rci,""); + flowTypeEnum = KqSplitFlowTypeEnum.OVERTIME; + }else if(kqtype == KqSplitFlowTypeEnum.SHIFT.getFlowtype()){ + KQFlowShiftUtil kqFlowShiftUtil = new KQFlowShiftUtil(); + kqFlowShiftUtil.handleKQShiftAction(sqlMap,splitBeans,datetimeFormatter,workflowId,requestId,rci); + flowTypeEnum = KqSplitFlowTypeEnum.SHIFT; + }else if(kqtype == KqSplitFlowTypeEnum.OTHER.getFlowtype()){ + KQFlowOtherUtil kqFlowOtherUtil = new KQFlowOtherUtil(); + result=kqFlowOtherUtil.handleKQOtherAction(sqlMap,splitBeans,datetimeFormatter,workflowId,requestId,rci); + flowTypeEnum = KqSplitFlowTypeEnum.OTHER; + }else if(kqtype == KqSplitFlowTypeEnum.CARD.getFlowtype()){ + KQFlowCardUtil kqFlowCardUtil = new KQFlowCardUtil(); + result=kqFlowCardUtil.handleKQCardAction(sqlMap,splitBeans,datetimeFormatter,workflowId,requestId,rci); + flowTypeEnum = KqSplitFlowTypeEnum.CARD; + }else if(kqtype == KqSplitFlowTypeEnum.LEAVEBACK.getFlowtype()){ + KQFlowLeaveBackUtil kqFlowLeaveBackUtil = new KQFlowLeaveBackUtil(); + result=kqFlowLeaveBackUtil.handleKQLeaveBackAction(sqlMap,splitBeans,datetimeFormatter,workflowId,requestId,rci); + flowTypeEnum = KqSplitFlowTypeEnum.LEAVEBACK; + }else if(kqtype == KqSplitFlowTypeEnum.PROCESSCHANGE.getFlowtype()){ + KQFlowProcessChangeUtil kqFlowProcessChangeUtil = new KQFlowProcessChangeUtil(); + result=kqFlowProcessChangeUtil.handleKQProcessChangeAction(sqlMap,splitBeans,datetimeFormatter,workflowId,requestId,rci); + flowTypeEnum = KqSplitFlowTypeEnum.PROCESSCHANGE; + }else{ + new BaseBean().writeLog("考勤流程没有找到对应类型:proc_set_id:"+proc_set_id+":requestId:"+requestId+":kqtype:"+kqtype); + } + if(!result.isEmpty()){ + if(!isUpgrade){ + return result; + } + } + if(!splitBeans.isEmpty() && flowTypeEnum != null){ + if(flowTypeEnum == KqSplitFlowTypeEnum.LEAVEBACK){ + KQFlowLeaveBackUtil kqFlowLeaveBackUtil = new KQFlowLeaveBackUtil(); + //销假流程需要再拆分下 + kqFlowLeaveBackUtil.handleSplitFLowActionData4LeaveBack(splitBeans,result,isUpgrade,requestId); + clear_flow_deduct_card(splitBeans,KqSplitFlowTypeEnum.LEAVEBACK.getFlowtype()+"",requestId); + }else if(flowTypeEnum == KqSplitFlowTypeEnum.PROCESSCHANGE){ + KQFlowProcessChangeUtil kqFlowProcessChangeUtil = new KQFlowProcessChangeUtil(); + kqFlowProcessChangeUtil.handleSplitFLowActionData4ProcessChange(splitBeans,result,isUpgrade,requestId); + }else if(flowTypeEnum != KqSplitFlowTypeEnum.CARD && flowTypeEnum != KqSplitFlowTypeEnum.SHIFT){ + KQFlowUtil kqFlowUtil = new KQFlowUtil(); + kqFlowUtil.handleSplitFLowActionData(splitBeans,flowTypeEnum,rci,result,isForce,requestId,workflowId,isUpgrade); + //流程抵扣打卡 + handle_flow_deduct_card(workflowId,splitBeans,requestId); + } + } + } + return result; + } + + /** + * 流程抵扣打卡逻辑 + * @param workflowId + * @param splitBeans + * @param requestId + */ + public void handle_flow_deduct_card(int workflowId, + List splitBeans, int requestId) { + KQAttProcSetComInfo kqAttProcSetComInfo = new KQAttProcSetComInfo(); + String flow_deduct_card = Util.null2String(kqAttProcSetComInfo.getFlow_deduct_card(""+workflowId)); + String kqType = Util.null2String(kqAttProcSetComInfo.getkqType(""+workflowId)); + kqLog.info("handle_flow_deduct_card:flow_deduct_card:"+ flow_deduct_card+":workflowId:"+workflowId+":requestId:"+requestId); + if("1".equalsIgnoreCase(flow_deduct_card)){ + do_flow_deduct_card(splitBeans,kqType,requestId); + }else{ +// 这里扩展个操作,如果没有开启就先把对应的requestid删除掉 + if(requestId > 0){ + RecordSet rs = new RecordSet(); + String sql1 = "select * from kq_flow_deduct_card where requestid = ? "; + rs.executeQuery(sql1,requestId); + List formateList = new ArrayList<>(); + while (rs.next()){ + String resourceid = rs.getString("resourceid"); + String belongdate = rs.getString("belongdate"); + String key = resourceid+"_"+belongdate; + formateList.add(key); + } + String sql = "delete from kq_flow_deduct_card where requestid = ? "; + rs.executeUpdate(sql, requestId); + kqLog.info("clear_flow_deduct_card:formateList:"+formateList); + for(String format: formateList){ + kqLog.info("clear_flow_deduct_card:format:"+ JSON.toJSONString(format)); + String[] formats = format.split("_"); + new KQFormatData().formatKqDate(formats[0],formats[1]); + } + } + } + } + + /** + * 销假流程 消除流程抵扣打卡 + * @param splitBeans + * @param kqType + * @param requestId + */ + public void clear_flow_deduct_card(List splitBeans, String kqType, int requestId) { + RecordSet rs = new RecordSet(); + RecordSet rs1 = new RecordSet(); + List clear_ids = new ArrayList<>(); + List formateList = new ArrayList<>(); + List updateParamList = new ArrayList(); + List updateList = new ArrayList(); + KQTimesArrayComInfo kqTimesArrayComInfo = new KQTimesArrayComInfo(); + for(SplitBean bean : splitBeans){ + String leavebackrequestid = bean.getLeavebackrequestid(); + String resourceId = bean.getResourceId(); + String belongDate = bean.getBelongDate(); + String fromdate = bean.getFromDate(); + String fromtime = bean.getFromTime(); + String todate = bean.getToDate(); + String totime = bean.getToTime(); + String key = resourceId+"_"+belongDate; + formateList.add(key); + int fromtimeIdx = kqTimesArrayComInfo.getArrayindexByTimes(fromtime); + int totimeIdx = kqTimesArrayComInfo.getArrayindexByTimes(totime); + String deduct_sql = "select * from kq_flow_deduct_card where requestid = '"+leavebackrequestid+"' and resourceId='"+resourceId+"' and belongDate='"+belongDate+"'"; + rs.executeQuery(deduct_sql); + while(rs.next()){ + String deduct_id = rs.getString("id"); + String signtype = rs.getString("signtype"); + String deduct_fromtime = rs.getString("fromtime"); + String deduct_totime = rs.getString("totime"); + int deduct_fromtimeIdx = kqTimesArrayComInfo.getArrayindexByTimes(deduct_fromtime); + int deduct_totimeIdx = kqTimesArrayComInfo.getArrayindexByTimes(deduct_totime); + updateList = new ArrayList(); + if("1".equalsIgnoreCase(signtype)){ + if(fromtimeIdx == deduct_fromtimeIdx && !clear_ids.contains(deduct_id)){ + clear_ids.add(deduct_id); + updateList.add(deduct_id); + updateParamList.add(updateList); + } + }else if("2".equalsIgnoreCase(signtype)){ + if(totimeIdx == deduct_totimeIdx && !clear_ids.contains(deduct_id)){ + clear_ids.add(deduct_id); + updateList.add(deduct_id); + updateParamList.add(updateList); + } + } + } + } + kqLog.info("clear_flow_deduct_card:clear_ids:"+ clear_ids.size()); +// if(!clear_ids.isEmpty()){ +// for(String id : clear_ids){ +// String sql = "update kq_flow_deduct_card set isclear=1 where id = "+id; +// rs1.executeUpdate(sql); +// } + /*更新抵扣打卡数据 start*/ + boolean isSuccess = true; + String updateSql = "update kq_flow_deduct_card set isclear=1 where id=?"; + if (updateParamList.size() > 0) { + isSuccess = rs1.executeBatchSql(updateSql, updateParamList); + kqLog.info("clear_flow_deduct_card:formateList:"+formateList); + for(String format: formateList){ + kqLog.info("clear_flow_deduct_card:format:"+ JSON.toJSONString(format)); + String[] formats = format.split("_"); + new KQFormatData().formatKqDate(formats[0],formats[1]); + } + } + /*更新抵扣打卡数据 end*/ + +// } + } + + /** + * 流程抵扣打卡逻辑 + * @param splitBeans + * @param kqType + * @param requestId + */ + public void do_flow_deduct_card(List splitBeans, String kqType, int requestId) { + RecordSet rs = new RecordSet(); + RecordSet rs1 = new RecordSet(); + String batchSql = "insert into kq_flow_deduct_card(requestid,resourceid,belongDate,fromdate,fromtime,todate,totime,workBeginTime,workEndTime,signtype,flowtype,serialnumber)"+ + " values(?,?,?,?,?,?,?,?,?,?,?,?) "; + List params = new ArrayList(); + List formateList = new ArrayList<>(); + kqLog.info("handle_flow_deduct_card:splitBeans:"+ JSON.toJSONString(splitBeans)); + for(SplitBean bean : splitBeans){ + do_flow_deduct_in_table(bean,formateList,params,kqType,requestId, ""); + + if(Util.getIntValue(kqType) == KqSplitFlowTypeEnum.EVECTION.getFlowtype()){ + String companion = Util.null2s(bean.getCompanion(), ""); + if(companion.length() > 0){ + String[] companions = companion.split(","); + if(companions != null && companions.length > 0 ) { + for (int i = 0; i < companions.length; i++) { + String compan_resid = companions[i]; + if(bean.getResourceId().equalsIgnoreCase(compan_resid)){ + //陪同人是自己的不要存到中间表里 + continue; + } + do_flow_deduct_in_table(bean,formateList,params,kqType,requestId,compan_resid); + } + } + } + } + } + if(!params.isEmpty()) { + //先根据requestid删除中间表里的数据,再做啥插入操作 + String delSql = "delete from kq_flow_deduct_card where requestid = " + requestId; + rs.executeUpdate(delSql); + boolean isOk = rs1.executeBatchSql(batchSql, params); + if(!isOk){ + kqLog.info("do_flow_deduct_card:requestId:"+requestId+":kq_flow_deduct_card error:"+params); + return ; + } + kqLog.info("do_flow_deduct_card:formateList:"+formateList); + for(String format: formateList){ + kqLog.info("do_flow_deduct_card:format:"+ JSON.toJSONString(format)); + String[] formats = format.split("_"); + new KQFormatData().formatKqDate(formats[0],formats[1]); + } + }else{ + if(!splitBeans.isEmpty()){ + //有流程数据,但是签到签退都不包含的情况,支持多次归档,所以需要先删除再插入 + String delSql = "delete from kq_flow_deduct_card where requestid = " + requestId; + rs.executeUpdate(delSql); + } + } + } + + /** + * 流程抵扣打卡数据整合到表里 + * @param bean + * @param formateList + * @param params + * @param kqType + * @param requestId + * @param compan_resid 出差流程的陪同人 + */ + public void do_flow_deduct_in_table(SplitBean bean, List formateList, + List params, String kqType, int requestId, String compan_resid) { + KQWorkTime kqWorkTime = new KQWorkTime(); + KQTimesArrayComInfo kqTimesArrayComInfo = new KQTimesArrayComInfo(); + String resourceId = bean.getResourceId(); + if(compan_resid.length() > 0 && Util.getIntValue(kqType) == KqSplitFlowTypeEnum.EVECTION.getFlowtype()){ + resourceId = compan_resid; + } + String belongDate = bean.getBelongDate(); + String fromdate = bean.getFromDate(); + String fromtime = bean.getFromTime(); + String todate = bean.getToDate(); + String totime = bean.getToTime(); + boolean oneSign = false; + WorkTimeEntity workTime = kqWorkTime.getWorkTime(resourceId, belongDate); + String key = resourceId+"_"+belongDate; + formateList.add(key); + List lsWorkTime = new ArrayList<>(); + List lsSignTime = new ArrayList<>(); + if (workTime != null) { + lsWorkTime = workTime.getWorkTime();//工作时间 + lsSignTime = workTime.getSignTime();//允许打卡时间 + oneSign = lsWorkTime!=null&&lsWorkTime.size()==1; + for (int i = 0; lsWorkTime != null && i < lsWorkTime.size(); i++) { + TimeScopeEntity workTimeScope = lsWorkTime.get(i); + String workBeginTime = Util.null2String(workTimeScope.getBeginTime()); + int workBeginIdx = kqTimesArrayComInfo.getArrayindexByTimes(workBeginTime); + boolean workBenginTimeAcross = workTimeScope.getBeginTimeAcross(); + String workEndTime = Util.null2String(workTimeScope.getEndTime()); + int workEndIdx = kqTimesArrayComInfo.getArrayindexByTimes(workEndTime); + boolean workEndTimeAcross = workTimeScope.getEndTimeAcross(); + int[] dayMins = new int[2880];//一天所有分钟数 + int beginIdx = kqTimesArrayComInfo.getArrayindexByTimes(Util.null2String(fromtime)); + int endIdx = kqTimesArrayComInfo.getArrayindexByTimes(Util.null2String(totime)); + if(beginIdx > endIdx){ + continue; + } + if(oneSign){ + boolean is_flow_humanized = KQSettingsBiz.is_flow_humanized(); + if(is_flow_humanized){ + //个性化设置只支持一天一次上下班 + ShiftInfoBean shiftInfoBean = new ShiftInfoBean(); + Map shifRuleMap = Maps.newHashMap(); + shiftInfoBean.setSplitDate(belongDate); + shiftInfoBean.setShiftRuleMap(workTime.getShiftRuleInfo()); + shiftInfoBean.setSignTime(lsSignTime); + shiftInfoBean.setWorkTime(lsWorkTime); + KQShiftRuleInfoBiz.getShiftRuleInfo(shiftInfoBean, resourceId, shifRuleMap); + if(!shifRuleMap.isEmpty()){ + 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); + } + } + 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); + } + } + } + } + } + if(Util.getIntValue(kqType) == KqSplitFlowTypeEnum.EVECTION.getFlowtype()){ + Arrays.fill(dayMins, beginIdx, endIdx, 7);//出差抵扣时段标识 7 + }else if(Util.getIntValue(kqType) == KqSplitFlowTypeEnum.OUT.getFlowtype()){ + Arrays.fill(dayMins, beginIdx, endIdx, 8);//公出抵扣时段标识 8 + }else if(Util.getIntValue(kqType) == KqSplitFlowTypeEnum.LEAVE.getFlowtype()){ + if (endIdx > beginIdx) { + Arrays.fill(dayMins, beginIdx, endIdx, 5);//流程抵扣时段标识 5 + } + }else{ + if (endIdx > beginIdx) { + Arrays.fill(dayMins, beginIdx, endIdx, 99);//异常流程抵扣时段标识99 + } + } + + int cnt_7 = kqTimesArrayComInfo.getCnt(dayMins, workBeginIdx, workEndIdx, 7); + int cnt_8 = kqTimesArrayComInfo.getCnt(dayMins, workBeginIdx, workEndIdx, 8); + int cnt_5 = kqTimesArrayComInfo.getCnt(dayMins, workBeginIdx, workEndIdx, 5); + int cnt_99 = kqTimesArrayComInfo.getCnt(dayMins, workBeginIdx, workEndIdx, 99); + //流程时长大于0的才去做流程抵扣的处理 + if(cnt_7 > 0 || cnt_8 > 0 || cnt_5 > 0 || cnt_99 > 0){ + //如果流程时长大于0 结束时间因为是下标,需要补1分钟 + if(Util.getIntValue(kqType) == KqSplitFlowTypeEnum.EVECTION.getFlowtype()){ + Arrays.fill(dayMins, endIdx, endIdx+1, 7);//出差抵扣时段标识 7 + }else if(Util.getIntValue(kqType) == KqSplitFlowTypeEnum.OUT.getFlowtype()){ + Arrays.fill(dayMins, endIdx, endIdx+1, 8);//公出抵扣时段标识 8 + }else if(Util.getIntValue(kqType) == KqSplitFlowTypeEnum.LEAVE.getFlowtype()){ + Arrays.fill(dayMins, endIdx, endIdx+1, 5);//流程抵扣时段标识 5 + }else{ + Arrays.fill(dayMins, endIdx, endIdx+1, 99);//异常流程抵扣时段标识99 + } + + if(dayMins[workBeginIdx]>=5){//签到时间点有流程 + List beanParams = new ArrayList(); + beanParams.add(requestId); + beanParams.add(resourceId); + beanParams.add(belongDate); + beanParams.add(fromdate); + beanParams.add(fromtime); + beanParams.add(todate); + beanParams.add(totime); + beanParams.add(workBeginTime); + beanParams.add(workEndTime); + beanParams.add("1"); + beanParams.add(kqType); + beanParams.add(i); + params.add(beanParams); + } + + if(dayMins[workEndIdx]>=5){//签退时间点有流程 + List beanParams = new ArrayList(); + beanParams.add(requestId); + beanParams.add(resourceId); + beanParams.add(belongDate); + beanParams.add(fromdate); + beanParams.add(fromtime); + beanParams.add(todate); + beanParams.add(totime); + beanParams.add(workBeginTime); + beanParams.add(workEndTime); + beanParams.add("2"); + beanParams.add(kqType); + beanParams.add(i); + params.add(beanParams); + } + }else{ + kqLog.info("handle_flow_deduct_card::i:"+i+":workBeginIdx:"+ workBeginIdx+":workEndIdx:"+ workEndIdx + +":cnt_7:"+cnt_7+":cnt_8:"+cnt_8+":cnt_5:"+cnt_5+":cnt_99:"+cnt_99); + } + } + }else{ + kqLog.info("handle_flow_deduct_card:workTime is null :resourceId:"+ resourceId+":belongDate:"+belongDate); + } + } + + + /** + * 拆分请假数据 生成splitBeans + * @param sqlMap + * @param splitBeans + * @param datetimeFormatter + * @param workflowId + * @param requestId + * @param rci + * @param durationTypeEnum + * @return + * @throws Exception + */ + public Map handleAction(Map sqlMap, + List splitBeans, DateTimeFormatter datetimeFormatter, int workflowId, + int requestId, ResourceComInfo rci,DurationTypeEnum durationTypeEnum) throws Exception{ + RecordSet rs1 = new RecordSet(); + KQFlowUtil kqFlowUtil = new KQFlowUtil(); + Map result = new HashMap<>(); + + if(!sqlMap.isEmpty()){ + for(Map.Entry me : sqlMap.entrySet()){ + String key = me.getKey(); + String value = me.getValue(); + + rs1.execute(value); + while (rs1.next()) { + SplitBean splitBean = new SplitBean(); + boolean isFillRight = kqFlowUtil.fillSplitBean(splitBean, rs1, ""+requestId, rci, ""+workflowId, durationTypeEnum,key,result,datetimeFormatter, + ""); + if(!isFillRight){ + new BaseBean().writeLog("升级失败:"+requestId+";;result>>>"+JSONObject.toJSONString(result)); + continue ; + } + if(result.containsKey("isProcessDrawBack")){ + result.clear(); + splitBeans.add(splitBean); + }else{ + doWorkSplitChain(splitBean, splitBeans); + } + + if(durationTypeEnum == DurationTypeEnum.EVECTION){ + String companion = Util.null2s(splitBean.getCompanion(), ""); + if(companion.length() > 0){ + List companionList = Util.splitString2List(companion,","); + for(int i = 0 ; i < companionList.size() ; i++){ + String be_companion = Util.null2String(companionList.get(i)); + if(be_companion.length() > 0 && Util.getIntValue(be_companion) > 0){ + SplitBean compSplitBean = new SplitBean(); + boolean compFillRight = kqFlowUtil.fillSplitBean(compSplitBean, rs1, ""+requestId, + rci, ""+workflowId, durationTypeEnum,key,result,datetimeFormatter, ""); + if(!compFillRight){ + return result; + } + if(splitBean.getResourceId().equalsIgnoreCase(be_companion)){ + //陪同人是自己的不要存到中间表里 + continue; + } + compSplitBean.setResourceId(be_companion); + compSplitBean.setSubcompanyid(Util.null2s(rci.getSubCompanyID(be_companion),"0")); + compSplitBean.setDepartmentid(Util.null2s(rci.getDepartmentID(be_companion),"0")); + compSplitBean.setJobtitle(Util.null2s(rci.getJobTitle(be_companion),"0")); + compSplitBean.setIscompanion("1"); + compSplitBean.setCompanion(""); + + if(result.containsKey("isProcessDrawBack")){ + result.clear(); + splitBeans.add(compSplitBean); + }else{ + doWorkSplitChain(compSplitBean, splitBeans); + } + } + } + } + } + } + } + } + return result; + } + + /** + * 生成处理的sql + * @param proc_set_id + * @param usedetails + * @param requestidInt + * @return + */ + public Map handleSql(String proc_set_id,String usedetails,int requestidInt,int kqtype,Map map) { + HrmAttProcSetManager hrmAttProcSetManager= new HrmAttProcSetManager(); + Map sqlMap = new HashMap<>(); + sqlMap = hrmAttProcSetManager.getSQLByField006Map(kqtype, map, false, true, proc_set_id,usedetails); + + return sqlMap; + } + + /** + * 计算工作时长拆分 + * @param splitBean + * @param splitBeans + * @throws Exception + */ + public void doWorkSplitChain(SplitBean splitBean,List splitBeans) throws Exception{ + + WorkDurationChain hourUnitSplitChain = new WorkHourUnitSplitChain(splitBeans); + WorkDurationChain dayUnitSplitChain = new WorkDayUnitSplitChain(splitBeans); + WorkDurationChain halfUnitSplitChain = new WorkHalfUnitSplitChain(splitBeans); + WorkDurationChain wholeUnitSplitChain = new WorkWholeUnitSplitChain(splitBeans); + + //设置执行链 + hourUnitSplitChain.setDurationChain(dayUnitSplitChain); + dayUnitSplitChain.setDurationChain(halfUnitSplitChain); + halfUnitSplitChain.setDurationChain(wholeUnitSplitChain); + //把初始数据设置进去 + hourUnitSplitChain.handleDuration(splitBean); + } + + /** + * 测试流程,删除测试数据的同时 + * 1、需要把冻结数据释放 + * 2、中间表数据清除 + * 3、格式化考勤报表 + * @param temprequestid + * @param workflowid + */ + public void delTest(int temprequestid, String workflowid,String from) { + RecordSet rs = new RecordSet(); + RecordSet rs1 = new RecordSet(); + RecordSet rs2 = new RecordSet(); + RecordSet rs3 = new RecordSet(); + try { + + kqLog.info("KQFlowActiontBiz delTest:workflowid:"+workflowid+":from:"+from); + if(Util.null2s(workflowid,"").length() == 0){ + return ; + } + + String getkqType = "select * from kq_att_proc_set where field001=? "; + rs.executeQuery(getkqType,workflowid); + if(rs.next()){ + boolean isCard = false; + boolean isOvertime = false; + boolean isLeave = false; + String tablename = ""; + int kqtype= Util.getIntValue(rs.getString("field006"),-1); + if(kqtype == KqSplitFlowTypeEnum.LEAVE.getFlowtype()){ + tablename = KqSplitFlowTypeEnum.LEAVE.getTablename(); + isLeave = true; + }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(); + isOvertime = true; + }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(); + isCard = true; + }else if(kqtype == KqSplitFlowTypeEnum.LEAVEBACK.getFlowtype()){ + tablename = KqSplitFlowTypeEnum.LEAVEBACK.getTablename(); + }else{ + new BaseBean().writeLog("删除测试流程异常,未找到考勤流程类型:workflowid:"+workflowid); + } + if(tablename.length() > 0){ + KQFormatBiz kqFormatBiz = new KQFormatBiz(); + + List formateList = new ArrayList<>(); + if(isCard){ + String signfrom_param = "|requestid|"+temprequestid; + String selTableSql = "select * from hrmschedulesign where signfrom like ? "; + rs2.executeQuery(selTableSql,"%"+signfrom_param+"%"); + while (rs2.next()){ + String userid = rs2.getString("userid"); + String signdate = rs2.getString("signdate"); + String key = userid+"_"+signdate; + formateList.add(key); + } + kqLog.info("KQFlowActiontBiz isCard delTest:formateList:"+formateList); + + String delTableSql = "delete from hrmschedulesign where signfrom like ? "; + boolean isUpdate = rs3.executeUpdate(delTableSql,"%"+signfrom_param+"%"); + kqLog.info("KQFlowActiontBiz isCard delTest:delTableSql:"+delTableSql+":temprequestid:"+temprequestid+":isUpdate:"+isUpdate); + if(isUpdate){ + for(String formateStr : formateList){ + String[] formateStrs = formateStr.split("_"); + new KQFormatData().formatKqDate(formateStrs[0],formateStrs[1]); + } + } + }else if(isOvertime){ + SplitActionUtil.clearSameRequestTX(temprequestid+""); + String delTableSql = "delete from "+tablename+" where requestId= ? "; + boolean isUpdate = rs2.executeUpdate(delTableSql,temprequestid); + kqLog.info("KQFlowActiontBiz delTest:delTableSql:"+delTableSql+":temprequestid:"+temprequestid+":isUpdate:"+isUpdate); + }else{ + List backsplitBeans = new ArrayList<>(); + String sql = "select * from "+tablename+" where requestId= ? "; + rs2.executeQuery(sql, temprequestid); + kqLog.info("KQFlowActiontBiz delTest:sql:"+sql+":requestId:"+temprequestid+":counts:"+rs2.getCounts()); + while (rs2.next()){ + String resourceid = rs2.getString("resourceid"); + String belongdate = rs2.getString("belongdate"); + String key = resourceid+"_"+belongdate; + formateList.add(key); + if(isLeave) { + SplitBean splitBean = new SplitBean(); + String requestid = rs2.getString("requestid"); + String newLeaveType = rs2.getString("newleavetype"); + String duration = rs2.getString("duration"); + String durationrule = rs2.getString("durationrule"); + String fromdatedb = rs2.getString("fromdatedb"); + splitBean.setRequestId(requestid); + splitBean.setResourceId(resourceid); + splitBean.setNewLeaveType(newLeaveType); + splitBean.setDuration(duration); + splitBean.setDurationrule(durationrule); + splitBean.setFromdatedb(fromdatedb); + backsplitBeans.add(splitBean); + } + } + kqLog.info("KQFlowActiontBiz delTest:isLeave:"+isLeave+":backsplitBeans:"+JSON.toJSONString(backsplitBeans)); + String delTableSql = "delete from "+tablename+" where requestId= ? "; + boolean isUpdate = rs2.executeUpdate(delTableSql,temprequestid); + kqLog.info("KQFlowActiontBiz delTest:delTableSql:"+delTableSql+":temprequestid:"+temprequestid+":isUpdate:"+isUpdate); + //如果有流程抵扣,删除对应流程抵扣的数据 + String delSql = "delete from kq_flow_deduct_card where requestid = ? "; + isUpdate = rs3.executeUpdate(delSql,temprequestid); + kqLog.info("KQFlowActiontBiz delTest:delSql:"+delSql+":temprequestid:"+temprequestid+":isUpdate:"+isUpdate); + + kqLog.info("KQFlowActiontBiz delTest:formateList:"+formateList); + for(String formateStr : formateList){ + String[] formateStrs = formateStr.split("_"); + new KQFormatData().formatKqDate(formateStrs[0],formateStrs[1]); + } + if(isLeave) { + for (SplitBean splitBean : backsplitBeans) { + String requestid = splitBean.getRequestId(); + String resourceId = splitBean.getResourceId(); + String newLeaveType = splitBean.getNewLeaveType(); + String duration = splitBean.getDuration(); + String durationrule = splitBean.getDurationrule(); + String fromdatedb = splitBean.getFromdatedb(); + boolean isLeaveFlowOver = isLeaveFlowOver(requestid); + kqLog.info("isLeaveFlowOver:"+isLeaveFlowOver); + if (isLeaveFlowOver) { + kqLog.info("流程退回后主动返还假期:delTest:resourceId:" + resourceId + ":duration:" + duration + ":newLeaveType:" + newLeaveType + ":durationrule:" + durationrule + ":requestid:" + requestid + ":fromdatedb:" + fromdatedb); + KQBalanceOfLeaveBiz.reduceUsedAmount(resourceId, fromdatedb, newLeaveType, duration, "", requestid); + } + } + String updateFreezeSql = "update KQ_ATT_VACATION set status=2 where requestId=? "; + isUpdate = rs1.executeUpdate(updateFreezeSql,temprequestid); + kqLog.info("KQFlowActiontBiz delTest:updateFreezeSql:"+updateFreezeSql+":temprequestid:"+temprequestid+":isUpdate:"+isUpdate); + } + } + } + } + }catch (Exception e){ + e.printStackTrace(); + rs.writeLog("KQFlowActiontBiz delTest:temprequestid:"+temprequestid+":workflowid:"+workflowid+":报错:"+e.getMessage()); + } + } + + /** + * 看下请假流程是不是已经归档并生成了扣减 + * @param requestId + * @return + */ + private boolean isLeaveFlowOver(String requestId) { + RecordSet rs = new RecordSet(); + String sql = "select * from kq_UsageHistory where wfRequestId=?"; + rs.executeQuery(sql, requestId); + boolean isOver = false; + if(rs.next()) { + isOver = true; + } + return isOver; + } + + /** + * 拆分请假数据 生成splitBeans + * @param sqlMap + * @param splitBeans + * @param datetimeFormatter + * @param workflowId + * @param requestId + * @param rci + * @return + * @throws Exception + */ + public Map handleKQLeaveAction(Map sqlMap, + List splitBeans, DateTimeFormatter datetimeFormatter, int workflowId, + int requestId, ResourceComInfo rci) throws Exception{ + KQFlowLeaveUtil kqFlowLeaveUtil = new KQFlowLeaveUtil(); + return kqFlowLeaveUtil.handleKQLeaveAction(sqlMap,splitBeans,datetimeFormatter,workflowId,requestId,rci); + } + + /** + * 拆分出差数据 生成splitBeans + * @param sqlMap + * @param splitBeans + * @param datetimeFormatter + * @param workflowId + * @param requestId + * @param rci + * @return + * @throws Exception + */ + public Map handleKQEvectionAction(Map sqlMap, + List splitBeans, DateTimeFormatter datetimeFormatter, int workflowId, + int requestId, ResourceComInfo rci) throws Exception{ + KQFlowEvectionUtil kqFlowEvectionUtil = new KQFlowEvectionUtil(); + return kqFlowEvectionUtil.handleKQEvectionAction(sqlMap,splitBeans,datetimeFormatter,workflowId,requestId,rci); + } + + /** + * 拆分公出数据 生成splitBeans + * @param sqlMap + * @param splitBeans + * @param datetimeFormatter + * @param workflowId + * @param requestId + * @param rci + * @return + * @throws Exception + */ + public Map handleKQOutAction(Map sqlMap, + List splitBeans, DateTimeFormatter datetimeFormatter, int workflowId, + int requestId, ResourceComInfo rci) throws Exception{ + KQFlowOutUtil kqFlowOutUtil = new KQFlowOutUtil(); + return kqFlowOutUtil.handleKQOutAction(sqlMap,splitBeans,datetimeFormatter,workflowId,requestId,rci); + } + + /** + * 拆分加班数据 生成splitBeans + * @param sqlMap + * @param splitBeans + * @param datetimeFormatter + * @param workflowId + * @param requestId + * @param rci + * @return + * @throws Exception + */ + public Map handleKQOvertimeAction(Map sqlMap, + List splitBeans, DateTimeFormatter datetimeFormatter, int workflowId, + int requestId, ResourceComInfo rci) throws Exception{ + KQFlowOvertimeUtil kqFlowOvertimeUtil = new KQFlowOvertimeUtil(); + return kqFlowOvertimeUtil.handleKQOvertimeAction(sqlMap,splitBeans,datetimeFormatter,workflowId,requestId,rci,""); + } + /** + * 拆分排班数据 + * @param sqlMap + * @param splitBeans + * @param datetimeFormatter + * @param workflowId + * @param requestId + * @param rci + * @return + * @throws Exception + */ + public void handleKQShiftAction(Map sqlMap, + List splitBeans, DateTimeFormatter datetimeFormatter, int workflowId, + int requestId, ResourceComInfo rci) throws Exception{ + KQFlowShiftUtil kqFlowShiftUtil = new KQFlowShiftUtil(); + kqFlowShiftUtil.handleKQShiftAction(sqlMap,splitBeans,datetimeFormatter,workflowId,requestId,rci); + } + /** + * 补卡流程数据 生成签到签退数据并更新考勤报表 + * @param sqlMap + * @param splitBeans + * @param datetimeFormatter + * @param workflowId + * @param requestId + * @param rci + * @return + * @throws Exception + */ + public Map handleKQCardAction(Map sqlMap, + List splitBeans, DateTimeFormatter datetimeFormatter, int workflowId, + int requestId, ResourceComInfo rci) throws Exception{ + KQFlowCardUtil kqFlowCardUtil = new KQFlowCardUtil(); + return kqFlowCardUtil.handleKQCardAction(sqlMap,splitBeans,datetimeFormatter,workflowId,requestId,rci); + } + /** + * 拆分销假流程数据 生成数据到splitBeans和backsplitBeans + * @param sqlMap + * @param splitBeans + * @param datetimeFormatter + * @param workflowId + * @param requestId + * @param rci + * @return + * @throws Exception + */ + public Map handleKQLeaveBackAction(Map sqlMap, + List splitBeans, DateTimeFormatter datetimeFormatter, int workflowId, + int requestId, ResourceComInfo rci) throws Exception{ + KQFlowLeaveBackUtil kqFlowLeaveBackUtil = new KQFlowLeaveBackUtil(); + return kqFlowLeaveBackUtil.handleKQLeaveBackAction(sqlMap,splitBeans,datetimeFormatter,workflowId,requestId,rci); + } +} diff --git a/src/com/engine/kq/biz/KQFormatBiz.java b/src/com/engine/kq/biz/KQFormatBiz.java new file mode 100644 index 0000000..92ee7c9 --- /dev/null +++ b/src/com/engine/kq/biz/KQFormatBiz.java @@ -0,0 +1,301 @@ +package com.engine.kq.biz; + +import com.alibaba.fastjson.JSON; +import com.engine.kq.entity.TimeScopeEntity; +import com.engine.kq.entity.WorkTimeEntity; +import com.engine.kq.log.KQLog; +import java.io.PrintWriter; +import java.io.StringWriter; +import weaver.common.DateUtil; +import weaver.conn.BatchRecordSet; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.Util; +import weaver.hrm.User; +import weaver.systeminfo.SystemEnv; + +import java.util.*; + +/** + * 考勤数据格式化 + */ +public class KQFormatBiz extends BaseBean { + private String today = DateUtil.getCurrentDate(); + protected KQLog kqLog = new KQLog(); + + /** + * 考勤报表格式化 + * + * @param lsFormatParams + */ + public void format(List> lsFormatParams) { + BatchRecordSet bRs = new BatchRecordSet(); + String sql = ""; + List params = null; + try { + if (KQSettingsBiz.getKqformatthread()) { + sql = " insert into kq_format_pool (resourceid, kqdate) values (?,?)"; + if (KQSettingsBiz.getKqformatAccurate()){ + sql = " insert into kq_format_pool (resourceid, kqdate, exectime) values (?,?,?)"; + lsFormatParams = processFormatParams(lsFormatParams); + } + bRs.executeBatchSql(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().formatKqDate(resourceid, kqdate); + } + } + } 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 =" + resourceid + " and kqdate = ? ";//删除非工作日数据 + rs.executeUpdate(sql, kqdate); + + sql = " delete from kq_format_total where resourceid =" + resourceid + " and kqdate = ? ";//删除非工作日数据 + rs.executeUpdate(sql, 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; + } + } + } + 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(); + formatParams.add(resourceId); + formatParams.add(kqDate); + formatParams.add(new java.sql.Timestamp(DateUtil.getCalendar(DateUtil.getFullDate()).getTimeInMillis())); + 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())); + lsFormatParamsTmp.add(formatParams); + + formatParams = new ArrayList<>(); + formatParams.add(resourceId); + formatParams.add(kqDate); + formatParams.add(new java.sql.Timestamp(DateUtil.getCalendar(workEndDateTime).getTimeInMillis())); + lsFormatParamsTmp.add(formatParams); + } + }else{ + formatParams = new ArrayList<>(); + formatParams.add(resourceId); + formatParams.add(kqDate); + lsFormatParamsTmp.add(formatParams); + } + } + + }catch (Exception e) { + StringWriter errorsWriter = new StringWriter(); + e.printStackTrace(new PrintWriter(errorsWriter)); + kqLog.info(errorsWriter.toString()); + } + return lsFormatParamsTmp; + } +} diff --git a/src/com/engine/kq/biz/KQFormatData.java b/src/com/engine/kq/biz/KQFormatData.java new file mode 100644 index 0000000..1bb928e --- /dev/null +++ b/src/com/engine/kq/biz/KQFormatData.java @@ -0,0 +1,1281 @@ +package com.engine.kq.biz; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.api.customization.qc2988837.Util.KqCustomUtil; +import com.cloudstore.dev.api.util.Util_DataMap; +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.enums.FlowReportTypeEnum; +import com.engine.kq.log.KQLog; +import com.engine.kq.timer.KQTaskBean; +import com.engine.kq.util.UtilKQ; +import com.engine.kq.wfset.util.SplitActionUtil; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.googlecode.aviator.AviatorEvaluator; +import com.googlecode.aviator.Expression; + +import java.text.SimpleDateFormat; +import java.util.concurrent.ConcurrentHashMap; +import org.apache.commons.lang3.StringUtils; +import weaver.common.DateUtil; +import weaver.conn.BatchRecordSet; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.formmode.setup.ModeRightInfo; +import weaver.general.BaseBean; +import weaver.general.InitServer; +import weaver.general.Util; +import weaver.hrm.resource.ResourceComInfo; + +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<>(); + + /*** + * 该方法不允许直接调用 + * @param userId + * @param kqDate + * @return + */ + public Map formatKqDate(String userId, String kqDate) { + KqCustomUtil kqCustomUtil = new KqCustomUtil(); + List> lsParam = new ArrayList<>(); + //非工作日处理 + 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; + } + 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") ||*/ !kqCustomUtil.isExclude(userId,kqDate)){ + kqLog.info("无需考勤人员没有异常状态 workTime.getIsExclude()="+workTime.getIsExclude()+"excludecount=="+excludecount); + return resultMap; + } + } + if( Util.null2String(workTime.getGroupId()).length()==0){ + //没有考勤组不需格式化 + return resultMap; + } + + if (workTime == null || (workTime.getWorkMins() == 0 && workTime.getRestShift() != 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)values(?,?,?,?,?,?,?,?,?,?,?,?,?,?) "; + rs.executeUpdate(sql, nonlsParam); + + 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)" + + " 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," + + " sum(case when absenteeismmins> 0 then 1 else 0 end) as absenteeism,sum(absenteeismmins) as absenteeismmins," + + " 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" + + " 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 = ""; + 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) { + 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+"":"")+") " + + " 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); + } + + 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+"":"")+") " + + " 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," + + " cast(sum(attendanceMins)AS decimal(10, 2))/sum(workmins) as attendancedays, sum(attendanceMins) as attendanceMins," + + " cast(sum(signmins)AS decimal(10, 2))/sum(workmins) 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, " + + " sum(case when absenteeismmins> 0 then 1 else 0 end) as absenteeism,sum(absenteeismmins) as absenteeismmins," + + " 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, " + + " sum(case when forgotbeginworkcheckmins> 0 then 1 else 0 end) as forgotbeginworkcheck,sum(forgotbeginworkcheckmins) as forgotbeginworkcheckmins " + + (definedField.length()>0?","+definedParamSum+"":"")+ + " 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(); + //晚餐次数-二开 + Integer wccs = getDinnerCount(userId,kqDate,kqDate); + //晚餐次数含夜班-二开 + Integer wccshyb = getDinnerCountOfNight(userId,kqDate,kqDate); + //午餐次数-二开 + Integer wuccs = getLanchCount(userId,kqDate,kqDate); + //午餐次数含夜班-二开 + Integer wuccshyb = getLanchCountOfNight(userId,kqDate,kqDate); + //夜班次数 + Map nightShiftInfo = getNightShiftInfo(userId,kqDate,kqDate); + Integer ybcs = nightShiftInfo.size(); + KQHolidaySetComInfo holidaySetComInfo = new KQHolidaySetComInfo(); + KQGroupMemberComInfo kqGroupMemberComInfo = new KQGroupMemberComInfo(); + /*获取考勤组的ID,因为考勤组有有效期,所以需要传入日期*/ + String groupId = kqGroupMemberComInfo.getKQGroupId(userId, kqDate); + String changeTypeNew = holidaySetComInfo.getChangeType(groupId, kqDate); + if("1".equals(changeTypeNew)|| DateUtil.getWeek(kqDate) == 6 || DateUtil.getWeek(kqDate) == 7){ + //节假日、周六、周日 + String serialid = Util.null2String(workTime.getSerialId()); + if(StringUtils.isBlank(serialid)){ + //班次为空置为0 + wccshyb = 0; + wuccshyb = 0; + ybcs = 0; + } + } + + String ryType = getField112(userId); + if("1".equals(ryType)||"2".equals(ryType)){ + wccshyb= 0; + wuccshyb = 0; + } + + bb.writeLog("userId"+userId+"kqdate"+kqDate+"wccs:"+wccs+"wccshyb:"+wccshyb+"wuccs:"+wuccs+"wuccshyb:"+wuccshyb+"ybcs:"+ybcs); + createKqModeInfo(userId,kqDate,wccs,wccshyb,wuccs,wuccshyb,ybcs); + + //重新计算加班 +// List tasks = new ArrayList<>(); +// SplitActionUtil splitActionUtil = new SplitActionUtil(); +// ResourceComInfo rci = new ResourceComInfo(); +// while (rci.next()){ +// String resourceid = rci.getResourceid(); +// splitActionUtil.pushOverTimeTasks(kqDate, kqDate, resourceid,tasks); +// } +// if(!tasks.isEmpty()){ +// splitActionUtil.handleOverTime(tasks); +// } + + + + }catch (Exception e) { + kqLog.info("KQFormatData失败:userId:"+userId+":kqDate:"+kqDate); + sql = " insert into kq_format_pool (resourceid, kqdate) values (?,?)"; + rs.executeUpdate(sql, userId, kqDate); + writeLog(e); + kqLog.info(e); + } + return resultMap; + } + + public List> format(String userId, String kqDate, WorkTimeEntity workTime, + Map workFlowInfo, String uuid) { + List> lsParam = new ArrayList<>(); + List params = null; + try { + KQSettingsComInfo kqSettingsComInfo = new KQSettingsComInfo(); + String nosign_is_absent = Util.null2String(kqSettingsComInfo.getMain_val("nosign_is_absent"),"1"); + 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(); + kqLog.info("format in >>>>>userId" + userId + "kqDate==" + kqDate+":hostIps:"+hostIps+":uuid::"+uuid); + boolean oneSign = false; + List lsSignTime = new ArrayList<>(); + List lsWorkTime = new ArrayList<>(); + List lsRestTime = new ArrayList<>(); + List workFlow = null; + + int workminsNew = 0; + if (workTime != null) { + lsSignTime = workTime.getSignTime();//允许打卡时间 + lsWorkTime = workTime.getWorkTime();//工作时间 + lsRestTime = workTime.getRestTime();//休息时段时间 + oneSign = lsWorkTime!=null&&lsWorkTime.size()==1; + workminsNew = workTime.getWorkMins(); + } + + int[] dayMins = new int[2880];//一天所有分钟数 + Arrays.fill(dayMins, -1); + for (int i = 0; lsWorkTime != null && i < lsWorkTime.size(); 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 leaveMins = 0;//请假时长 + Map leaveInfo = new HashMap<>();//请假信息 + Map otherinfo = 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(oneSign){ + //个性化设置只支持一天一次上下班 + ShiftInfoBean shiftInfoBean = new ShiftInfoBean(); + shiftInfoBean.setSplitDate(kqDate); + shiftInfoBean.setShiftRuleMap(workTime.getShiftRuleInfo()); + shiftInfoBean.setSignTime(lsSignTime); + shiftInfoBean.setWorkTime(lsWorkTime); + 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(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); + } + List lsCheckInfo = new KQFormatSignData().getSignInfo(userId,signTimeScope,workTimeScope,kqDate,preDate,nextDate,kqTimesArrayComInfo,hostIps,uuid); + 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(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; + } + if(oneSign){ + if(workBeginIdx>signInTimeIndx) { + earlyInMins = workBeginIdx-signInTimeIndx; + } + } + } 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(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); + } + + 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 serial = Util.null2String(data.get("serial")); + String requestId = Util.null2String(data.get("requestId")); + beginIdx = kqTimesArrayComInfo.getArrayindexByTimes(Util.null2String(data.get("begintime"))); + endIdx = kqTimesArrayComInfo.getArrayindexByTimes(Util.null2String(data.get("endtime"))); + if (beginIdx >= endIdx) { + continue; + } + + 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(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 (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, -1);//休息时间 + workMins = workMins-(endIdx-beginIdx); + } + } + + for (int j = workBeginIdx; j < workEndIdx; j++) { + switch (dayMins[j]) { + case 1: + tmpAttendanceMins++; + break; + case 2: + beLateMins++; + break; + case 3: + leaveEarlyMins++; + break; + case 4: + absenteeismMins++; + break; + case 5: + leaveMins++; + break; + case 6: + forgotCheckMins++; + break; + case 7: + evectionMins++; + break; + case 8: + outMins++; + break; + case 66: + forgotBeginWorkCheckMins++; + break; + case 99: + otherMins++; + break; + default: + break; + } + } + + if(forgotCheckMins == 1 && beLateMins==0 && tmpAttendanceMins==0){//forgotCheckMins==1表示下班后漏签,不是迟到,流程已完全抵扣异常 + forgotCheckMins = 0; + } + + 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); + 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(); + + 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; + }else if(!new KQFormatBiz().needCal(workEndDate,workEndTime)) {//还未到下班时间 + kqLog.writeLog("还未到上班时间"); + leaveEarlyMins = 0; + graveLeaveEarlyMins = 0; + forgotCheckMins = 0; + } + + if (workminsNew == 0 || workTime.getIsExclude()) {//无需考勤人员没有异常状态 + beLateMins = 0; + graveBeLateMins = 0; + leaveEarlyMins = 0; + graveLeaveEarlyMins = 0; + absenteeismMins = 0; + forgotCheckMins = 0; + forgotBeginWorkCheckMins = 0; + } + + //计算实际出勤时间(出差公出算出勤)=应出勤-旷工-请假-迟到-早退 + attendanceMins = workMins - absenteeismMins-leaveMins-beLateMins-graveBeLateMins-leaveEarlyMins-graveLeaveEarlyMins; + // 如果没有开启"漏签是否算实际出勤"开关,则漏签不算实际出勤时长 + if("0".equals(nosign_is_absent)) { + attendanceMins = attendanceMins-forgotCheckMins-forgotBeginWorkCheckMins; + } + if(workminsNew == 0) { + attendanceMins = 0; + workMins = 0; + } + if(beforeBegin || attendanceMins < 0) {//还未到上班时间,不用计算任何状体 + attendanceMins = 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)); + lsParam.add(params); + } + } catch (Exception e) { + writeLog(e); + kqLog.info(e); + } + 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 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")); + beginIdx = kqTimesArrayComInfo.getArrayindexByTimes(Util.null2String(data.get("begintime"))); + endIdx = kqTimesArrayComInfo.getArrayindexByTimes(Util.null2String(data.get("endtime"))); + 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); + } + + + + /** + * 获取晚餐信息 + * @param resourceid + * @param fromDate + * @param toDate + * @return + */ + public int getDinnerCount(String resourceid,String fromDate,String toDate){ + int dinnerCount = 0; + + RecordSet rs = new RecordSet(); + String sql = " select count(distinct(belongdate)) as num from kq_flow_overtime a " + + " left join kq_format_detail b on a.resourceid=b.resourceid and a.belongdate =b.kqdate " + + " where a.resourceid =? and a.belongdate >=? and a.belongdate <=? " + + " and (b.signintime >='06:00:00' and b.signintime <='18:10:00' ) " + + " and ((b.signouttime >='18:10:00' and b.signouttime<='23:59:59') or (b.signouttime >='00:00:00' and b.signouttime<='12:00:00') ) " + + " and (duration_min/60)>=0.5 "; + + boolean isCleanStaff = cleanStaff(resourceid); + if(isCleanStaff){ + sql = " select count(distinct(belongdate)) as num from kq_flow_overtime a " + + " left join kq_format_detail b on a.resourceid=b.resourceid and a.belongdate =b.kqdate " + + " where a.resourceid =? and a.belongdate >=? and a.belongdate <=? " + + " and (b.signintime >='06:00:00' and b.signintime <='17:20:00' ) " + + " and (b.signouttime >='17:50:00' and b.signouttime<='23:59:59') " + + " and (duration_min/60)>=0.5 "; + } + rs.executeQuery(sql,resourceid,fromDate,toDate); + if(rs.next()){ + dinnerCount = Util.getIntValue(rs.getString("num"),0); + } + return dinnerCount; + } + + /** + * 判断是否是保洁人员 + * @param userid + * @return + */ + public boolean cleanStaff(String userid){ + RecordSet rs = new RecordSet(); + String sql = " select 1 from hrmroles a, hrmrolemembers b where a.rolesmark='保洁人员' and a.id=b.roleid and b.resourceid=? "; + rs.executeQuery(sql,userid); + return rs.next(); + } + + /** + * 查询晚餐次数(当天有夜班) + * @param resourceid + * @param fromDate + * @param toDate + * @return + */ + public int getDinnerCountOfNight(String resourceid,String fromDate,String toDate){ + int dinnerWithNightCount = 0; + RecordSet rs = new RecordSet(); + String sql = " select count(distinct(belongdate)) as num from kq_flow_overtime a " + + " left join kq_format_detail b on a.resourceid=b.resourceid and a.belongdate =b.kqdate " + + " where b.serialid in(3,4,9,10) and a.resourceid =? and a.belongdate >=? and a.belongdate <=? " + + " and b.signouttime >='04:30:00' and b.signouttime <='12:00:00' and (duration_min/60)>=0.5 "; + rs.executeQuery(sql,resourceid,fromDate,toDate); + if(rs.next()){ + dinnerWithNightCount = Util.getIntValue(rs.getString("num"),0); + } + return dinnerWithNightCount; + } + + /** + * 获取午餐次数 + * @param resourceid + * @param fromDate + * @param toDate + * @return + */ + public int getLanchCount(String resourceid, String fromDate, String toDate){ + int lanchCount = 0; + RecordSet rs = new RecordSet(); + String bbsql = " select count(distinct(kqdate)) as num from kq_format_detail a " + + " left join kq_flow_overtime b on a.resourceid=b.resourceid and a.kqdate =b.belongdate " + + " where a.resourceid=? and kqdate>=? and kqdate <=? " + + " and signintime>='06:00:00' and signintime<='12:00:00' and (ifnull(attendanceMins,0)+ifnull(duration_min,0) /60)>=4 "; + rs.executeQuery(bbsql,resourceid,fromDate,toDate); + if(rs.next()){ + lanchCount = Util.getIntValue(rs.getString("num"),0); + } + return lanchCount; + } + + /** + * 查询午餐次数(含夜班)次数 + * @param resourceid + * @param fromDate + * @param toDate + * @return + */ + public int getLanchCountOfNight(String resourceid,String fromDate,String toDate){ + int lanchWithNightCount = 0; + RecordSet rs = new RecordSet(); + String sql = " select count(distinct(kqdate)) as num from kq_format_detail a " + + " left join kq_flow_overtime b on a.resourceid=b.resourceid and a.kqdate =b.belongdate " + + " where a.resourceid=? and kqdate >=? and kqdate <=? " + + " and (signintime>='06:00:00' and signintime<='23:59:59') and (signouttime>='00:00:00' and signouttime<='12:00:00') " + + " and datediff(signoutdate ,signindate)=1 and (ifnull(attendanceMins,0)+ifnull(duration_min,0)) /60>=4"; + rs.executeQuery(sql,resourceid,fromDate,toDate); + if(rs.next()){ + lanchWithNightCount = Util.getIntValue(rs.getString("num"),0); + } + return lanchWithNightCount; + } + + /** + * 获取人员夜班情况 + * @param resourceid + * @param fromDate + * @param toDate + * @return + */ + public Map getNightShiftInfo(String resourceid,String fromDate,String toDate){ + Map ybInfo = new HashMap<>(); + RecordSet rs = new RecordSet(); + String ryType = getField112(resourceid); + String ybSql = ""; + if("0".equals(ryType)){ + ybSql = " select * from kq_format_detail " + + " where resourceid=? and kqdate>=? and kqdate<=? " + + " and serialid in(3,4,9,10) and attendanceMins/60>=3.5 and signouttime>='00:00:00' and signouttime<='12:00:00' "; + }else if("1".equals(ryType) || "2".equals(ryType)){ + //不定时打卡人员,上班卡在 下班卡前一天,计1次 + //上班卡 不等于 下班卡,不计1次 + ybSql = " select * from kq_format_detail " + + " where resourceid=? and kqdate>=? and kqdate<=? " + + " and signouttime>='00:00:00' and signouttime<='12:00:00' and signoutdate <>signindate"; + } + //1.夜班、特殊夜班班次,判断在班次内是否有过零点的打卡记录 ,记1次;(2023-9-13)下班卡最晚到次日9:00、当日有效出勤>=3.5H; + rs.executeQuery(ybSql,resourceid,fromDate,toDate); + while(rs.next()){ + ybInfo.put(Util.null2String(rs.getString("kqdate")),1); + } + + //2.白班班次(加班情况,白班不存在跨0点),加班下班卡最晚到次日9:00,且有效出勤>=3.5H,记1次; + // 休息日/法定节假日加班有效出勤时长>=3.5H(非工作日跨0点加班必须提外出流程),且下班卡过0点,记1次 + //0913修改,不用考虑加班流程,只看打卡时间和出勤时长 + //String jbSql = " select a.*,b.signindate ,b.signintime ,b.signoutdate ,b.signouttime from kq_flow_overtime a " + + // " left join kq_format_detail b on a.resourceid=b.resourceid and a.belongdate =b.kqdate " + + // " where a.resourceid =? and a.belongdate >=? and a.belongdate <=? " + + // " and (b.signouttime >='00:00:00' and b.signouttime <='09:00:00') and (attendanceMins+duration_min)/60>=3.5 "; + // + String ybsql = " select a.* from kq_format_detail a " + + " right join kq_flow_overtime b on a.resourceid=b.resourceid and a.kqdate =b.belongdate " + + " where a.resourceid=? and kqdate>=? and kqdate<=? " + + " and signouttime >='00:00:00' and signouttime <='12:00:00' and (ifnull(attendanceMins,0)+ifnull(duration_min,0)) /60>=3.5 "; + rs.executeQuery(ybsql,resourceid,fromDate,toDate); + while(rs.next()){ + ybInfo.put(Util.null2String(rs.getString("kqdate")),1); + } + return ybInfo; + } + + /** + * 获取人员类型 + * @param userid + * @return + */ + private static String getField112(String userid){ + RecordSet rs = new RecordSet(); + String sql = "select field112 from cus_fielddata where id = "+userid+" and scope = 'HrmCustomFieldByInfoType' and scopeid = 3"; + rs.executeQuery(sql); + String field112 = ""; + if (rs.next()){ + field112 = Util.null2String(rs.getString("field112")); + } + return field112; + } + + /** + * 格式化生成台账数据 + * @param userId + * @param date + */ + public static void createKqModeInfo(String userId,String date,Integer wccs,Integer wccshyb,Integer wuccs,Integer wuccshyb,Integer ybcs){ + RecordSet rs = new RecordSet(); + BaseBean bb = new BaseBean(); + bb.writeLog("createKqModeInfo == >userId:"+userId+" date:"+date); + //先删除当天历史生成数据 + String deleteSql = "delete from uf_zdyzdgsh where xm = ? and rq = ?"; + rs.executeUpdate(deleteSql,userId,date); + //插入 + String idNew = ""; + int modeid = getFormModeIdByCubeName("uf_zdyzdgsh"); + 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()); + String sqlMode = "insert into uf_zdyzdgsh (xm,rq,wccs,waccshyb,wuccs,wccshyb,ybcs,FORMMODEID,MODEDATACREATER,MODEDATACREATERTYPE,MODEDATACREATEDATE,MODEDATACREATETIME) \n" + + "values (?,?,?,?,?,?,?,?,?,?,?,?)"; + rs.executeUpdate(sqlMode, userId,date,wccs,wccshyb,wuccs,wuccshyb,ybcs,modeid, userId, "0", modedatacreatedate, modedatacreatetime); + + RecordSet findNew = new RecordSet(); + String sqlFindnew ="select Id from uf_zdyzdgsh 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 = Integer.valueOf(idNew); + ModeRightInfo modeRightInfo = new ModeRightInfo(); + modeRightInfo.editModeDataShare(Integer.valueOf(userId), modeid, dataId); + } + + /** + * 根据建模表名获取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"); + } + + + +} diff --git a/src/com/engine/kq/biz/KQFormatJob.java b/src/com/engine/kq/biz/KQFormatJob.java new file mode 100644 index 0000000..560e180 --- /dev/null +++ b/src/com/engine/kq/biz/KQFormatJob.java @@ -0,0 +1,90 @@ +package com.engine.kq.biz; + +import com.engine.kq.log.KQLog; +import com.weaver.util.threadPool.ThreadPoolUtil; +import com.weaver.util.threadPool.constant.ModulePoolEnum; +import weaver.common.DateUtil; +import weaver.conn.ConnStatement; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.WArrayList; + +import java.util.TimerTask; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +/** + * 考勤数据格式化定时任务 + */ +public class KQFormatJob extends TimerTask { + private static KQFormatJob instance = new KQFormatJob(); + public static WArrayList kqformatIds = new WArrayList(); + private static boolean flag = false; + private KQLog kqLog = new KQLog(); + + public static KQFormatJob getInstance(){ + return instance; + } + + public void run() { + KQFormatThread kqFormatThread = null; + ConnStatement cs = new ConnStatement(); + String sql = ""; + try{ + if(flag) return; + flag = true; + if(kqformatIds.size()>0){ + flag = false; + return; + } + sql = " select id, kqdate, resourceid from kq_format_pool where status = 0 order by kqdate, resourceid asc"; + boolean kqformatAccurate = KQSettingsBiz.getKqformatAccurate(); + if (kqformatAccurate){ + String currentFullTime = DateUtil.getFullDate(); + RecordSet rs = new RecordSet(); + if(rs.getDBType().equals("oracle")){ + sql = " select id, kqdate, resourceid,exectime from kq_format_pool where status = 0 and exectime is not null and exectime < to_date('"+currentFullTime+"','yyyy-mm-dd hh24:mi:ss') order by kqdate, resourceid, exectime asc"; + } + else if(rs.getDBType().equals("postgresql")){ + sql = " select id, kqdate, resourceid,exectime from kq_format_pool where status = 0 and exectime is not null and exectime < to_date('"+currentFullTime+"','yyyy-mm-dd hh24:mi:ss') order by kqdate, resourceid, exectime asc"; + } + else if (rs.getDBType().equals("mysql")) { + sql = " select id, kqdate, resourceid,exectime from kq_format_pool where status = 0 and exectime is not null and exectime>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + cs.getString("id") + "==" + cs.getString("kqdate") + "==" + cs.getString("resourceid") + "==" + cs.getString("exectime")); + }else{ + kqLog.info(Thread.currentThread().getId() + "===KQFormatJob in>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + cs.getString("id") + "==" + cs.getString("kqdate") + "==" + cs.getString("resourceid")); + } + //kqformatPool.execute(kqFormatThread); + ThreadPoolUtil.fixedPoolExecute(ModulePoolEnum.HRM, "KQFormatJob", kqFormatThread); + } + + + flag = false; + }catch (Exception e){ + flag = false; + new BaseBean().writeLog(e); + kqLog.info("考勤数据格式化定时任务错误:",e); + }finally { + try { + cs.close(); + }catch(Exception ex) {new BaseBean().writeLog("关闭考勤数据格式化定时任务数据库链接错误");} + } + } +} \ No newline at end of file diff --git a/src/com/engine/kq/biz/KQFormatSignData.java b/src/com/engine/kq/biz/KQFormatSignData.java new file mode 100644 index 0000000..c98eb67 --- /dev/null +++ b/src/com/engine/kq/biz/KQFormatSignData.java @@ -0,0 +1,544 @@ +package com.engine.kq.biz; + +import com.alibaba.fastjson.JSON; +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.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(), ""); + } + /*** + * 获取班次打卡数据 + * @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) { + kqLog.info("in getSignInfo ::userId" + userId + "kqDate==" + kqDate+":hostIps:"+hostIps+":uuid::"+uuid+" in "); + List lsCheckInfo = new ArrayList<>(); + 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); + + List> sqlConditions = getCanSignInfo(signTimeScope,kqDate,preDate,nextDate,kqTimesArrayComInfo,workTimeScope); + 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); + if(sqlConditions != null && !sqlConditions.isEmpty()){ + 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")); + 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(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); + }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); + } + } + } + } + } + } + }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) { + + 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; + + signEndDateTime+=" "+kqTimesArrayComInfo.turn48to24Time(signTimeScope.getEndTime())+":59"; + + + + if(timeSignScopeEntity == null){ + //没有设置 签到最晚时间和签退最早时间 + 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"; + + 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/src/com/engine/kq/biz/KQFormatThread.java b/src/com/engine/kq/biz/KQFormatThread.java new file mode 100644 index 0000000..3beb237 --- /dev/null +++ b/src/com/engine/kq/biz/KQFormatThread.java @@ -0,0 +1,57 @@ +package com.engine.kq.biz; + +import com.engine.kq.log.KQLog; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; + +public class KQFormatThread extends com.weaver.util.threadPool.entity.LocalRunnable { + private String id; + private String resourceid; + private String kqdate; + private KQLog kqLog = new KQLog(); + + @Override + public void execute() { + RecordSet rs = new RecordSet(); + //更新已处理的记录 + String key = this.kqdate+ "|"+ this.resourceid; + try { + kqLog.info("执行KQFormatThread this.resourceid=="+this.resourceid+"this.kqdate=="+this.kqdate); + KQFormatData kqFormatData = new KQFormatData(); + kqFormatData.formatKqDate(this.resourceid, this.kqdate); + + boolean isremove = KQFormatJob.kqformatIds.remove(key); + if(isremove){ + rs.execute("update kq_format_pool set status=1 where id=" + this.id); + } + } catch (Exception e) { + KQFormatJob.kqformatIds.remove(key); + kqLog.info(e); + writeLog(e); + } + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getResourceid() { + return resourceid; + } + + public void setResourceid(String resourceid) { + this.resourceid = resourceid; + } + + public String getKqdate() { + return kqdate; + } + + public void setKqdate(String kqdate) { + this.kqdate = kqdate; + } +} diff --git a/src/com/engine/kq/biz/KQLeaveRulesBiz.java b/src/com/engine/kq/biz/KQLeaveRulesBiz.java new file mode 100644 index 0000000..04adc19 --- /dev/null +++ b/src/com/engine/kq/biz/KQLeaveRulesBiz.java @@ -0,0 +1,911 @@ +package com.engine.kq.biz; + +import com.alibaba.fastjson.JSONObject; +import com.engine.kq.log.KQLog; +import com.engine.kq.util.KQTransMethod; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.resource.ResourceComInfo; +import weaver.systeminfo.SystemEnv; + +import java.util.*; + +public class KQLeaveRulesBiz { + + /** + * 记录日志 + */ + 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; + } + } + + /** + * 获取最小请假单位 + * 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()); + 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); + + 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; + } + + /** + * 初始化年假 + * + * @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; + } + + /** + * 是否是调休 + * @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; + } + + /** + * 是否是调休 + * @param ruleId + * @return + */ + public static boolean isTiaoXiu2(String ruleId){ + boolean flag = false; + try { + String sql = "select * from kq_LeaveRulesDetail where (isDelete is null or isDelete<>1) and distributionMode in(9,10) and ruleId=?"; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql, ruleId); + if (recordSet.next()) { + flag = true; + } + } catch (Exception e) { + logger.info(e.getMessage()); + } + return flag; + } + + /** + * 是否是工作日调休或者休息日调休 + * @param ruleId + * @return + */ + public static boolean isTiaoXiuByMode(String ruleId,int distributionMode){ + boolean flag = false; + try { + String sql = "select * from kq_LeaveRulesDetail where (isDelete is null or isDelete<>1) and distributionMode=? and ruleId=?"; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql, distributionMode,ruleId); + if (recordSet.next()) { + flag = true; + } + } catch (Exception e) { + logger.info(e.getMessage()); + } + return flag; + } + + + + + /** + * 是否是育儿假 + * @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()) { + 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; + } +} diff --git a/src/com/engine/kq/biz/KQOverTimeFlowBiz.java b/src/com/engine/kq/biz/KQOverTimeFlowBiz.java new file mode 100644 index 0000000..72501f9 --- /dev/null +++ b/src/com/engine/kq/biz/KQOverTimeFlowBiz.java @@ -0,0 +1,848 @@ +package com.engine.kq.biz; + +import com.alibaba.fastjson.JSONObject; +import com.engine.kq.biz.chain.shiftinfo.ShiftInfoBean; +import com.engine.kq.entity.KQOvertimeRulesDetailEntity; +import com.engine.kq.log.KQLog; +import com.engine.kq.util.KQDurationCalculatorUtil; +import com.engine.kq.wfset.bean.OvertimeBalanceTimeBean; +import com.engine.kq.wfset.bean.SplitBean; +import com.engine.kq.wfset.util.KQFlowUtil; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import org.springframework.beans.BeanUtils; +import weaver.common.StringUtil; +import weaver.general.Util; +import weaver.hrm.User; + +/** + * 加班流程 非工作时长计算 重新搞一把 + * 现在是根据归属来拆分流程 + */ +public class KQOverTimeFlowBiz { + private KQLog kqLog = new KQLog(); + + /** + * 之前的加班拆分是根据每一天进行拆分的,但是我们是有个默认归属的,就是上班前是属于前一天的,再加上这次标准改造,加了临界点, + * 加班的拆分改造一下,改成和请假拆分一样,根据归属区间来拆分 + * 未设置加班归属的逻辑是 + * 工作日A-工作日B ,从工作日A的上班时间往后加24小时,都算工作日A的加班区间 + * 工作日A-非工作日,从工作日A的上班时间往后加24小时,都算工作日A的加班区间 + * 非工作日-工作日A,从非工作日的0点到工作日A的上班前,都属于非工作日的区间 + * + * 计算加班逻辑很特殊, + * 需要知道昨日,今日和明日的类型,是工作日还是非工作日 + * @param splitBean + * @param splitBeans + */ + public void getSplitDurationBean_new(SplitBean splitBean,List splitBeans) { + try{ + long a = System.currentTimeMillis(); + + double oneDayHour = KQFlowUtil.getOneDayHour(splitBean.getDurationTypeEnum(),""); + int workmins = (int)(oneDayHour * 60); + String resourceid = splitBean.getResourceId(); + String fromDate = splitBean.getFromdatedb(); + String toDate = splitBean.getTodatedb(); + String overtime_type = splitBean.getOvertime_type(); + + User tmp_user = User.getUser(Util.getIntValue(resourceid), 0); + KQShiftManagementComInfo kQShiftManagementComInfo = new KQShiftManagementComInfo(); + + LocalDate localFromDate = LocalDate.parse(fromDate); + LocalDate localToDate = LocalDate.parse(toDate); + DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + LocalDate preFromDate = localFromDate.minusDays(1); + KQTimesArrayComInfo kqTimesArrayComInfo = new KQTimesArrayComInfo(); + + KQOvertimeRulesBiz kqOvertimeRulesBiz = new KQOvertimeRulesBiz(); + KQOverTimeRuleCalBiz kqOverTimeRuleCalBiz = new KQOverTimeRuleCalBiz(); + Map changeTypeMap = Maps.newHashMap(); + Map overRulesDetailMap = Maps.newHashMap(); + Map> restTimeMap = Maps.newHashMap(); + Map computingModeMap = Maps.newHashMap(); + kqOverTimeRuleCalBiz.getOverTimeDataMap(resourceid, fromDate, toDate, dateFormatter,changeTypeMap,overRulesDetailMap,restTimeMap,computingModeMap); + + if(overRulesDetailMap.isEmpty()){ + return; + } + String fromTime = splitBean.getFromtimedb(); + String toTime = splitBean.getTotimedb(); + long betweenDays = localToDate.toEpochDay() - preFromDate.toEpochDay(); + //默认是从加班开始日期的前一天开始计算 需要特殊处理的就三个情况,i=0的时候,i=1的时候就是加班流程开始日期那一天,i=最后一天就是加班流程结束日期那一天 + for (int i = 0; i <= betweenDays; i++) { + SplitBean overSplitBean = new SplitBean(); + //然后把bean重新赋值下,根据拆分后的时间 + BeanUtils.copyProperties(splitBean, overSplitBean); + + //从加班流程开始的前一天开始算归属 + LocalDate curLocalDate = preFromDate.plusDays(i); + String splitDate = curLocalDate.format(dateFormatter); + String preSplitDate = LocalDate.parse(splitDate).minusDays(1).format(dateFormatter); + LocalDate nextLocalDate = curLocalDate.plusDays(1); + String nextSplitDate = nextLocalDate.format(dateFormatter); + String change_key = splitDate+"_"+resourceid; + String pre_change_key = preSplitDate+"_"+resourceid; + String next_change_key = nextSplitDate+"_"+resourceid; + int changeType = Util.getIntValue(""+changeTypeMap.get(change_key),-1); + int preChangeType = Util.getIntValue(""+changeTypeMap.get(pre_change_key),-1); + int next_changeType = Util.getIntValue(""+changeTypeMap.get(next_change_key),-1); + + boolean shouldAcross = false; + String changeType_key = splitDate+"_"+changeType; + String preChangeType_key = preSplitDate+"_"+preChangeType; + String nextChangeType_key = nextSplitDate+"_"+next_changeType; + if(!computingModeMap.containsKey(changeType_key)){ + continue; + } + int computingMode = computingModeMap.get(changeType_key); + if(computingMode == 3){ + //如果是纯打卡为主的不生成加班 + continue; + } + + int[] initArrays = kqTimesArrayComInfo.getInitArr(); + //当前日期的加班分割点 分割点都是次日的 + String overtime_cut_point = ""; + int before_startTime = 0; + int startTime = 0; + int curMins = 0 ; + //排除休息类型 + int restTimeType = -1; + String next_beginwork_time = ""; + String cur_beginwork_time = ""; + String serialid = ""; + boolean isRestshift_next = false; + boolean isRestshift = false; + String tmp_next_beginwork_time = ""; + String tmp_cur_beginwork_time = ""; + //需要知道明日的类型:如果今天是工作日的话,那么今天的加班临界点可能和明日的上班时间冲突,需要知道明日的上班时间进行比较, + // 如果今天是休息日,那么明天如果是工作日的话,默认规则下,明天的上班前都是属于今天的加班区间 + if(next_changeType == 2){ + ShiftInfoBean next_shiftInfoBean = KQDurationCalculatorUtil.getWorkTime(resourceid, nextSplitDate, false); + if(next_shiftInfoBean != null){ + List workLongTimeIndex = next_shiftInfoBean.getWorkLongTimeIndex(); + List real_workLongTimeIndex = Lists.newArrayList(); + get_real_workLongTimeIndex(workLongTimeIndex,real_workLongTimeIndex,next_shiftInfoBean,kqTimesArrayComInfo,splitBean); + + if(real_workLongTimeIndex != null && !real_workLongTimeIndex.isEmpty()){ + next_beginwork_time = kqTimesArrayComInfo.getTimesByArrayindex(real_workLongTimeIndex.get(0)[0]); + } + } + } + + //休息日有开发的休息班次,单独搞下 + kqLog.info(i+">>>resourceid="+resourceid+",splitDate="+splitDate+",next_changeType="+next_changeType); + if(next_changeType == 3){ + if(null != tmp_user){ + ShiftInfoBean next_shiftInfoBean = KQDurationCalculatorUtil.getWorkTime(tmp_user, nextSplitDate, false,true,false); + if(next_shiftInfoBean != null){ + int tmp_serialid = StringUtil.parseToInt(next_shiftInfoBean.getSerialid(), 0); + int restShift = StringUtil.parseToInt(kQShiftManagementComInfo.getRestShift(String.valueOf(tmp_serialid)), 0); +// kqLog.info(i+">>>resourceid="+resourceid+",splitDate="+splitDate+",tmp_serialid="+ tmp_serialid+",restShift="+ restShift); + if(tmp_serialid > 0 && restShift == 1) { + isRestshift_next = true; + } + + List workLongTimeIndex = next_shiftInfoBean.getWorkLongTimeIndex(); + List real_workLongTimeIndex = Lists.newArrayList(); + get_real_workLongTimeIndex(workLongTimeIndex,real_workLongTimeIndex,next_shiftInfoBean,kqTimesArrayComInfo,splitBean); + + if(real_workLongTimeIndex != null && !real_workLongTimeIndex.isEmpty()){ + tmp_next_beginwork_time = kqTimesArrayComInfo.getTimesByArrayindex(real_workLongTimeIndex.get(0)[0]); + } + kqLog.info(i+">>>resourceid="+resourceid+",splitDate="+splitDate+",tmp_next_beginwork_time="+ tmp_next_beginwork_time+",isRestshift_next="+ isRestshift_next); + } + } + } + +// kqLog.info(i+">>>resourceid="+resourceid+",splitDate="+splitDate+",changeType="+changeType); + if(changeType == 2){ + ShiftInfoBean cur_shiftInfoBean = KQDurationCalculatorUtil.getWorkTime(resourceid, splitDate, false); + if(cur_shiftInfoBean != null){ + List workLongTimeIndex = cur_shiftInfoBean.getWorkLongTimeIndex(); + List real_workLongTimeIndex = Lists.newArrayList(); + get_real_workLongTimeIndex(workLongTimeIndex,real_workLongTimeIndex,cur_shiftInfoBean,kqTimesArrayComInfo,splitBean); + + if(real_workLongTimeIndex != null && !real_workLongTimeIndex.isEmpty()){ + cur_beginwork_time = kqTimesArrayComInfo.getTimesByArrayindex(real_workLongTimeIndex.get(0)[0]); + } + } + } + + //休息日有开发的休息班次,单独搞下 + if(changeType == 3){ +// kqLog.info(i+">>>resourceid="+resourceid+",splitDate="+splitDate+",tmp_user="+tmp_user); + if(null != tmp_user){ + ShiftInfoBean tmp_shiftInfoBean = KQDurationCalculatorUtil.getWorkTime(tmp_user, splitDate,false,true,false); +// kqLog.info(i+">>>resourceid="+resourceid+",splitDate="+splitDate+",tmp_shiftInfoBean="+ JSONObject.toJSONString(tmp_shiftInfoBean)); + if(tmp_shiftInfoBean != null){ + int tmp_serialid = StringUtil.parseToInt(tmp_shiftInfoBean.getSerialid(), 0); + int restShift = StringUtil.parseToInt(kQShiftManagementComInfo.getRestShift(String.valueOf(tmp_serialid)), 0); +// kqLog.info(i+">>>resourceid="+resourceid+",splitDate="+splitDate+",tmp_serialid="+ tmp_serialid+",restShift="+ restShift); + if(tmp_serialid > 0 && restShift == 1) { + isRestshift = true; + } + + List workLongTimeIndex = tmp_shiftInfoBean.getWorkLongTimeIndex(); + List real_workLongTimeIndex = Lists.newArrayList(); + get_real_workLongTimeIndex(workLongTimeIndex,real_workLongTimeIndex,tmp_shiftInfoBean,kqTimesArrayComInfo,splitBean); + + if(real_workLongTimeIndex != null && !real_workLongTimeIndex.isEmpty()){ + tmp_cur_beginwork_time = kqTimesArrayComInfo.getTimesByArrayindex(real_workLongTimeIndex.get(0)[0]); + } + kqLog.info(i+">>>resourceid="+resourceid+",splitDate="+splitDate+",tmp_cur_beginwork_time="+ tmp_cur_beginwork_time+",isRestshift="+ isRestshift); + } + } + } + boolean needSplitByTime = false; +// 按照加班时长转调休的 时长设置 + List timepointList = null; + List overtimeBalanceTimeBeans = Lists.newArrayList(); + KQOvertimeRulesDetailEntity curKqOvertimeRulesDetailEntity = overRulesDetailMap.get(changeType_key); + if(curKqOvertimeRulesDetailEntity != null){ + int has_cut_point = curKqOvertimeRulesDetailEntity.getHas_cut_point(); + before_startTime = curKqOvertimeRulesDetailEntity.getBefore_startTime(); + int overtimeEnable = curKqOvertimeRulesDetailEntity.getOvertimeEnable(); + if(overtimeEnable != 1){ + continue; + } + if(has_cut_point != 1){ + before_startTime = -1; + } + startTime = curKqOvertimeRulesDetailEntity.getStartTime(); + restTimeType = curKqOvertimeRulesDetailEntity.getRestTimeType(); + int paidLeaveEnable = kqOverTimeRuleCalBiz.getPaidLeaveEnable(curKqOvertimeRulesDetailEntity,overtime_type); + needSplitByTime = kqOverTimeRuleCalBiz.getNeedSplitByTime(curKqOvertimeRulesDetailEntity,paidLeaveEnable); + if(needSplitByTime){ + int ruleDetailid = curKqOvertimeRulesDetailEntity.getId(); + Map> balanceTimethDetailMap = kqOvertimeRulesBiz.getBalanceTimeDetailMap(ruleDetailid); + if(balanceTimethDetailMap != null && !balanceTimethDetailMap.isEmpty()){ + timepointList = balanceTimethDetailMap.get("timepointList"); + } + } + kqLog.info(i+">>>resourceid="+resourceid+",splitDate="+splitDate+",has_cut_point="+ has_cut_point+",changeType="+ changeType+",isRestshift="+ isRestshift+",isRestshift_next="+ isRestshift_next); + if(has_cut_point == 0){ + if(changeType == 2){ + overtime_cut_point = cur_beginwork_time; + }else { + if(changeType == 3){ + if(isRestshift){ + overtime_cut_point = tmp_cur_beginwork_time; + } + + /** + * 测试过程中有连续排很多休息班次的情况,比如今天休息班次是09:00-18:00,明天休息班次是12:00-22:00,导致计算次日的加班时长会受这个上班时间12:00的影响导致加班时长计算不准 + * 先全部按开始日期的所在的休息班次的上班时间来为分界点,下面的代码逻辑先注释 + * + if(isRestshift_next && overtime_cut_point.length() > 0 && tmp_next_beginwork_time.length() > 0){ + int next_beginwork_time_index = kqTimesArrayComInfo.getArrayindexByTimes(tmp_next_beginwork_time); + int overtime_cut_point_index = kqTimesArrayComInfo.getArrayindexByTimes(overtime_cut_point); + if(overtime_cut_point_index > next_beginwork_time_index){ + overtime_cut_point = next_beginwork_time; + } + } + */ + + } + + if(next_beginwork_time.length() > 0){ + overtime_cut_point = next_beginwork_time; + } + } + }else{ + overtime_cut_point = curKqOvertimeRulesDetailEntity.getCut_point(); + if(next_beginwork_time.length() > 0){ + int next_beginwork_time_index = kqTimesArrayComInfo.getArrayindexByTimes(next_beginwork_time); + int overtime_cut_point_index = kqTimesArrayComInfo.getArrayindexByTimes(overtime_cut_point); + if(overtime_cut_point_index > next_beginwork_time_index){ + overtime_cut_point = next_beginwork_time; + } + } + } + if(overtime_cut_point.length() == 0){ + overtime_cut_point = "00:00"; + } + }else{ + continue; + } + int fromTime_index = 0; + int toTime_index = 0; + kqLog.info(i+"resourceid="+resourceid+",splitDate="+splitDate+",overtime_cut_point11="+ overtime_cut_point); + if(i == 0){ + //i=0就是加班开始日期的前一天,只有当加班临界点超过了加班流程开始时间的话,i=0才会有可能计算出时长 + if(overtime_cut_point.compareTo(fromTime) > 0){ + fromTime_index = kqTimesArrayComInfo.getArrayindexByTimes(kqTimesArrayComInfo.turn24to48Time(fromTime)); + toTime_index = kqTimesArrayComInfo.getArrayindexByTimes(kqTimesArrayComInfo.turn24to48Time(overtime_cut_point)); + if(fromDate.equalsIgnoreCase(toDate)){ + //如果开始日期和结束日期是同一天,还需要比较流程的结束时间和归属点的大小 + int oriTotime_index = kqTimesArrayComInfo.getArrayindexByTimes(kqTimesArrayComInfo.turn24to48Time(toTime)); + if(toTime_index > oriTotime_index){ + toTime_index = oriTotime_index; + } + } + kqLog.info(i+">>>resourceid="+resourceid+",splitDate="+splitDate+",fromTime_index="+ fromTime_index+",toTime_index="+ toTime_index); + Arrays.fill(initArrays, fromTime_index, toTime_index, 0); +// 1-节假日、2-工作日、3-休息日 + if(changeType == 1){ + handle_changeType_1(initArrays,overRulesDetailMap,nextChangeType_key,next_changeType,next_beginwork_time); + }else if(changeType == 2){ + boolean isok = handle_changeType_2(initArrays, resourceid, splitDate, before_startTime, startTime, fromTime_index,kqTimesArrayComInfo,splitBean, + toTime_index); + serialid = splitBean.getSerialid(); + if(!isok){ + continue; + } + }else if(changeType == 3){ + handle_changeType_3(initArrays,overRulesDetailMap,nextChangeType_key,next_changeType,next_beginwork_time); + } + if(restTimeType == 1){ + //如果排除设置的休息时间 + handle_resttime(restTimeMap,changeType_key,kqTimesArrayComInfo,shouldAcross,initArrays); + } + curMins = kqTimesArrayComInfo.getCnt(initArrays, fromTime_index,toTime_index,0); + if(restTimeType == 2){ + //如果排除休息时间是扣除时长 + curMins = handle_restlength(curMins,restTimeMap,changeType_key); + } + kqLog.info(i+">>>resourceid="+resourceid+",splitDate="+splitDate+",curMins="+ curMins); + }else{ + continue; + } + }else{ + //除了i=0的情况,其他的每一天都是要获取一下昨日的临界点的 + String pre_overtime_cut_point = get_pre_overtime_cut_point(overRulesDetailMap,preChangeType_key,resourceid,preSplitDate,splitDate,preChangeType,kqTimesArrayComInfo,splitBean,changeType); + if(changeType == 2){ + //如果今天是工作日,昨日的打卡归属会受到今日的上班前开始加班分钟数的影响 + int cur_beginwork_time_index = kqTimesArrayComInfo.getArrayindexByTimes(cur_beginwork_time); + if(before_startTime > -1){ + int pre_overtime_cut_point_index = kqTimesArrayComInfo.getArrayindexByTimes(pre_overtime_cut_point); + int before_cur_beginwork_time_index = cur_beginwork_time_index - before_startTime; + } + } + //计算区间加班开始日期和加班结束日期这两天都是要特殊处理的 + fromTime_index = kqTimesArrayComInfo.getArrayindexByTimes(pre_overtime_cut_point); + if(i == 1){ + if(fromTime.compareTo(pre_overtime_cut_point) > 0){ + fromTime_index = kqTimesArrayComInfo.getArrayindexByTimes(fromTime); + } + } + kqLog.info(i+">>>resourceid="+resourceid+",splitDate="+splitDate+",betweenDays="+ betweenDays); + if(i == betweenDays){ + toTime_index = kqTimesArrayComInfo.getArrayindexByTimes(toTime); + }else{ + toTime_index = kqTimesArrayComInfo.turn24to48TimeIndex(kqTimesArrayComInfo.getArrayindexByTimes(overtime_cut_point)); +// kqLog.info(i+">>>resourceid="+resourceid+",splitDate="+splitDate+",toTime_index22="+ toTime_index); + if(tmp_next_beginwork_time.length() > 0){ + int overtime_cut_point_index = kqTimesArrayComInfo.getArrayindexByTimes(overtime_cut_point); + int next_beginwork_time_index = kqTimesArrayComInfo.getArrayindexByTimes(tmp_next_beginwork_time); + //如果临界点都已经超过第二天上班的开始时间了,要相应的缩短成第二天上班时间 + if(overtime_cut_point_index > next_beginwork_time_index){ + toTime_index = kqTimesArrayComInfo.turn24to48TimeIndex(next_beginwork_time_index); + } + } + if(next_beginwork_time.length() > 0){ + int overtime_cut_point_index = kqTimesArrayComInfo.getArrayindexByTimes(overtime_cut_point); + int next_beginwork_time_index = kqTimesArrayComInfo.getArrayindexByTimes(next_beginwork_time); + //如果临界点都已经超过第二天上班的开始时间了,要相应的缩短成第二天上班时间 + if(overtime_cut_point_index > next_beginwork_time_index){ + toTime_index = kqTimesArrayComInfo.turn24to48TimeIndex(next_beginwork_time_index); + } + } + if(i == betweenDays-1){ + int ori_totime_index = kqTimesArrayComInfo.turn48to24TimeIndex(toTime_index); + int last_toTime_index = kqTimesArrayComInfo.getArrayindexByTimes(toTime); + if(ori_totime_index > last_toTime_index){ + toTime_index = kqTimesArrayComInfo.turn24to48TimeIndex(last_toTime_index); + } + } + } + System.out.println(i+":betweenDays:"+betweenDays+":fromTime_index:"+fromTime_index+":toTime_index:"+toTime_index+":changeType:"+changeType); + + if(fromTime_index > toTime_index){ + continue; + } + Arrays.fill(initArrays, fromTime_index, toTime_index, 0); + + if(changeType == 1){ + handle_changeType_1(initArrays, overRulesDetailMap, nextChangeType_key, next_changeType, + next_beginwork_time); + }else if(changeType == 2){ + serialid = splitBean.getSerialid(); + boolean isok = handle_changeType_2(initArrays, resourceid, splitDate, before_startTime, startTime, fromTime_index, + kqTimesArrayComInfo, splitBean, toTime_index); + if(!isok){ + continue; + } + }else if(changeType == 3){ + handle_changeType_3(initArrays, overRulesDetailMap, nextChangeType_key, next_changeType, + overtime_cut_point); + } + if(restTimeType == 1) { + //如果排除设置的休息时间 + handle_resttime(restTimeMap, changeType_key, kqTimesArrayComInfo, shouldAcross,initArrays); + } + curMins = kqTimesArrayComInfo.getCnt(initArrays, fromTime_index,toTime_index,0); + + if(restTimeType == 2){ + //如果排除休息时间是扣除时长 + curMins = handle_restlength(curMins,restTimeMap,changeType_key); + } + kqLog.info(i+">>>resourceid="+resourceid+",splitDate="+splitDate+",curMins111="+ curMins); + } + int minimumUnit = curKqOvertimeRulesDetailEntity.getMinimumLen(); + if(curMins < minimumUnit){ + continue; + } + if(needSplitByTime){ + kqOverTimeRuleCalBiz.get_overtimeBalanceTimeBeans(timepointList,overtimeBalanceTimeBeans,kqTimesArrayComInfo,initArrays,toTime_index,fromTime_index,0); + + if(overtimeBalanceTimeBeans != null && !overtimeBalanceTimeBeans.isEmpty()){ + String bean_cross_fromtime = kqTimesArrayComInfo.getTimesByArrayindex(fromTime_index); + String bean_cross_totime = kqTimesArrayComInfo.getTimesByArrayindex(toTime_index); + for(int timeIndex = 0 ; timeIndex < overtimeBalanceTimeBeans.size() ;timeIndex++) { + OvertimeBalanceTimeBean overtimeBalanceTimeBean = overtimeBalanceTimeBeans.get(timeIndex); + String timePointStart = overtimeBalanceTimeBean.getTimepoint_start(); + String timePointEnd = overtimeBalanceTimeBean.getTimepoint_end(); + boolean isNeedTX = overtimeBalanceTimeBean.isNeedTX(); + int timePointStart_index = kqTimesArrayComInfo.getArrayindexByTimes(timePointStart); + int timePointEnd_index = kqTimesArrayComInfo.getArrayindexByTimes(timePointEnd); + if(timePointStart_index > fromTime_index){ + bean_cross_fromtime = kqTimesArrayComInfo.getTimesByArrayindex(timePointStart_index); + }else{ + bean_cross_fromtime = kqTimesArrayComInfo.getTimesByArrayindex(fromTime_index); + } + if(timePointEnd_index < toTime_index){ + bean_cross_totime = kqTimesArrayComInfo.getTimesByArrayindex(timePointEnd_index); + }else{ + bean_cross_totime = kqTimesArrayComInfo.getTimesByArrayindex(toTime_index); + } + int timepoint_mins = overtimeBalanceTimeBean.getTimepoint_mins(); + if(isNeedTX){ + if(timepoint_mins > 0){ + overSplitBean = new SplitBean(); + //然后把bean重新赋值下,根据拆分后的时间 + BeanUtils.copyProperties(splitBean, overSplitBean); + overSplitBean.setChangeType(changeType); + overSplitBean.setPreChangeType(preChangeType); + overSplitBean.setOneDayHour(oneDayHour); + overSplitBean.setWorkmins(workmins); + overSplitBean.setComputingMode(computingMode+""); + overSplitBean.setChangeType(changeType); + overSplitBean.setFromDate(splitDate); + overSplitBean.setFromTime(bean_cross_fromtime); + overSplitBean.setToDate(splitDate); + overSplitBean.setToTime(bean_cross_totime); + overSplitBean.setBelongDate(splitDate); + overSplitBean.setD_Mins(timepoint_mins); + overSplitBean.setOvertimeBalanceTimeBeans(overtimeBalanceTimeBeans); + overSplitBean.setSerialid(serialid); + getDurationByRule(overSplitBean); + splitBeans.add(overSplitBean); + } + } + } + } + }else{ + curMins = (int) kqOverTimeRuleCalBiz.getD_MinsByUnit(curMins); + overSplitBean.setChangeType(changeType); + overSplitBean.setPreChangeType(preChangeType); + overSplitBean.setOneDayHour(oneDayHour); + overSplitBean.setWorkmins(workmins); + overSplitBean.setComputingMode(computingMode+""); + overSplitBean.setChangeType(changeType); + overSplitBean.setFromDate(splitDate); + overSplitBean.setFromTime(kqTimesArrayComInfo.getTimesByArrayindex(fromTime_index)); + overSplitBean.setToDate(splitDate); + overSplitBean.setToTime(kqTimesArrayComInfo.getTimesByArrayindex(toTime_index)); + overSplitBean.setBelongDate(splitDate); + overSplitBean.setD_Mins(curMins); + overSplitBean.setOvertimeBalanceTimeBeans(overtimeBalanceTimeBeans); + overSplitBean.setSerialid(serialid); + getDurationByRule(overSplitBean); + splitBeans.add(overSplitBean); + } + } + + long b = System.currentTimeMillis(); + System.out.println("::"+(b-a)); + + }catch (Exception e){ + StringWriter errorsWriter = new StringWriter(); + e.printStackTrace(new PrintWriter(errorsWriter)); + kqLog.info(errorsWriter.toString()); + } + } + + + /** + * 被个性化设置处理下 得到实际的上下班时间 + * @param workLongTimeIndex + * @param real_workLongTimeIndex + * @param shiftInfoBean + * @param kqTimesArrayComInfo + * @param splitBean + */ + public void get_real_workLongTimeIndex(List workLongTimeIndex, + List real_workLongTimeIndex, + ShiftInfoBean shiftInfoBean, KQTimesArrayComInfo kqTimesArrayComInfo, + SplitBean splitBean) { + + //list带数组,这里要深拷贝 + for(int[] tmp : workLongTimeIndex){ + int[] real_tmp = new int[tmp.length]; + System.arraycopy(tmp, 0, real_tmp, 0, tmp.length); + real_workLongTimeIndex.add(real_tmp); + } + if(real_workLongTimeIndex.size() == 1){ + //个性化设置只支持一次打卡的 + KQShiftRuleInfoBiz kqShiftRuleInfoBiz = new KQShiftRuleInfoBiz(); + kqShiftRuleInfoBiz.rest_workLongTimeIndex(shiftInfoBean,splitBean,real_workLongTimeIndex,kqTimesArrayComInfo,null); + } + + } + + /** + * 获取一下昨日的临界点 + * @param overRulesDetailMap + * @param preChangeType_key + * @param resourceid + * @param preSplitDate + * @param splitDate + * @param preChangeType + * @param kqTimesArrayComInfo + * @param splitBean + * @param changeType + * @return + */ + private String get_pre_overtime_cut_point( + Map overRulesDetailMap, + String preChangeType_key, String resourceid, String preSplitDate, String splitDate, + int preChangeType, KQTimesArrayComInfo kqTimesArrayComInfo, + SplitBean splitBean, int changeType) { + + String pre_overtime_cut_point = ""; + KQOvertimeRulesDetailEntity preKqOvertimeRulesDetailEntity = overRulesDetailMap.get(preChangeType_key); + if(preKqOvertimeRulesDetailEntity != null){ + int has_cut_point = preKqOvertimeRulesDetailEntity.getHas_cut_point(); + if(has_cut_point == 0){ + if(preChangeType == 2){ + ShiftInfoBean pre_shiftInfoBean = KQDurationCalculatorUtil.getWorkTime(resourceid, preSplitDate, false); + if(pre_shiftInfoBean != null){ + List workLongTimeIndex = pre_shiftInfoBean.getWorkLongTimeIndex(); + List real_workLongTimeIndex = Lists.newArrayList(); + get_real_workLongTimeIndex(workLongTimeIndex,real_workLongTimeIndex,pre_shiftInfoBean,kqTimesArrayComInfo,splitBean); + + if(real_workLongTimeIndex != null && !real_workLongTimeIndex.isEmpty()){ + pre_overtime_cut_point = kqTimesArrayComInfo.getTimesByArrayindex(real_workLongTimeIndex.get(0)[0]); + } + } + }else { + String next_beginwork_time = ""; + //单独搞下开发的休息班次 + if(preChangeType == 3){ + ShiftInfoBean pre_shiftInfoBean = KQDurationCalculatorUtil.getWorkTimeNew(resourceid, preSplitDate, false); + if(pre_shiftInfoBean != null){ + int serialid = StringUtil.parseToInt(pre_shiftInfoBean.getSerialid(), 0); + KQShiftManagementComInfo kQShiftManagementComInfo = new KQShiftManagementComInfo(); + int restShift = StringUtil.parseToInt(kQShiftManagementComInfo.getRestShift(String.valueOf(serialid)), 0); + if(serialid > 0 && restShift == 1) { + List workLongTimeIndex = pre_shiftInfoBean.getWorkLongTimeIndex(); + List real_workLongTimeIndex = Lists.newArrayList(); + get_real_workLongTimeIndex(workLongTimeIndex,real_workLongTimeIndex,pre_shiftInfoBean,kqTimesArrayComInfo,splitBean); + + if(real_workLongTimeIndex != null && !real_workLongTimeIndex.isEmpty()){ + pre_overtime_cut_point = kqTimesArrayComInfo.getTimesByArrayindex(real_workLongTimeIndex.get(0)[0]); + } + } + } + +// ShiftInfoBean next_shiftInfoBean = KQDurationCalculatorUtil.getWorkTimeNew(resourceid, splitDate, false); +// if(next_shiftInfoBean != null){ +// int serialid = StringUtil.parseToInt(next_shiftInfoBean.getSerialid(), 0); +// KQShiftManagementComInfo kQShiftManagementComInfo = new KQShiftManagementComInfo(); +// int restShift = StringUtil.parseToInt(kQShiftManagementComInfo.getRestShift(String.valueOf(serialid)), 0); +// if(serialid > 0 && restShift == 1) { +// List workLongTimeIndex = next_shiftInfoBean.getWorkLongTimeIndex(); +// List real_workLongTimeIndex = Lists.newArrayList(); +// get_real_workLongTimeIndex(workLongTimeIndex,real_workLongTimeIndex,next_shiftInfoBean,kqTimesArrayComInfo,splitBean); +// +// if(real_workLongTimeIndex != null && !real_workLongTimeIndex.isEmpty()){ +// next_beginwork_time = kqTimesArrayComInfo.getTimesByArrayindex(real_workLongTimeIndex.get(0)[0]); +// } +// } +// } + } + + if(changeType == 2){ + ShiftInfoBean next_shiftInfoBean = KQDurationCalculatorUtil.getWorkTime(resourceid, splitDate, false); + if(next_shiftInfoBean != null){ + List workLongTimeIndex = next_shiftInfoBean.getWorkLongTimeIndex(); + List real_workLongTimeIndex = Lists.newArrayList(); + get_real_workLongTimeIndex(workLongTimeIndex,real_workLongTimeIndex,next_shiftInfoBean,kqTimesArrayComInfo,splitBean); + + if(real_workLongTimeIndex != null && !real_workLongTimeIndex.isEmpty()){ + next_beginwork_time = kqTimesArrayComInfo.getTimesByArrayindex(real_workLongTimeIndex.get(0)[0]); + } + } + } + if(next_beginwork_time.length() > 0){ + pre_overtime_cut_point = next_beginwork_time; + } + } + }else{ + pre_overtime_cut_point = preKqOvertimeRulesDetailEntity.getCut_point(); + } + if(pre_overtime_cut_point.length() == 0){ + pre_overtime_cut_point = "00:00"; + } + } + return pre_overtime_cut_point; + } + + /** + * 处理节假日的加班 + * @param initArrays + * @param overRulesDetailMap + * @param nextChangeType_key + * @param next_changeType + * @param next_beginwork_time + */ + public void handle_changeType_1(int[] initArrays, + Map overRulesDetailMap, + String nextChangeType_key, int next_changeType, String next_beginwork_time){ + KQOvertimeRulesDetailEntity nextKqOvertimeRulesDetailEntity = overRulesDetailMap.get(nextChangeType_key); +// if(nextKqOvertimeRulesDetailEntity != null){ +// if(next_changeType == 2){ +// //如果明日是工作日 工作日如果设置了上班前分钟,会导致加班归属被设置的分钟数给切断,上班前某些部分属于今天不属于昨日 +// int overtimeEnable = nextKqOvertimeRulesDetailEntity.getOvertimeEnable(); +// if(overtimeEnable == 1){ +// KQTimesArrayComInfo kqTimesArrayComInfo = new KQTimesArrayComInfo(); +// int before_startTime = nextKqOvertimeRulesDetailEntity.getBefore_startTime(); +// int has_cut_point = nextKqOvertimeRulesDetailEntity.getHas_cut_point(); +// if(has_cut_point != 1){ +// before_startTime = -1; +// } +// int next_beginwork_time_index = kqTimesArrayComInfo.getArrayindexByTimes(next_beginwork_time); +// if(before_startTime > -1){ +// int before_next_beginwork_time_index = next_beginwork_time_index - before_startTime; +// if(before_next_beginwork_time_index > 0 && before_next_beginwork_time_index < next_beginwork_time_index){ +// before_next_beginwork_time_index = kqTimesArrayComInfo.turn24to48TimeIndex(before_next_beginwork_time_index); +// next_beginwork_time_index = kqTimesArrayComInfo.turn24to48TimeIndex(next_beginwork_time_index); +// Arrays.fill(initArrays, before_next_beginwork_time_index,next_beginwork_time_index,-1); +// } +// } +// } +// } +// } + } + + /** + * 排除休息时间 现在工作日,节假日和休息日都可以设置排除休息时间 + * @param restTimeMap + * @param changeType_key + * @param kqTimesArrayComInfo + * @param shouldAcross + * @param initArrays + */ + public void handle_resttime(Map> restTimeMap, String changeType_key, KQTimesArrayComInfo kqTimesArrayComInfo, boolean shouldAcross, int[] initArrays) { + + if(restTimeMap.containsKey(changeType_key)){ + List restTimeList = restTimeMap.get(changeType_key); + //再把休息时间填充上去 + if(!restTimeList.isEmpty()){ + for(int k =0 ; k < restTimeList.size() ; k++){ + String[] restTimes = restTimeList.get(k); + if(restTimes.length == 2){ + int restStart = kqTimesArrayComInfo.getArrayindexByTimes(restTimes[0]); + int restEnd = kqTimesArrayComInfo.getArrayindexByTimes(restTimes[1]); +// if(shouldAcross && restEnd == 1439){ + if(restEnd == 1439){ + //针对跨天的休息时段单独处理排除掉23:59-00:00的时间 + restEnd = 1440; + } + int hasRestMins = kqTimesArrayComInfo.getCnt(initArrays, restStart,restEnd,0); + if(hasRestMins == 0) { + restStart = kqTimesArrayComInfo.turn24to48TimeIndex(restStart); + restEnd = kqTimesArrayComInfo.turn24to48TimeIndex(restEnd); + } + Arrays.fill(initArrays, restStart, restEnd, 1); + } + } + } + } + } + + /** + * 排除休息时长 根据加班时长排除指定时长 + * @param curMins + * @param restTimeMap + * @param changeType_key + * @return + */ + public int handle_restlength(int curMins, Map> restTimeMap, String changeType_key) { + if(restTimeMap.containsKey(changeType_key)) { + List restTimeList = restTimeMap.get(changeType_key); + //再把休息时间填充上去 + if (!restTimeList.isEmpty()) { + for(int k = restTimeList.size()-1 ; k >= 0 ; k--) { + String[] restTimes = restTimeList.get(k); + if (restTimes.length == 2) { + //overlength 是满多少小时 cutlength是减去多少小时 + double overlength = Util.getDoubleValue(restTimes[0],-1); + double cutlength = Util.getDoubleValue(restTimes[1],-1); + if(overlength > -1 && cutlength > -1){ + double min_overlength = overlength * 60; + double min_cutlength = cutlength * 60; + if(curMins >= min_overlength){ + curMins = (int) (curMins-min_cutlength); + break; + } + } + } + } + + } + } + return curMins; + } + + /** + * 处理工作日的加班 + * @param initArrays + * @param resourceid + * @param splitDate + * @param before_startTime + * @param startTime + * @param fromTime_index + * @param kqTimesArrayComInfo + * @param splitBean + * @param toTime_index + * @return + */ + public boolean handle_changeType_2(int[] initArrays, String resourceid, String splitDate, + int before_startTime, int startTime, int fromTime_index, + KQTimesArrayComInfo kqTimesArrayComInfo, SplitBean splitBean, int toTime_index){ + + boolean isok = true; + ShiftInfoBean cur_shiftInfoBean = KQDurationCalculatorUtil.getWorkTime(resourceid, splitDate, false); + if(cur_shiftInfoBean != null){ + splitBean.setSerialid(cur_shiftInfoBean.getSerialid()); + List workLongTimeIndex = cur_shiftInfoBean.getWorkLongTimeIndex(); + List real_workLongTimeIndex = Lists.newArrayList(); + get_real_workLongTimeIndex(workLongTimeIndex,real_workLongTimeIndex,cur_shiftInfoBean,kqTimesArrayComInfo,splitBean); + if(real_workLongTimeIndex != null && !real_workLongTimeIndex.isEmpty()){ + int all_firstworktime = 0; + int all_lastworktime = 0; + boolean need_middle_time = false; + for(int k = 0 ; k < real_workLongTimeIndex.size() ; k++){ + int workLongTimeStartIndex = real_workLongTimeIndex.get(k)[0]; + int workLongTimeEndIndex = real_workLongTimeIndex.get(k)[1]; + if(k == 0){ + if(before_startTime > -1){ + int before_workLongTimeStartIndex = workLongTimeStartIndex-before_startTime; + if(before_workLongTimeStartIndex > 0){ + //从前一天的加班归属点到今天的上班前开始加班点,这段时间属于两不靠。需要排除 + if(fromTime_index < before_workLongTimeStartIndex){ + Arrays.fill(initArrays, fromTime_index,before_workLongTimeStartIndex,-1); + } + } + } + all_firstworktime = workLongTimeStartIndex; + } + if(k == real_workLongTimeIndex.size()-1){ + if(startTime > -1){ + int after_workLongTimeEndIndex = workLongTimeEndIndex+startTime; + if(workLongTimeEndIndex < after_workLongTimeEndIndex){ + Arrays.fill(initArrays, workLongTimeEndIndex,after_workLongTimeEndIndex,-1); + } + } + all_lastworktime = workLongTimeEndIndex; + } + if(!need_middle_time){ + //目前标准加班,一天多次打卡的话是不算中间时间的,只算上班前和下班后的加班 + }else{ + //这个里面是可以算一天多次打卡的话是中间时间的 + Arrays.fill(initArrays, workLongTimeStartIndex,workLongTimeEndIndex,1); + } + } + if(!need_middle_time){ + Arrays.fill(initArrays, all_firstworktime,all_lastworktime,1); + } + List restLongTimeIndex = cur_shiftInfoBean.getRestLongTimeIndex(); + if(restLongTimeIndex != null && !restLongTimeIndex.isEmpty()){ + for (int k = 0; k < restLongTimeIndex.size(); k++) { + //休息时段填充2 + Arrays.fill(initArrays, restLongTimeIndex.get(k)[0], restLongTimeIndex.get(k)[1], 2); + } + } + }else { + System.out.println("error"); + isok = false; + } + }else { + System.out.println("error"); + isok = false; + } + + return isok; + } + /** + * 处理休息日的加班 + * @param restTimeMap + * @param initArrays + * @param overRulesDetailMap + * @param nextChangeType_key + * @param next_changeType + * @param next_beginwork_time + */ + public void handle_changeType_3(int[] initArrays, + Map overRulesDetailMap, + String nextChangeType_key, int next_changeType, String next_beginwork_time){ + KQOvertimeRulesDetailEntity nextKqOvertimeRulesDetailEntity = overRulesDetailMap.get(nextChangeType_key); +// if(nextKqOvertimeRulesDetailEntity != null){ +// if(next_changeType == 2){ +// //如果明日是工作日 工作日如果设置了上班前分钟,会导致加班归属被设置的分钟数给切断,上班前某些部分属于今天不属于昨日 +// int overtimeEnable = nextKqOvertimeRulesDetailEntity.getOvertimeEnable(); +// if(overtimeEnable == 1){ +// KQTimesArrayComInfo kqTimesArrayComInfo = new KQTimesArrayComInfo(); +// int before_startTime = nextKqOvertimeRulesDetailEntity.getBefore_startTime(); +// int has_cut_point = nextKqOvertimeRulesDetailEntity.getHas_cut_point(); +// if(has_cut_point != 1){ +// before_startTime = -1; +// } +// int next_beginwork_time_index = kqTimesArrayComInfo.getArrayindexByTimes(next_beginwork_time); +// if(before_startTime > -1){ +// int before_next_beginwork_time_index = next_beginwork_time_index - before_startTime; +// if(before_next_beginwork_time_index > 0 && before_next_beginwork_time_index < next_beginwork_time_index){ +// before_next_beginwork_time_index = kqTimesArrayComInfo.turn24to48TimeIndex(before_next_beginwork_time_index); +// next_beginwork_time_index = kqTimesArrayComInfo.turn24to48TimeIndex(next_beginwork_time_index); +// Arrays.fill(initArrays, before_next_beginwork_time_index,next_beginwork_time_index,-1); +// } +// } +// } +// } +// } + } + + public void getDurationByRule(SplitBean splitBean) { + double D_Mins = splitBean.getD_Mins(); + int workmins = splitBean.getWorkmins(); + String durationrule = splitBean.getDurationrule(); + if("3".equalsIgnoreCase(durationrule) || "5".equalsIgnoreCase(durationrule) + || "6".equalsIgnoreCase(durationrule)){ + double d_hour = D_Mins/60.0; + splitBean.setDuration(KQDurationCalculatorUtil.getDurationRound5(""+d_hour)); + }else if("1".equalsIgnoreCase(durationrule)){ + double d_day = D_Mins/workmins; + splitBean.setDuration(KQDurationCalculatorUtil.getDurationRound5(""+d_day)); + } + } +} diff --git a/src/com/engine/kq/biz/KQOverTimeRuleCalBiz.java b/src/com/engine/kq/biz/KQOverTimeRuleCalBiz.java new file mode 100644 index 0000000..3a494ff --- /dev/null +++ b/src/com/engine/kq/biz/KQOverTimeRuleCalBiz.java @@ -0,0 +1,2798 @@ +package com.engine.kq.biz; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.engine.kq.biz.chain.shiftinfo.ShiftInfoBean; +import com.engine.kq.entity.KQOvertimeRulesDetailEntity; +import com.engine.kq.entity.KQUsageHistoryEntity; +import com.engine.kq.entity.TimeScopeEntity; +import com.engine.kq.entity.WorkTimeEntity; +import com.engine.kq.log.KQLog; +import com.engine.kq.timer.KQOvertimeCardBean; +import com.engine.kq.util.KQDurationCalculatorUtil; +import com.engine.kq.wfset.bean.OvertimeBalanceTimeBean; +import com.engine.kq.wfset.bean.SplitBean; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.UUID; +import java.util.stream.Collectors; +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.general.Util; + +/** + * 根据加班规则计算加班和调休数据 + * 主要是针对 流程+打卡 打卡 这几种方式 + */ +public class KQOverTimeRuleCalBiz { + private KQLog kqLog = new KQLog(); + + /** + * 生成加班数据 + * @param resourceid + * @param fromDate + * @param toDate + * @param eventtype + */ + public void buildOvertime(String resourceid, String fromDate, String toDate, String eventtype){ + + try{ + DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + + KQTimesArrayComInfo kqTimesArrayComInfo = new KQTimesArrayComInfo(); + Map changeTypeMap = Maps.newHashMap(); + Map overRulesDetailMap = Maps.newHashMap(); + Map> restTimeMap = Maps.newHashMap(); + Map computingModeMap = Maps.newHashMap(); + //先获取一些前提数据,加班規則和假期規則 + getOverTimeDataMap(resourceid, fromDate, toDate, dateFormatter,changeTypeMap,overRulesDetailMap,restTimeMap,computingModeMap); + Map eventLogMap = Maps.newHashMap(); + eventLogMap.put("fromDate", fromDate); + eventLogMap.put("toDate", toDate); + eventLogMap.put("eventtype", eventtype); + KQOvertimeLogBiz kqEventLogBiz = new KQOvertimeLogBiz(); + String logKey = "|key|"+resourceid+"_"+fromDate+"_"+toDate; + String uuid = kqEventLogBiz.logEvent(resourceid,eventLogMap,"buildOvertime|生成加班调休"+logKey); + + LocalDate localFromDate = LocalDate.parse(fromDate); + LocalDate localToDate = LocalDate.parse(toDate); + LocalDate preFromDate = localFromDate.minusDays(1); + LocalDate nextToDate = localToDate.plusDays(1); + //之前是考虑外部考勤数据导入跨天打卡,判断归属的问题,向前算一天,现在不管了,都是默认只处理当天的 + if(eventtype.indexOf("#flow,") > -1 || eventtype.indexOf("punchcard") > -1 || true){ + //如果是正常走的加班流程,就是流程开始日期和结束日期,只有补卡,打卡,同步的时候才需要处理一下前一天和后一天的数据 + preFromDate = localFromDate; + nextToDate = localToDate; + } + long betweenDays = nextToDate.toEpochDay() - preFromDate.toEpochDay(); + for (int i = 0; i <= betweenDays; i++) { + LocalDate curLocalDate = preFromDate.plusDays(i); + String splitDate = curLocalDate.format(dateFormatter); + String key = resourceid + "_" + splitDate; + String change_key = splitDate + "_" + resourceid; + int changeType = Util.getIntValue("" + changeTypeMap.get(change_key), -1); + String changeType_key = splitDate + "_" + changeType; + int computingMode = Util.getIntValue(""+computingModeMap.get(changeType_key),-1); + if(computingMode == 2){ +// 需审批,以打卡为准,但是不能超过审批时长 + doComputingMode2(resourceid,splitDate,dateFormatter,changeTypeMap,overRulesDetailMap,restTimeMap, + computingModeMap,kqTimesArrayComInfo,uuid); + } + if(computingMode == 3){ +// 无需审批,根据打卡时间计算加班时长 + doComputingMode3(resourceid,splitDate,dateFormatter,changeTypeMap,overRulesDetailMap,restTimeMap, + computingModeMap,kqTimesArrayComInfo,uuid); + } + if(computingMode == 4){ +// 需审批,以打卡为准,取流程和打卡的交集 + doComputingMode4(resourceid,splitDate,dateFormatter,changeTypeMap,overRulesDetailMap,restTimeMap, + computingModeMap,kqTimesArrayComInfo,uuid); + } + } + fromDate=preFromDate.format(dateFormatter); + updateTiaoXiu(resourceid, fromDate, toDate); + }catch (Exception e){ + kqLog.info("加班生成数据报错:KQOverTimeRuleCalBiz:"); + StringWriter errorsWriter = new StringWriter(); + e.printStackTrace(new PrintWriter(errorsWriter)); + kqLog.info(errorsWriter.toString()); + } + } + + + /** + * 更新调休 + * @param resourceid + * @param fromDate + * @param toDate + */ + public void updateTiaoXiu(String resourceid, String fromDate, String toDate){ + //假期类型的缓存类 + KQLeaveRulesComInfo rulesComInfo = new KQLeaveRulesComInfo(); + //[调休]的假期类型的ID + String leaveRulesId = ""; + //找到[调休]的假期类型ID + rulesComInfo.setTofirstRow(); + while (rulesComInfo.next()) { + if (KQLeaveRulesBiz.isTiaoXiu(rulesComInfo.getId())) { + if("1".equals(rulesComInfo.getIsEnable())){ + leaveRulesId = rulesComInfo.getId(); + break; + } + } + } + if("".equals(leaveRulesId) || null == leaveRulesId){ + return; + } + RecordSet recordSet = new RecordSet(); + String sql = " select * from kq_balanceOfLeave " + + " where (isDelete is null or isDelete<>1) and resourceId=" + resourceid + + " and leaveRulesId=" + leaveRulesId + + " and effectiveDate>='" + fromDate + "' and effectiveDate<='" +toDate+"'"+ + " order by belongYear asc,effectiveDate asc,id asc "; + recordSet.executeQuery(sql); + String all_tiaoxiuids = ""; + BigDecimal duration = new BigDecimal("0"); + while (recordSet.next()) { + //额外 + 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")); + + if (extraAmount.add(tiaoxiuAmount).subtract(usedAmount).doubleValue() >= 0) { + continue; + } + String id = recordSet.getString("id"); + if(id.length() > 0 && Util.getIntValue(id) > 0){ + all_tiaoxiuids += ","+id; + duration =duration.add(extraAmount).add(tiaoxiuAmount).subtract(usedAmount); + } + } + duration = duration.abs(); + List updateList = new ArrayList(); + sql = " select * from kq_balanceOfLeave " + + " where (isDelete is null or isDelete<>1) and resourceId=" + resourceid + + " and leaveRulesId=" + leaveRulesId + + " and effectiveDate>='" + fromDate + "'"+ + " order by belongYear asc,effectiveDate asc,id asc "; + recordSet.executeQuery(sql); + int total = recordSet.getCounts(); + int index = 0; + while (recordSet.next()) { + index++; + String id = recordSet.getString("id"); + //额外 + 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")); + + if (extraAmount.add(tiaoxiuAmount).subtract(usedAmount).doubleValue() <= 0) { + continue; + } + BigDecimal temp = extraAmount.add(tiaoxiuAmount).subtract(usedAmount).subtract(duration); + /*该假期剩余假期余额不足以扣减,记录错误日志,退出方法*/ + if (index == total && temp.doubleValue() < 0) { + kqLog.info("该人员的该假期所有的剩余假期余额都不足以扣减。" + + "resourceId=" + resourceid + ",date=" + fromDate + ",ruleId=" + leaveRulesId + ",duration=" + duration + ",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) + " where id=" + id; + updateList.add(updateSql); + break; + } + if (temp.doubleValue() >= 0) { + String newUsedAmount = usedAmount.add(duration).setScale(5, RoundingMode.HALF_UP).toPlainString(); + String updateSql = "update kq_balanceOfLeave set usedAmount=" + (newUsedAmount) + " where id=" + id; + updateList.add(updateSql); + break; + } else { + duration = duration.add(usedAmount).subtract(extraAmount).subtract(tiaoxiuAmount); + String newUsedAmount = extraAmount.add(tiaoxiuAmount).setScale(5, RoundingMode.HALF_UP).toPlainString(); + String updateSql = "update kq_balanceOfLeave set usedAmount=" + (newUsedAmount) + " where id=" + id; + updateList.add(updateSql); + continue; + } + } + if(all_tiaoxiuids.length() > 0) { + all_tiaoxiuids = all_tiaoxiuids.substring(1); + updateList.add("update kq_balanceOfLeave set isDelete=1 where id in (" +all_tiaoxiuids+")"); + } + kqLog.info("updateList:"+updateList); + /*SQL操作批处理*/ + for (int i = 0; i < updateList.size(); i++) { + boolean flag = recordSet.executeUpdate(updateList.get(i)); + if (!flag) { + kqLog.info("刷新加班流程数据失败:数据库更新失败" ); + return; + } + } + + } + + /** + * 需审批,以打卡为准,取流程和打卡的交集 + * @param resourceid + * @param splitDate + * @param dateFormatter + * @param changeTypeMap + * @param overRulesDetailMap + * @param restTimeMap + * @param computingModeMap + * @param kqTimesArrayComInfo + * @param main_uuid + */ + private void doComputingMode4(String resourceid, String splitDate, + DateTimeFormatter dateFormatter, Map changeTypeMap, + Map overRulesDetailMap, + Map> restTimeMap, Map computingModeMap, + KQTimesArrayComInfo kqTimesArrayComInfo, String main_uuid) throws Exception{ + String key = resourceid+"_"+splitDate; + //加班日志记录类 + KQWorkTime kqWorkTime = new KQWorkTime(); + WorkTimeEntity workTimeEntity = kqWorkTime.getWorkTime(resourceid, splitDate); + Map workTimeEntityLogMap = Maps.newHashMap(); + workTimeEntityLogMap.put("resourceid", resourceid); + workTimeEntityLogMap.put("splitDate", splitDate); + workTimeEntityLogMap.put("workTimeEntity", workTimeEntity); + KQOvertimeLogBiz kqEventLogBiz = new KQOvertimeLogBiz(); + String uuid = kqEventLogBiz.logDetailWorkTimeEntity(resourceid,workTimeEntityLogMap,main_uuid,"doComputingMode4|加班计算,需审批,以打卡为准,取流程和打卡的交集|key|"+key); + Map overtimeLogMap = Maps.newLinkedHashMap(); + + Map eventMap = Maps.newLinkedHashMap(); + Map lsCheckInfoMaps = Maps.newLinkedHashMap(); + //获取加班打卡数据 + getOverTimeCardDataMap(resourceid, splitDate, splitDate, dateFormatter,kqTimesArrayComInfo,overRulesDetailMap,changeTypeMap,lsCheckInfoMaps,eventMap); + + if(lsCheckInfoMaps.isEmpty()){ + logOvertimeMap(overtimeLogMap, "没有打卡数据", "打卡和上下班数据|KQOvertimeCardBean"); + kqEventLogBiz.logDetailOvertimeMap(resourceid,overtimeLogMap,uuid); + kqEventLogBiz.logDetailEvent(resourceid,eventMap,uuid,"doComputingMode4|对应的加班流程数据|key|"+key); + return; + } + RecordSet rs = new RecordSet(); + + Iterator> iterator = lsCheckInfoMaps.entrySet().iterator(); + while (iterator.hasNext()) { + Entry next = iterator.next(); + String mapKey = next.getKey(); + KQOvertimeCardBean kqOvertimeCardBean = next.getValue(); + String[] mapKeys = mapKey.split("_"); + if (mapKeys.length != 2) { + continue; + } + String realSplitDate = mapKeys[1]; + + Map> splitBeanMaps = Maps.newHashMap(); + //获取加班流程数据 + getOverTimeFlowData(resourceid,realSplitDate,realSplitDate,splitBeanMaps,dateFormatter); + + String change_key = realSplitDate+"_"+resourceid; + int changeType = Util.getIntValue(""+changeTypeMap.get(change_key),-1); + String changeType_key = realSplitDate+"_"+changeType; + String changetypeName = 1==changeType ? "节假日" : (2 == changeType ? "工作日" : (3 == changeType ? "休息日" : "异常")); + String changetypeLogInfo = change_key+"|changeType|"+changeType+"|"+changetypeName; + logOvertimeMap(overtimeLogMap, changetypeLogInfo, mapKey+"|"+"加班日期属性|changetypeLogInfo"); + + clearOvertimeTX(resourceid, realSplitDate,overtimeLogMap,splitDate); + logOvertimeMap(overtimeLogMap, kqOvertimeCardBean, mapKey+"|"+"打卡和上下班数据|KQOvertimeCardBean"); + + KQOvertimeRulesDetailEntity kqOvertimeRulesDetailEntity = overRulesDetailMap.get(changeType_key); + if(kqOvertimeRulesDetailEntity == null){ + String overRuleInfo = "changeType_key:"+changeType_key+":kqOvertimeRulesDetailEntity:"+kqOvertimeRulesDetailEntity; + logOvertimeMap(overtimeLogMap, overRuleInfo, mapKey+"|"+"加班规则为null|kqOvertimeRulesDetailEntity"); + continue; + } + int overtimeEnable = kqOvertimeRulesDetailEntity.getOvertimeEnable(); + if(overtimeEnable != 1){ + String overtimeEnableInfo = "overtimeEnable:"+overtimeEnable; + logOvertimeMap(overtimeLogMap, overtimeEnableInfo, mapKey+"|"+"未开启加班规则|overtimeEnable"); + continue; + } + + if(kqOvertimeCardBean != null){ + + int[] initArrays = kqTimesArrayComInfo.getInitArr(); + List> hasOverTime4SignList = Lists.newArrayList(); + getHasOverTimeData(resourceid,realSplitDate,hasOverTime4SignList); + Map signinoffMap = buildOvertimeCard(kqOvertimeCardBean, resourceid, realSplitDate, kqTimesArrayComInfo, restTimeMap, changeType_key,initArrays,hasOverTime4SignList, + overRulesDetailMap,true,overtimeLogMap); + logOvertimeMap(overtimeLogMap, signinoffMap, mapKey+"|"+"获取上下班打卡数据|signinoffMap"); + + String signinTime = Util.null2String(signinoffMap.get("signinTime")); + String signoutTime = Util.null2String(signinoffMap.get("signoutTime")); + String signinDate = Util.null2String(signinoffMap.get("signinDate")); + String signoutDate = Util.null2String(signinoffMap.get("signoutDate")); + int signinTimeIndex = kqTimesArrayComInfo.getArrayindexByTimes(signinTime); + int signoutTimeIndex = kqTimesArrayComInfo.getArrayindexByTimes(signoutTime); + + if(signinTimeIndex < signoutTimeIndex){ + //先覆盖打卡 打卡区间都是1 + int over_count = kqTimesArrayComInfo.getCnt(initArrays, signinTimeIndex, signoutTimeIndex, 1); + String overCountLogInfo = "signinTimeIndex:"+signinTimeIndex+":signoutTimeIndex:"+signoutTimeIndex+":over_count:"+over_count; + logOvertimeMap(overtimeLogMap, overCountLogInfo, mapKey+"|"+"打卡区间,得到打卡时长|over_count"); + if(over_count > 0){ + int restTimeType = 1; + String kqOvertimeRulesDetailEntityLogInfo = kqOvertimeRulesDetailEntity==null ? "" :JSON.toJSONString(kqOvertimeRulesDetailEntity); + logOvertimeMap(overtimeLogMap, kqOvertimeRulesDetailEntityLogInfo, mapKey+"|具体这个人这一天对应的加班规则|KQOvertimeRulesDetailEntity"); + int minimumLen = -1; + if(kqOvertimeRulesDetailEntity != null){ + minimumLen = kqOvertimeRulesDetailEntity.getMinimumLen(); + if(over_count < minimumLen){ + String minInfo = "over_count:"+over_count+":minimumLen:"+minimumLen; + logOvertimeMap(overtimeLogMap, minInfo, mapKey+"|打卡时长小于最小加班时长|over_count splitBeans = splitBeanMaps.get(mapKey); + String flowinfo = ""; + if(splitBeans != null && !splitBeans.isEmpty()){ + flowinfo = JSON.toJSONString(splitBeans, SerializerFeature.DisableCheckSpecialChar,SerializerFeature.DisableCircularReferenceDetect); + } + eventMap.put(mapKey+"|"+"加班流程数据|flowinfo", flowinfo); + + if(splitBeans == null || splitBeans.isEmpty()){ + return; + } + + for (int m = 0; m < splitBeans.size(); m++) { + SplitBean splitBean = splitBeans.get(m); + String dataid = splitBean.getDataId(); + String detailid = splitBean.getDetailId(); + String flow_fromdate = splitBean.getFromDate(); + String flow_fromtime = splitBean.getFromTime(); + String flow_todate = splitBean.getToDate(); + String flow_totime = splitBean.getToTime(); + String fromdatedb = splitBean.getFromdatedb(); + String fromtimedb = splitBean.getFromtimedb(); + String todatedb = splitBean.getTodatedb(); + String totimedb = splitBean.getTotimedb(); + String requestid = splitBean.getRequestId(); + double d_mins = splitBean.getD_Mins(); + if(d_mins <= 0){ + continue; + } + String flow_key = mapKey+"|"+"flow_fromdate|"+flow_fromdate+"|flow_todate|"+flow_todate + +"|flow_fromtime|"+flow_fromtime+"|flow_totime|"+flow_totime; + //如果打卡数据有了,再拿流程数据去覆盖,得到有效的打卡区间,这个区间肯定已经是去除了上下班时间和休息时间还有重复打卡的部分 + List cross_time_list = Lists.newArrayList(); +// cross_time_list里存的是排除了工作时间的打卡段,找到1表示找到打卡开始的点了,找到-2表示找到打卡结束的点了 + get_cross_time_list(cross_time_list,initArrays,signinTimeIndex,signoutTimeIndex,1,-2); + logOvertimeMap(overtimeLogMap, cross_time_list, flow_key+"|cross_time_list"); + int[] initArrays_flow = Arrays.copyOfRange(initArrays,0,initArrays.length); + if(flow_fromdate.compareTo(realSplitDate) > 0){ + flow_fromtime = kqTimesArrayComInfo.turn24to48Time(flow_fromtime); + } + if(flow_todate.compareTo(realSplitDate) > 0){ + flow_totime = kqTimesArrayComInfo.turn24to48Time(flow_totime); + } + int flow_fromIndex = kqTimesArrayComInfo.getArrayindexByTimes(flow_fromtime); + int flow_toIndex = kqTimesArrayComInfo.getArrayindexByTimes(flow_totime); + //在已经打卡的区间1上覆盖2,那么在有效打卡范围内是2的就是交集的部分 + Arrays.fill(initArrays_flow, flow_fromIndex, flow_toIndex,2); +// 本来下面的这个地方是处理重复流程的问题,比如提了两个流程19-20,19-21,那么这俩流程相互交叉的话也只能生成2个小时,但是后来讨论 +// 流程直接的重复校验就通过开那个校验规则了,每一个流程都是和打卡的比较,所以一个是1一个是2.总共3 +// List> hasOverTimeList = Lists.newArrayList(); +// getHasOverTimeData(resourceid,realSplitDate,hasOverTimeList); +// logOvertimeMap(overtimeLogMap, hasOverTimeList, flow_key+"|是否已经生成过加班,返回已经生成过加班的区间|hasOverTimeList"); +// if(hasOverTimeList != null && !hasOverTimeList.isEmpty()){ +// for(int p = 0 ; p < hasOverTimeList.size(); p++){ +// Map hasOverTimeMap = hasOverTimeList.get(p); +// +// String fromdate_flow = Util.null2String(hasOverTimeMap.get("fromdate_flow")); +// String fromtime_flow = Util.null2String(hasOverTimeMap.get("fromtime_flow")); +// String todate_flow = Util.null2String(hasOverTimeMap.get("todate_flow")); +// String totime_flow = Util.null2String(hasOverTimeMap.get("totime_flow")); +// int has_flow_fromIndex = kqTimesArrayComInfo.getArrayindexByTimes(fromtime_flow); +// int has_totime_flow = kqTimesArrayComInfo.getArrayindexByTimes(totime_flow); +// //把重复的流程给去掉,覆盖成-1 +// Arrays.fill(initArrays_flow, has_flow_fromIndex, has_totime_flow,-2); +// } +// } + + int across_mins = 0; + for(int i = 0 ; i < cross_time_list.size() ;) { + int cross_fromtime_index = cross_time_list.get(i); + int cross_totime_index = cross_time_list.get(i + 1); + //前面打卡区间段已经都被流程给覆盖了,所以取获取打卡区间段内有多少流程的标识2,就是交叉部分了 + int flow_count = kqTimesArrayComInfo.getCnt(initArrays_flow, cross_fromtime_index, cross_totime_index, 2); + logOvertimeMap(overtimeLogMap, flow_count, flow_key+"|取打卡和流程相交的时长|flow_count"); + + if(flow_count > 0){ + List flow_cross_time_list = Lists.newArrayList(); + // 找到2表示找到流程开始的点了,找到1表示找到流程结束的点了 + get_cross_time_list(flow_cross_time_list,initArrays_flow,cross_fromtime_index,cross_totime_index,2,1); + + logOvertimeMap(overtimeLogMap, flow_cross_time_list, flow_key+"|取打卡和流程相交的区间|flow_cross_time_list"); + for(int j = 0 ; j < flow_cross_time_list.size() ;){ + int flow_cross_fromtime_index = flow_cross_time_list.get(j); + int flow_cross_totime_index = flow_cross_time_list.get(j+1); + + int mins = flow_cross_totime_index-flow_cross_fromtime_index; + if(mins <= 0){ + String crossInfo = "flow_cross_fromtime_index:"+flow_cross_fromtime_index+":flow_cross_totime_index:"+flow_cross_totime_index+":mins:"+mins; + logOvertimeMap(overtimeLogMap, crossInfo, flow_key+"|打卡时长小于最小加班时长|crossInfo"); + continue; + } + across_mins += mins; + + String flow_cross_key = "加班计算区间|"+kqTimesArrayComInfo.getTimesByArrayindex(flow_cross_fromtime_index)+"-"+kqTimesArrayComInfo.getTimesByArrayindex(flow_cross_totime_index); + logOvertimeMap(overtimeLogMap, mins, flow_cross_key+"|原始加班区间生成的加班时长|mins"); + + String cross_fromtime = kqTimesArrayComInfo.getTimesByArrayindex(flow_cross_fromtime_index); + String cross_totime = kqTimesArrayComInfo.getTimesByArrayindex(flow_cross_totime_index); + String cross_fromdate = realSplitDate; + String cross_todate = realSplitDate; + + boolean needSplitByTime = false; + if(needSplitByTime){ + // 按照加班时长转调休的 时长设置 这个逻辑如果后面要开启来可以直接用的 + List timepointList = null; + if(kqOvertimeRulesDetailEntity != null){ + timepointList = get_timepointList(kqOvertimeRulesDetailEntity); + logOvertimeMap(overtimeLogMap, timepointList, flow_cross_key+"|如果要生成调休且是根据时间区间来转调休,返回对应的时间区间|timepointList"); + } + + List overtimeBalanceTimeBeans = Lists.newArrayList(); + if(timepointList != null && !timepointList.isEmpty()){ + int[] time_initArrays = kqTimesArrayComInfo.getInitArr(); + for(int t = flow_cross_fromtime_index;t < flow_cross_totime_index; t++){ + time_initArrays[t] = initArrays_flow[t]; + } + get_overtimeBalanceTimeBeans(timepointList,overtimeBalanceTimeBeans,kqTimesArrayComInfo,time_initArrays,flow_cross_totime_index,flow_cross_fromtime_index,2); + } + String overtimeBalanceTimeBeansLogInfo = ""; + if(overtimeBalanceTimeBeans == null || overtimeBalanceTimeBeans.isEmpty()){ + }else{ + overtimeBalanceTimeBeansLogInfo = JSON.toJSONString(overtimeBalanceTimeBeans); + } + logOvertimeMap(overtimeLogMap, overtimeBalanceTimeBeansLogInfo, flow_cross_key+"|如果要生成调休且是根据时间区间来转调休,返回对应的时间区间对应的时长|overtimeBalanceTimeBeans"); + + if(overtimeBalanceTimeBeans != null && !overtimeBalanceTimeBeans.isEmpty()){ + String bean_cross_fromtime = cross_fromtime; + String bean_cross_totime = cross_totime; + for(int timeIndex = 0 ; timeIndex < overtimeBalanceTimeBeans.size() ;timeIndex++){ + OvertimeBalanceTimeBean overtimeBalanceTimeBean = overtimeBalanceTimeBeans.get(timeIndex); + String timePointStart = overtimeBalanceTimeBean.getTimepoint_start(); + String timePointEnd = overtimeBalanceTimeBean.getTimepoint_end(); + boolean isNeedTX = overtimeBalanceTimeBean.isNeedTX(); + int timePointStart_index = kqTimesArrayComInfo.getArrayindexByTimes(timePointStart); + int timePointEnd_index = kqTimesArrayComInfo.getArrayindexByTimes(timePointEnd); + if(timePointStart_index > flow_cross_fromtime_index){ + bean_cross_fromtime = kqTimesArrayComInfo.getTimesByArrayindex(timePointStart_index); + }else{ + bean_cross_fromtime = cross_fromtime; + } + if(timePointEnd_index < flow_cross_totime_index){ + bean_cross_totime = kqTimesArrayComInfo.getTimesByArrayindex(timePointEnd_index); + }else{ + bean_cross_totime = cross_totime; + } + int timepoint_mins = overtimeBalanceTimeBean.getTimepoint_mins(); + if(timepoint_mins == 0){ + continue; + } + mins = timepoint_mins; + } + } + }else{ + } + j =j + 2; + } }else{ + + } + i = i +2; + } + + if(kqOvertimeRulesDetailEntity != null){ + //我这个方法是针对每次生成的加班数据做排除休息时长的处理 + restTimeType = kqOvertimeRulesDetailEntity.getRestTimeType(); + if(restTimeType == 2){ + across_mins = new KQOverTimeFlowBiz().handle_restlength(across_mins,restTimeMap,changeType_key); + } + } + int card_mins = over_count; + double double_mins = getD_MinsByUnit((1.0*across_mins)); + across_mins = (int)double_mins; + if(across_mins <= 0){ + logOvertimeMap(overtimeLogMap, across_mins, flow_key+"|经过单位换算之后时长为0|across_mins"); + continue; + } + if(across_mins < minimumLen){ + String minInfo = "across_mins:"+across_mins+":minimumLen:"+minimumLen; + logOvertimeMap(overtimeLogMap, minInfo, flow_key+"|打卡时长小于最小加班时长|over_count otherParam = Maps.newHashMap(); + otherParam.put("overtime_type", overtime_type); + int paidLeaveEnableType = kqOvertimeRulesDetailEntity.getPaidLeaveEnableType(); + if(2 == paidLeaveEnableType){ + logOvertimeMap(overtimeLogMap, overtime_type, flow_key+"|关联调休与否来自于流程选择,加班类型下拉框值|overtime_type"); + } + + int paidLeaveEnable = getPaidLeaveEnable(kqOvertimeRulesDetailEntity, overtime_type); + //目前不处理按照时间段生成调休 + boolean needSplitByTime = false;//getNeedSplitByTime(kqOvertimeRulesDetailEntity, paidLeaveEnable); + if(needSplitByTime){ + + }else{ + otherParam.put("overtimeLogMap", overtimeLogMap); + logOvertimeMap(overtimeLogMap, across_mins, flow_key+"|最终生成的加班分钟数|overtime_mins"); + tiaoxiuId = KQBalanceOfLeaveBiz.addExtraAmountByDis5(resourceid,realSplitDate,across_mins+"","0",workingHours,requestid,"1",realSplitDate,otherParam); + if(Util.getIntValue(tiaoxiuId) > 0){ + kqLog.info("doComputingMode4 生成调休成功,调休id:"+tiaoxiuId+":resourceid:"+resourceid+":realSplitDate:"+realSplitDate); + }else{ + kqLog.info("doComputingMode4 生成调休失败,调休id:"+tiaoxiuId+":resourceid:"+resourceid+":realSplitDate:"+realSplitDate); + } + logOvertimeMap(overtimeLogMap, tiaoxiuId, flow_key+"|最终生成的调休id|tiaoxiuId"); + + String flow_overtime_sql = "insert into kq_flow_overtime (requestid,resourceid,fromdate,fromtime,todate,totime,duration_min,expiringdate,belongdate," + + "workMins,durationrule,changetype,paidLeaveEnable,computingMode,tiaoxiuId,uuid,fromdatedb,fromtimedb,todatedb,totimedb,flow_mins,card_mins,ori_belongdate,flow_dataid)"+ + " values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) "; + signinTime = kqTimesArrayComInfo.turn48to24Time(signinTime); + signoutTime = kqTimesArrayComInfo.turn48to24Time(signoutTime); + if(signinTime.length() == 5){ + signinTime = signinTime+":00"; + } + if(signoutTime.length() == 5){ + signoutTime = signoutTime+":00"; + } + boolean isUp = rs.executeUpdate(flow_overtime_sql, requestid,resourceid,signinDate,signinTime,signoutDate,signoutTime,across_mins,"",realSplitDate, + "",unit,changeType,paidLeaveEnable,computingMode,tiaoxiuId,overtime_uuid,fromdatedb,fromtimedb,todatedb,totimedb,d_mins,card_mins,splitDate,flow_dataid); + + String overtimeid = get_overtime_uuid(overtime_uuid); + kqEventLogBiz.updateOvertimeId(uuid, overtimeid); + } + } + }else{ + //有打卡没有流程 + logOvertimeMap(overtimeLogMap, mapKey, mapKey+"|"+"加班流程为空"); + } + }else{ + logOvertimeMap(overtimeLogMap, overCountLogInfo, mapKey+"|"+"打卡数据时长为0"); + } + }else{ + String overCountLogInfo = "signinTimeIndex:"+signinTimeIndex+":signoutTimeIndex:"+signoutTimeIndex; + logOvertimeMap(overtimeLogMap, overCountLogInfo, mapKey+"|"+"打卡数据异常"); + } + }else{ + logOvertimeMap(overtimeLogMap, "打卡数据KQOvertimeCardBean为null", mapKey+"|"+"打卡和上下班数据|KQOvertimeCardBean"); + } + } + kqEventLogBiz.logDetailOvertimeMap(resourceid,overtimeLogMap,uuid); + kqEventLogBiz.logDetailEvent(resourceid,eventMap,uuid,"doComputingMode4|对应的加班流程数据|key|"+key); + + } + + /** + * 得到有效的打卡区间,这个区间肯定已经是去除了上下班时间和休息时间还有重复打卡的部分 + * @param cross_time_list + * @param initArrays + * @param fromIndex + * @param toIndex + * @param cross_from_index + * @param cross_to_index + */ + public void get_cross_time_list(List cross_time_list, int[] initArrays, + int fromIndex, int toIndex,int cross_from_index,int cross_to_index) { + for(int i = fromIndex ; i < toIndex+1 ; i++){ + if(cross_time_list.isEmpty()){ + if(initArrays[i] == cross_from_index){ + cross_time_list.add(i); + } + }else{ + if(cross_time_list.size() % 2 != 0){ + if(initArrays[i] == cross_to_index){ + cross_time_list.add(i); + } + }else{ + if(initArrays[i] == cross_from_index){ + cross_time_list.add(i); + } + } + } + } + if(cross_time_list.size() % 2 != 0){ + cross_time_list.add(toIndex); + } + } + + /** + * 处理加班方式是 无需审批,根据打卡时间计算加班时长 + * @param resourceid + * @param splitDate + * @param dateFormatter + * @param changeTypeMap + * @param overRulesDetailMap + * @param restTimeMap + * @param computingModeMap + * @param kqTimesArrayComInfo + */ + private void doComputingMode3(String resourceid, String splitDate, + DateTimeFormatter dateFormatter, Map changeTypeMap, + Map overRulesDetailMap, + Map> restTimeMap, Map computingModeMap, + KQTimesArrayComInfo kqTimesArrayComInfo, String main_uuid) throws Exception{ + String key = resourceid+"_"+splitDate; + //加班日志记录类 + KQWorkTime kqWorkTime = new KQWorkTime(); + WorkTimeEntity workTimeEntity = kqWorkTime.getWorkTime(resourceid, splitDate); + Map workTimeEntityLogMap = Maps.newHashMap(); + workTimeEntityLogMap.put("resourceid", resourceid); + workTimeEntityLogMap.put("splitDate", splitDate); + workTimeEntityLogMap.put("workTimeEntity", workTimeEntity); + KQOvertimeLogBiz kqEventLogBiz = new KQOvertimeLogBiz(); + String uuid = kqEventLogBiz.logDetailWorkTimeEntity(resourceid,workTimeEntityLogMap,main_uuid,"doComputingMode3|加班计算,无需审批,根据打卡时间计算加班时长|key|"+key); + Map overtimeLogMap = Maps.newLinkedHashMap(); + + Map eventMap = Maps.newHashMap(); + Map lsCheckInfoMaps = Maps.newLinkedHashMap(); + //获取加班打卡数据 + getOverTimeCardDataMap(resourceid, splitDate, splitDate, dateFormatter,kqTimesArrayComInfo,overRulesDetailMap,changeTypeMap,lsCheckInfoMaps, + eventMap); + kqEventLogBiz.logDetailEvent(resourceid,eventMap,uuid,"doComputingMode3|对应的打卡数据|key|"+key); + + if(lsCheckInfoMaps.isEmpty()){ + logOvertimeMap(overtimeLogMap, "没有打卡数据", "打卡和上下班数据|KQOvertimeCardBean"); + kqEventLogBiz.logDetailOvertimeMap(resourceid,overtimeLogMap,uuid); + return; + } + + Iterator> iterator = lsCheckInfoMaps.entrySet().iterator(); + while (iterator.hasNext()) { + Entry next = iterator.next(); + String mapKey = next.getKey(); + KQOvertimeCardBean kqOvertimeCardBean = next.getValue(); + String[] mapKeys = mapKey.split("_"); + if (mapKeys.length != 2) { + continue; + } + String realSplitDate = mapKeys[1]; + String change_key = realSplitDate+"_"+resourceid; + int changeType = Util.getIntValue(""+changeTypeMap.get(change_key),-1); + String changeType_key = realSplitDate+"_"+changeType; + String changetypeName = 1==changeType ? "节假日" : (2 == changeType ? "工作日" : (3 == changeType ? "休息日" : "异常")); + String changetypeLogInfo = change_key+"|changeType|"+changeType+"|"+changetypeName; + logOvertimeMap(overtimeLogMap, changetypeLogInfo, "加班日期属性|changetypeLogInfo"); + + clearOvertimeTX(resourceid, realSplitDate,overtimeLogMap, splitDate); + + logOvertimeMap(overtimeLogMap, kqOvertimeCardBean, "打卡和上下班数据|KQOvertimeCardBean"); + + KQOvertimeRulesDetailEntity kqOvertimeRulesDetailEntity = overRulesDetailMap.get(changeType_key); + if(kqOvertimeRulesDetailEntity == null){ + String overRuleInfo = "changeType_key:"+changeType_key+":kqOvertimeRulesDetailEntity:"+kqOvertimeRulesDetailEntity; + logOvertimeMap(overtimeLogMap, overRuleInfo, mapKey+"|"+"加班规则为null|kqOvertimeRulesDetailEntity"); + continue; + } + int overtimeEnable = kqOvertimeRulesDetailEntity.getOvertimeEnable(); + if(overtimeEnable != 1){ + String overtimeEnableInfo = "overtimeEnable:"+overtimeEnable; + logOvertimeMap(overtimeLogMap, overtimeEnableInfo, mapKey+"|"+"未开启加班规则|overtimeEnable"); + continue; + } + if(kqOvertimeCardBean != null){ + + int[] initArrays = kqTimesArrayComInfo.getInitArr(); + Map signinoffMap = buildOvertimeCard(kqOvertimeCardBean, resourceid, realSplitDate, kqTimesArrayComInfo, restTimeMap, changeType_key,initArrays,Lists.newArrayList(),overRulesDetailMap, + true, overtimeLogMap); + logOvertimeMap(overtimeLogMap, signinoffMap, "获取上下班打卡数据|signinoffMap"); + + String signinTime = Util.null2String(signinoffMap.get("signinTime")); + String signoutTime = Util.null2String(signinoffMap.get("signoutTime")); + String signinDate = Util.null2String(signinoffMap.get("signinDate")); + String signoutDate = Util.null2String(signinoffMap.get("signoutDate")); + int signinTimeIndex = kqTimesArrayComInfo.getArrayindexByTimes(signinTime); + int signoutTimeIndex = kqTimesArrayComInfo.getArrayindexByTimes(signoutTime); + String flow_cross_key = mapKey+"|"+"加班计算区间|"+signinTime+"-"+signoutTime; + + if(signinTimeIndex < signoutTimeIndex){ + int over_count = kqTimesArrayComInfo.getCnt(initArrays, signinTimeIndex, signoutTimeIndex, 1); + String countLogInfo = "signinTimeIndex:"+signinTimeIndex+":signoutTimeIndex:"+signoutTimeIndex+":over_count:"+over_count; + logOvertimeMap(overtimeLogMap, countLogInfo, mapKey+"|"+"打卡区间,得到打卡时长|over_count"); + if(over_count > 0){ + //表示加班打卡是存在的 + int restTimeType = 1; + if(kqOvertimeRulesDetailEntity != null){ + int minimumLen = kqOvertimeRulesDetailEntity.getMinimumLen(); + if(over_count < minimumLen){ + continue; + } + logOvertimeMap(overtimeLogMap, JSON.toJSONString(kqOvertimeRulesDetailEntity), mapKey+"|"+"加班规则|KQOvertimeRulesDetailEntity"); + //我这个方法是针对每次生成的加班数据做排除休息时长的处理 + restTimeType = kqOvertimeRulesDetailEntity.getRestTimeType(); + if(restTimeType == 2){ + over_count = new KQOverTimeFlowBiz().handle_restlength(over_count,restTimeMap,changeType_key); + } + } + if(over_count <= 0){ + logOvertimeMap(overtimeLogMap, "没有打卡数据", mapKey+"|"+"打卡时长|over_count"); + continue; + } + logOvertimeMap(overtimeLogMap, over_count, mapKey+"|"+"经历过休息时间之后的加班时长|over_rest_count"); + + int mins = over_count; + double double_mins = getD_MinsByUnit((1.0*mins)); + mins = (int)double_mins; + + RecordSet rs = new RecordSet(); + String overtime_uuid = UUID.randomUUID().toString(); + String tiaoxiuId = ""; + String workingHours = ""; + int computingMode = 3; + + Map otherParam = Maps.newHashMap(); + int unit = KQOvertimeRulesBiz.getMinimumUnit(); + + int paidLeaveEnable = kqOvertimeRulesDetailEntity.getPaidLeaveEnable(); + int paidLeaveEnableType = kqOvertimeRulesDetailEntity.getPaidLeaveEnableType(); + boolean needSplitByTime = false;//getNeedSplitByTime(kqOvertimeRulesDetailEntity, paidLeaveEnable); + if(needSplitByTime){ + // 按照加班时长转调休的 时长设置 + List timepointList = null; + if(kqOvertimeRulesDetailEntity != null){ + timepointList = get_timepointList(kqOvertimeRulesDetailEntity); + logOvertimeMap(overtimeLogMap, timepointList, flow_cross_key+"|如果要生成调休且是根据时间区间来转调休,返回对应的时间区间|timepointList"); + } + + List overtimeBalanceTimeBeans = Lists.newArrayList(); + if(timepointList != null && !timepointList.isEmpty()){ + int[] time_initArrays = kqTimesArrayComInfo.getInitArr(); + for(int t = signinTimeIndex;t < signoutTimeIndex; t++){ + time_initArrays[t] = initArrays[t]; + } + get_overtimeBalanceTimeBeans(timepointList,overtimeBalanceTimeBeans,kqTimesArrayComInfo,time_initArrays,signoutTimeIndex,signinTimeIndex,1); + } + String overtimeBalanceTimeBeansLogInfo = ""; + if(overtimeBalanceTimeBeans == null || overtimeBalanceTimeBeans.isEmpty()){ + }else{ + overtimeBalanceTimeBeansLogInfo = JSON.toJSONString(overtimeBalanceTimeBeans); + } + logOvertimeMap(overtimeLogMap, overtimeBalanceTimeBeansLogInfo, flow_cross_key+"|如果要生成调休且是根据时间区间来转调休,返回对应的时间区间对应的时长|overtimeBalanceTimeBeans"); + + if(overtimeBalanceTimeBeans != null && !overtimeBalanceTimeBeans.isEmpty()){ + String bean_cross_fromtime = signinTime; + String bean_cross_totime = signoutTime; + for(int timeIndex = 0 ; timeIndex < overtimeBalanceTimeBeans.size() ;timeIndex++) { + OvertimeBalanceTimeBean overtimeBalanceTimeBean = overtimeBalanceTimeBeans.get(timeIndex); + String timePointStart = overtimeBalanceTimeBean.getTimepoint_start(); + String timePointEnd = overtimeBalanceTimeBean.getTimepoint_end(); + int timePointStart_index = kqTimesArrayComInfo.getArrayindexByTimes(timePointStart); + int timePointEnd_index = kqTimesArrayComInfo.getArrayindexByTimes(timePointEnd); + if(timePointStart_index > signinTimeIndex){ + bean_cross_fromtime = kqTimesArrayComInfo.getTimesByArrayindex(timePointStart_index); + }else{ + bean_cross_fromtime = signinTime; + } + if(timePointEnd_index < signoutTimeIndex){ + bean_cross_totime = kqTimesArrayComInfo.getTimesByArrayindex(timePointEnd_index); + }else{ + bean_cross_totime = signoutTime; + } + int timepoint_mins = overtimeBalanceTimeBean.getTimepoint_mins(); + if(timepoint_mins == 0){ + continue; + } + mins = timepoint_mins; + otherParam.put("OvertimeBalanceTimeBean", overtimeBalanceTimeBean); + otherParam.put("overtimeLogMap", overtimeLogMap); + String timepoint_key = flow_cross_key+"|调休按照分段计算加班时间("+signinTime+"-"+signoutTime+")"; + otherParam.put("timepoint_key", timepoint_key); + logOvertimeMap(overtimeLogMap, mins, timepoint_key+"最终生成的加班分钟数|overtime_mins"); + + tiaoxiuId = KQBalanceOfLeaveBiz.addExtraAmountByDis5(resourceid,realSplitDate,mins+"","0",workingHours,"","",realSplitDate,otherParam); + if(Util.getIntValue(tiaoxiuId) > 0){ + kqLog.info("doComputingMode3 生成调休成功,调休id:"+tiaoxiuId+":resourceid:"+resourceid+":realSplitDate:"+realSplitDate); + }else{ + kqLog.info("doComputingMode3 生成调休失败,调休id:"+tiaoxiuId+":resourceid:"+resourceid+":realSplitDate:"+realSplitDate); + } + overtime_uuid = UUID.randomUUID().toString(); + String flow_overtime_sql = "insert into kq_flow_overtime (requestid,resourceid,fromdate,fromtime,todate,totime,duration_min,expiringdate,belongdate," + + "workMins,durationrule,changetype,paidLeaveEnable,computingMode,tiaoxiuId,uuid,fromdatedb,fromtimedb,todatedb,totimedb,flow_mins,ori_belongdate)"+ + " values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) "; + signinTime = kqTimesArrayComInfo.turn48to24Time(signinTime); + signoutTime = kqTimesArrayComInfo.turn48to24Time(signoutTime); + boolean isUp = rs.executeUpdate(flow_overtime_sql, "",resourceid,signinDate,signinTime,signoutDate,signoutTime,mins,"",realSplitDate, + "",unit,changeType,paidLeaveEnable,computingMode,tiaoxiuId,overtime_uuid,"","","","",0,splitDate); + + String overtimeid = get_overtime_uuid(overtime_uuid); + kqEventLogBiz.updateOvertimeId(uuid, overtimeid); + } + } + }else{ + + logOvertimeMap(overtimeLogMap, mins, flow_cross_key+"|最终生成的加班分钟数|overtime_mins"); + tiaoxiuId = KQBalanceOfLeaveBiz.addExtraAmountByDis5(resourceid,realSplitDate,mins+"","0",workingHours,"","",realSplitDate,otherParam); + if(Util.getIntValue(tiaoxiuId) > 0){ + kqLog.info("doComputingMode3 生成调休成功,调休id:"+tiaoxiuId+":resourceid:"+resourceid+":realSplitDate:"+realSplitDate); + }else{ + kqLog.info("doComputingMode3 生成调休失败,调休id:"+tiaoxiuId+":resourceid:"+resourceid+":realSplitDate:"+realSplitDate); + } + + String flow_overtime_sql = "insert into kq_flow_overtime (requestid,resourceid,fromdate,fromtime,todate,totime,duration_min,expiringdate,belongdate," + + "workMins,durationrule,changetype,paidLeaveEnable,computingMode,tiaoxiuId,uuid,fromdatedb,fromtimedb,todatedb,totimedb,flow_mins,ori_belongdate)"+ + " values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) "; + signinTime = kqTimesArrayComInfo.turn48to24Time(signinTime); + signoutTime = kqTimesArrayComInfo.turn48to24Time(signoutTime); + boolean isUp = rs.executeUpdate(flow_overtime_sql, "",resourceid,signinDate,signinTime,signoutDate,signoutTime,mins,"",realSplitDate, + "",unit,changeType,paidLeaveEnable,computingMode,tiaoxiuId,overtime_uuid,"","","","",0,splitDate); + + String overtimeid = get_overtime_uuid(overtime_uuid); + kqEventLogBiz.updateOvertimeId(uuid, overtimeid); + } + + } + }else{ + logOvertimeMap(overtimeLogMap, "打卡区间不正确|"+flow_cross_key, mapKey+"|"+"打卡区间,得到打卡时长|over_count"); + } + }else{ + logOvertimeMap(overtimeLogMap, "打卡数据KQOvertimeCardBean为null", mapKey+"|"+"打卡和上下班数据|KQOvertimeCardBean"); + } + } + kqEventLogBiz.logDetailOvertimeMap(resourceid,overtimeLogMap,uuid); + kqEventLogBiz.logDetailEvent(resourceid,eventMap,uuid,"doComputingMode3|对应的加班流程数据|key|"+key); + + + } + + /** + * 获取生成的加班id + * @param overtime_uuid + * @return + */ + public String get_overtime_uuid(String overtime_uuid) { + RecordSet rs = new RecordSet(); + String sql = "select * from kq_flow_overtime where uuid='"+overtime_uuid+"' "; + rs.executeQuery(sql); + if(rs.next()){ + return rs.getString("id"); + } + return ""; + } + + /** + * 按加班的时间段设置转调休时长 + * @param kqOvertimeRulesDetailEntity + * @return + */ + public List get_timepointList(KQOvertimeRulesDetailEntity kqOvertimeRulesDetailEntity) { + List timepointList = Lists.newArrayList(); + KQOvertimeRulesBiz kqOvertimeRulesBiz = new KQOvertimeRulesBiz(); + int ruleDetailid = kqOvertimeRulesDetailEntity.getId(); + int paidLeaveEnableType = kqOvertimeRulesDetailEntity.getPaidLeaveEnableType(); + if(1 == paidLeaveEnableType){ + int paidLeaveEnableDefaultType = kqOvertimeRulesDetailEntity.getPaidLeaveEnableDefaultType(); + + if(paidLeaveEnableDefaultType == 3){ + Map> balanceTimethDetailMap = kqOvertimeRulesBiz.getBalanceTimeDetailMap(ruleDetailid); + if(balanceTimethDetailMap != null && !balanceTimethDetailMap.isEmpty()){ + timepointList = balanceTimethDetailMap.get("timepointList"); + } + } + }else if(2 == paidLeaveEnableType){ + int paidLeaveEnableFlowType = kqOvertimeRulesDetailEntity.getPaidLeaveEnableFlowType(); + + if(paidLeaveEnableFlowType == 3){ + Map> balanceTimethDetailMap = kqOvertimeRulesBiz.getBalanceTimeDetailMap(ruleDetailid); + if(balanceTimethDetailMap != null && !balanceTimethDetailMap.isEmpty()){ + timepointList = balanceTimethDetailMap.get("timepointList"); + } + } + } + return timepointList; + } + + /** + * 加班补偿规则里,按照加班时段补偿方式需要获取每一个时间区间内的加班时长 + * @param timepointList + * @param overtimeBalanceTimeBeans + * @param kqTimesArrayComInfo + * @param initArrays + * @param toTime_index + * @param fromTime_index + * @param arrayIndexValue + */ + public void get_overtimeBalanceTimeBeans(List timepointList, + List overtimeBalanceTimeBeans, + KQTimesArrayComInfo kqTimesArrayComInfo, int[] initArrays, + int toTime_index,int fromTime_index,int arrayIndexValue) { + //如果 [按加班的时间段设置转调休时长] 是这种方式,还需要根据时间点来判断时间区间内的加班时长,艹 + for(int k = 0 ; k < timepointList.size() ; k++){ + OvertimeBalanceTimeBean overtimeBalanceTimeBean = new OvertimeBalanceTimeBean(); + String start_pointtime = timepointList.get(k); + int start_pointtime_index = kqTimesArrayComInfo.getArrayindexByTimes(start_pointtime); + if(k == 0){ + if(start_pointtime_index > fromTime_index){ + int timepoint_curMins = kqTimesArrayComInfo.getCnt(initArrays, fromTime_index,start_pointtime_index,arrayIndexValue); + OvertimeBalanceTimeBean ori_overtimeBalanceTimeBean = new OvertimeBalanceTimeBean(); + ori_overtimeBalanceTimeBean.setTimepoint(kqTimesArrayComInfo.getTimesByArrayindex(start_pointtime_index)); + ori_overtimeBalanceTimeBean.setTimepoint_start(kqTimesArrayComInfo.getTimesByArrayindex(fromTime_index)); + ori_overtimeBalanceTimeBean.setTimepoint_end(kqTimesArrayComInfo.getTimesByArrayindex(start_pointtime_index)); + ori_overtimeBalanceTimeBean.setTimepoint_mins(timepoint_curMins); + ori_overtimeBalanceTimeBean.setNeedTX(false); + overtimeBalanceTimeBeans.add(ori_overtimeBalanceTimeBean); + } + } + if(start_pointtime_index > toTime_index){ + continue; + } + overtimeBalanceTimeBean.setList_index(k); + int start_index = -1; + int end_index = -1; + if(k == timepointList.size()-1){ + start_index = start_pointtime_index; + end_index = toTime_index; + }else{ + if(k+1 < timepointList.size()){ + String end_pointtime = timepointList.get(k+1); + start_index = start_pointtime_index; + end_index = kqTimesArrayComInfo.getArrayindexByTimes(end_pointtime); + } + } + if(start_index < end_index){ + int timepoint_curMins = kqTimesArrayComInfo.getCnt(initArrays, start_index,end_index,arrayIndexValue); + overtimeBalanceTimeBean.setTimepoint(kqTimesArrayComInfo.getTimesByArrayindex(start_index)); + overtimeBalanceTimeBean.setTimepoint_start(kqTimesArrayComInfo.getTimesByArrayindex(start_index)); + overtimeBalanceTimeBean.setTimepoint_end(kqTimesArrayComInfo.getTimesByArrayindex(end_index)); + overtimeBalanceTimeBean.setTimepoint_mins(timepoint_curMins); + overtimeBalanceTimeBean.setNeedTX(true); + overtimeBalanceTimeBeans.add(overtimeBalanceTimeBean); + } + } + } + + /** + * 处理加班方式是 需审批,以打卡为准,但是不能超过审批时长的加班时长 + * @param resourceid + * @param splitDate + * @param dateFormatter + * @param changeTypeMap + * @param overRulesDetailMap + * @param restTimeMap + * @param computingModeMap + * @param kqTimesArrayComInfo + */ + private void doComputingMode2(String resourceid, String splitDate, + DateTimeFormatter dateFormatter, Map changeTypeMap, + Map overRulesDetailMap, + Map> restTimeMap, Map computingModeMap, + KQTimesArrayComInfo kqTimesArrayComInfo, String main_uuid) throws Exception{ + String key = resourceid+"_"+splitDate; + //加班日志记录类 + KQWorkTime kqWorkTime = new KQWorkTime(); + WorkTimeEntity workTimeEntity = kqWorkTime.getWorkTime(resourceid, splitDate); + Map workTimeEntityLogMap = Maps.newHashMap(); + workTimeEntityLogMap.put("resourceid", resourceid); + workTimeEntityLogMap.put("splitDate", splitDate); + workTimeEntityLogMap.put("workTimeEntity", workTimeEntity); + KQOvertimeLogBiz kqEventLogBiz = new KQOvertimeLogBiz(); + String uuid = kqEventLogBiz.logDetailWorkTimeEntity(resourceid,workTimeEntityLogMap,main_uuid,"doComputingMode2|加班计算,需审批,以打卡为准,但是不能超过审批时长的加班时长|key|"+key); + Map overtimeLogMap = Maps.newLinkedHashMap(); + + Map eventMap = Maps.newHashMap(); + Map lsCheckInfoMaps = Maps.newLinkedHashMap(); + //获取加班打卡数据 + getOverTimeCardDataMap(resourceid, splitDate, splitDate, dateFormatter,kqTimesArrayComInfo,overRulesDetailMap,changeTypeMap,lsCheckInfoMaps, + eventMap); + + Map> splitBeanMaps = Maps.newHashMap(); + //获取加班流程数据 + getOverTimeFlowData(resourceid,splitDate,splitDate,splitBeanMaps,dateFormatter); + + if(lsCheckInfoMaps.isEmpty()){ + logOvertimeMap(overtimeLogMap, "没有打卡数据", "打卡和上下班数据|KQOvertimeCardBean"); + kqEventLogBiz.logDetailOvertimeMap(resourceid,overtimeLogMap,uuid); + kqEventLogBiz.logDetailEvent(resourceid,eventMap,uuid,"doComputingMode2|对应的加班流程数据|key|"+key); + return; + } + + Iterator> iterator = lsCheckInfoMaps.entrySet().iterator(); + while (iterator.hasNext()){ + Entry next = iterator.next(); + String mapKey = next.getKey(); + KQOvertimeCardBean kqOvertimeCardBean = next.getValue(); + String[] mapKeys = mapKey.split("_"); + if(mapKeys.length != 2){ + continue; + } + String realSplitDate = mapKeys[1]; + + String change_key = realSplitDate+"_"+resourceid; + int changeType = Util.getIntValue(""+changeTypeMap.get(change_key),-1); + String changeType_key = realSplitDate+"_"+changeType; + String changetypeName = 1==changeType ? "节假日" : (2 == changeType ? "工作日" : (3 == changeType ? "休息日" : "异常")); + String changetypeLogInfo = change_key+"|changeType|"+changeType+"|"+changetypeName; + logOvertimeMap(overtimeLogMap, changetypeLogInfo, mapKey+"|"+"加班日期属性|changetypeLogInfo"); + + clearOvertimeTX(resourceid, realSplitDate,overtimeLogMap, splitDate); + logOvertimeMap(overtimeLogMap, kqOvertimeCardBean, mapKey+"|"+"打卡和上下班数据|KQOvertimeCardBean"); + + KQOvertimeRulesDetailEntity kqOvertimeRulesDetailEntity = overRulesDetailMap.get(changeType_key); + if(kqOvertimeRulesDetailEntity == null){ + String overRuleInfo = "changeType_key:"+changeType_key+":kqOvertimeRulesDetailEntity:"+kqOvertimeRulesDetailEntity; + logOvertimeMap(overtimeLogMap, overRuleInfo, mapKey+"|"+"加班规则为null|kqOvertimeRulesDetailEntity"); + continue; + } + int overtimeEnable = kqOvertimeRulesDetailEntity.getOvertimeEnable(); + if(overtimeEnable != 1){ + String overtimeEnableInfo = "overtimeEnable:"+overtimeEnable; + logOvertimeMap(overtimeLogMap, overtimeEnableInfo, mapKey+"|"+"未开启加班规则|overtimeEnable"); + continue; + } + + if(kqOvertimeCardBean != null){ + if(splitBeanMaps.containsKey(mapKey)) { + List splitBeans = splitBeanMaps.get(mapKey); + String flowinfo = ""; + if(splitBeans != null && !splitBeans.isEmpty()){ + flowinfo = JSON.toJSONString(splitBeans, SerializerFeature.DisableCheckSpecialChar,SerializerFeature.DisableCircularReferenceDetect); + }else{ + logOvertimeMap(overtimeLogMap, "打卡数据KQOvertimeCardBean为null", mapKey+"|"+"打卡和上下班数据|KQOvertimeCardBean"); + continue; + } + eventMap.put(mapKey+"|"+"加班流程数据|flowinfo", flowinfo); + for (int m = 0; m < splitBeans.size(); m++) { + int[] initArrays_flow = kqTimesArrayComInfo.getInitArr(); + SplitBean splitBean = splitBeans.get(m); + String dataid = splitBean.getDataId(); + String detailid = splitBean.getDetailId(); + String flow_fromdate = splitBean.getFromDate(); + String flow_fromtime = splitBean.getFromTime(); + String flow_todate = splitBean.getToDate(); + String flow_totime = splitBean.getToTime(); + String fromdatedb = splitBean.getFromdatedb(); + String fromtimedb = splitBean.getFromtimedb(); + String todatedb = splitBean.getTodatedb(); + String totimedb = splitBean.getTotimedb(); + String requestid = splitBean.getRequestId(); + double d_mins = splitBean.getD_Mins(); + if(d_mins <= 0){ + continue; + } + String flow_key = mapKey+"|"+"dataid|"+dataid+"|"+"detailid|"+detailid+"|"+"requestid|"+requestid+"|flow_fromdate|"+flow_fromdate + +"|flow_fromtime|"+flow_fromtime+"|flow_todate|"+flow_todate+"|flow_totime|"+flow_totime; + int flow_count = (int) d_mins; + String flowLogInfo = "flow_fromdate:"+flow_fromdate+":flow_fromtime:"+flow_fromtime + +":flow_todate:"+flow_todate+":flow_totime:"+flow_totime+":requestid:"+requestid + +":d_mins:"+d_mins; + logOvertimeMap(overtimeLogMap, flowLogInfo, flow_key+"|加班流程信息|flowLogInfo"); + + List> hasOverTimeList = Lists.newArrayList(); + getHasOverTimeData(resourceid,realSplitDate,hasOverTimeList); + logOvertimeMap(overtimeLogMap, hasOverTimeList, flow_key+"|是否已经生成过加班,返回已经生成过加班的区间|hasOverTimeList"); + + if(flow_fromdate.compareTo(realSplitDate) > 0){ + flow_fromtime = kqTimesArrayComInfo.turn24to48Time(flow_fromtime); + } + if(flow_todate.compareTo(realSplitDate) > 0){ + flow_totime = kqTimesArrayComInfo.turn24to48Time(flow_totime); + } + int flow_fromIndex = kqTimesArrayComInfo.getArrayindexByTimes(flow_fromtime); + int flow_toIndex = kqTimesArrayComInfo.getArrayindexByTimes(flow_totime); + Arrays.fill(initArrays_flow, flow_fromIndex, flow_toIndex,1); + int all_has_duration_min = 0; + //因为存在下班后的打卡和上班前的打卡。这两块的打卡需要合在一起来和合在一起的流程比较时长 + Map hasCardMap = Maps.newHashMap(); + if(hasOverTimeList != null && !hasOverTimeList.isEmpty()){ + for(int p = 0 ; p < hasOverTimeList.size(); p++){ + Map hasOverTimeMap = hasOverTimeList.get(p); + String duration_min = Util.null2String(hasOverTimeMap.get("duration_min")); + String flow_dataid = Util.null2String(hasOverTimeMap.get("flow_dataid")); + String ori_belongdate = Util.null2String(hasOverTimeMap.get("ori_belongdate")); + String has_requestid = Util.null2String(hasOverTimeMap.get("requestid")); + + String card_fromdate = Util.null2String(hasOverTimeMap.get("fromdate_flow")); + String card_fromtime = Util.null2String(hasOverTimeMap.get("fromtime_flow")); + String card_todate = Util.null2String(hasOverTimeMap.get("todate_flow")); + String card_totime = Util.null2String(hasOverTimeMap.get("totime_flow")); + String card_key = card_fromdate+"_"+card_fromtime+"_"+card_todate+"_"+card_totime; + + int int_duration_min = Util.getIntValue(duration_min,0); + String has_key = has_requestid; + String cur_key = requestid; + if(flow_dataid.length() > 0){ + has_key += "_"+dataid+"_"+detailid; + cur_key += "_"+flow_dataid; + } + //为什么要加这个判断呢,因为有可能我请假3小时,打卡1小时,然后这个时候生成1小时加班,然后我后面又补卡了2小时,这时候,加班流程虽然已经 +// 生成过加班,但是其实只用了1小时,还需要拿这个加班流程来,减去已经用的1小时,d_mins就是这个加班流程实际可用的加班流程时长 + if(has_key.equalsIgnoreCase(cur_key)){ + if(int_duration_min > 0){ + d_mins = d_mins-(int_duration_min*1.0); + } + } + all_has_duration_min += int_duration_min; + if(hasCardMap.containsKey(card_key)){ + int tmp_int_duration_min = Util.getIntValue(hasCardMap.get(card_key)); + hasCardMap.put(card_key, ""+(int_duration_min+tmp_int_duration_min)); + }else{ + hasCardMap.put(card_key, int_duration_min+""); + } + } + } + if(d_mins > 0){ + + int[] initArrays = kqTimesArrayComInfo.getInitArr(); + Map signinoffMap = buildOvertimeCard(kqOvertimeCardBean, resourceid, realSplitDate, kqTimesArrayComInfo, restTimeMap, changeType_key,initArrays,hasOverTimeList, + overRulesDetailMap, false, overtimeLogMap); + + String signinTime = Util.null2String(signinoffMap.get("signinTime")); + String signoutTime = Util.null2String(signinoffMap.get("signoutTime")); + String signinDate = Util.null2String(signinoffMap.get("signinDate")); + String signoutDate = Util.null2String(signinoffMap.get("signoutDate")); + int signinTimeIndex = kqTimesArrayComInfo.getArrayindexByTimes(signinTime); + int signoutTimeIndex = kqTimesArrayComInfo.getArrayindexByTimes(signoutTime); + + if(signinTimeIndex < signoutTimeIndex){ + String nowCardKey = signinDate+"_"+kqTimesArrayComInfo.turn48to24Time(signinTime) + +"_"+signoutDate+"_"+kqTimesArrayComInfo.turn48to24Time(signoutTime); + int over_count = kqTimesArrayComInfo.getCnt(initArrays, signinTimeIndex, signoutTimeIndex, 1); + int card_mins = over_count; + logOvertimeMap(overtimeLogMap, over_count, flow_key+"|加班打卡生成的时长|over_count"); + if(over_count > 0){ + //表示加班打卡是存在的 + String flow_cross_key = flow_key+"|加班计算区间|"+signinTime+"-"+signoutTime; + + int restTimeType = 1; + if(kqOvertimeRulesDetailEntity != null){ + int minimumLen = kqOvertimeRulesDetailEntity.getMinimumLen(); + if(card_mins < minimumLen){ + continue; + } + logOvertimeMap(overtimeLogMap, JSON.toJSONString(kqOvertimeRulesDetailEntity), flow_key+"|加班规则|KQOvertimeRulesDetailEntity"); + //我这个方法是针对每次生成的加班数据做排除休息时长的处理 打卡数据也要去掉休息时长 + restTimeType = kqOvertimeRulesDetailEntity.getRestTimeType(); + if(restTimeType == 2){ + over_count = new KQOverTimeFlowBiz().handle_restlength(over_count,restTimeMap,changeType_key); + } + } + if(all_has_duration_min > 0){ + for(Map.Entry me : hasCardMap.entrySet()){ + String cardKey = me.getKey(); + String cardValue = me.getValue(); + if(cardKey.equalsIgnoreCase(nowCardKey)){ + }else{ + all_has_duration_min = all_has_duration_min - Util.getIntValue(cardValue); + } + } + over_count = over_count-all_has_duration_min; + } + if(over_count <= 0){ + continue; + } + int mins = over_count < d_mins ? over_count : (int)d_mins; + double double_mins = getD_MinsByUnit((1.0*mins)); + mins = (int)double_mins; + + RecordSet rs = new RecordSet(); + String overtime_uuid = UUID.randomUUID().toString(); + String flow_dataid = dataid+"_"+detailid; + String tiaoxiuId = ""; + int computingMode = 2; + + int unit = KQOvertimeRulesBiz.getMinimumUnit(); + String workingHours = ""; + String overtime_type = splitBean.getOvertime_type(); + Map otherParam = Maps.newHashMap(); + otherParam.put("overtime_type", overtime_type); + int paidLeaveEnableType = kqOvertimeRulesDetailEntity.getPaidLeaveEnableType(); + if(2 == paidLeaveEnableType){ + logOvertimeMap(overtimeLogMap, overtime_type, flow_cross_key+"|关联调休与否来自于流程选择,加班类型下拉框值|overtime_type"); + } + + int paidLeaveEnable = getPaidLeaveEnable(kqOvertimeRulesDetailEntity, overtime_type); + boolean needSplitByTime = false;//getNeedSplitByTime(kqOvertimeRulesDetailEntity, paidLeaveEnable); + if(needSplitByTime){ + // 按照加班时长转调休的 时长设置 + List timepointList = null; + if(kqOvertimeRulesDetailEntity != null){ + timepointList = get_timepointList(kqOvertimeRulesDetailEntity); + logOvertimeMap(overtimeLogMap, timepointList, flow_cross_key+"|如果要生成调休且是根据时间区间来转调休,返回对应的时间区间|timepointList"); + } + + List overtimeBalanceTimeBeans = Lists.newArrayList(); + //需要分段根据设置的时间区间来计算加班,这个第二种加班方式有有点冲突,不能做 +// if(timepointList != null && !timepointList.isEmpty()){ +// int[] time_initArrays = kqTimesArrayComInfo.getInitArr(); +// get_overtimeBalanceTimeBeans(timepointList,overtimeBalanceTimeBeans,kqTimesArrayComInfo,time_initArrays,flow_cross_totime_index,2); +// } + }else{ + logOvertimeMap(overtimeLogMap, mins, flow_cross_key+"|最终生成的加班时长|mins"); + otherParam.put("overtimeLogMap", overtimeLogMap); + + tiaoxiuId = KQBalanceOfLeaveBiz.addExtraAmountByDis5(resourceid,realSplitDate,mins+"","0",workingHours,requestid,"1",flow_fromdate,otherParam); + if(Util.getIntValue(tiaoxiuId) > 0){ + kqLog.info("doComputingMode2 生成调休成功,调休id:"+tiaoxiuId+":resourceid:"+resourceid+":realSplitDate:"+realSplitDate+":requestid:"+requestid); + }else{ + kqLog.info("doComputingMode2 生成调休失败,调休id:"+tiaoxiuId+":resourceid:"+resourceid+":realSplitDate:"+realSplitDate+":requestid:"+requestid); + } + logOvertimeMap(overtimeLogMap, tiaoxiuId, flow_cross_key+"|最终生成的调休id|tiaoxiuId"); + + String flow_overtime_sql = "insert into kq_flow_overtime (requestid,resourceid,fromdate,fromtime,todate,totime,duration_min,expiringdate,belongdate," + + "workMins,durationrule,changetype,paidLeaveEnable,computingMode,tiaoxiuId,uuid,fromdatedb,fromtimedb,todatedb,totimedb,flow_mins,card_mins,ori_belongdate,flow_dataid)"+ + " values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) "; + signinTime = kqTimesArrayComInfo.turn48to24Time(signinTime); + signoutTime = kqTimesArrayComInfo.turn48to24Time(signoutTime); + if(fromtimedb.length() == 5){ + fromtimedb = fromtimedb+":00"; + } + if(totimedb.length() == 5){ + totimedb = totimedb+":00"; + } + boolean isUp = rs.executeUpdate(flow_overtime_sql, requestid,resourceid,fromdatedb,fromtimedb,todatedb,totimedb,mins,"",realSplitDate, + "",unit,changeType,paidLeaveEnable,computingMode,tiaoxiuId,overtime_uuid,signinDate,signinTime,signoutDate,signoutTime,flow_count,card_mins,splitDate,flow_dataid); + String overtimeid = get_overtime_uuid(overtime_uuid); + kqEventLogBiz.updateOvertimeId(uuid, overtimeid); + } + + } + } + }else{ + logOvertimeMap(overtimeLogMap, "流程时长d_mins为0,不生成加班", flow_key+"|加班流程信息|flowLogInfo"); + } + } + } + + }else{ + logOvertimeMap(overtimeLogMap, "打卡数据KQOvertimeCardBean为null", "打卡和上下班数据|KQOvertimeCardBean"); + } + } + kqEventLogBiz.logDetailOvertimeMap(resourceid,overtimeLogMap,uuid); + kqEventLogBiz.logDetailEvent(resourceid,eventMap,uuid,"doComputingMode2|对应的加班流程数据|key|"+key); + + } + + /** + * 打卡的时长计算,流程+打卡 和纯打卡的可以拿来共用 + * needHasOverTime 是否需要按照打卡区间排除重复打卡的数据,第二种流程和打卡比较时长的不需要这个方式 + */ + public Map buildOvertimeCard(KQOvertimeCardBean kqOvertimeCardBean, + String resourceid, String splitDate, KQTimesArrayComInfo kqTimesArrayComInfo, + Map> restTimeMap, String changeType_key, int[] initArrays, + List> hasOverTimeList, + Map overRulesDetailMap, boolean needHasOverTime, + Map overtimeLogMap) throws Exception{ + Map signinoffMap = Maps.newHashMap(); + + String signinDate = kqOvertimeCardBean.getSigninDate(); + String signinTime = kqOvertimeCardBean.getSigninTime(); + String signoutDate = kqOvertimeCardBean.getSignoutDate(); + String signoutTime = kqOvertimeCardBean.getSignoutTime(); + + if(hasOverTimeList.isEmpty()){ + getHasOverTimeData(resourceid,splitDate,hasOverTimeList); + } + + if(signinDate.compareTo(splitDate) > 0){ + signinTime = kqTimesArrayComInfo.turn24to48Time(signinTime); + if(signinTime.length() > 0){ + signinTime = signinTime+ ":00"; + } + } + if(signoutDate.compareTo(splitDate) > 0){ + signoutTime = kqTimesArrayComInfo.turn24to48Time(signoutTime); + if(signoutTime.length() > 0){ + signoutTime = signoutTime+ ":00"; + } + } + if(signinTime.length() == 0 || signoutTime.length() == 0){ + return signinoffMap; + } + + int signinTimeIndex = kqTimesArrayComInfo.getArrayindexByTimes(signinTime); + int signoutTimeIndex = kqTimesArrayComInfo.getArrayindexByTimes(signoutTime); + + signinoffMap.put("signinTime", signinTime); + signinoffMap.put("signoutTime", signoutTime); + signinoffMap.put("signinDate", signinDate); + signinoffMap.put("signoutDate", signoutDate); + //先把打卡数据都列出来 置位1 + if(signinTimeIndex < signoutTimeIndex){ + Arrays.fill(initArrays, signinTimeIndex, signoutTimeIndex,1); + } + KQOvertimeRulesDetailEntity kqOvertimeRulesDetailEntity = overRulesDetailMap.get(changeType_key); + if(restTimeMap.containsKey(changeType_key)){ + List restTimeList = restTimeMap.get(changeType_key); + logOvertimeMap(overtimeLogMap, restTimeList, "非工作时间设置的排除休息时间区间|restTimeList"); + //再把休息时间填充上去 + if(!restTimeList.isEmpty()){ + int restTimeType = 1; + if(kqOvertimeRulesDetailEntity != null){ + restTimeType = kqOvertimeRulesDetailEntity.getRestTimeType(); + } + if(restTimeType == 1){ + for(int j =0 ; j < restTimeList.size() ; j++){ + String[] restTimes = restTimeList.get(j); + if(restTimes.length == 2){ + int restStart = kqTimesArrayComInfo.getArrayindexByTimes(restTimes[0]); + int restEnd = kqTimesArrayComInfo.getArrayindexByTimes(restTimes[1]); + if(restEnd == 1439){ + //针对跨天的休息时段单独处理排除掉23:59-00:00的时间 + restEnd = 1440; + } + int hasRestMins = kqTimesArrayComInfo.getCnt(initArrays, restStart,restEnd,1); + if(hasRestMins == 0) { + restStart = kqTimesArrayComInfo.turn24to48TimeIndex(restStart); + restEnd = kqTimesArrayComInfo.turn24to48TimeIndex(restEnd); + } + if(restStart < restEnd){ + Arrays.fill(initArrays, restStart, restEnd, -2); + } + } + } + }else{ + } + } + } + + boolean isNextDay = false; + clearWorkAndRestTime(resourceid,splitDate,isNextDay,kqTimesArrayComInfo,overtimeLogMap,kqOvertimeRulesDetailEntity,initArrays,signinTimeIndex); + isNextDay = true; + clearWorkAndRestTime(resourceid,DateUtil.addDate(splitDate, 1),isNextDay, kqTimesArrayComInfo, + overtimeLogMap, kqOvertimeRulesDetailEntity, initArrays, signinTimeIndex); + + if(!hasOverTimeList.isEmpty() && needHasOverTime){ + if(hasOverTimeList != null && !hasOverTimeList.isEmpty()){ + for(int p = 0 ; p < hasOverTimeList.size(); p++){ + Map hasOverTimeMap = hasOverTimeList.get(p); + String duration_min = Util.null2String(hasOverTimeMap.get("duration_min")); + String fromdate = Util.null2String(hasOverTimeMap.get("fromdate")); + String fromtime = Util.null2String(hasOverTimeMap.get("fromtime")); + String todate = Util.null2String(hasOverTimeMap.get("todate")); + String totime = Util.null2String(hasOverTimeMap.get("totime")); + if(fromdate.compareTo(splitDate) > 0){ + fromtime = kqTimesArrayComInfo.turn24to48Time(fromtime); + } + if(todate.compareTo(splitDate) > 0){ + totime = kqTimesArrayComInfo.turn24to48Time(totime); + } + int begintimeIndex = kqTimesArrayComInfo.getArrayindexByTimes(fromtime); + int endtimeIndex = kqTimesArrayComInfo.getArrayindexByTimes(totime); + if(begintimeIndex < endtimeIndex){ + Arrays.fill(initArrays, begintimeIndex, endtimeIndex, -2); + } + } + } + } + return signinoffMap; + } + + /** + * 把指定的打卡区间内的上下班时间和休息时间去除 + * @param resourceid + * @param splitDate + * @param isNextDay 是否是处理处理明日的,如果是true的话,上下班时间和休息时间都要+1440 + * @param kqTimesArrayComInfo + * @param overtimeLogMap + * @param kqOvertimeRulesDetailEntity + * @param initArrays + * @param signinTimeIndex + */ + public void clearWorkAndRestTime(String resourceid, String splitDate, boolean isNextDay, + KQTimesArrayComInfo kqTimesArrayComInfo, + Map overtimeLogMap, + KQOvertimeRulesDetailEntity kqOvertimeRulesDetailEntity, int[] initArrays, + int signinTimeIndex) { + + KQWorkTime kqWorkTime = new KQWorkTime(); + WorkTimeEntity workTime = kqWorkTime.getWorkTime(resourceid, splitDate); + if (workTime == null || workTime.getWorkMins() == 0) { + }else{ + if (workTime.getKQType().equals("3")) {//自由工时 + //目前自由工时不加班 + } else { + boolean oneSign = false; + List lsSignTime = new ArrayList<>(); + List lsWorkTime = new ArrayList<>(); + List lsRestTime = new ArrayList<>(); + if (workTime != null) { + lsSignTime = workTime.getSignTime();//允许打卡时间 + lsWorkTime = workTime.getWorkTime();//工作时间 + lsRestTime = workTime.getRestTime();//休息时段时间 + oneSign = lsWorkTime!=null&&lsWorkTime.size()==1; + + if(lsWorkTime != null && !lsWorkTime.isEmpty()){ + for (int i = 0; lsWorkTime != null && i < lsWorkTime.size(); i++) { + TimeScopeEntity workTimeScope = lsWorkTime.get(i); + if(oneSign){ + boolean is_flow_humanized = KQSettingsBiz.is_flow_humanized(); + if(is_flow_humanized){ + 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(); + + Map shifRuleMap = Maps.newHashMap(); + //个性化设置只支持一天一次上下班 + ShiftInfoBean shiftInfoBean = new ShiftInfoBean(); + shiftInfoBean.setSplitDate(splitDate); + shiftInfoBean.setShiftRuleMap(workTime.getShiftRuleInfo()); + shiftInfoBean.setSignTime(lsSignTime); + shiftInfoBean.setWorkTime(lsWorkTime); + List logList = Lists.newArrayList(); + KQShiftRuleInfoBiz.getShiftRuleInfo(shiftInfoBean, resourceid, shifRuleMap,logList); + if(!shifRuleMap.isEmpty()){ + 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(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); + } + } + } + } + } + } + //目前只处理上班前和下班后的加班数据,上班中间的数据不处理,所以从第一次上班时间到最后下班时间都是无效的加班打卡 + TimeScopeEntity first_TimeScopeEntity = lsWorkTime.get(0); + TimeScopeEntity last_TimeScopeEntity = lsWorkTime.get(lsWorkTime.size()-1); + + String begintime = first_TimeScopeEntity.getBeginTime(); + String endtime = last_TimeScopeEntity.getEndTime(); + int begintimeIndex = kqTimesArrayComInfo.getArrayindexByTimes(begintime); + int endtimeIndex = kqTimesArrayComInfo.getArrayindexByTimes(endtime); + if(isNextDay){ + begintimeIndex = begintimeIndex + 1440; + endtimeIndex = endtimeIndex + 1440; + if(begintimeIndex >= initArrays.length){ + begintimeIndex = initArrays.length-1; + } + if(endtimeIndex >= initArrays.length){ + endtimeIndex = initArrays.length-1; + } + } + String workTimeLogInfo = "begintime:"+begintime+":endtime:"+endtime+":isNextDay:"+isNextDay; + logOvertimeMap(overtimeLogMap, workTimeLogInfo, "工作日的上下班时间|workTimeLogInfo"); + if(begintimeIndex < endtimeIndex){ + Arrays.fill(initArrays, begintimeIndex, endtimeIndex, -2); + } + if(!isNextDay){ + if(kqOvertimeRulesDetailEntity != null){ + int startTime = kqOvertimeRulesDetailEntity.getStartTime(); + if(startTime > -1){ + int after_endtimeIndex = endtimeIndex + startTime; + if(after_endtimeIndex > endtimeIndex){ + Arrays.fill(initArrays, endtimeIndex, after_endtimeIndex, -2); + } + } + int has_cut_point = kqOvertimeRulesDetailEntity.getHas_cut_point(); + if(has_cut_point == 1){ + int before_startTime = kqOvertimeRulesDetailEntity.getBefore_startTime(); + if(before_startTime > -1){ + int before_begintimeIndex = begintimeIndex - before_startTime; + if(before_begintimeIndex > signinTimeIndex){ + Arrays.fill(initArrays, signinTimeIndex, before_begintimeIndex, -2); + } + } + } + } + } + } + if(lsRestTime != null && !lsRestTime.isEmpty()){ + String restTimeLogInfo = JSON.toJSONString(lsRestTime); + logOvertimeMap(overtimeLogMap, restTimeLogInfo, "工作日的休息时间|restTimeLogInfo"); + for(int p = 0 ; p < lsRestTime.size(); p++){ + TimeScopeEntity rest_TimeScopeEntity = lsRestTime.get(p); + String begintime = rest_TimeScopeEntity.getBeginTime(); + String endtime = rest_TimeScopeEntity.getEndTime(); + int begintimeIndex = kqTimesArrayComInfo.getArrayindexByTimes(begintime); + int endtimeIndex = kqTimesArrayComInfo.getArrayindexByTimes(endtime); + if(isNextDay){ + begintimeIndex = begintimeIndex + 1440; + endtimeIndex = endtimeIndex + 1440; + if(begintimeIndex >= initArrays.length){ + begintimeIndex = initArrays.length-1; + } + if(endtimeIndex >= initArrays.length){ + endtimeIndex = initArrays.length-1; + } + } + if(begintimeIndex < endtimeIndex){ + Arrays.fill(initArrays, begintimeIndex, endtimeIndex, -2); + } + } + } + + } + } + } + } + + /** + * 根据打卡数据和加班归属 拆分出来需要计算加班的区段 + * @param resourceid + * @param fromDate + * @param toDate + * @param dateFormatter + * @param kqTimesArrayComInfo + * @param overRulesDetailMap + * @param changeTypeMap + * @param lsCheckInfoMaps + * @param eventMap + */ + public void getOverTimeCardDataMap(String resourceid, String fromDate, String toDate, + DateTimeFormatter dateFormatter, + KQTimesArrayComInfo kqTimesArrayComInfo, + Map overRulesDetailMap, + Map changeTypeMap, Map lsCheckInfoMaps, + Map eventMap) throws Exception{ + + KQOverTimeFlowBiz kqOverTimeFlowBiz = new KQOverTimeFlowBiz(); + + List lsCheckInfos = Lists.newArrayList(); + Map result = getSignData(resourceid, fromDate, dateFormatter,eventMap,lsCheckInfos,changeTypeMap,overRulesDetailMap); + + //获取一下当天的上班时间 + String firstworkDate = Util.null2String(result.get("firstworkDate")); + String firstworkTime = Util.null2String(result.get("firstworkTime")); + int pre_has_cut_point = Util.getIntValue(Util.null2String(result.get("pre_has_cut_point"))); + String pre_cut_point = Util.null2String(result.get("pre_cut_point")); + int has_cut_point = Util.getIntValue(Util.null2String(result.get("has_cut_point"))); + String cut_point = Util.null2String(result.get("cut_point")); + int before_startTime = Util.getIntValue(Util.null2String(result.get("before_startTime"))); + int preChangeType = Util.getIntValue(Util.null2String(result.get("preChangeType"))); + int changeType = Util.getIntValue(Util.null2String(result.get("changeType"))); + + LocalDate localbelongDate = LocalDate.parse(fromDate); + String splitDate = localbelongDate.format(dateFormatter); + LocalDate preLocalDate = localbelongDate.minusDays(1); + String preSplitDate = preLocalDate.format(dateFormatter); + String nextSplitDate = localbelongDate.plusDays(1).format(dateFormatter); + + String preKey = resourceid+"_"+preSplitDate; + String key = resourceid+"_"+splitDate; + String nextkey = resourceid+"_"+nextSplitDate; + + eventMap.put("lsCheckInfos", lsCheckInfos); + if(!lsCheckInfos.isEmpty()){ + Map signMap = (Map) lsCheckInfos.get(0); + String signindate = ""; + String signintime = ""; + String signoutdate = ""; + String signouttime = ""; + + if(signMap != null && !signMap.isEmpty()){ + signindate = Util.null2String(signMap.get("signindate")); + signintime = Util.null2String(signMap.get("signintime")); + signoutdate = Util.null2String(signMap.get("signoutdate")); + signouttime = Util.null2String(signMap.get("signouttime")); + if(lsCheckInfos.size() > 1){ + Map lastSignMap = (Map) lsCheckInfos.get(lsCheckInfos.size()-1); + signoutdate = Util.null2String(lastSignMap.get("signoutdate")); + signouttime = Util.null2String(lastSignMap.get("signouttime")); + } + } + KQOvertimeCardBean kqOvertimeBean = new KQOvertimeCardBean(); + kqOvertimeBean.setSigninDate(signindate); + kqOvertimeBean.setSigninTime(signintime); + kqOvertimeBean.setSignoutDate(signoutdate); + kqOvertimeBean.setSignoutTime(signouttime); + kqOvertimeBean.setBelongDate(splitDate); + eventMap.put("has_cut_point", has_cut_point); + if(pre_has_cut_point == 0){ + //未设置打卡归属 + if(preChangeType == 2){ + eventMap.put("preChangeType", preChangeType); + //如果前一天是工作日 + String pre_overtime_cut_point = ""; + ShiftInfoBean pre_shiftInfoBean = KQDurationCalculatorUtil + .getWorkTime(resourceid, preSplitDate, false); + if(pre_shiftInfoBean != null){ + List workLongTimeIndex = pre_shiftInfoBean.getWorkLongTimeIndex(); + List real_workLongTimeIndex = Lists.newArrayList(); + SplitBean splitBean = new SplitBean(); + splitBean.setResourceId(resourceid); + kqOverTimeFlowBiz.get_real_workLongTimeIndex(workLongTimeIndex,real_workLongTimeIndex,pre_shiftInfoBean,kqTimesArrayComInfo,splitBean); + + if(real_workLongTimeIndex != null && !real_workLongTimeIndex.isEmpty()){ + pre_overtime_cut_point = kqTimesArrayComInfo.getTimesByArrayindex(real_workLongTimeIndex.get(0)[0]); + } + eventMap.put("pre_overtime_cut_point", pre_overtime_cut_point); + if(pre_overtime_cut_point.length() >= 0){ + rePutCheckInfoMap(lsCheckInfoMaps, kqOvertimeBean, preKey, key, pre_overtime_cut_point, splitDate,eventMap); + } + }else{ + String errorMsg = "前一天是工作日但是前一天的ShiftInfoBean班次获取不到信息"; + eventMap.put("errorMsg", errorMsg); + } + }else { + eventMap.put("changeType", changeType); + if(changeType == 2){ + eventMap.put("firstworkTime", firstworkTime); + if(has_cut_point == 1 && before_startTime > 0){ + firstworkTime = kqTimesArrayComInfo.getTimesByArrayindex(kqTimesArrayComInfo.getArrayindexByTimes(firstworkTime)-before_startTime); + } + //如果前一天是非工作日,今天是工作日的话 + rePutCheckInfoMap(lsCheckInfoMaps, kqOvertimeBean, preKey, key, firstworkTime, splitDate, + eventMap); + }else{ + //如果前一天是非工作日,今天是非工作日的话,那就是打卡获取的是啥就是啥 + lsCheckInfoMaps.put(key, kqOvertimeBean); + } + } + }else{ + String pre_splittime = ""; + List pre_lsCheckInfos = Lists.newArrayList(); + getSignData(resourceid, preSplitDate, dateFormatter, eventMap, pre_lsCheckInfos, changeTypeMap, overRulesDetailMap); + if(!pre_lsCheckInfos.isEmpty()){ + Map preSignMap = (Map) pre_lsCheckInfos.get(0); + String pre_signindate = ""; + String pre_signintime = ""; + String pre_signoutdate = ""; + String pre_signouttime = ""; + if(preSignMap != null && !preSignMap.isEmpty()){ + pre_signindate = Util.null2String(preSignMap.get("signindate")); + pre_signintime = Util.null2String(preSignMap.get("signintime")); + pre_signoutdate = Util.null2String(preSignMap.get("signoutdate")); + pre_signouttime = Util.null2String(preSignMap.get("signouttime")); + if(pre_signindate.length() > 0 && pre_signintime.length() > 0){ + pre_splittime = pre_signindate+" "+pre_signintime; + }else if(pre_signoutdate.length() > 0 && pre_signouttime.length() > 0){ + pre_splittime = pre_signoutdate+" "+pre_signouttime; + } + } + } + eventMap.put("pre_cut_point", pre_cut_point); + //设置了打卡归属 那么一天的打卡就可能被前一天给拆成两部分和后一天的打卡归属给拆分成两部分 + rePutCheckInfoCutPointMap(lsCheckInfoMaps, kqOvertimeBean, preKey, key, pre_cut_point, splitDate, + eventMap,cut_point,nextSplitDate,nextkey,has_cut_point,pre_splittime); + } + } + } + + /** + * 获取打卡数据 + * @param resourceid + * @param belongDate + * @param dateFormatter + * @param eventMap + * @param lsCheckInfos + * @param changeTypeMap + * @param overRulesDetailMap + */ + public Map getSignData(String resourceid, String belongDate, + DateTimeFormatter dateFormatter, Map eventMap, + List lsCheckInfos, Map changeTypeMap, + Map overRulesDetailMap) throws Exception{ + Map result = Maps.newHashMap(); + String firstworkDate = ""; + String firstworkTime = ""; + + KQTimesArrayComInfo kqTimesArrayComInfo = new KQTimesArrayComInfo(); + LocalDate localbelongDate = LocalDate.parse(belongDate); + String splitDate = localbelongDate.format(dateFormatter); + LocalDate preLocalDate = localbelongDate.minusDays(1); + String preSplitDate = preLocalDate.format(dateFormatter); + String nextSplitDate = localbelongDate.plusDays(1).format(dateFormatter); + + String change_key = splitDate+"_"+resourceid; + String preChange_key = preSplitDate+"_"+resourceid; + String nextChange_key = nextSplitDate+"_"+resourceid; + int changeType = Util.getIntValue(""+changeTypeMap.get(change_key),-1); + int preChangeType = Util.getIntValue(""+changeTypeMap.get(preChange_key),-1); + int nextChangeType = Util.getIntValue(""+changeTypeMap.get(nextChange_key),-1); + String changeType_key = splitDate+"_"+changeType; + String preChangeType_key = preSplitDate+"_"+preChangeType; + String nextChangeType_key = nextSplitDate+"_"+nextChangeType; + + KQOvertimeRulesDetailEntity curKqOvertimeRulesDetailEntity = overRulesDetailMap.get(changeType_key); + KQOvertimeRulesDetailEntity preKqOvertimeRulesDetailEntity = overRulesDetailMap.get(preChangeType_key); + KQOvertimeRulesDetailEntity nextKqOvertimeRulesDetailEntity = overRulesDetailMap.get(preChangeType_key); + + int pre_has_cut_point = 0; + String pre_cut_point = ""; + if(preKqOvertimeRulesDetailEntity != null){ + pre_has_cut_point = preKqOvertimeRulesDetailEntity.getHas_cut_point(); + pre_cut_point = preKqOvertimeRulesDetailEntity.getCut_point(); + } + int has_cut_point = 0; + String cut_point = ""; + int before_startTime = -1; + if(curKqOvertimeRulesDetailEntity != null){ + has_cut_point = curKqOvertimeRulesDetailEntity.getHas_cut_point(); + cut_point = curKqOvertimeRulesDetailEntity.getCut_point(); + before_startTime =curKqOvertimeRulesDetailEntity.getBefore_startTime(); + } + + result.put("pre_has_cut_point", ""+pre_has_cut_point); + result.put("pre_cut_point", pre_cut_point); + result.put("has_cut_point", ""+has_cut_point); + result.put("cut_point", cut_point); + result.put("before_startTime", ""+before_startTime); + result.put("preChangeType", ""+preChangeType); + result.put("changeType", ""+changeType); + + KQWorkTime kqWorkTime = new KQWorkTime(); + WorkTimeEntity workTime = kqWorkTime.getWorkTime(resourceid, splitDate); + + LocalDate pre_curLocalDate = localbelongDate.minusDays(1); + String preDate = pre_curLocalDate.format(dateFormatter); + LocalDate next_curLocalDate = localbelongDate.plusDays(1); + String nextDate = next_curLocalDate.format(dateFormatter); + + if (workTime == null || (workTime.getWorkMins() == 0 && workTime.getRestShift() != 1)) { + Map signMap = getRestSignInfo(resourceid,splitDate,preDate,nextDate,curKqOvertimeRulesDetailEntity,eventMap,preKqOvertimeRulesDetailEntity); + if(signMap != null && !signMap.isEmpty()){ + lsCheckInfos.add(signMap); + } + }else{ + if (workTime.getKQType().equals("3")) {//自由工时 + //目前自由工时不加班 + } else { + boolean oneSign = false; + List lsSignTime = new ArrayList<>(); + List lsWorkTime = new ArrayList<>(); + List lsRestTime = new ArrayList<>(); + oneSign = lsWorkTime!=null&&lsWorkTime.size()==1; + boolean need_middle_time = false; + + if (workTime != null) { + lsSignTime = workTime.getSignTime();//允许打卡时间 + lsWorkTime = workTime.getWorkTime();//工作时间 + result.put("lsWorkTime_size", ""+lsWorkTime.size()); + lsRestTime = workTime.getRestTime();//休息时段时间 + oneSign = lsWorkTime!=null&&lsWorkTime.size()==1; + for (int i = 0; lsWorkTime != null && i < lsWorkTime.size(); i++) { + TimeScopeEntity signTimeScope = lsSignTime.get(i); + TimeScopeEntity workTimeScope = lsWorkTime.get(i); + if(i == 0){ + firstworkDate = splitDate; + firstworkTime = workTimeScope.getBeginTime(); + } + if(!oneSign){ + if(!need_middle_time){ + //多次打卡的时候,中间打卡不算加班 + if(i != 0 && i != lsWorkTime.size()-1){ + continue; + } + } + }else { + boolean is_flow_humanized = KQSettingsBiz.is_flow_humanized(); + if(is_flow_humanized){ + 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(); + + Map shifRuleMap = Maps.newHashMap(); + //个性化设置只支持一天一次上下班 + ShiftInfoBean shiftInfoBean = new ShiftInfoBean(); + shiftInfoBean.setSplitDate(splitDate); + shiftInfoBean.setShiftRuleMap(workTime.getShiftRuleInfo()); + shiftInfoBean.setSignTime(lsSignTime); + shiftInfoBean.setWorkTime(lsWorkTime); + List logList = Lists.newArrayList(); + KQShiftRuleInfoBiz.getShiftRuleInfo(shiftInfoBean, resourceid, shifRuleMap,logList); + if(!shifRuleMap.isEmpty()){ + 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(i == 0){ + firstworkDate = workBeginIdx>=1440 ? nextDate : splitDate; + firstworkTime = workBeginTime; + } + } + } + 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); + } + } + } + } + } + Map signMap = getSignInfo(resourceid,signTimeScope,workTimeScope,splitDate,preDate,nextDate,kqTimesArrayComInfo,eventMap,i,result); + if(signMap != null && !signMap.isEmpty()){ + //目前一天多次打卡的话,只获取第一次和最后一次打卡 + lsCheckInfos.add(signMap); + } + } + } + } + } + + if(firstworkDate.length() > 0 && firstworkTime.length() > 0){ + result.put("firstworkDate", firstworkDate); + result.put("firstworkTime", firstworkTime); + } + return result; + } + + public void rePutCheckInfoCutPointMap(Map lsCheckInfoMaps, + KQOvertimeCardBean kqOvertimeBean, String preKey, String key, String pre_cut_point, + String splitDate, Map eventMap, String cut_point, String nextDate, + String nextkey, int has_cut_point, String pre_splitdatetime) { + String preDate = DateUtil.addDate(splitDate, -1); + KQTimesArrayComInfo kqTimesArrayComInfo = new KQTimesArrayComInfo(); + + String pre_cut_points = pre_cut_point+":00"; + String pre_date_cut_point = splitDate+" "+pre_cut_points; + + String cut_points = cut_point+":00"; + String cur_date_cut_point = nextDate+" "+cut_points; + + String signindate = kqOvertimeBean.getSigninDate(); + String signoutdate = kqOvertimeBean.getSignoutDate(); + String signintime = kqOvertimeBean.getSigninTime(); + String signouttime = kqOvertimeBean.getSignoutTime(); + String signindatetime = kqOvertimeBean.getSigninDate()+" "+kqOvertimeBean.getSigninTime(); + String signoutdatetime = ""; + if(kqOvertimeBean.getSignoutDate().length() > 0 && kqOvertimeBean.getSignoutTime().length() > 0){ + //如果是休息日的话,可能存在没有上班时间的情况 + signoutdatetime = kqOvertimeBean.getSignoutDate()+" "+kqOvertimeBean.getSignoutTime(); + } + String pre_splittime_date = ""; + String pre_splittime_time = ""; + if(pre_splitdatetime.length() > 0){ + String[] pre_splittimes = pre_splitdatetime.split(" "); + if(pre_splittimes.length == 2){ + pre_splittime_date = pre_splittimes[0]; + pre_splittime_time = pre_splittimes[1]; + } + } + + String timeInfo = "date_cut_point:"+pre_date_cut_point+":signoutdatetime:"+signoutdatetime+":signindatetime:"+signindatetime; + String timeCompare1 = "date_cut_point.compareTo(signoutdatetime):"+pre_date_cut_point.compareTo(signoutdatetime); + String timeCompare2 = "date_cut_point.compareTo(signindatetime):"+pre_date_cut_point.compareTo(signindatetime); + eventMap.put("timeInfo", timeInfo); + eventMap.put("timeCompare1", timeCompare1); + eventMap.put("timeCompare2", timeCompare2); + if(pre_date_cut_point.compareTo(signindatetime) > 0){ + //如果归属大于签到时间,小于签退时间,表示归属之前是属于前一天的,归属之后的是属于今天的 + //开启了归属之后,归属点之前的打卡就属于前一天的签退卡了,相当于是从前一天的下班时间到这个卡都算是前一天的加班卡,和不开归属的时候不一样 + KQOvertimeCardBean preKqOvertimeBean = new KQOvertimeCardBean(); + if(pre_splittime_date.length() > 0 && pre_splittime_time.length() > 0){ + preKqOvertimeBean.setSigninDate(pre_splittime_date); + preKqOvertimeBean.setSigninTime(pre_splittime_time); + preKqOvertimeBean.setSignoutDate(signindate); + preKqOvertimeBean.setSignoutTime(signintime); + preKqOvertimeBean.setBelongDate(preDate); + lsCheckInfoMaps.put(preKey, preKqOvertimeBean); + } + if(signoutdatetime.length() > 0 && signoutdatetime.compareTo(pre_date_cut_point) > 0){ + KQOvertimeCardBean curOvertimeBean = new KQOvertimeCardBean(); + curOvertimeBean.setSigninDate(splitDate); + curOvertimeBean.setSigninTime(pre_cut_points); + curOvertimeBean.setSignoutDate(signoutdate); + curOvertimeBean.setSignoutTime(signouttime); + curOvertimeBean.setBelongDate(splitDate); + lsCheckInfoMaps.put(key, curOvertimeBean); + } + + }else if(signoutdatetime.length() > 0 && pre_date_cut_point.compareTo(signoutdatetime) > 0){ + //如果归属大于签退时间 表示这个时间都是属于前一天的 + lsCheckInfoMaps.put(preKey, kqOvertimeBean); + }else { + lsCheckInfoMaps.put(key, kqOvertimeBean); + } + if(signoutdate.length() > 0){ + if(signoutdate.compareTo(splitDate) > 0){ + if(1 == has_cut_point){ + //如果签退大于签到 表示打卡跨天 + if(cur_date_cut_point.compareTo(signoutdatetime) < 0){ + String hasSigninDate = signindate; + String hasSigninTime = signintime; + if(lsCheckInfoMaps.containsKey(key)){ + KQOvertimeCardBean hasOvertimeBean = lsCheckInfoMaps.get(key); + hasSigninDate = hasOvertimeBean.getSigninDate(); + hasSigninTime = hasOvertimeBean.getSigninTime(); + } + KQOvertimeCardBean curOvertimeBean = new KQOvertimeCardBean(); + curOvertimeBean.setSigninDate(hasSigninDate); + curOvertimeBean.setSigninTime(hasSigninTime); + curOvertimeBean.setSignoutDate(nextDate); + curOvertimeBean.setSignoutTime(cut_points); + curOvertimeBean.setBelongDate(splitDate); + lsCheckInfoMaps.put(key, curOvertimeBean); + + KQOvertimeCardBean nextOvertimeBean = new KQOvertimeCardBean(); + nextOvertimeBean.setSigninDate(nextDate); + nextOvertimeBean.setSigninTime(cut_points); + nextOvertimeBean.setSignoutDate(signoutdate); + nextOvertimeBean.setSignoutTime(signouttime); + nextOvertimeBean.setBelongDate(nextDate); + lsCheckInfoMaps.put(nextkey, nextOvertimeBean); + } + } + } + } + } + + + /** + * 重新把打卡数据按照归属来赋值 + * @param lsCheckInfoMaps + * @param kqOvertimeBean + * @param preKey + * @param key + * @param overtime_cut_point + * @param splitDate + * @param eventMap + */ + public void rePutCheckInfoMap(Map lsCheckInfoMaps, + KQOvertimeCardBean kqOvertimeBean, + String preKey, String key, String overtime_cut_point, String splitDate, + Map eventMap){ + + String preDate = DateUtil.addDate(splitDate, -1); + String overtime_cut_points = overtime_cut_point+":00"; + String date_cut_point = splitDate+" "+overtime_cut_points; + String signindate = kqOvertimeBean.getSigninDate(); + String signoutdate = kqOvertimeBean.getSignoutDate(); + String signintime = kqOvertimeBean.getSigninTime(); + String signouttime = kqOvertimeBean.getSignoutTime(); + String signindatetime = kqOvertimeBean.getSigninDate()+" "+kqOvertimeBean.getSigninTime(); + String signoutdatetime = ""; + if(kqOvertimeBean.getSignoutDate().length() > 0 && kqOvertimeBean.getSignoutTime().length() > 0){ + //如果是休息日的话,可能存在没有上班时间的情况 + signoutdatetime = kqOvertimeBean.getSignoutDate()+" "+kqOvertimeBean.getSignoutTime(); + } + + String timeInfo = "date_cut_point:"+date_cut_point+":signoutdatetime:"+signoutdatetime+":signindatetime:"+signindatetime; + String timeCompare1 = "date_cut_point.compareTo(signoutdatetime):"+date_cut_point.compareTo(signoutdatetime); + String timeCompare2 = "date_cut_point.compareTo(signindatetime):"+date_cut_point.compareTo(signindatetime); + eventMap.put("timeInfo", timeInfo); + eventMap.put("timeCompare1", timeCompare1); + eventMap.put("timeCompare2", timeCompare2); + if(date_cut_point.compareTo(signindatetime) > 0){ + //如果归属大于签到时间,小于签退时间,表示归属之前是属于前一天的,归属之后的是属于今天的 + //不开启了归属的时候,根据打卡的性质来判断,如果是签到卡,那么签到时间到前一天上班时间,这段区间内算是前一天的加班卡,和开启了归属不一样 + KQOvertimeCardBean preKqOvertimeBean = new KQOvertimeCardBean(); + preKqOvertimeBean.setSigninDate(signindate); + preKqOvertimeBean.setSigninTime(signintime); + preKqOvertimeBean.setSignoutDate(splitDate); + preKqOvertimeBean.setSignoutTime(overtime_cut_points); + preKqOvertimeBean.setBelongDate(preDate); + preKqOvertimeBean.setHas_cut_point("0"); + lsCheckInfoMaps.put(preKey, preKqOvertimeBean); + + if(signoutdatetime.length() > 0 && signoutdatetime.compareTo(date_cut_point) > 0){ + KQOvertimeCardBean curOvertimeBean = new KQOvertimeCardBean(); + curOvertimeBean.setSigninDate(splitDate); + curOvertimeBean.setSigninTime(overtime_cut_points); + curOvertimeBean.setSignoutDate(signoutdate); + curOvertimeBean.setSignoutTime(signouttime); + curOvertimeBean.setBelongDate(splitDate); + curOvertimeBean.setHas_cut_point("0"); + lsCheckInfoMaps.put(key, curOvertimeBean); + } + }else if(signoutdatetime.length() > 0 && date_cut_point.compareTo(signoutdatetime) > 0){ + //如果归属大于签退时间 表示这个时间都是属于前一天的 + lsCheckInfoMaps.put(preKey, kqOvertimeBean); + }else{ + //如果归属 小于签到时间,则都属于今天 + lsCheckInfoMaps.put(key, kqOvertimeBean); + } + } + + + /** + * 获取加班流程数据 + * @param resourceid + * @param fromDate + * @param toDate + * @param splitBeanMaps + * @param dateFormatter + */ + public void getOverTimeFlowData(String resourceid, String fromDate, String toDate, + Map> splitBeanMaps, + DateTimeFormatter dateFormatter) { + LocalDate localFromDate = LocalDate.parse(fromDate); + LocalDate preFromDate = localFromDate.minusDays(1); + LocalDate localToDate = LocalDate.parse(toDate); + long betweenDays = localToDate.toEpochDay() - preFromDate.toEpochDay(); + for (int k = 0; k <= betweenDays; k++) { + LocalDate curLocalDate = preFromDate.plusDays(k); + String splitDate = curLocalDate.format(dateFormatter); + String key = resourceid+"_"+splitDate; + String order_sql = " order by belongdate,fromtime "; + KQFlowDataBiz kqFlowDataBiz = new KQFlowDataBiz.FlowDataParamBuilder().belongDateParam(splitDate).resourceidParam(resourceid).orderby_sqlParam(order_sql).build(); + Map flowMaps = Maps.newHashMap(); + List splitBeans = kqFlowDataBiz.getOverTimeData(flowMaps); + if(!splitBeans.isEmpty()){ + splitBeanMaps.put(key, splitBeans); + } + } + } + + /** + * 获取非工作日的打卡数据 + * @param resourceid + * @param splitDate + * @param preDate + * @param nextDate + * @param curKqOvertimeRulesDetailEntity + * @param eventMap + * @param preKqOvertimeRulesDetailEntity + * @return + */ + private Map getRestSignInfo(String resourceid, String splitDate, String preDate, + String nextDate, + KQOvertimeRulesDetailEntity curKqOvertimeRulesDetailEntity, + Map eventMap, + KQOvertimeRulesDetailEntity preKqOvertimeRulesDetailEntity) { + Map signMap = Maps.newHashMap(); + WorkTimeEntity pre_workTime = new KQWorkTime().getWorkTime(resourceid, 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(resourceid, nextDate); + List next_lsSignTime = new ArrayList<>(); + + if (next_workTime != null) { + next_lsSignTime = next_workTime.getSignTime();//允许打卡时间 + next_lsSignTime = next_lsSignTime != null ? next_lsSignTime : new ArrayList<>(); + } + + signMap = getNonWorkSignInfo(resourceid,nextDate,splitDate,pre_lsSignTime,next_lsSignTime,curKqOvertimeRulesDetailEntity,eventMap,preKqOvertimeRulesDetailEntity); + + return signMap; + } + + + /** + * 获取非工作日的打卡数据 封装处理下 + * @param resourceid + * @param nextDate + * @param kqDate + * @param pre_lsSignTime + * @param next_lsSignTime + * @param curKqOvertimeRulesDetailEntity + * @param eventMap + * @param preKqOvertimeRulesDetailEntity + * @return + */ + public Map getNonWorkSignInfo(String resourceid, String nextDate, String kqDate, + List pre_lsSignTime, + List next_lsSignTime, + KQOvertimeRulesDetailEntity curKqOvertimeRulesDetailEntity, + Map eventMap, + KQOvertimeRulesDetailEntity preKqOvertimeRulesDetailEntity) { + Map signMap = Maps.newHashMap(); + KQFormatSignData kqFormatSignData = new KQFormatSignData(); + 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 signBeginDateTime = kqDate+" 00:00:00"; + String signEndDateTime = kqDate+" 23:59:59"; + //有这么一种情况,比如前一天是工作日,最晚签退是2点,然后工作日的归属是设置的5点,那么如果4点打一个卡的话,其实是需要生成加班的,因为4带你这个卡是昨日的签退 + String ore_signBeginDateTime = signBeginDateTime; + String base_sql = kqFormatSignData.signSignSql(rs); + + int pre_has_cut_point = preKqOvertimeRulesDetailEntity != null ? preKqOvertimeRulesDetailEntity.getHas_cut_point() : 0; + + if(pre_Worktime4Today.length() > 0){ + if(pre_has_cut_point == 1){ + String cut_point = Util.null2String(preKqOvertimeRulesDetailEntity.getCut_point()); + if(cut_point.length() > 0){ + if(cut_point.compareTo(pre_Worktime4Today) > 0){ + pre_Worktime4Today = cut_point; + }else{ + if(pre_Worktime4Today.length() == 5){ + pre_Worktime4Today += ":00"; + } + ore_signBeginDateTime = kqDate+" "+pre_Worktime4Today; + } + /** + 打卡数据:2022/04/29 09:00:00----2022/04/29 23:59:59---2022/04/30 00:00:00----2022/04/30 02:00:00 + 加班流程:2022-04-29 20:00---2022-04-30 03:00 + 加班规则:2022-04-29周五工作日自定义跨天归属设置为00:00,取交集,然后30号的00:00-02:00两个小时加班无法生成 + 问题原因:当29的下班卡结束打卡时间在自定义跨天00:00之后,那么读卡范围是:29号结束打卡时间(pre_Worktime4Today)开始的 + */ + pre_Worktime4Today = cut_point+":01"; + } + } + if(pre_Worktime4Today.length() == 5){ + pre_Worktime4Today += ":00"; + } + signBeginDateTime = kqDate+" "+pre_Worktime4Today; + }else{ + if(pre_has_cut_point == 1){ + String cut_point = Util.null2String(preKqOvertimeRulesDetailEntity.getCut_point()); + if(cut_point.length() > 0){ + String cut_point_time = kqDate+" "+cut_point+":00"; + signBeginDateTime = cut_point_time; + } + } + } + if(next_Worktime4Today.length() > 0){ + if(next_Worktime4Today.length() == 5){ + next_Worktime4Today += ":00"; + } + signEndDateTime = kqDate+" "+next_Worktime4Today; + }else{ + if(curKqOvertimeRulesDetailEntity != null){ + int cur_has_cut_point = curKqOvertimeRulesDetailEntity.getHas_cut_point(); + if(cur_has_cut_point == 1){ + String cut_point = Util.null2String(curKqOvertimeRulesDetailEntity.getCut_point()); + if(cut_point.length() > 0){ + String cut_point_time = nextDate+" "+cut_point+":00"; + signEndDateTime = cut_point_time; + } + } + } + } + String sql = "select * from ("+base_sql+") a "+" order by signdate asc,signtime asc "; + rs.executeQuery(sql,resourceid,signBeginDateTime,signEndDateTime); + String nonwork_card_sql = "sql:"+sql+"|resourceid|"+resourceid+"|signBeginDateTime|"+signBeginDateTime+"|signEndDateTime|"+signEndDateTime; + eventMap.put("非工作日打卡sql|nonwork_card_sql", nonwork_card_sql); + eventMap.put("非工作日打卡sql结果|nonwork_card_sql_getCounts", rs.getCounts()); + 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); + } + } + if(lsCheckInfo != null && !lsCheckInfo.isEmpty()){ + if(lsCheckInfo.size() == 2){ + Map begin_signMap = (Map) lsCheckInfo.get(0); + Map end_signMap = (Map) lsCheckInfo.get(lsCheckInfo.size()-1); + signMap.put("signindate", begin_signMap.get("signDate")); + signMap.put("signintime", begin_signMap.get("signTime")); + signMap.put("signoutdate", end_signMap.get("signDate")); + signMap.put("signouttime", end_signMap.get("signTime")); + }else if(lsCheckInfo.size() == 1){ + Map begin_signMap = (Map) lsCheckInfo.get(0); + signMap.put("signindate", begin_signMap.get("signDate")); + signMap.put("signintime", begin_signMap.get("signTime")); + } + }else{ + if(pre_has_cut_point == 1){ + sql = "select * from ("+base_sql+") a "+" order by signdate asc,signtime asc "; + rs.executeQuery(sql,resourceid,ore_signBeginDateTime,signEndDateTime); + nonwork_card_sql = "sql:"+sql+"|resourceid|"+resourceid+"|ore_signBeginDateTime|"+ore_signBeginDateTime+"|signEndDateTime|"+signEndDateTime; + eventMap.put("昨日开启了打卡归属,非工作日打卡sql|nonwork_card_sql", nonwork_card_sql); + eventMap.put("昨日开启了打卡归属,非工作日打卡sql结果|nonwork_card_sql_getCounts", rs.getCounts()); + 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); + } + } + if(lsCheckInfo != null && !lsCheckInfo.isEmpty()){ + //这种情况下,就只是把签到卡传回去作为前一天的签退了 + Map begin_signMap = (Map) lsCheckInfo.get(0); + signMap.put("signindate", begin_signMap.get("signDate")); + signMap.put("signintime", begin_signMap.get("signTime")); + } + } + } + return signMap; + } + /** + * 获取工作日的打卡数据 + * @param userId + * @param signTimeScope + * @param workTimeScope + * @param kqDate + * @param preDate + * @param nextDate + * @param kqTimesArrayComInfo + * @param eventMap + * @param index + * @param result + * @return + */ + public Map getSignInfo(String userId, TimeScopeEntity signTimeScope, + TimeScopeEntity workTimeScope, String kqDate, String preDate, + String nextDate, KQTimesArrayComInfo kqTimesArrayComInfo,Map eventMap, + int index,Map result) { + Map signMap = Maps.newHashMap(); + KQFormatSignData kqFormatSignData = new KQFormatSignData(); + List lsCheckInfo = new ArrayList<>(); + Map checkInfo = null; + String base_sql = ""; + RecordSet rs = new RecordSet(); + String dbtype = rs.getDBType(); + + int has_cut_point = Util.getIntValue(Util.null2String(result.get("has_cut_point"))); + String cut_point = Util.null2String(result.get("cut_point")); + + int pre_has_cut_point = Util.getIntValue(Util.null2String(result.get("pre_has_cut_point"))); + String pre_cut_point = Util.null2String(result.get("pre_cut_point")); + int lsWorkTime_size = Util.getIntValue(Util.null2String(result.get("lsWorkTime_size"))); + + //流程抵扣打卡不处理 + Map flow_deduct_card_map = Maps.newHashMap(); + + List> sqlConditions = kqFormatSignData.getCanSignInfo(signTimeScope,kqDate,preDate,nextDate,kqTimesArrayComInfo); + base_sql = kqFormatSignData.signSignSql(rs); + + if(sqlConditions != null && !sqlConditions.isEmpty()){ + for (int i = 0; i < sqlConditions.size(); i++) { + Map sqlMap = sqlConditions.get(i); + String sql = ""; + String orderSql = ""; + int idx = 0; + String signBeginDateTime = Util.null2String(sqlMap.get("signBeginDateTime")); + String signEndDateTime = Util.null2String(sqlMap.get("signEndDateTime")); + if(index == lsWorkTime_size-1 && i == sqlConditions.size()-1){ + //最后一次的打卡范围会被打卡临界点给修改 + if(has_cut_point == 1){ + String cut_point_datettime = nextDate+" "+cut_point+":59"; + signEndDateTime = cut_point_datettime; + } + } + if(index == 0 && i == 0){ + //第一次的打卡范围会被打卡临界点给修改 + if(pre_has_cut_point == 1){ + String cut_point_datettime = kqDate+" "+pre_cut_point+":00"; + signBeginDateTime = cut_point_datettime; + } + } + String type = Util.null2String(sqlMap.get("type")); + 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); + String work_card_sql = "index:"+index+":idx:"+idx+"|sql:"+sql+"|resourceid|"+userId+"|signBeginDateTime|"+signBeginDateTime+"|signEndDateTime|"+signEndDateTime; + + eventMap.put("工作日打卡sql|work_card_sql_"+index, work_card_sql); + eventMap.put("工作日打卡sql结果|work_card_sql_getCounts_"+index, rs.getCounts()); + 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);//签到签退时间 + checkInfo.put("type", type);//是否有打卡归属,type有值就是有打卡归属 + idx++; + if(type.length() > 0){ + if("signin".equalsIgnoreCase(type)){ + checkInfo.put("signType", "1"); + lsCheckInfo.add(checkInfo); + }else { + checkInfo.put("signType", "2"); + lsCheckInfo.add(checkInfo); + } + }else{ + if(idx==1){//第一条算签到 + checkInfo.put("signType", "1"); + lsCheckInfo.add(checkInfo); + }else if(idx==rs.getCounts()){//最后一条算签退 + checkInfo.put("signType", "2"); + lsCheckInfo.add(checkInfo); + } + } + } + } + } + if(lsCheckInfo != null && !lsCheckInfo.isEmpty()){ + if(lsCheckInfo.size() == 1){ + Map checkInfoMap = (Map) lsCheckInfo.get(0); + String type = Util.null2String(checkInfoMap.get("type")); + if("signin".equalsIgnoreCase(type)){ + signMap.put("signindate", checkInfoMap.get("signDate")); + signMap.put("signintime", checkInfoMap.get("signTime")); + signMap.put("signoutdate", workTimeScope.getBeginTimeAcross()?nextDate:kqDate); + signMap.put("signouttime", workTimeScope.getBeginTime()+":00"); + }else if("signoff".equalsIgnoreCase(type)){ + signMap.put("signindate", workTimeScope.getEndTimeAcross()?nextDate:kqDate); + signMap.put("signintime", workTimeScope.getEndTime()+":00"); + signMap.put("signoutdate", checkInfoMap.get("signDate")); + signMap.put("signouttime", checkInfoMap.get("signTime")); + }else{ + signMap.put("signindate", checkInfoMap.get("signDate")); + signMap.put("signintime", checkInfoMap.get("signTime")); + signMap.put("signoutdate", workTimeScope.getBeginTimeAcross()?nextDate:kqDate); + signMap.put("signouttime", workTimeScope.getBeginTime()+":00"); + } + }else{ + Map begin_signMap = (Map) lsCheckInfo.get(0); + Map end_signMap = (Map) lsCheckInfo.get(lsCheckInfo.size()-1); + signMap.put("signindate", begin_signMap.get("signDate")); + signMap.put("signintime", begin_signMap.get("signTime")); + signMap.put("signoutdate", end_signMap.get("signDate")); + signMap.put("signouttime", end_signMap.get("signTime")); + } + } + return signMap; + } + + /** + * 获取已经生成过的加班数据 + * @param resourceid + * @param belongdate + * @param hasOverTimeList + */ + public void getHasOverTimeData(String resourceid, String belongdate,List> hasOverTimeList) { + RecordSet rs = new RecordSet(); + + String sql = " select * from kq_flow_overtime where resourceid = ? and belongdate = ? "; + rs.executeQuery(sql,resourceid,belongdate); + while (rs.next()){ + String requestid =rs.getString("requestid"); + String fromdate =rs.getString("fromdate"); + String fromtime =rs.getString("fromtime"); + String todate =rs.getString("todate"); + String totime =rs.getString("totime"); + String duration_min =Util.null2String(rs.getString("duration_min")); + String flow_dataid =Util.null2String(rs.getString("flow_dataid")); + String ori_belongdate =Util.null2String(rs.getString("ori_belongdate")); + //流程+打卡的时候,存的对应的流程数据 + String fromdate_flow =rs.getString("fromdatedb"); + String fromtime_flow =rs.getString("fromtimedb"); + String todate_flow =rs.getString("todatedb"); + String totime_flow =rs.getString("totimedb"); + Map hasOverTimeMap = Maps.newHashMap(); + hasOverTimeMap.put("resourceid", resourceid); + hasOverTimeMap.put("belongdate", belongdate); + hasOverTimeMap.put("requestid", requestid); + hasOverTimeMap.put("fromdate", fromdate); + hasOverTimeMap.put("fromtime", fromtime); + hasOverTimeMap.put("todate", todate); + hasOverTimeMap.put("totime", totime); + hasOverTimeMap.put("fromdate_flow", fromdate_flow); + hasOverTimeMap.put("fromtime_flow", fromtime_flow); + hasOverTimeMap.put("todate_flow", todate_flow); + hasOverTimeMap.put("totime_flow", totime_flow); + hasOverTimeMap.put("duration_min", duration_min); + hasOverTimeMap.put("flow_dataid", flow_dataid); + hasOverTimeMap.put("ori_belongdate", ori_belongdate); + + hasOverTimeList.add(hasOverTimeMap); + } + } + + /** + * 根据人和日期获取加班规则里的信息 + * @param resourceid + * @param fromDate + * @param toDate + * @param dateFormatter + * @param changeTypeMap + * @param overRulesDetailMap + * @param restTimeMap + * @param computingModeMap + */ + public void getOverTimeDataMap(String resourceid, String fromDate, String toDate, + DateTimeFormatter dateFormatter, Map changeTypeMap, + Map overRulesDetailMap,Map> restTimeMap,Map computingModeMap){ + + LocalDate localFromDate = LocalDate.parse(fromDate); + LocalDate localToDate = LocalDate.parse(toDate); + LocalDate preFromDate = localFromDate.minusDays(2); + LocalDate nextToDate = localToDate.plusDays(1); + long betweenDays = nextToDate.toEpochDay() - preFromDate.toEpochDay(); + for (int i = 0; i <= betweenDays; i++) { + LocalDate curLocalDate = preFromDate.plusDays(i); + String splitDate = curLocalDate.format(dateFormatter); + KQOvertimeRulesBiz.getOverTimeData(resourceid, splitDate,changeTypeMap,overRulesDetailMap,restTimeMap,computingModeMap); + } + } + + public void logOvertimeMap(Map overtimeLogMap,Object params, String keys){ + if(overtimeLogMap != null){ + overtimeLogMap.put(keys, params); + } + } + + /** + * 根据加班规则设置,分段获取每一段的加班时长 + * @param resourceId + * @param fromdate + * @param fromtime + * @param todate + * @param totime + * @param changeTypeMap + * @param kqOvertimeRulesDetailEntity + * @param splitBean + * @param restTimeMap + * @param overRulesDetailMap + */ + public List getOvertimeBalanceTimeBean(String resourceId, + String fromdate, String fromtime, String todate, String totime, + Map changeTypeMap, + KQOvertimeRulesDetailEntity kqOvertimeRulesDetailEntity, SplitBean splitBean, + Map> restTimeMap, + Map overRulesDetailMap){ + KQOverTimeFlowBiz kqOverTimeFlowBiz = new KQOverTimeFlowBiz(); + KQTimesArrayComInfo kqTimesArrayComInfo= new KQTimesArrayComInfo(); + KQOverTimeRuleCalBiz kqOverTimeRuleCalBiz = new KQOverTimeRuleCalBiz(); + int[] initArrays = kqTimesArrayComInfo.getInitArr(); + boolean shouldAcross = false; + int before_startTime = -1; + int startTime = 0; + String change_key = fromdate+"_"+resourceId; + int changeType = Util.getIntValue(""+changeTypeMap.get(change_key),-1); + String changeType_key = fromdate+"_"+changeType; + + String nextSplitDate = DateUtil.addDate(fromdate,1); + String next_change_key = nextSplitDate+"_"+resourceId; + int next_changeType = Util.getIntValue(""+changeTypeMap.get(next_change_key),-1); + String nextChangeType_key = nextSplitDate+"_"+next_changeType; + + String next_beginwork_time = ""; + String serialid = ""; + //需要知道明日的类型:如果今天是工作日的话,那么今天的加班临界点可能和明日的上班时间冲突,需要知道明日的上班时间进行比较, + // 如果今天是休息日,那么明天如果是工作日的话,默认规则下,明天的上班前都是属于今天的加班区间 + if(next_changeType == 2){ + ShiftInfoBean next_shiftInfoBean = KQDurationCalculatorUtil.getWorkTime(resourceId, nextSplitDate, false); + if(next_shiftInfoBean != null){ + List workLongTimeIndex = next_shiftInfoBean.getWorkLongTimeIndex(); + List real_workLongTimeIndex = Lists.newArrayList(); + kqOverTimeFlowBiz.get_real_workLongTimeIndex(workLongTimeIndex,real_workLongTimeIndex,next_shiftInfoBean,kqTimesArrayComInfo,splitBean); + + if(real_workLongTimeIndex != null && !real_workLongTimeIndex.isEmpty()){ + next_beginwork_time = kqTimesArrayComInfo.getTimesByArrayindex(real_workLongTimeIndex.get(0)[0]); + } + } + } + + int fromTime_index = kqTimesArrayComInfo.getArrayindexByTimes(fromtime); + int toTime_index = kqTimesArrayComInfo.getArrayindexByTimes(totime); + Arrays.fill(initArrays, fromTime_index, toTime_index, 0); + if(changeType == 1){ + kqOverTimeFlowBiz.handle_changeType_1(initArrays, overRulesDetailMap, nextChangeType_key, + next_changeType, next_beginwork_time); + }else if(changeType == 2){ + if(kqOvertimeRulesDetailEntity != null){ + before_startTime = kqOvertimeRulesDetailEntity.getBefore_startTime(); + int has_cut_point = kqOvertimeRulesDetailEntity.getHas_cut_point(); + if(has_cut_point != 1){ + before_startTime = -1; + } + startTime = kqOvertimeRulesDetailEntity.getStartTime(); + } + boolean isok = kqOverTimeFlowBiz.handle_changeType_2(initArrays, resourceId, fromdate, before_startTime, startTime, fromTime_index, + kqTimesArrayComInfo, splitBean,toTime_index); + }else if(changeType == 3){ + kqOverTimeFlowBiz.handle_changeType_3(initArrays, overRulesDetailMap, nextChangeType_key, + next_changeType, next_beginwork_time); + } + int restTimeType = -1; + if(kqOvertimeRulesDetailEntity != null){ + restTimeType = kqOvertimeRulesDetailEntity.getRestTimeType(); + } + if(restTimeType == 1){ + //如果排除设置的休息时间 + kqOverTimeFlowBiz.handle_resttime(restTimeMap,changeType_key,kqTimesArrayComInfo,shouldAcross,initArrays); + } + // 按照加班时长转调休的 时长设置 + List timepointList = null; + List overtimeBalanceTimeBeans = Lists.newArrayList(); + if(kqOvertimeRulesDetailEntity != null){ + timepointList = kqOverTimeRuleCalBiz.get_timepointList(kqOvertimeRulesDetailEntity); + } + + if(timepointList != null && !timepointList.isEmpty()){ + kqOverTimeRuleCalBiz.get_overtimeBalanceTimeBeans(timepointList,overtimeBalanceTimeBeans,kqTimesArrayComInfo,initArrays,toTime_index,fromTime_index,0); + } + + return overtimeBalanceTimeBeans; + } + + /** + * 判断是否开启了调休的 按照时间点分段生成调休 + * @param kqOvertimeRulesDetailEntity + * @param paidLeaveEnable + * @return + */ + public boolean getNeedSplitByTime(KQOvertimeRulesDetailEntity kqOvertimeRulesDetailEntity, + int paidLeaveEnable) { + //因为【按加班时长范围设置转调休时长问题】这个方式存在问题,暂不使用 + if(true){ + return false; + } + boolean needSplitByTime = false; + if(paidLeaveEnable == 1){ + int paidLeaveEnableType = kqOvertimeRulesDetailEntity.getPaidLeaveEnableType(); + //如果开启了转调休,并且调休是分段折算的,可以按照分段来显示加班 + if(1 == paidLeaveEnableType){ + int paidLeaveEnableDefaultType = kqOvertimeRulesDetailEntity.getPaidLeaveEnableDefaultType(); + if(paidLeaveEnableDefaultType == 3){ + needSplitByTime = true; + } + }else if(2 == paidLeaveEnableType){ + int paidLeaveEnableFlowType = kqOvertimeRulesDetailEntity.getPaidLeaveEnableFlowType(); + if(paidLeaveEnableFlowType == 3){ + needSplitByTime = true; + } + } + } + return needSplitByTime; + } + + /** + * 判断是否开启了调休 + * @param kqOvertimeRulesDetailEntity + * @param overtime_type + * @return + */ + public int getPaidLeaveEnable(KQOvertimeRulesDetailEntity kqOvertimeRulesDetailEntity, + String overtime_type) { + int paidLeaveEnable = -1; + if (kqOvertimeRulesDetailEntity != null){ + paidLeaveEnable = kqOvertimeRulesDetailEntity.getPaidLeaveEnable(); + paidLeaveEnable = paidLeaveEnable == 1?1:0; + } + int paidLeaveEnableType = kqOvertimeRulesDetailEntity.getPaidLeaveEnableType(); + if(2 == paidLeaveEnableType){ +// logOvertimeMap(overtimeLogMap, overtime_type, flow_cross_key+"|关联调休与否来自于流程选择,加班类型下拉框值|overtime_type"); + if("0".equalsIgnoreCase(overtime_type)){ + paidLeaveEnable = 1; + }else if("1".equalsIgnoreCase(overtime_type)){ + paidLeaveEnable = 0; + }else{ + paidLeaveEnable = 0; + } + } + return paidLeaveEnable; + } + + + /** + * 清掉之前的加班和调休,重新生成 + * @param resourceid + * @param belongdate + * @param overtimeLogMap + * @param splitDate + */ + public void clearOvertimeTX(String resourceid, String belongdate, + Map overtimeLogMap, String splitDate) { + List all_tiaoxiuidList = Lists.newArrayList(); + String all_tiaoxiuids = ""; + RecordSet rs = new RecordSet(); + String sql = "select * from kq_flow_overtime where resourceid = ? and belongdate=? and ori_belongdate=? "; + rs.executeQuery(sql,resourceid, belongdate,splitDate); + while (rs.next()){ + String tiaoxiuid = Util.null2String(rs.getString("tiaoxiuid"),""); + if(tiaoxiuid.length() > 0 && Util.getIntValue(tiaoxiuid) > 0){ + all_tiaoxiuids += ","+tiaoxiuid; + all_tiaoxiuidList.add(tiaoxiuid); + } + } + logOvertimeMap(overtimeLogMap, all_tiaoxiuids, "需要重新生成的调休|all_tiaoxiuids"); + if(all_tiaoxiuids.length() > 0){ + all_tiaoxiuids = all_tiaoxiuids.substring(1); + + Map tiaoxiuamountMap = Maps.newLinkedHashMap(); + String selSql = "select * from kq_balanceofleave where "+Util.getSubINClause(all_tiaoxiuids, "id", "in"); + rs.executeQuery(selSql); + while (rs.next()){ + String id = rs.getString("id"); + String tiaoxiuamount = rs.getString("tiaoxiuamount"); + tiaoxiuamountMap.put(id, tiaoxiuamount); + } + if(!tiaoxiuamountMap.isEmpty()){ + logOvertimeMap(overtimeLogMap, tiaoxiuamountMap, "先记录下之前的加班生成的调休数据|tiaoxiuamountMap"); + } + String tiaoxiuidis0 = ""; + String delSql0 = "select * from kq_balanceofleave where "+Util.getSubINClause(all_tiaoxiuids, "id", "in")+" and " + + " baseamount =0 and extraamount=0 and usedamount=0 and baseamount2=0 and extraamount2=0 and usedamount2=0 "; + if(rs.getDBType().equalsIgnoreCase("oracle")) { + delSql0 = "select * from kq_balanceofleave where "+Util.getSubINClause(all_tiaoxiuids, "id", "in")+" and " + + " nvl(baseamount,0) =0 and nvl(extraamount,0)=0 and nvl(usedamount,0)=0 and nvl(baseamount2,0)=0 " + + " and nvl(extraamount2,0)=0 and nvl(usedamount2,0)=0 "; + }else if((rs.getDBType()).equalsIgnoreCase("mysql")){ + delSql0 = "select * from kq_balanceofleave where "+Util.getSubINClause(all_tiaoxiuids, "id", "in")+" and " + + " ifnull(baseamount,0) =0 and ifnull(extraamount,0)=0 and ifnull(usedamount,0)=0 and ifnull(baseamount2,0)=0 " + + " and ifnull(extraamount2,0)=0 and ifnull(usedamount2,0)=0 "; + }else { + delSql0 = "select * from kq_balanceofleave where "+Util.getSubINClause(all_tiaoxiuids, "id", "in")+" and " + + " isnull(baseamount,0) =0 and isnull(extraamount,0)=0 and isnull(usedamount,0)=0 and isnull(baseamount2,0)=0 " + + " and isnull(extraamount2,0)=0 and isnull(usedamount2,0)=0 "; + } + rs.executeQuery(delSql0); + while (rs.next()){ + String tiaoxiuid = Util.null2String(rs.getString("id"),""); + if(tiaoxiuid.length() > 0 && Util.getIntValue(tiaoxiuid) > 0){ + tiaoxiuidis0 += ","+tiaoxiuid; + all_tiaoxiuidList.remove(tiaoxiuid); + } + } + String delSql = ""; + if(tiaoxiuidis0.length() > 0){ + delSql = "delete from kq_balanceofleave where "+Util.getSubINClause(tiaoxiuidis0, "id", "in"); + boolean flag= rs.executeUpdate(delSql); + if (!flag) { + kqLog.info("加班流程删除之前的调休数据失败:数据库更新失败" ); + } + } + String clearSql = ""; + boolean isclearOk = false; + if(!all_tiaoxiuidList.isEmpty()){ + String clear_tiaoxiuids = all_tiaoxiuidList.stream().collect(Collectors.joining(",")); + clearSql = "update kq_balanceofleave set tiaoxiuamount=0.0 where "+Util.getSubINClause(clear_tiaoxiuids, "id", "in"); + isclearOk = rs.executeUpdate(clearSql); + } + + String delUsageSql = "delete from kq_usagehistory where "+Util.getSubINClause(all_tiaoxiuids, "balanceofleaveid", "in"); + boolean isdelUsageOk = rs.executeUpdate(delUsageSql); + Map logSqlMap = Maps.newLinkedHashMap(); + logSqlMap.put("tiaoxiuidis0",tiaoxiuidis0); + logSqlMap.put("all_tiaoxiuidList",all_tiaoxiuidList); + logSqlMap.put("delSql",delSql); + logSqlMap.put("clearSql",clearSql); + logSqlMap.put("isclearOk",isclearOk); + logSqlMap.put("delUsageSql",delUsageSql); + logSqlMap.put("isdelUsageOk",isdelUsageOk); + logOvertimeMap(overtimeLogMap, logSqlMap, "需要重新生成的调休对应的信息|logSqlMap"); + } + String delSql = "delete from kq_flow_overtime where resourceid = ? and belongdate=? and ori_belongdate=? "; + boolean isDelOk = rs.executeUpdate(delSql,resourceid, belongdate,splitDate); + String delSqlLog = delSql+":resourceid:"+resourceid+":belongdate:"+belongdate+":splitDate:"+splitDate+":isDelOk:"+isDelOk; + logOvertimeMap(overtimeLogMap, delSqlLog, "删除加班中间表数据|delSql"); + + } + /** + * 加班单位 + * @param d_mins + * @return + */ + public double getD_MinsByUnit(double d_mins) { + Map map = KQOvertimeRulesBiz.getMinimumUnitAndConversion(); + if(!map.isEmpty()){ + double conversionMins = 0.0; + int minimumUnit = Util.getIntValue(Util.null2String(map.get("minimumUnit")),-1); + int overtimeConversion = Util.getIntValue(Util.null2String(map.get("overtimeConversion")),-1); + if(5 == minimumUnit || 6 == minimumUnit){ + int halfHourInt = 30; + int wholeHourInt = 60; + if(5 == minimumUnit){ + conversionMins = getConversionMins(halfHourInt,d_mins,overtimeConversion); + }else { + conversionMins = getConversionMins(wholeHourInt,d_mins,overtimeConversion); + } + return conversionMins; + } + } + return d_mins; + } + + /** + * 根据转换规则得到转换后的加班时长 + * @param halfHourInt + * @param d_mins + * @param overtimeConversion + * @return + */ + public double getConversionMins(int halfHourInt, double d_mins, int overtimeConversion) { + double conversionMins = 0.0; + int step = (int) (d_mins/halfHourInt); + double leftMins = d_mins - halfHourInt*step; + //半小时 + if(1 == overtimeConversion){ +// 四舍五入 + if(leftMins >= halfHourInt/2){ + conversionMins = halfHourInt*step+halfHourInt; + }else{ + conversionMins = halfHourInt*step; + } + }else if(2 == overtimeConversion){ +// 向上取整 + if(leftMins > 0){ + conversionMins = halfHourInt*step+halfHourInt; + }else{ + conversionMins = halfHourInt*step; + } + }else if(3 == overtimeConversion){ +// 向下取整 + if(leftMins < halfHourInt){ + conversionMins = halfHourInt*step; + }else{ + conversionMins = halfHourInt*step; + } + } + return conversionMins; + } +} diff --git a/src/com/engine/kq/biz/KQOvertimeLogBiz.java b/src/com/engine/kq/biz/KQOvertimeLogBiz.java new file mode 100644 index 0000000..aa5ad1c --- /dev/null +++ b/src/com/engine/kq/biz/KQOvertimeLogBiz.java @@ -0,0 +1,261 @@ +package com.engine.kq.biz; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; +import java.io.Writer; +import java.util.Map; +import java.util.UUID; +import com.engine.kq.log.KQLog; +import weaver.conn.ConnStatement; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.common.DbFunctionUtil; + +/** + * 加班记录考勤事件日志 + * 现在先做一个加班的,把加班生成的时候流转,对应流程,班次,考勤组信息,加班规则信息 + */ +public class KQOvertimeLogBiz { + private KQLog kqLog = new KQLog(); + + /** + * 明细表里记录一下班次和考勤组信息 + * @param resourceid + * @param workTimeEntityLogMap + * @param main_uuid + * @param worktimeType + * @return + */ + public String logDetailWorkTimeEntity(String resourceid, Map workTimeEntityLogMap, + String main_uuid,String worktimeType) { + RecordSet rs = new RecordSet(); + + String serial_info = ""; + if(workTimeEntityLogMap != null){ + serial_info = JSON.toJSONString(workTimeEntityLogMap,SerializerFeature.DisableCheckSpecialChar,SerializerFeature.DisableCircularReferenceDetect); + } + String uuid = UUID.randomUUID().toString(); + kqLog.info("serial_info::::"+serial_info+":::uuid:::"+uuid); + if(true) { + return uuid; + } + boolean isok = false; + if(rs.getDBType().equalsIgnoreCase("oracle")&& Util.null2String(rs.getOrgindbtype()).equals("oracle")){ + String sql = "insert into kq_overtime_log_detail(resourceid,createdatetime,serial_info,overtime_info,event_info,uuid,overtimetype,main_uuid) " + + " values(?,"+ DbFunctionUtil.getCurrentFullTimeFunction(rs.getDBType())+",empty_clob(),empty_clob(),empty_clob(),?,?,?) "; + isok = rs.executeUpdate(sql,resourceid,uuid,worktimeType,main_uuid); + }else{ + String sql = "insert into kq_overtime_log_detail(resourceid,createdatetime,serial_info,uuid,overtimetype,main_uuid) " + + " values("+resourceid+","+DbFunctionUtil.getCurrentFullTimeFunction(rs.getDBType())+",'"+serial_info+"','"+uuid+"','"+worktimeType+"','"+main_uuid+"') "; + rs.executeUpdate(sql); + } + + if(rs.getDBType().equalsIgnoreCase("oracle")&& Util.null2String(rs.getOrgindbtype()).equals("oracle")){ + ConnStatement stat=null; + try { + stat = new ConnStatement(); + // 需要使用for update方法来进行更新, + // 但是,特别需要注意,如果原来CLOB字段有值,需要使用empty_clob()将其清空。 + // 如果原来是null,也不能更新,必须是empty_clob()返回的结果。 + stat.setStatementSql("select serial_info from kq_overtime_log_detail where uuid=? for update", false); + stat.setString(1,uuid); + stat.executeQuery(); + if (stat.next()) { + oracle.sql.CLOB clob = (oracle.sql.CLOB) stat.getClob("serial_info"); + Writer outStream = clob.getCharacterOutputStream(); + char[] c = serial_info.toCharArray(); + outStream.write(c, 0, c.length); + outStream.flush(); + outStream.close(); + } + + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (stat != null) { + stat.close(); + } + } + } + + return uuid; + } + + /** + * 在日志表里更新一下生成的加班id + * 这样可以根据加班id找到对应的日志 + * @param uuid + * @param overtimeid + * @return + */ + public void updateOvertimeId(String uuid,String overtimeid) { + if(true) { + return; + } + RecordSet rs = new RecordSet(); + String sql = "update kq_overtime_log_detail set overtimeid="+overtimeid+" where uuid='"+uuid+"' "; + boolean isOk = rs.executeUpdate(sql); + } + /** + * 记录一下加班生成明细 + * @param resourceid + * @param overtimeLogMap + * @param uuid + */ + public void logDetailOvertimeMap(String resourceid, Map overtimeLogMap,String uuid) { + RecordSet rs = new RecordSet(); + + String overtime_info = ""; + if(overtimeLogMap != null){ + overtime_info = JSON.toJSONString(overtimeLogMap, SerializerFeature.DisableCheckSpecialChar,SerializerFeature.DisableCircularReferenceDetect); + } + kqLog.info("overtime_info::::"+overtime_info+":::uuid:::"+uuid); + if(true) { + return; + } + if(rs.getDBType().equalsIgnoreCase("oracle")&& Util.null2String(rs.getOrgindbtype()).equals("oracle")){ + ConnStatement stat=null; + try { + stat = new ConnStatement(); + // 需要使用for update方法来进行更新, + // 但是,特别需要注意,如果原来CLOB字段有值,需要使用empty_clob()将其清空。 + // 如果原来是null,也不能更新,必须是empty_clob()返回的结果。 + stat.setStatementSql("select overtime_info from kq_overtime_log_detail where uuid=? for update", false); + stat.setString(1,uuid); + stat.executeQuery(); + if (stat.next()) { + oracle.sql.CLOB clob = (oracle.sql.CLOB) stat.getClob("overtime_info"); + Writer outStream = clob.getCharacterOutputStream(); + char[] c = overtime_info.toCharArray(); + outStream.write(c, 0, c.length); + outStream.flush(); + outStream.close(); + } + + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (stat != null) { + stat.close(); + } + } + }else{ + String sql = "update kq_overtime_log_detail set overtime_info='"+overtime_info+"' where uuid='"+uuid+"'"; + rs.executeUpdate(sql); + } + + } + + /** + * 记录一下流程开始日期结束日期的 + * @param resourceid + * @param eventLogMap + * @param overtimetype + * @return + */ + public String logEvent(String resourceid, Map eventLogMap, String overtimetype) { + RecordSet rs = new RecordSet(); + + String event_info = ""; + if(eventLogMap != null){ + event_info = JSON.toJSONString(eventLogMap,SerializerFeature.DisableCheckSpecialChar,SerializerFeature.DisableCircularReferenceDetect); + } + String uuid = UUID.randomUUID().toString(); + kqLog.info("event_info::::"+event_info+":::uuid:::"+uuid); + if(true) { + return uuid; + } + boolean isok = false; + if(rs.getDBType().equalsIgnoreCase("oracle")&& Util.null2String(rs.getOrgindbtype()).equals("oracle")){ + String sql = "insert into kq_overtime_log(resourceid,createdatetime,event_info,uuid,overtimetype) " + + " values("+resourceid+","+ DbFunctionUtil.getCurrentFullTimeFunction(rs.getDBType())+",empty_clob(),'"+uuid+"','"+overtimetype+"') "; + isok = rs.executeUpdate(sql); + }else{ + String sql = "insert into kq_overtime_log(resourceid,createdatetime,event_info,uuid,overtimetype) " + + " values("+resourceid+","+DbFunctionUtil.getCurrentFullTimeFunction(rs.getDBType())+",'"+event_info+"','"+uuid+"','"+overtimetype+"') "; + rs.executeUpdate(sql); + } + if(isok && rs.getDBType().equalsIgnoreCase("oracle")&& Util.null2String(rs.getOrgindbtype()).equals("oracle")){ + ConnStatement stat=null; + try { + stat = new ConnStatement(); + // 需要使用for update方法来进行更新, + // 但是,特别需要注意,如果原来CLOB字段有值,需要使用empty_clob()将其清空。 + // 如果原来是null,也不能更新,必须是empty_clob()返回的结果。 + stat.setStatementSql("select event_info from kq_overtime_log where uuid=? for update", false); + stat.setString(1,uuid); + stat.executeQuery(); + if (stat.next()) { + oracle.sql.CLOB clob = (oracle.sql.CLOB) stat.getClob("event_info"); + Writer outStream = clob.getCharacterOutputStream(); + char[] c = event_info.toCharArray(); + outStream.write(c, 0, c.length); + outStream.flush(); + outStream.close(); + } + + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (stat != null) { + stat.close(); + } + } + } + return uuid; + } + + /** + * 记录对应的加班生成过程中使用的表sql和表数据 + * @param resourceid + * @param eventLogMap + * @param uuid + * @param overtimetype + */ + public void logDetailEvent(String resourceid, Map eventLogMap, String uuid, String overtimetype) { + RecordSet rs = new RecordSet(); + + String event_info = ""; + if(eventLogMap != null){ + event_info = JSON.toJSONString(eventLogMap,SerializerFeature.DisableCheckSpecialChar,SerializerFeature.DisableCircularReferenceDetect); + } + kqLog.info("event_info::::"+event_info+":::uuid:::"+uuid); + if(true) { + return; + } + + if(rs.getDBType().equalsIgnoreCase("oracle")&&rs.getOrgindbtype().equalsIgnoreCase("oracle")){ + ConnStatement stat=null; + try { + stat = new ConnStatement(); + // 需要使用for update方法来进行更新, + // 但是,特别需要注意,如果原来CLOB字段有值,需要使用empty_clob()将其清空。 + // 如果原来是null,也不能更新,必须是empty_clob()返回的结果。 + stat.setStatementSql("select event_info from kq_overtime_log_detail where uuid=? for update", false); + stat.setString(1,uuid); + stat.executeQuery(); + if (stat.next()) { + oracle.sql.CLOB clob = (oracle.sql.CLOB) stat.getClob("event_info"); + Writer outStream = clob.getCharacterOutputStream(); + char[] c = event_info.toCharArray(); + outStream.write(c, 0, c.length); + outStream.flush(); + outStream.close(); + } + + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (stat != null) { + stat.close(); + } + } + }else{ + String regexp = "\'"; + event_info =event_info.replaceAll(regexp, "\""); + String sql = "update kq_overtime_log_detail set event_info='"+event_info+"' where uuid='"+uuid+"'"; + rs.executeUpdate(sql); + } + + } +} \ No newline at end of file diff --git a/src/com/engine/kq/biz/KQReportBiz.java b/src/com/engine/kq/biz/KQReportBiz.java new file mode 100644 index 0000000..dd5e7b8 --- /dev/null +++ b/src/com/engine/kq/biz/KQReportBiz.java @@ -0,0 +1,2325 @@ +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.enums.KqSplitFlowTypeEnum; +import com.engine.kq.log.KQLog; +import com.engine.kq.util.KQDurationCalculatorUtil; +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.TimeUtil; +import weaver.general.Util; +import weaver.hrm.User; +import weaver.systeminfo.SystemEnv; + +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +public class KQReportBiz extends BaseBean { + + private static DecimalFormat df = new DecimalFormat("0.00"); + 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); + } + } + + /*** + * 获取考勤状态 + * @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 "+ + " 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 "; + + rs.executeQuery(sql,resourceId,fromdate, todate); + while(rs.next()){ + 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){ + 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 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; + } + + 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(getOvertimeCount(params,user)); + //二开:计算夜班次数 + datas.putAll(getOvertimeNightCount(params,user)); + //二开:计算午餐次数 + datas.putAll(getLunchCount(params,user)); + }catch (Exception e){ + writeLog(e); + } + return datas; + } + + /** + * 统计每个人的加班次数 + * @param params + * @param user + * @return + */ + public Map getOvertimeCount(Map params, User user){ + Map datas = new HashMap<>();; + RecordSet rs = new RecordSet(); + String sql = ""; + String sqlWhere = " "; + try{ + 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<>'' "); + } +// 暂时无法用打卡数据进行计算(先注释掉) +// sql = "select resourceid,requestid,minSignTime,maxSignTime,fromdatedb,fromtimedb,time_to_sec(timediff(IFNULL(maxSignTime,0),IFNULL(fromtimedb,0))) duration from (\n" + +// "select resourceid,requestid,b.fromdatedb,b.fromtimedb \n" + +// "from hrmresource a, kq_flow_overtime b\n" + +// "where a.id = b.resourceid and fromdatedb >='"+fromDate+"' and fromdatedb <='"+toDate+"' "+sqlWhere+ +// "group by resourceid,requestid) m\n" + +// "INNER JOIN\n" + +// "(SELECT userid,signdate,max(SIGNTIME) maxSignTime,min(SIGNTIME) minSignTime FROM HrmScheduleSign \n" + +// "group by userid,signdate) n on m.resourceid=n.userid and m.fromdatedb=n.signdate"; + sql = "select b.resourceid,b.requestid,b.fromdatedb,b.fromtimedb,b.todatedb,b.totimedb,c.duration\n" + + "from hrmresource a, kq_flow_overtime b,hs_view_jiaban c\n" + + "where a.id = b.resourceid and b.requestid=c.requestid and fromdatedb >='"+fromDate+"' and fromdatedb <='"+toDate+"' "+sqlWhere+ + "group by resourceid,requestid"; + rs.execute(sql); + kqLog.info("getOvertimeCount:sql:"+sql); + + KQGroupMemberComInfo kqGroupMemberComInfo = new KQGroupMemberComInfo(); + String shiftsSql = " select a.id resourceid,c.id groupid,d.weekday,e.id serialId,e.serial from hrmresource a \n" + + " inner join kq_groupmember b on a.id=b.typevalue\n" + + " inner join kq_group c on b.groupid=c.id\n" + + " inner join kq_fixedschedulce d on c.id=d.groupid \n" + + " inner join kq_ShiftManagement e on d.serialid=e.id where a.id=? and c.id=?"; + RecordSet recordSet = new RecordSet(); + while (rs.next()) { + int count = 0; + String resourceid = rs.getString("resourceid"); + String fromdatedb = rs.getString("fromdatedb"); + String currentGroupId = Util.null2String(kqGroupMemberComInfo.getKQGroupId(resourceid, DateUtil.getCurrentDate()));// 生效考勤组 + recordSet.executeQuery(shiftsSql,resourceid,currentGroupId); + if (recordSet.next()) { + String serialId = Util.null2String(recordSet.getString("serialId")); + if (serialId.equals("2")) {//白班:2 + double value = rs.getDouble("duration")<0?0:rs.getDouble("duration"); + value = Util.getDoubleValue(KQDurationCalculatorUtil.getDurationRound(value+"")); + if (value >= 0.5) {//流程中时长>0.5 + count ++; + } + } + } + String flowType = "jiabancishu"; + String key = resourceid+"|"+flowType; + datas.put(key,String.valueOf(getMapValue(key,datas)+count)); + } + }catch (Exception e){ + writeLog(e); + } + return datas; + } + + private int getMapValue(String key,Map map){ + int count = 0; + if (map.containsKey(key)) { + String countS = (String) map.get(key); + count = Integer.parseInt(countS); + } + return count; + } + + /** + * 统计每个人的夜班次数 + * @param params + * @param user + * @return + */ + public Map getOvertimeNightCount(Map params, User user){ + Map datas = new HashMap<>();; + RecordSet rs = new RecordSet(); + RecordSet recordSet = new RecordSet(); + String sql = ""; + String sqlWhere = " "; + try{ + 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<>'' "); + } + //查询班次(白班:2,夜班:3,特殊夜班:4) + KQGroupMemberComInfo kqGroupMemberComInfo = new KQGroupMemberComInfo(); + + String shiftsSql = " select a.id resourceid,c.id groupid,d.weekday,e.id serialId,e.serial from hrmresource a \n" + + " inner join kq_groupmember b on a.id=b.typevalue\n" + + " inner join kq_group c on b.groupid=c.id\n" + + " inner join kq_fixedschedulce d on c.id=d.groupid \n" + + " inner join kq_ShiftManagement e on d.serialid=e.id where a.id=? and c.id=?";// and d.weekday=DAYOFWEEK(?)-1 + + sql = "select resourceid,requestid,b.fromdatedb,b.fromtimedb,b.todatedb,b.totimedb \n" + + "from hrmresource a, kq_flow_overtime b\n" + + "where a.id = b.resourceid and fromdatedb >='"+fromDate+"' and fromdatedb <='"+toDate+"' "+sqlWhere+ + "group by resourceid,requestid"; + rs.execute(sql); + kqLog.info("getOvertimeNightCount:sql:"+sql); + while (rs.next()) { + int count = 0; + String resourceid = rs.getString("resourceid"); + String fromdatedb = rs.getString("fromdatedb"); + String todatedb = rs.getString("todatedb"); + String totimedb = rs.getString("totimedb"); + int dateFlag = todatedb.compareTo(fromdatedb); + String currentGroupId = Util.null2String(kqGroupMemberComInfo.getKQGroupId(resourceid, DateUtil.getCurrentDate())); + recordSet.executeQuery(shiftsSql,resourceid,currentGroupId); + if(recordSet.next()) { + String serialId = Util.null2String(recordSet.getString("serialId")); + if (serialId.equals("3") || serialId.equals("4")) { + count++; + } else if (serialId.equals("2")) { + if (dateFlag > 0) { + count++; + } + } + } + String flowType = "yebancishu"; + String key = resourceid+"|"+flowType; + datas.put(key,String.valueOf(getMapValue(key,datas)+count)); + } + }catch (Exception e){ + writeLog(e); + } + return datas; + } + + /** + * 统计每个人的午餐次数(当天考勤时间满4H,记录一次午餐) + * @param params + * @param user + * @return + */ + public Map getLunchCount(Map params, User user){ + Map datas = new HashMap<>();; + RecordSet rs = new RecordSet(); + RecordSet recordSet = new RecordSet(); + String sql = ""; + String sqlWhere = " "; + try{ + 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<>'' "); + } + + sql = "select userid,count(1) as lunchCounts from (select b.userid,b.signdate,max(b.SIGNTIME) maxSignTime,min(b.SIGNTIME) minSignTime,\n" + + "time_to_sec(timediff(max(b.SIGNTIME),min(b.SIGNTIME)))/3600 duration\n" + + "from hrmresource a,HrmScheduleSign b where a.ID = b.USERID and b.signdate >='"+fromDate+"' and b.signdate <='"+toDate+"' "+sqlWhere+ + "group by b.userid,b.signdate having min( b.SIGNTIME ) < '12:00:00') c where c.duration >= 4 group by c.userid "; + rs.execute(sql); + kqLog.info("getLunchCount:sql:"+sql); + while (rs.next()) { + String resourceid = rs.getString("userid"); + String lunchCounts = rs.getString("lunchCounts"); + String flowType = "wucancishu"; + String key = resourceid+"|"+flowType; + datas.put(key,lunchCounts); + } + }catch (Exception e){ + writeLog(e); + } + return datas; + } + + /** + * 为每日统计报表做流程数据查询 + * @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)); + }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, df.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, df.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 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,df.format(value)); + } + }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,df.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, df.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,df.format(value)); + } + }catch (Exception e){ + writeLog(e); + } + return datas; + } + + /** + * 获取每日销假数据 + * @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,df.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,df.format(tmpVal)); + }else{ + datas.put(key,df.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,df.format(tmpVal)); + }else{ + datas.put(key,df.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,df.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, df.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){ + KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo(); + Map datas = new HashMap<>(); + Map data = null; + Map tmpdatas = new HashMap<>(); + Map tmpdata = null; + Map tmpmap = null; + RecordSet rs = new RecordSet(); + String sql = ""; + try { + sql = " select resourceid, kqdate, workMins, 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"); + 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")); + } + + if (workMins<=0) { + if(text.length()>0) text +=" "; + text += SystemEnv.getHtmlLabelName(26593, user.getLanguage()); + } else { + if (absenteeismMins > 0) {//旷工 + if(text.length()>0) text+=" "; + text += SystemEnv.getHtmlLabelName(20085, user.getLanguage()); + }else { + if (beLateMins > 0) {//迟到 + if (text.length() > 0) text += " "; + text += SystemEnv.getHtmlLabelName(20081, user.getLanguage()); + } + if (graveBeLateMins > 0) {//严重迟到 + if (text.length() > 0) text += " "; + text += SystemEnv.getHtmlLabelName(500546, user.getLanguage()); + } + if (leaveEarlyMins > 0) {//早退 + if (text.length() > 0) text += " "; + text += SystemEnv.getHtmlLabelName(20082, user.getLanguage()); + } + if (graveLeaveEarlyMins > 0) {//严重早退 + if (text.length() > 0) text += " "; + text += SystemEnv.getHtmlLabelName(500547, user.getLanguage()); + } + if (forgotCheckMins > 0) {//漏签 + if (text.length() > 0) text += " "; + text += SystemEnv.getHtmlLabelName(20086, user.getLanguage()); + } + if (forgotBeginWorkCheckMins > 0) {//漏签 + if (text.length() > 0) text += " "; + 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.length()==0) { + text = "√"; + }else{ + flag = "false";//有其他的异常状态,则表示为false,不需要处理直接全部显示即可 + } + + 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)){//需要加工的数据 + data1 = new HashMap<>(); + data1.put("text", "√"); + datas.put(mapKey, data1); + } + } +// writeLog("datas="+JSONObject.toJSONString(datas)); + } + }catch (Exception e){ + writeLog(e); + } + return datas; + } + + + /** + *日报表数据 + * @param resourceId + * @param fromDate + * @param toDate + * @return + */ + public Map getDetialDatasOnlyTime(String resourceId,String fromDate, String toDate, User user){ + Map datas = new HashMap<>(); + RecordSet rs = new RecordSet(); + String sql = " select resourceid, kqdate, workMins,attendanceMins, 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"); + String attendanceMins = Util.null2s(rs.getString("attendanceMins"),"0"); + attendanceMins = KQDurationCalculatorUtil.getDurationRound(("" + (Util.getDoubleValue(attendanceMins) / 60.0))); + datas.put(key,attendanceMins); + } + return datas; + } + + + /** + * 查询加班明细数据 + * @param resourceId + * @param fromDate + * @param toDate + * @return + */ + public Map getDetialOvtimeData(String resourceId,String fromDate, String toDate){ + Map datas = new HashMap<>(); + KQOvertimeRulesBiz kqOvertimeRulesBiz = new KQOvertimeRulesBiz(); + int uintType = kqOvertimeRulesBiz.getMinimumUnit();//当前加班单位 + double hoursToDay = kqOvertimeRulesBiz.getHoursToDay();//当前天跟小时计算关系 + RecordSet rs = new RecordSet(); + String sql = " select resourceid, belongdate,sum(cast(duration_min as decimal(18,4))) as val " + + " from hrmresource a, kq_flow_overtime b " + + " where resourceid=? and a.id = b.resourceid and belongdate >=? and belongdate <=? " + + " group by resourceid, belongdate "; + rs.executeQuery(sql,resourceId, fromDate,toDate); + while (rs.next()) { + 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 key = rs.getString("resourceid") + "|" + rs.getString("belongdate"); + datas.put(key,value); + } + return datas; + } + + + + +// 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 getSignStatus(Map signInfo, User user,String onOrOff){ + KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo(); + String text = ""; + String workdate = Util.null2String(signInfo.get("workdate")); + String worktime = Util.null2String(signInfo.get("worktime")); + if(!new KQFormatBiz().needCal(workdate,worktime)) {//还未到时间无需计算 + 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); + 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 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"))); + + if (worktime.length() > 0) { + 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();; + }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删除中间表里的数据,再做啥插入操作 + String delSql = "delete from "+tablename+" where requestid = "+requestid; + rs1.executeUpdate(delSql); + if(kqtype == KqSplitFlowTypeEnum.OVERTIME.getFlowtype()) { + delSql = "delete from kq_flow_overtime where requestid = "+requestid; + rs1.executeUpdate(delSql); + } + + Map result = kqFlowActiontBiz.handleKQFlowAction(proc_set_id, usedetails, Util.getIntValue(requestid), kqtype, Util.getIntValue(workflowid), isForce1,isUpgrade1,map); + + if(!result.isEmpty()){ + + } + } + long end = System.currentTimeMillis(); + }catch (Exception e){ + e.printStackTrace();; + } + } +} diff --git a/src/com/engine/kq/biz/KQSettingsBiz.java b/src/com/engine/kq/biz/KQSettingsBiz.java new file mode 100644 index 0000000..44c1368 --- /dev/null +++ b/src/com/engine/kq/biz/KQSettingsBiz.java @@ -0,0 +1,220 @@ +package com.engine.kq.biz; + +import com.engine.kq.log.KQLog; +import weaver.conn.RecordSet; +import weaver.general.Util; + +/** + * 考勤自定义配置类 + */ +public class KQSettingsBiz { + + public static KQLog kqLog = new KQLog(); + + public static boolean showLeaveTypeSet(String main_key) { + RecordSet rs = new RecordSet(); + String main_val = "1"; + String sql = "select * from kq_settings where main_key=? "; + rs.executeQuery(sql, main_key); + if (rs.next()) { + main_val = Util.null2String(rs.getString("main_val")); + } + + return "1".equalsIgnoreCase(main_val); + } + + /** + * 考勤报表使用线程格式化 + * @return + */ + public static boolean getKqformatthread() { + RecordSet rs = new RecordSet(); + String main_val = "1"; + String sql = "select * from kq_settings where main_key='kqformatthread' "; + rs.executeQuery(sql); + if (rs.next()) { + main_val = Util.null2String(rs.getString("main_val")); + } + return "1".equalsIgnoreCase(main_val); + } + + /** + * 考勤报表按班次时间点触发计算 + * @return + */ + public static boolean getKqformatAccurate() { + RecordSet rs = new RecordSet(); + String main_val = "1"; + String sql = "select * from kq_settings where main_key='kqformataccurate' "; + rs.executeQuery(sql); + if (rs.next()) { + main_val = Util.null2String(rs.getString("main_val")); + } + return "1".equalsIgnoreCase(main_val); + } + + /** + * 销假流程带出的明细是否要清空默认值 + * @return + */ + public static boolean is_leaveback_clear() { + RecordSet rs = new RecordSet(); + String is_leaveback_clear = "0"; + String show_ajax_balance_sql = "select * from kq_settings where main_key='leaveback_clear'"; + rs.executeQuery(show_ajax_balance_sql); + if(rs.next()) { + String main_val = rs.getString("main_val"); + if ("1".equalsIgnoreCase(main_val)) { + is_leaveback_clear = "1"; + } + } + return "1".equalsIgnoreCase(is_leaveback_clear); + } + + /** + * 开启后,允许早到早走,允许晚到晚走,允许晚走晚到支持考勤流程抵扣;关闭,则不支持考勤流程抵扣;此开关默认关闭 + * @return + */ + public static boolean is_flow_humanized() { + RecordSet rs = new RecordSet(); + String is_flow_humanized = "0"; + String show_flow_humanized_sql = "select * from kq_settings where main_key='flow_humanized'"; + rs.executeQuery(show_flow_humanized_sql); + if(rs.next()) { + String main_val = rs.getString("main_val"); + if ("1".equalsIgnoreCase(main_val)) { + is_flow_humanized = "1"; + } + } + return "1".equalsIgnoreCase(is_flow_humanized); + } + + /** + * 开启了这个开关,晚到晚走,超过了设置的规则也可以按照晚到晚走设置来处理迟到 + * @return + */ + public static boolean is_lateinlateout_outrule() { + RecordSet rs = new RecordSet(); + String is_lateinlateout_outrule = "0"; + String show_lateinlateout_outrule_sql = "select * from kq_settings where main_key='lateinlateout_outrule'"; + rs.executeQuery(show_lateinlateout_outrule_sql); + if(rs.next()) { + String main_val = rs.getString("main_val"); + if ("1".equalsIgnoreCase(main_val)) { + is_lateinlateout_outrule = "1"; + } + } + return "1".equalsIgnoreCase(is_lateinlateout_outrule); + } + + /** + * 开启了这个开关,判断历年是否包含今年之后的假期。 + * @return + */ + public static boolean is_balanceofleave() { + RecordSet rs = new RecordSet(); + String is_balanceofleave = "0"; + String show_is_balanceofleave_sql = "select * from kq_settings where main_key='is_balanceofleave'"; + rs.executeQuery(show_is_balanceofleave_sql); + if(rs.next()) { + String main_val = rs.getString("main_val"); + if ("1".equalsIgnoreCase(main_val)) { + is_balanceofleave = "1"; + } + } + return "1".equalsIgnoreCase(is_balanceofleave); + } + + /** + * 开启了这个开关,判断晚走晚到是根据上一个工作日还是直接判断前一天,区别场景是:比如周五跨到下周一 + * @return + */ + public static boolean is_lateoutlatein() { + RecordSet rs = new RecordSet(); + String is_lateoutlatein = "1"; + String show_is_lateoutlatein_sql = "select main_val from kq_settings where main_key='is_lateoutlatein'"; + rs.executeQuery(show_is_lateoutlatein_sql); + if(rs.next()) { + String main_val = rs.getString("main_val"); + if ("1".equalsIgnoreCase(main_val)) { + is_lateoutlatein = "1"; + }else{ + is_lateoutlatein = "0"; + } + } + return "1".equalsIgnoreCase(is_lateoutlatein); + } + + /** + * 开启了这个开关,弹性工作制可以跨天 + * @return + */ + public static boolean is_freeAcross() { + RecordSet rs = new RecordSet(); + String is_balanceofleave = "0"; + String show_is_balanceofleave_sql = "select * from kq_settings where main_key='is_freeAcross'"; + rs.executeQuery(show_is_balanceofleave_sql); + if(rs.next()) { + String main_val = rs.getString("main_val"); + if ("1".equalsIgnoreCase(main_val)) { + is_balanceofleave = "1"; + } + } + return "1".equalsIgnoreCase(is_balanceofleave); + } + + /** + * 开启了这个开关,打卡按钮默认会显示获取地理位置 + * @return + */ + public static boolean isFirstLocation() { + RecordSet rs = new RecordSet(); + String is_balanceofleave = "0"; + String show_is_balanceofleave_sql = "select * from kq_settings where main_key='isFirstLocation'"; + rs.executeQuery(show_is_balanceofleave_sql); + if(rs.next()) { + String main_val = rs.getString("main_val"); + if ("1".equalsIgnoreCase(main_val)) { + is_balanceofleave = "1"; + } + } + return "1".equalsIgnoreCase(is_balanceofleave); + } + + /** + * 强制归档考勤流程处理,true的话强制归档流程写入报表且生成调休、扣减假期 + * false的话,不做考勤相关处理 + * @return + */ + public static boolean isforceflow_attend() { + RecordSet rs = new RecordSet(); + String isforceflow_attend = "1"; + String show_isforceflow_attend_sql = "select * from kq_settings where main_key='forceflow_attend'"; + rs.executeQuery(show_isforceflow_attend_sql); + if(rs.next()) { + String main_val = rs.getString("main_val"); + if ("0".equalsIgnoreCase(main_val)) { + isforceflow_attend = "0"; + } + } + return "1".equalsIgnoreCase(isforceflow_attend); + } + /** + * 是否按照本年、历年来显示假期余额,1表示是 + * @return + */ + public static boolean show_split_balance() { + boolean show_split_balance = true; + RecordSet rs = new RecordSet(); + String settingSql = "select * from KQ_SETTINGS where main_key='show_split_balance'"; + rs.executeQuery(settingSql); + if(rs.next()){ + String main_val = rs.getString("main_val"); + if(!"1".equalsIgnoreCase(main_val)){ + show_split_balance = false; + } + } + return show_split_balance; + } + +} \ No newline at end of file diff --git a/src/com/engine/kq/biz/KQShiftManagementComInfo.java b/src/com/engine/kq/biz/KQShiftManagementComInfo.java new file mode 100644 index 0000000..0f28c31 --- /dev/null +++ b/src/com/engine/kq/biz/KQShiftManagementComInfo.java @@ -0,0 +1,759 @@ +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 rest_shift; + + private KQLog kqLog = new KQLog(); + + @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 restShiftMap = 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 restShift = rs.getString("rest_shift"); + + getShiftInfoBean(serialid,isresttimeopen,worktime,punchsetting,shiftInfoBeanMap,halfcalrule,halfcalpoint,halfcalpoint2cross,restShift); + + 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); + restShiftMap.put(serialid,restShift); + } + + + if(shiftInfoBeanMap.size()>0){ + CacheItem cacheItem = createCacheItem(); + Iterator> iterator = shiftInfoBeanMap.entrySet().iterator(); + while (iterator.hasNext()) { + Map.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(rest_shift,restShiftMap.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 restShiftMap = 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 restShift = rs.getString("rest_shift"); + + getShiftInfoBean(serialid,isresttimeopen,worktime,punchsetting,shiftInfoBeanMap,halfcalrule,halfcalpoint,halfcalpoint2cross,restShift); + + 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); + restShiftMap.put(serialid,restShift); + } + + + if(shiftInfoBeanMap.size()>0){ + Iterator> iterator = shiftInfoBeanMap.entrySet().iterator(); + while (iterator.hasNext()) { + Map.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(rest_shift,restShiftMap.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 getRestShift() { + return (String) getRowValue(rest_shift); + } + + public String getRestShift(String key) { + return (String) getValue(rest_shift, key); + } + + private void getShiftInfoBean(String serialid, String isresttimeopen, String worktime, + String punchsettings, + ConcurrentHashMap serialMap, + String halfcalrule,String halfcalpoint,String halfcalpoint2cross, String restShift) 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("restShift", restShift.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){ + + 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)); + ShiftInfoBean shiftInfoBean = new ShiftInfoBean(); + shiftInfoBean.setPreSplitDate(preSplitDate); + shiftInfoBean.setSplitDate(workdate); + shiftInfoBean.setD_Mins(0.0); + shiftInfoBean.setPreSerialid(preSerialid); + shiftInfoBean.setSerialid(serialid); + 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()); + } + } + + /** + * 每次获取的话都需要获取昨天和今天的班次数据 + * @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); + } + + //把当前班次的填充好 + 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()); + } + } + + 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; + } + +} diff --git a/src/com/engine/kq/biz/KQShiftManagementRedis.java b/src/com/engine/kq/biz/KQShiftManagementRedis.java new file mode 100644 index 0000000..5f8916c --- /dev/null +++ b/src/com/engine/kq/biz/KQShiftManagementRedis.java @@ -0,0 +1,299 @@ +package com.engine.kq.biz; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.cloudstore.dev.api.util.Util_DataCache; +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.IOException; +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.Set; +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.cluster.CacheManager; +import weaver.cluster.CacheMessage; +import weaver.conn.RecordSet; +import weaver.email.MailReciveStatusUtils; +import weaver.email.domain.AccountStautsBean; +import weaver.general.BaseBean; +import weaver.general.StaticObj; +import weaver.general.Util; + +/** + * 班次管理缓存类 改成用redis的 + */ +public class KQShiftManagementRedis { + public static final String KQ_SHIFT_COMINFO_STATUS = "KQ_SHIFT_COMINFO_STATUS"; + + private static final BaseBean baseBean = new BaseBean(); + + /** + * 是否是E9 radis缓存方案。false:未启用radis。true:使用radis。 + */ + public static boolean isNewSession = false; + + /** + * 非集群,单节点服务器部署时,账号接收状态量获取方法。(线程安全的) + */ + public static ConcurrentHashMap KQ_SHIFT_COMINFO_STATUS_MAP = new ConcurrentHashMap(); + + // 初始化执行 + static { + useNewSessionMode(); + } + + /** + * 判断是否开启redis缓存。 + */ + public static void useNewSessionMode() { + String status = Util.null2String(baseBean.getPropValue("weaver_new_session", "status")).trim(); + isNewSession = "1".equals(status); + } + + private KQLog kqLog = new KQLog(); + + public void getShiftInfoBean(String serialid, String isresttimeopen, String worktime, + String punchsettings, + ConcurrentHashMap shiftInfoBeanMap, + String halfcalrule,String halfcalpoint,String halfcalpoint2cross) throws Exception { + getShiftInfoBean(serialid, isresttimeopen, worktime, punchsettings, shiftInfoBeanMap, halfcalrule, halfcalpoint, halfcalpoint2cross, "0"); + } + + public void getShiftInfoBean(String serialid, String isresttimeopen, String worktime, + String punchsettings, + ConcurrentHashMap shiftInfoBeanMap, + String halfcalrule,String halfcalpoint,String halfcalpoint2cross, String restShift) 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("restShift", restShift.equals("1") ? "1" : "0"); + + ShiftInfoCominfoBean shiftInfoCominfoBean = setShiftInfoBean(workTimeMap); + shiftInfoBeanMap.put(serialid, shiftInfoCominfoBean); + } + + } + + public 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; + } + + public ConcurrentHashMap getShiftInfoBeanMap() { + ConcurrentHashMap shiftInfoBeanMap = new ConcurrentHashMap<>(); + kqLog = new KQLog(); + try { + + RecordSet rs = new RecordSet(); + String getShiftInfo = "select * from kq_ShiftManagement where 1=1 order by id "; + rs.executeQuery(getShiftInfo); + while(rs.next()){ + String serialid = rs.getString("id"); + try { + String isresttimeopen = rs.getString("isresttimeopen"); + String worktime = rs.getString("worktime"); + String punchsetting = "1"; + String halfcalrule = rs.getString("halfcalrule"); + halfcalrule = Util.null2String(halfcalrule).length() == 0 ? "0" : halfcalrule; + String halfcalpoint = rs.getString("halfcalpoint"); + String halfcalpoint2cross = rs.getString("halfcalpoint2cross"); + String restShift = rs.getString("rest_shift"); + getShiftInfoBean(serialid,isresttimeopen,worktime,punchsetting,shiftInfoBeanMap,halfcalrule,halfcalpoint,halfcalpoint2cross,restShift); + } catch (Exception e) { + kqLog.info("班次缓存报错:getShiftInfoBeanMap:serialid:"+serialid); + StringWriter errorsWriter = new StringWriter(); + e.printStackTrace(new PrintWriter(errorsWriter)); + kqLog.info(errorsWriter.toString()); + } + } + + } catch (Exception e) { + kqLog.info("班次缓存报错:getShiftInfoBeanMap:"); + StringWriter errorsWriter = new StringWriter(); + e.printStackTrace(new PrintWriter(errorsWriter)); + kqLog.info(errorsWriter.toString()); + } + return shiftInfoBeanMap; + } + + + public ShiftInfoCominfoBean getShiftInfoBeanMapBySql(String serialid) { + ConcurrentHashMap shiftInfoBeanMap = new ConcurrentHashMap<>(); + kqLog = new KQLog(); + try { + RecordSet rs = new RecordSet(); + String getShiftInfo = "select * from kq_ShiftManagement where 1=1 and id=? order by id "; + rs.executeQuery(getShiftInfo,serialid); + if(rs.next()){ + String isresttimeopen = rs.getString("isresttimeopen"); + String worktime = rs.getString("worktime"); + String punchsetting = "1"; + String halfcalrule = rs.getString("halfcalrule"); + halfcalrule = Util.null2String(halfcalrule).length() == 0 ? "0" : halfcalrule; + String halfcalpoint = rs.getString("halfcalpoint"); + String halfcalpoint2cross = rs.getString("halfcalpoint2cross"); + String restShift = rs.getString("rest_shift"); + getShiftInfoBean(serialid,isresttimeopen,worktime,punchsetting,shiftInfoBeanMap,halfcalrule,halfcalpoint,halfcalpoint2cross,restShift); + } + if(shiftInfoBeanMap.containsKey(serialid)){ + return shiftInfoBeanMap.get(serialid); + } + + } catch (Exception e) { + kqLog.info("班次缓存报错:getShiftInfoBeanMapBySql:"); + StringWriter errorsWriter = new StringWriter(); + e.printStackTrace(new PrintWriter(errorsWriter)); + kqLog.info(errorsWriter.toString()); + } + return null; + } + + /** + * 三套缓存,redis staticobj 和当前本身自制的map + * 把缓存数据重置下 + */ + public void resetShiftValWithRedis(){ + boolean isCluster = StaticObj.getInstance().isCluster(); + Map shiftInfoBeanMap = getShiftInfoBeanMap(); + if(isCluster) { + if(isNewSession) { + try { + Util_DataCache.setObjValWithRedis(KQ_SHIFT_COMINFO_STATUS, shiftInfoBeanMap); + } catch (IOException e) { + baseBean.writeLog(e); + StaticObj staticObj = StaticObj.getInstance(); + staticObj.putObject(KQ_SHIFT_COMINFO_STATUS, shiftInfoBeanMap); + sendNotificationToCache(CacheManager.ACTION_UPDATE, KQ_SHIFT_COMINFO_STATUS); + } + }else{ + StaticObj staticObj = StaticObj.getInstance(); + staticObj.putObject(KQ_SHIFT_COMINFO_STATUS, shiftInfoBeanMap); + sendNotificationToCache(CacheManager.ACTION_UPDATE, KQ_SHIFT_COMINFO_STATUS); + } + } else { + KQ_SHIFT_COMINFO_STATUS_MAP.put(KQ_SHIFT_COMINFO_STATUS, shiftInfoBeanMap); + } + } + + public ShiftInfoCominfoBean getShiftInfoBean(String serialid){ + ShiftInfoCominfoBean shiftInfoCominfoBean = null; + Map shiftInfoBeanMap = getShiftBeanMapValWithRedis(); + if(shiftInfoBeanMap == null){ + resetShiftValWithRedis(); + shiftInfoBeanMap = getShiftBeanMapValWithRedis(); + } + if(shiftInfoBeanMap != null && shiftInfoBeanMap.containsKey(serialid)){ + shiftInfoCominfoBean = shiftInfoBeanMap.get(serialid); + } + return shiftInfoCominfoBean; + } + + public Map getShiftBeanMapValWithRedis() { + Map shiftInfoBeanMap = null; + boolean isCluster = StaticObj.getInstance().isCluster(); + + if(isCluster) { // 判断是否是集群环境。true 是集群,false非集群 + if(isNewSession){ + try { + if(Util_DataCache.containsKeyWithRedis(KQ_SHIFT_COMINFO_STATUS)) { + shiftInfoBeanMap = (Map) Util_DataCache.getObjValWithRedis(KQ_SHIFT_COMINFO_STATUS); + } + }catch (Exception e){ + StaticObj staticObj = StaticObj.getInstance(); + shiftInfoBeanMap = (Map) staticObj.getObject(KQ_SHIFT_COMINFO_STATUS); + } + }else{ + StaticObj staticObj = StaticObj.getInstance(); + shiftInfoBeanMap = (Map) staticObj.getObject(KQ_SHIFT_COMINFO_STATUS); + } + } else { + shiftInfoBeanMap = (Map) KQ_SHIFT_COMINFO_STATUS_MAP.get(KQ_SHIFT_COMINFO_STATUS); + } + return shiftInfoBeanMap; + } + + /** + * 通知其他集群环境其他节点进行更新等操作. + * @param optType + * @param cacheKey + */ + public static void sendNotificationToCache(String optType, String cacheKey) { + StaticObj staticObj = StaticObj.getInstance(); + if(staticObj.isCluster()) { + CacheMessage msg = new CacheMessage(); + msg.setAction(optType); + msg.setCacheType(cacheKey); + staticObj.sendNotification(msg); + } + } +} diff --git a/src/com/engine/kq/biz/KQWorkTime.java b/src/com/engine/kq/biz/KQWorkTime.java new file mode 100644 index 0000000..cb7feb4 --- /dev/null +++ b/src/com/engine/kq/biz/KQWorkTime.java @@ -0,0 +1,426 @@ +package com.engine.kq.biz; + +import com.alibaba.fastjson.JSON; +import com.api.customization.qc2988837.Util.KqCustomUtil; +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 weaver.common.DateUtil; +import weaver.common.StringUtil; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.Util; +import weaver.hrm.resource.ResourceComInfo; + +import java.util.*; + +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{ + int serialid = Util.getIntValue(Util.null2String(serialInfo.get(workdate)), 0); + KQShiftManagementComInfo kQShiftManagementComInfo = new KQShiftManagementComInfo(); + int restShift = StringUtil.parseToInt(kQShiftManagementComInfo.getRestShift(String.valueOf(serialid)), 0); + isWorkDay = restShift == 1 ? false : serialid > 0; + } + } + } + return isWorkDay; + } + + public Map getWorkButton(String userId, String workdate, boolean containYesterday) { + Map result = new HashMap<>(); + try { + KQShiftManagementComInfo kQShiftManagementComInfo = new KQShiftManagementComInfo(); + Map serialInfo = getSerialInfo(userId, workdate, containYesterday, true); + 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(); + ShiftManagementToolKit shiftManagementToolKit = new ShiftManagementToolKit(); + Map serialInfo = getSerialInfo(userId, workdate, false, true); + 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")); + 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"))); + } + workTimeEntity.setRestShift(0); + }else{ + int serialid = Util.getIntValue(Util.null2String(serialInfo.get(workdate)), 0); + int restShift = StringUtil.parseToInt(kQShiftManagementComInfo.getRestShift(String.valueOf(serialid)), 0); + if(kqType.equals("1") && KQHolidaySetBiz.isHoliday(userId,workdate)) restShift = 1; + workTimeEntity.setRestShift(restShift); + if (serialid > 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.setRestTime(formatTimeScope((List)dateWorkTimeMap.get("restTime"),false)); + 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)); + if(restShift != 1) { + workTimeEntity.setWorkMins(Util.getIntValue(Util.null2String(dateWorkTimeMap.get("workMins")))); + } + workTimeEntity.setIsAcross(Util.null2String(dateWorkTimeMap.get("isAcross"))); + } + } + } + //如果在建模表维护的人员对应日期无需考勤 + KqCustomUtil kqCustomUtil = new KqCustomUtil(); + boolean isExculde = kqCustomUtil.isExclude(userId,workdate); + if (isExculde){ + workTimeEntity.setIsExclude(true); + } + } 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) { + return getSerialInfo(userId, workdate, containYesterday, false); + } + + public Map getSerialInfo(String userId, String workdate, boolean containYesterday, boolean includeHoliday) { + 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); + KQGroupEntity kqGroupEntity = groupMemberComInfo.getUserKQGroupInfo(userId,workdate); + ResourceComInfo resourceComInfo = new ResourceComInfo(); + + preworkdate = DateUtil.addDate(workdate,-1); + if(containYesterday){ + Map pre_serialInfo = getSerialInfo(userId, preworkdate, false, includeHoliday); + if(pre_serialInfo != null && !pre_serialInfo.isEmpty()){ + if(pre_serialInfo.containsKey(preworkdate)){ + serialInfo.put(preworkdate,pre_serialInfo.get(preworkdate));//获取前一天的班次 + } + } + } + + if(kqGroupEntity==null){//不在考勤组内 + 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)); + 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)); + 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); + 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); + serialInfo.put("isHoliday",isHoliday); + if(includeHoliday) isHoliday = false; + + 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( !isHoliday&&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)));//获取前一天的班次 +// } + serialid = Util.null2String(kqShiftScheduleComInfo.getSerialId(userId,workdate)); + if(serialid.length()>0 && !isHoliday && 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); + } + } + } + } catch (Exception e) { + writeLog(e); + } + return serialInfo; + } + + + public void setIsFormat(boolean isFormat){ + this.isFormat = isFormat; + } +} \ No newline at end of file diff --git a/src/com/engine/kq/biz/chain/cominfo/ShiftInfoCominfoBean.java b/src/com/engine/kq/biz/chain/cominfo/ShiftInfoCominfoBean.java new file mode 100644 index 0000000..e55f900 --- /dev/null +++ b/src/com/engine/kq/biz/chain/cominfo/ShiftInfoCominfoBean.java @@ -0,0 +1,519 @@ +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 restShift; + + 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"; + this.restShift = "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 getRestShift() { + return restShift; + } + + public void setRestShift(String restShift) { + this.restShift = restShift; + } +} + diff --git a/src/com/engine/kq/biz/chain/cominfo/WorkShiftComIndex.java b/src/com/engine/kq/biz/chain/cominfo/WorkShiftComIndex.java new file mode 100644 index 0000000..f00e88c --- /dev/null +++ b/src/com/engine/kq/biz/chain/cominfo/WorkShiftComIndex.java @@ -0,0 +1,37 @@ +package com.engine.kq.biz.chain.cominfo; + +import java.util.List; +import java.util.Map; + +import weaver.common.StringUtil; +import weaver.general.Util; + +/** + * 规则时段计算规则 + */ +public class WorkShiftComIndex extends ShiftComIndex { + + public WorkShiftComIndex(String name,Map workTimeMap){ + super(name,workTimeMap); + } + + @Override + public void handleDuration(ShiftInfoCominfoBean shiftInfoCominfoBean) throws Exception { + + handleWorkTime(shiftInfoCominfoBean); + this.success.handleDuration(shiftInfoCominfoBean); + } + + private void handleWorkTime(ShiftInfoCominfoBean shiftInfoCominfoBean) throws Exception { + List workTimes = (List)workTimeMap.get("workTime"); + int workmins = Util.getIntValue(Util.null2String(workTimeMap.get("workmins"))); + shiftInfoCominfoBean.setWorkmins(workmins); + String serialid = Util.null2String(workTimeMap.get("serialid")); + shiftInfoCominfoBean.setSerialid(serialid); + shiftInfoCominfoBean.setRestShift(StringUtil.vString(workTimeMap.get("restShift"), "0")); + + setWorkDuration(workTimes, shiftInfoCominfoBean); + + } + +} diff --git a/src/com/engine/kq/cmd/attendanceButton/PunchButtonCmd.java b/src/com/engine/kq/cmd/attendanceButton/PunchButtonCmd.java new file mode 100644 index 0000000..9609dc1 --- /dev/null +++ b/src/com/engine/kq/cmd/attendanceButton/PunchButtonCmd.java @@ -0,0 +1,618 @@ +package com.engine.kq.cmd.attendanceButton; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.cloudstore.dev.api.util.EMManager; +import com.engine.common.biz.AbstractCommonCommand; +import com.engine.common.entity.BizLogContext; +import com.engine.core.interceptor.CommandContext; +import com.engine.kq.biz.KQShiftManagementComInfo; +import com.engine.kq.biz.KQCardLogBiz; +import com.engine.kq.biz.KQFormatBiz; +import com.engine.kq.biz.KQGroupBiz; +import com.engine.kq.biz.KQGroupMemberComInfo; +import com.engine.kq.biz.KQLoactionComInfo; +import com.engine.kq.biz.KQShiftRuleInfoBiz; +import com.engine.kq.biz.KQTimesArrayComInfo; +import com.engine.kq.biz.KQWorkTime; +import com.engine.kq.biz.chain.shiftinfo.ShiftInfoBean; +import com.engine.kq.entity.KQGroupEntity; +import com.engine.kq.entity.WorkTimeEntity; +import com.engine.kq.log.KQLog; +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.Maps; +import java.time.Duration; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import javax.servlet.http.HttpServletRequest; +import weaver.common.DateUtil; +import weaver.common.StringUtil; +import weaver.conn.RecordSet; +import weaver.dateformat.DateTransformer; +import weaver.dateformat.TimeZoneVar; +import weaver.general.Util; +import weaver.hrm.User; +import weaver.systeminfo.SystemEnv; + +/** + * 考勤的 签到签退 + */ +public class PunchButtonCmd extends AbstractCommonCommand> { + public KQLog kqLog = new KQLog(); + private HttpServletRequest request; + private Map logMap = Maps.newHashMap(); + private Map workTimeEntityLogMap = Maps.newHashMap(); + + public PunchButtonCmd(HttpServletRequest request,Map params, User user) { + this.request = request; + this.user = user; + this.params = params; + } + + @Override + public Map execute(CommandContext commandContext) { + Map retmap = new HashMap(); + try{ + insertSign(retmap); + + }catch (Exception e) { + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(382661,user.getLanguage())); + writeLog(e); + } + kqLog.info(user.getLastname()+":PunchButtonCmd:retmap:"+retmap); + KQCardLogBiz.logCardInfo(user.getUID()+"", logMap, workTimeEntityLogMap, "punchButton"); + + return retmap; + } + + /** + * 检验ip是否在考勤组设置的范围要求内 + * @param ismobile + */ + private boolean checkIsInIp(String ismobile) { +// if("1".equalsIgnoreCase(ismobile)){ +// return true; +// } + KQGroupBiz kqGroupBiz = new KQGroupBiz(); + String clientAddress = Util.getIpAddr(request); + kqLog.info("PunchButtonCmd:clientAddress:"+clientAddress); + return kqGroupBiz.getIsInScopeV4V6(user.getUID()+"", clientAddress,ismobile); + } + + public void insertSign(Map retmap) throws Exception{ + logMap.put("lastname", user.getLastname()); + logMap.put("params", params); + kqLog.info(user.getLastname()+":PunchButtonCmd:params:"+params); + RecordSet rs = new RecordSet(); + String deviceInfo = Util.null2String(params.get("deviceInfo")); + JSONObject jsonObject = null; + if(deviceInfo.length() > 0){ + jsonObject = JSON.parseObject(deviceInfo); + JSONObject jsonObject1 = new JSONObject(); + Set> jsonSet = jsonObject.entrySet(); + for(Entry js : jsonSet){ + String key = js.getKey(); + String value = Util.null2String(js.getValue()); + jsonObject1.put(key, value); + } + if(!jsonObject1.isEmpty()){ + deviceInfo = jsonObject1.toJSONString(); + } + } + //应上班 工作时间点 + String time = Util.null2String(params.get("time")); + //应上班 工作时间 带日期 + String datetime = Util.null2String(params.get("datetime")); + //允许打卡时段 带日期 + String signSectionTime = Util.null2String(params.get("signSectionTime")); + //上传照片 + String attachment = Util.null2String(params.get("fileids")); + + //打卡所属worksection的对应的点 + String type = Util.null2String(params.get("type")); + //所属打卡日期 + String belongdate = Util.null2String(params.get("belongdate")); + belongdate = belongdate.length() == 0 ? DateUtil.getCurrentDate() : belongdate; + String islastsign = Util.null2String(params.get("islastsign")); + String isfirstsign = Util.null2String(params.get("isfirstsign")); + + String workmins = Util.null2String(params.get("workmins")); + //针对非工作时段 签退的时候记录的签到数据 用于计算加班 + String signInTime4Out = Util.null2String(params.get("signInTime4Out")); + //允许打卡的范围 + String signsection = Util.null2String(params.get("signSection")); + + //手机打卡部分 + String longitude = Util.null2String(params.get("longitude")); + String latitude = Util.null2String(params.get("latitude")); + double d_longitude = Util.getDoubleValue(longitude); + double d_latitude = Util.getDoubleValue(latitude); + if(d_latitude <= 0){ + latitude = ""; + } + if(d_longitude <= 0){ + longitude = ""; + } + //wifi用的 + String mac = Util.null2String(params.get("mac")); + String sid = Util.null2String(params.get("sid")); + String addr = Util.null2String(params.get("position")); + String ismobile = Util.null2String(params.get("ismobile")); + //区分是来自于钉钉还是EM7 + String browser = Util.null2String(params.get("browser")); + //自由班制处理 + String isfree = Util.null2String(Util.null2String(params.get("isfree")),"0"); + + //上班打卡 允许最晚打卡时间 + String signSectionEndTime = Util.null2String(params.get("signSectionEndTime")); + //下班打卡 允许最早打卡时间 + String signSectionBeginTime = Util.null2String(params.get("signSectionBeginTime")); + + String locationshowaddress = Util.null2String(params.get("locationshowaddress")); + if(locationshowaddress.equals("1")){//记录统一地址 + String locationid = Util.null2String(params.get("locationid"));//办公地点id + if(locationid.length()>0){//如果开启统一显示,就用配置的地址 + KQLoactionComInfo kqLoactionComInfo = new KQLoactionComInfo(); + addr = kqLoactionComInfo.getLocationname(locationid); + } + } + + DateTimeFormatter fullFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss"); + LocalTime localTime = LocalTime.now(); + String signTime =localTime.format(dateTimeFormatter); + String signDate = LocalDate.now().format(dateFormatter); + + String timeZone = Util.null2String(TimeZoneVar.getTimeZone(),""); + //处理多时区 + String timeZoneConversion = Util.null2String(new weaver.general.BaseBean().getPropValue("weaver_timezone_conversion","timeZoneConversion")).trim(); + logMap.put("timeZoneConversion", timeZoneConversion); + if("1".equals(timeZoneConversion)) { + DateTransformer dateTransformer=new DateTransformer(); + String[] zone_localTime = dateTransformer.getLocaleDateAndTime(signDate,signTime); + kqLog.info(user.getLastname()+":TimeZoneVar.getTimeZone():"+TimeZoneVar.getTimeZone()+":zone_localTime:"+JSON.toJSONString(zone_localTime)); + if(zone_localTime != null && zone_localTime.length == 2){ + signDate = zone_localTime[0]; + signTime = zone_localTime[1]; + } + } + + int userId = user.getUID(); + String userType = user.getLogintype(); + String signType = "on".equalsIgnoreCase(type) ? "1" : "2"; + String clientAddress = Util.getIpAddr(request); + boolean isInIp = checkIsInIp(ismobile); + logMap.put("clientAddress", clientAddress); + + if(!isInIp){ + retmap.put("message", SystemEnv.getHtmlLabelName(20157,user.getLanguage())); + retmap.put("isInIp", "0"); + } + String isInCom = isInIp ? "1" : "0"; + + //是否是考勤例外人员 + boolean isExclude = false; + + KQGroupMemberComInfo kqGroupMemberComInfo = new KQGroupMemberComInfo(); + KQWorkTime kqWorkTime = new KQWorkTime(); + WorkTimeEntity workTimeEntity = kqWorkTime.getWorkTime(user.getUID()+"", signDate); + String userinfo = "#userid#"+user.getUID()+"#getUserSubCompany1#"+user.getUserSubCompany1()+"#getUserSubCompany1#"+user.getUserDepartment() + +"#getJobtitle#"+user.getJobtitle(); + workTimeEntityLogMap.put("resourceid", userinfo); + workTimeEntityLogMap.put("splitDate", signDate); + workTimeEntityLogMap.put("workTimeEntity", workTimeEntity); + String groupid = workTimeEntity.getGroupId(); + logMap.put("groupid", groupid); + KQGroupEntity kqGroupEntity = kqGroupMemberComInfo.getUserKQGroupInfo(user.getUID()+""); + String kqGroupEntityInfo = kqGroupEntity != null ? JSON.toJSONString(kqGroupEntity): ""; + logMap.put("kqGroupEntityInfo", kqGroupEntityInfo); + if (kqGroupEntity != null && ("," + kqGroupEntity.getExcludeid() + ",").indexOf("," + user.getUID() + ",")>-1) {//排除人员无需计算考勤时间 + isExclude = true; + } + + String[] signsections = signsection.split("#"); + if(!"1".equalsIgnoreCase(isfree)){ + if(signsections != null && signsections.length == 2){ + //判断是未签到直接签退 + String signedMsg = signedMsg(userId+"", signType, user,signsections,signSectionBeginTime,signSectionEndTime); + if(signedMsg.length() > 0){ + retmap.put("status", "1"); + retmap.put("message", signedMsg); + isInCom = "0"; + } + } + } + + String datetime_timezone = signDate+" "+signTime; + LocalDateTime nowDateTime = LocalDateTime.parse(datetime_timezone,fullFormatter); + kqLog.info("timeZone:"+timeZone+":signDate:"+signDate+":signTime:"+signTime+":nowDateTime:"+nowDateTime); + + if("1".equalsIgnoreCase(signType) && signSectionTime.length() > 0 ){ + LocalDateTime startWorkDateTime = LocalDateTime.parse(signSectionTime,fullFormatter); + if(nowDateTime.isBefore(startWorkDateTime)){ + Duration duration = Duration.between(nowDateTime, startWorkDateTime); + retmap.put("status", "1"); + retmap.put("message", ""+weaver.systeminfo.SystemEnv.getHtmlLabelName(10005326,weaver.general.ThreadVarLanguage.getLang())+""+duration.toMinutes()+""+weaver.systeminfo.SystemEnv.getHtmlLabelName(15049,weaver.general.ThreadVarLanguage.getLang())+""); + isInCom = "0"; + } + + }else if("2".equalsIgnoreCase(signType) && signSectionTime.length() > 0 ){ + LocalDateTime endWorkDateTime = LocalDateTime.parse(signSectionTime,fullFormatter); + if(nowDateTime.isAfter(endWorkDateTime)){ + Duration duration = Duration.between(endWorkDateTime, nowDateTime); + retmap.put("status", "1"); + retmap.put("message", ""+weaver.systeminfo.SystemEnv.getHtmlLabelName(10005327,weaver.general.ThreadVarLanguage.getLang())+""+duration.toMinutes()+""+weaver.systeminfo.SystemEnv.getHtmlLabelName(15049,weaver.general.ThreadVarLanguage.getLang())+""); + isInCom = "0"; + } + } + + //记录下是来自于E9的pc端签到 + String signfrom = "e9pc"; + if("1".equalsIgnoreCase(ismobile)){ + signfrom = "e9mobile"; + boolean needLocationRange = false; + boolean needWifiRange = false; + boolean isLocationRange = false; + boolean isWifiRange = false; + KQGroupBiz kqGroupBiz = new KQGroupBiz(); + Map locationMap = kqGroupBiz.checkLocationScope(userId+"",longitude,latitude); + logMap.put("locationMap", locationMap); + String locationNeedCheck = Util.null2String(locationMap.get("needCheck")); + boolean locationInScope = Boolean.parseBoolean(Util.null2String(locationMap.get("inScope"))); + if("1".equalsIgnoreCase(locationNeedCheck)){ + needLocationRange = true; + if(locationInScope){ + isLocationRange = true; + } + } + String wifiNeedCheck = ""; + Map wifiMap = kqGroupBiz.checkWifiScope(userId+"", sid, mac); + logMap.put("wifiMap", wifiMap); + wifiNeedCheck = Util.null2String(wifiMap.get("needCheck")); + boolean wifiInScope = Boolean.parseBoolean(Util.null2String(wifiMap.get("inScope"))); + if("1".equalsIgnoreCase(wifiNeedCheck)){ + needWifiRange = true; + if(wifiInScope){ + isWifiRange = true; + } + } + if(needLocationRange){ + if(isLocationRange){ + }else{ + if(needWifiRange){ + if(isWifiRange){ + }else{ + //地理位置开启,而且不在范围内,且开启wifi验证,不在范围内 + retmap.put("message", SystemEnv.getHtmlLabelName(507524, user.getLanguage())); + isInCom = "0"; + } + }else { + //地理位置开启,而且不在范围内,且未开启wifi验证 + retmap.put("message", SystemEnv.getHtmlLabelName(500510, user.getLanguage())); + isInCom = "0"; + } + } + }else{ + if(needWifiRange) { + if (isWifiRange) { + } else { + //地理位置未开启,且开启wifi验证,不在范围内 + retmap.put("message", SystemEnv.getHtmlLabelName(507524, user.getLanguage())); + isInCom = "0"; + } + } + } + + if("DingTalk".equalsIgnoreCase(browser)){ + signfrom = "DingTalk"; + }else if("Wechat".equalsIgnoreCase(browser)){ + signfrom = "Wechat"; + String weChat_deviceid = Util.null2String(request.getSession().getAttribute(EMManager.DeviceId)); + logMap.put("weChat_deviceid", weChat_deviceid); + kqLog.info("EMManager.DeviceId:"+EMManager.DeviceId+":weChat_deviceid:"+weChat_deviceid); + if(weChat_deviceid.length() > 0){ + //微信打卡的设备号需要单独处理 + if(jsonObject != null){ + jsonObject.put("deviceId", weChat_deviceid); + }else{ + jsonObject = new JSONObject(); + jsonObject.put("deviceId", weChat_deviceid); + } + if(!jsonObject.isEmpty()){ + deviceInfo = jsonObject.toJSONString(); + } + } + } + } + String signStatus = ""; + + if(!"1".equalsIgnoreCase(isfree) && datetime.length() > 0){ + signStatus = getSignStatus(signType,datetime,user.getUID()+"",belongdate,nowDateTime); + logMap.put("signStatus", signStatus); + } + + if(isExclude){ + signStatus = ButtonStatusEnum.NORMAL.getStatusCode(); + } + + String punchSql = "insert into HrmScheduleSign(userId,userType,signType,signDate,signTime,clientAddress,isInCom,timeZone,belongdate,signfrom,longitude,latitude,addr,deviceInfo) "+ + " values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + boolean isOk = rs.executeUpdate(punchSql,userId,userType,signType,signDate,signTime,clientAddress,isInCom, + timeZone,belongdate,signfrom,longitude,latitude,addr,deviceInfo); + if(!isOk){ + retmap.put("status", "1"); + retmap.put("message", SystemEnv.getHtmlLabelName(382661,user.getLanguage())); + return ; + } + logMap.put("punchSql", punchSql); + logMap.put("punchSql_isOk", isOk); + kqLog.info(user.getLastname()+":PunchButtonCmd:punchSql:"+punchSql+":isOk:"+isOk); + + //打卡提醒处理 + String remindSql = "insert into hrmschedulesign_remind(userId,signType,signDate,signTime,belongdate) values(?,?,?,?,?)"; + isOk = rs.executeUpdate(remindSql, userId,signType,signDate,signTime,belongdate); + kqLog.info(user.getLastname()+":PunchButtonCmd:remindSql:"+remindSql+":isOk:"+isOk); + + //同步更新考勤数据到考勤报表 + new KQFormatBiz().formatDate(""+userId,(belongdate.length() == 0 ? DateUtil.getCurrentDate() : belongdate)); + //点击签退的时候,可能存在加班数据生成的情况 + if("2".equalsIgnoreCase(signType)){ + if("1".equalsIgnoreCase(islastsign)){ + List tasks = new ArrayList<>(); + List after_tasks = new ArrayList<>(); + SplitActionUtil.pushOverTimeTasks(belongdate, belongdate, ""+userId,tasks); + if(!tasks.isEmpty()){ + for(KQTaskBean kqTaskBean : tasks){ + after_tasks.add(kqTaskBean); + } + } + logMap.put("after_tasks", after_tasks); + if(!after_tasks.isEmpty()){ + KQQueue.writeTasks(after_tasks); + } + } + } + if("1".equalsIgnoreCase(signType)){ + if("1".equalsIgnoreCase(isfirstsign)){ + List tasks = new ArrayList<>(); + List before_tasks = new ArrayList<>(); + SplitActionUtil.pushOverTimeTasks(belongdate, belongdate, ""+userId,tasks); + if(!tasks.isEmpty()){ + for(KQTaskBean kqTaskBean : tasks){ + kqTaskBean.setTasktype("punchcard"); + before_tasks.add(kqTaskBean); + } + } + logMap.put("before_tasks", before_tasks); + if(!before_tasks.isEmpty()){ + KQQueue.writeTasks(before_tasks); + } + } + } + + String reSignStatus = reSignStatus(user.getUID()+"",signType,nowDateTime,belongdate); + if(Util.null2String(reSignStatus,"").length() > 0){ + signStatus = reSignStatus; + } + + retmap.put("status", "1"); + retmap.put("signdate", signDate); + retmap.put("signtime", signTime); + retmap.put("kqstatus", signStatus); + + if(!"1".equalsIgnoreCase(signStatus) && !"2".equalsIgnoreCase(signStatus)){ + if("".equalsIgnoreCase(Util.null2String(retmap.get("message")))){ + retmap.put("success", "1"); + retmap.put("message", SystemEnv.getHtmlLabelName(512596,weaver.general.Util.getIntValue(user.getLanguage()))); + } + } + logMap.put("retmap", retmap); + } + + public String reSignStatus(String userid, String signType, LocalDateTime nowDateTime, + String workdate) { + String signStatus = ""; + + String shift_begindateworktime = ""; + String shift_enddateworktime = ""; + ShiftInfoBean shiftInfoBean = KQDurationCalculatorUtil.getWorkTime(userid, workdate,false); + if(shiftInfoBean == null){ + return signStatus; + } + //休息班次打卡去掉迟到、早退的打卡异常提醒 + int serialid = StringUtil.parseToInt(shiftInfoBean.getSerialid(), 0); + KQShiftManagementComInfo kQShiftManagementComInfo = new KQShiftManagementComInfo(); + int restShift = StringUtil.parseToInt(kQShiftManagementComInfo.getRestShift(String.valueOf(serialid)), 0); + if(serialid <= 0 || restShift == 1) { + return "-1"; + } + + Map shifRuleMap = Maps.newHashMap(); + KQShiftRuleInfoBiz.getShiftRuleInfo(shiftInfoBean,userid,shifRuleMap); + KQTimesArrayComInfo arrayComInfo = new KQTimesArrayComInfo(); + if(!shifRuleMap.isEmpty()) { + DateTimeFormatter fullFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + String datetime = ""; + if (shifRuleMap.containsKey("shift_beginworktime")) { + String shift_beginworktime = Util.null2String(shifRuleMap.get("shift_beginworktime")); + if (shift_beginworktime.length() > 0) { + int shift_beginworktime_index = -1; + shift_beginworktime_index = arrayComInfo.getArrayindexByTimes(shift_beginworktime); + datetime = workdate+" "+shift_beginworktime+":00"; + if(shift_beginworktime_index >= 1440){ + //跨天了 + datetime = DateUtil.addDate(workdate, 1)+" "+arrayComInfo.turn48to24Time(shift_beginworktime)+":00"; + } + } + } + if (shifRuleMap.containsKey("shift_endworktime")) { + String shift_endworktime = Util.null2String(shifRuleMap.get("shift_endworktime")); + if (shift_endworktime.length() > 0) { + int shift_endworktime_index = -1; + shift_endworktime_index = arrayComInfo.getArrayindexByTimes(shift_endworktime); + datetime = workdate+" "+shift_endworktime+":00"; + if(shift_endworktime_index >= 1440) { + //跨天了 + datetime = DateUtil.addDate(workdate, 1)+" "+arrayComInfo.turn48to24Time(shift_endworktime)+":00"; + } + } + } + + if (datetime.length() > 0) { + if("1".equalsIgnoreCase(signType)) { + LocalDateTime startWorkDateTime = LocalDateTime.parse(datetime, fullFormatter); + //打卡时间比上班时间晚,迟到了 + if (nowDateTime.isAfter(startWorkDateTime)) { + signStatus = ButtonStatusEnum.BELATE.getStatusCode(); + } else { + signStatus = ButtonStatusEnum.NORMAL.getStatusCode(); + } + } else if ("2".equalsIgnoreCase(signType)) { + LocalDateTime endWorkDateTime = LocalDateTime.parse(datetime, fullFormatter); + //签退的话 + if (nowDateTime.isBefore(endWorkDateTime)) { + signStatus = ButtonStatusEnum.LEAVEERALY.getStatusCode(); + } else { + signStatus = ButtonStatusEnum.NORMAL.getStatusCode(); + } + } else { + writeLog(user.getLastname() + nowDateTime + ":竟然没有传:" + signType); + return ""; + } + } + } + return signStatus; + } + + /** + * 上班前打卡目前是 视作前一天的跨天加班 + * @param resourceid + * @param pre_splitDate + * @param signtime + * @param pre_bengintime + * @param signdate + */ + public void doBeforeAcrossOvertime(String resourceid,String pre_splitDate,String signtime,String pre_bengintime,String signdate) { + + KQTaskBean kqTaskBean = new KQTaskBean(); + kqTaskBean.setResourceId(resourceid); + kqTaskBean.setTaskDate(pre_splitDate); + kqTaskBean.setLastWorkTime(signtime); + if(pre_bengintime.length() == 5){ + kqTaskBean.setTaskSignTime(pre_bengintime+":00"); + }else{ + kqTaskBean.setTaskSignTime(pre_bengintime); + } + kqTaskBean.setSignDate(signdate); + kqTaskBean.setSignEndDate(signdate); + kqTaskBean.setTimesource("before"); + KQQueue.writeTask(kqTaskBean); + } + + /** + * 校验是否已经签到过 + * @param userid + * @param signtype + * @param curUser + * @param signsections + * @param signSectionBeginTime 下班打卡 允许最早打卡时间 + * @param signSectionEndTime 上班打卡 允许最晚打卡时间 + * @return + */ + public String signedMsg(String userid, String signtype, User curUser, String[] signsections, + String signSectionBeginTime, String signSectionEndTime) throws Exception{ + String signedMsg = ""; + RecordSet rs = new RecordSet(); + boolean hasSigned = false; + String onSignSectionTime = signsections[0]; + String offSignSectionTime = signsections[1]; + if(onSignSectionTime.length() > 0 && offSignSectionTime.length() > 0){ + String hasSign = "select 1 from hrmschedulesign where 1 = 1 and isInCom = '1' and userid = ? "; + + StringBuffer sql = new StringBuffer(); + if(rs.getDBType().equals("oracle")||rs.getDBType().equals("postgresql")){ + sql.append(" AND signDate||' '||signTime>=? "); + sql.append(" AND signDate||' '||signTime<=? "); + }else if(rs.getDBType().equals("mysql")){ + sql.append(" AND concat(signDate,' ',signTime)>=? "); + sql.append(" AND concat(signDate,' ',signTime)<=? "); + }else{ + sql.append(" AND signDate+' '+signTime>=? "); + sql.append(" AND signDate+' '+signTime<=? "); + } + hasSign += sql.toString(); + rs.executeQuery(hasSign, userid,onSignSectionTime,offSignSectionTime); + if(rs.next()){ + hasSigned = true; + } + if("1".equalsIgnoreCase(signtype)){ + if(signSectionBeginTime.length() > 0 || signSectionEndTime.length() > 0){ + }else{ + if(hasSigned){ + signedMsg = SystemEnv.getHtmlLabelName(129706, curUser.getLanguage()); + } + } + }else if("2".equalsIgnoreCase(signtype)){ + if(signSectionBeginTime.length() > 0 || signSectionEndTime.length() > 0){ + }else{ + if(!hasSigned){ + signedMsg = SystemEnv.getHtmlLabelName(501301, curUser.getLanguage()); + } + } + } + } + return signedMsg; + } + /** + * 在签到签退的时候先根据打卡数据 + * 粗步 得到打卡状态 正常,迟到,早退 + * @return + */ + public String getSignStatus(String signType, String datetime, String userid, String workdate, + LocalDateTime nowDateTime) { + DateTimeFormatter fullFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + String signStatus = ""; + + //签到的话 + if("1".equalsIgnoreCase(signType)){ + LocalDateTime startWorkDateTime = LocalDateTime.parse(datetime,fullFormatter); + //打卡时间比上班时间晚,迟到了 + if(nowDateTime.isAfter(startWorkDateTime)){ + signStatus = ButtonStatusEnum.BELATE.getStatusCode(); + }else{ + signStatus = ButtonStatusEnum.NORMAL.getStatusCode(); + } + }else if("2".equalsIgnoreCase(signType)){ + LocalDateTime endWorkDateTime = LocalDateTime.parse(datetime,fullFormatter); + //签退的话 + if(nowDateTime.isBefore(endWorkDateTime)){ + signStatus = ButtonStatusEnum.LEAVEERALY.getStatusCode(); + }else{ + signStatus = ButtonStatusEnum.NORMAL.getStatusCode(); + } + }else{ + writeLog(user.getLastname()+nowDateTime+":竟然没有传:"+signType); + return ""; + } + return signStatus; + } + + @Override + public BizLogContext getLogContext() { + return null; + } + +} diff --git a/src/com/engine/kq/cmd/attendanceEvent/GetOverTimeWorkDurationCmd.java b/src/com/engine/kq/cmd/attendanceEvent/GetOverTimeWorkDurationCmd.java new file mode 100644 index 0000000..b99b943 --- /dev/null +++ b/src/com/engine/kq/cmd/attendanceEvent/GetOverTimeWorkDurationCmd.java @@ -0,0 +1,100 @@ +package com.engine.kq.cmd.attendanceEvent; + +import com.engine.common.biz.AbstractCommonCommand; +import com.engine.common.entity.BizLogContext; +import com.engine.core.interceptor.CommandContext; +import com.engine.kq.biz.KQGroupMemberComInfo; +import com.engine.kq.biz.KQOvertimeRulesBiz; +import com.engine.kq.biz.KQWorkTime; +import com.engine.kq.entity.WorkTimeEntity; +import com.engine.kq.enums.DurationTypeEnum; +import com.engine.kq.util.KQDurationCalculatorUtil; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.locks.ReentrantLock; + +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.User; +import weaver.hrm.resource.ResourceComInfo; +import weaver.systeminfo.SystemEnv; + +/** + * 加班用的时长计算 + */ +public class GetOverTimeWorkDurationCmd extends AbstractCommonCommand> { + + public GetOverTimeWorkDurationCmd(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 = ""; + ReentrantLock lock = new ReentrantLock(); + try { + lock.lock(); + String resourceId = Util.null2String(params.get("resourceId")); + String fromDate = Util.null2String(params.get("fromDate")); + String toDate = Util.null2String(params.get("toDate")); + String fromTime = Util.null2String(params.get("fromTime")); + String toTime = Util.null2String(params.get("toTime")); + String overtime_type = Util.null2String(params.get("overtime_type")); + String timestamp = Util.null2String(params.get("timestamp")); + writeLog("resourceId="+resourceId+",fromDate="+fromDate+",toDate="+toDate+",fromTime="+fromTime+",toTime="+toTime+",timestamp="+timestamp); + + int minimumUnit = KQOvertimeRulesBiz.getMinimumUnit(); + // + KQWorkTime kqWorkTime = new KQWorkTime(); + WorkTimeEntity kqWorkTimeEntity = kqWorkTime.getWorkTime(resourceId, fromDate); + if (kqWorkTimeEntity != null) { + String kqType = Util.null2String(kqWorkTimeEntity.getKQType()); + if ("3".equalsIgnoreCase(kqType)) { + writeLog("自由班制不计算加班"); + retmap.put("status", "1"); + retmap.put("message", "" + weaver.systeminfo.SystemEnv.getHtmlLabelName(10005330, weaver.general.ThreadVarLanguage.getLang()) + ""); + return retmap; + } + } + ResourceComInfo rci = new ResourceComInfo(); + KQGroupMemberComInfo kqGroupMemberComInfo = new KQGroupMemberComInfo(); + String groupid = kqGroupMemberComInfo.getKQGroupId(resourceId, fromDate); + if (resourceId.length() > 0 && groupid.length() == 0) { + retmap.put("status", "-1"); + retmap.put("message", rci.getLastname(resourceId) + "," + fromDate + "" + weaver.systeminfo.SystemEnv.getHtmlLabelName(10005329, weaver.general.ThreadVarLanguage.getLang()) + ""); + return retmap; + } + + + //加班默认是工作日加班 + KQDurationCalculatorUtil kqDurationCalculatorUtil = new KQDurationCalculatorUtil.DurationParamBuilder(resourceId). + fromDateParam(fromDate).toDateParam(toDate).fromTimeParam(fromTime).toTimeParam(toTime).computingModeParam("1"). + durationRuleParam(minimumUnit + "").durationTypeEnumParam(DurationTypeEnum.OVERTIME). + overtime_typeParam(overtime_type).build(); + + Map durationMap = kqDurationCalculatorUtil.getWorkDuration(); + + retmap.put("duration", Util.null2String(durationMap.get("duration"))); + + retmap.put("timestamp", timestamp); + retmap.put("status", "1"); + } catch (Exception e) { + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(382661, user.getLanguage())); + writeLog(e); + }finally { + lock.unlock(); + } + return retmap; + } + + @Override + public BizLogContext getLogContext() { + return null; + } + +} diff --git a/src/com/engine/kq/cmd/balanceofleaverp/ExportExcelCmd.java b/src/com/engine/kq/cmd/balanceofleaverp/ExportExcelCmd.java new file mode 100644 index 0000000..aa9c779 --- /dev/null +++ b/src/com/engine/kq/cmd/balanceofleaverp/ExportExcelCmd.java @@ -0,0 +1,468 @@ +package com.engine.kq.cmd.balanceofleaverp; + +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.KQTransMethod; +import org.apache.poi.hssf.usermodel.*; +import org.apache.poi.ss.usermodel.*; +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.systeminfo.SystemEnv; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.OutputStream; +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.net.URLEncoder; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 员工假期余额报表--将查询结果导出为Excel文件 + */ +public class ExportExcelCmd extends AbstractCommonCommand> { + + private HttpServletRequest request; + private HttpServletResponse response; + + public ExportExcelCmd(Map params, User user, HttpServletRequest request, HttpServletResponse response) { + this.user = user; + this.params = params; + this.request = request; + this.response = response; + } + + @Override + public BizLogContext getLogContext() { + return null; + } + + @Override + public Map execute(CommandContext commandContext) { + long startTime = System.currentTimeMillis(); + Map resultMap = new HashMap(); + /** + * 展示列 + */ + String displayColumn = Util.null2String(params.get("displayColumn")); + List displayColumnList = Util.TokenizerString(displayColumn, ","); + /** + * 时间范围选择的年份 + * 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")); + + try { + /** + * 获取考勤报表权限共享设置 + */ + KQReportBiz kqReportBiz = new KQReportBiz(); + String rightStr = kqReportBiz.getReportRight("4", "" + user.getUID(), "a"); + + /** + * 拼凑查询结果Excel文件的表头 + */ + HSSFWorkbook workbook = new HSSFWorkbook(); + HSSFSheet sheet = workbook.createSheet(SystemEnv.getHtmlLabelName(389441, user.getLanguage()));//员工假期余额 + // 设置字体 + 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); + + int index = 0; + HSSFRow headerRow = sheet.createRow(0); + String[] tempArr = new String[]{SystemEnv.getHtmlLabelName(413, user.getLanguage()) + ",lastName", SystemEnv.getHtmlLabelName(141, user.getLanguage()) + ",subcom", SystemEnv.getHtmlLabelName(124, user.getLanguage()) + ",dept", SystemEnv.getHtmlLabelName(6086, user.getLanguage()) + ",jobtitle", SystemEnv.getHtmlLabelName(714, user.getLanguage()) + ",workcode"}; + for (int i = 0; i < tempArr.length; i++) { + String[] fieldInfo = tempArr[i].split(","); + if (fieldInfo[1].equals("lastName") || displayColumnList.indexOf(fieldInfo[1]) > -1) { + headerRow.setHeight((short) 312); + HSSFCell headCell = headerRow.createCell(index); + headCell.setCellValue(fieldInfo[0]); + headCell.setCellStyle(style); + sheet.setColumnWidth((short) index, (short) (6 * 1000)); + index++; + } + } + + /**********************************************************************************************************/ + + /**获取假期类型的相关设置*/ + + /*请假类型的ID*/ + String leaveRulesId = ""; + + /*假期类型的名称,用作查询结果列表的表头显示*/ + String leaveName = ""; + + /*最小请假单位:1-按天请假、2-按半天请假、3-按小时请假、4-按整天请假*/ + int minimumUnit = 1; + + /*请假单位的显示名称是天还是小时*/ + String unitName = ""; + + /*是否开启假期余额,没有开启假期余额时需要提示“不限制余额*/ + int balanceEnable = 0; + + /**********************************************************************************************************/ + + /*是否是混合模式(福利年假+法定年假)*/ + boolean isMixMode = false; + + //是否是调休 + boolean isTiaoXiu = false; + + /**********************************************************************************************************/ + + /*获取当前日期*/ + String currentDate = DateUtil.getCurrentDate(); + + Map balanceMap = new HashMap(); + KQLeaveRulesComInfo rulesComInfo = new KQLeaveRulesComInfo(); + rulesComInfo.setTofirstRow(); + while (rulesComInfo.next()) { + /*该假期没有启用,不显示*/ + if (!rulesComInfo.getIsEnable().equals("1")) { + continue; + } + /*展示列不展示,不显示*/ + if (displayColumnList.indexOf(rulesComInfo.getId()) < 0) { + continue; + } + /*获取假期类型的设置 start*/ + leaveRulesId = rulesComInfo.getId(); + leaveName = Util.formatMultiLang(rulesComInfo.getLeaveName(), "" + user.getLanguage()); + minimumUnit = Util.getIntValue(rulesComInfo.getMinimumUnit(), 1); + if (minimumUnit == 1 || minimumUnit == 2 || minimumUnit == 4) { + unitName = SystemEnv.getHtmlLabelName(389325, user.getLanguage());//(天) + } else { + unitName = SystemEnv.getHtmlLabelName(389326, user.getLanguage());//(小时) + } + String showName = leaveName + unitName; + balanceEnable = Util.getIntValue(rulesComInfo.getBalanceEnable(), 0); + + isMixMode = KQLeaveRulesBiz.isMixMode(leaveRulesId); + //isTiaoXiu = KQLeaveRulesBiz.isTiaoXiu(leaveRulesId); + isTiaoXiu = KQLeaveRulesBiz.isTiaoXiu2(leaveRulesId); + /*获取假期类型的设置 end*/ + + headerRow.setHeight((short) 312); + HSSFCell headCell = headerRow.createCell(index); + headCell.setCellValue(showName); + headCell.setCellStyle(style); + sheet.setColumnWidth((short) index, (short) (6 * 1000)); + index++; + + /*判断该假期规则是否开启了假期余额,若没有开启,则无需查找该假期的余额,直接遍历下一个假期*/ + if (balanceEnable == 0) { + continue; + } + //如果是调休,获取假期余额的方式有些不同 + if (isTiaoXiu) { + params.put("leaveRulesId", leaveRulesId); + params.put("showAll", "true"); + Map _balanceMap = KQBalanceOfLeaveBiz.getRestAmountMapByDis5(params, user); + balanceMap.putAll(_balanceMap); + continue; + } + + /*查询指定年份指定假期的余额数据,并放入集合中,用于后续拼凑查询结果数据*/ + KQTransMethod transMethod = new KQTransMethod(); + RecordSet recordSet = new RecordSet(); + String sql = "select a.id hrmResourceId,b.* from HrmResource a left join kq_balanceOfLeave b on a.id=b.resourceId " + + "and belongYear='" + selectedYear + "' and b.leaveRulesId=" + leaveRulesId + " 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 (isNoAccount.equals("false")) { + if (recordSet.getDBType().equalsIgnoreCase("sqlserver") + || recordSet.getDBType().equalsIgnoreCase("mysql")) { + sql += " and (loginId is not null and loginId<>'')"; + } else if (recordSet.getDBType().equalsIgnoreCase("postgresql")) { + sql += " and (loginId is not null and loginId<>'')"; + } else { + sql += " and (loginId is not null)"; + } + } + 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 (!rightStr.equals("") && !dataScope.equals("4")) { + sql += rightStr; + } + sql += " order by dspOrder,hrmResourceId "; + recordSet.executeQuery(sql); + while (recordSet.next()) { + String hrmResourceId = recordSet.getString("hrmResourceId"); + //所属年份 + String belongYear = recordSet.getString("belongYear"); + //失效日期 + String effectiveDate = recordSet.getString("effectiveDate"); + //失效日期 + String expirationDate = recordSet.getString("expirationDate"); + /*判断假期余额的有效期*/ + boolean status = KQBalanceOfLeaveBiz.getBalanceStatus(leaveRulesId, hrmResourceId, belongYear, currentDate, effectiveDate, expirationDate); + if (!status) { + continue; + } + BigDecimal baseAmount = new BigDecimal(Util.getDoubleValue(recordSet.getString("baseAmount"), 0.00));//假期基数 + BigDecimal usedAmount = new BigDecimal(Util.getDoubleValue(recordSet.getString("usedAmount"), 0.00));//已用假期 + BigDecimal extraAmount = new BigDecimal(Util.getDoubleValue(recordSet.getString("extraAmount"), 0.00));//额外假期 + BigDecimal baseAmount2 = new BigDecimal(Util.getDoubleValue(recordSet.getString("baseAmount2"), 0.00));//用于混合模式时:福利年假基数 + BigDecimal usedAmount2 = new BigDecimal(Util.getDoubleValue(recordSet.getString("usedAmount2"), 0.00));//用于混合模式时:已用福利年假 + BigDecimal extraAmount2 = new BigDecimal(Util.getDoubleValue(recordSet.getString("extraAmount2"), 0.00));//用于混合模式时:额外福利年假 + + BigDecimal restAmount = new BigDecimal(0); + if (isMixMode) { + /*释放规则*/ + baseAmount = KQBalanceOfLeaveBiz.getCanUseAmount(hrmResourceId, leaveRulesId, belongYear, baseAmount, "legal", currentDate); + baseAmount2 = KQBalanceOfLeaveBiz.getCanUseAmount(hrmResourceId, leaveRulesId, belongYear, baseAmount2, "welfare", currentDate); + + restAmount = baseAmount.add(extraAmount).subtract(usedAmount).add(baseAmount2).add(extraAmount2).subtract(usedAmount2); + } else { + /*释放规则*/ + baseAmount = KQBalanceOfLeaveBiz.getCanUseAmount(hrmResourceId, leaveRulesId, belongYear, baseAmount, "", currentDate); + + restAmount = baseAmount.add(extraAmount).subtract(usedAmount); + } + balanceMap.put(hrmResourceId + "_" + leaveRulesId, restAmount); + } + } + + /** + * 用于拼凑查询结果列表的表数据 + */ + SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo(); + DepartmentComInfo departmentComInfo = new DepartmentComInfo(); + JobTitlesComInfo jobTitlesComInfo = new JobTitlesComInfo(); + + index = 0; + String sql = "select * from HrmResource a 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() + ")"; + } + } + RecordSet recordSet = new RecordSet(); + if (isNoAccount.equals("false")) { + if (recordSet.getDBType().equalsIgnoreCase("sqlserver") + || recordSet.getDBType().equalsIgnoreCase("mysql")) { + sql += " and (a.loginId is not null and a.loginId<>'')"; + }else if (recordSet.getDBType().equalsIgnoreCase("postgresql")) { + sql += " and (a.loginId is not null and a.loginId<>'')"; + } else { + sql += " and (a.loginId is not null)"; + } + } + 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 (!rightStr.equals("") && !dataScope.equals("4")) { + sql += rightStr; + } + sql += " order by dspOrder,id "; + recordSet.executeQuery(sql); + + // #1475814-概述:满足考勤报分部部门显示及导出时显示全路径 + String fullPathMainKey = "show_full_path"; + KQSettingsComInfo kqSettingsComInfo = new KQSettingsComInfo(); + String isShowFullPath = Util.null2String(kqSettingsComInfo.getMain_val(fullPathMainKey),"0"); + String subCompanyNameTmp = ""; + String departmentNameTmp = ""; + + while (recordSet.next()) { + HSSFRow row = sheet.createRow(++index); + + String id = recordSet.getString("id"); + String lastName = recordSet.getString("lastName"); + String departmentId = recordSet.getString("departmentId"); + String subcompanyId = recordSet.getString("subcompanyId1"); + String jobtitleId = recordSet.getString("jobtitle"); + String workcode = recordSet.getString("workcode"); + + int cellIndex = 0; + HSSFCell cell = row.createCell(cellIndex); + cell.setCellValue(Util.formatMultiLang(lastName, "" + user.getLanguage())); + cellIndex++; + if (displayColumnList.indexOf("subcom") > -1) { + cell = row.createCell(cellIndex); + + // 导出时,是否显示全路径 + subCompanyNameTmp = "1".equals(isShowFullPath) ? + SubCompanyComInfo.getSubcompanyRealPath(subcompanyId, "/", "0") : + subCompanyComInfo.getSubCompanyname(subcompanyId); + cell.setCellValue(Util.formatMultiLang(subCompanyNameTmp, "" + user.getLanguage())); + + // cell.setCellValue(Util.formatMultiLang(subCompanyComInfo.getSubcompanyname(subcompanyId), "" + user.getLanguage())); + cellIndex++; + } + if (displayColumnList.indexOf("dept") > -1) { + cell = row.createCell(cellIndex); + + // 导出时,是否显示全路径 + departmentNameTmp = "1".equals(isShowFullPath) ? + departmentComInfo.getDepartmentRealPath(departmentId, "/", "0") : + departmentComInfo.getDepartmentname(departmentId); + cell.setCellValue(Util.formatMultiLang(departmentNameTmp, "" + user.getLanguage())); + + // cell.setCellValue(Util.formatMultiLang(departmentComInfo.getDepartmentname(departmentId), "" + user.getLanguage())); + cellIndex++; + } + if (displayColumnList.indexOf("jobtitle") > -1) { + cell = row.createCell(cellIndex); + cell.setCellValue(Util.formatMultiLang(jobTitlesComInfo.getJobTitlesname(jobtitleId), "" + user.getLanguage())); + cellIndex++; + } + if (displayColumnList.indexOf("workcode") > -1) { + cell = row.createCell(cellIndex); + cell.setCellValue(Util.formatMultiLang(workcode, "" + user.getLanguage())); + cellIndex++; + } + + rulesComInfo.setTofirstRow(); + while (rulesComInfo.next()) { + /*展示列不展示,不显示*/ + if (displayColumnList.indexOf(rulesComInfo.getId()) < 0) { + continue; + } + /*该假期没有启用,不显示*/ + if (!rulesComInfo.getIsEnable().equals("1")) { + continue; + } + /*该假期没有开启余额限制,显示不限制余额*/ + if (rulesComInfo.getBalanceEnable().equals("0")) { + cell = row.createCell(cellIndex); + cell.setCellValue(SystemEnv.getHtmlLabelName(389731, user.getLanguage())); + cellIndex++; + continue; + } + BigDecimal restAmount = balanceMap.get(id + "_" + rulesComInfo.getId()); + cell = row.createCell(cellIndex); + cell.setCellValue(restAmount != null ? restAmount.setScale(2, RoundingMode.HALF_UP).doubleValue() : 0); + cellIndex++; + } + + } + + String encodedFileName = SystemEnv.getHtmlLabelName(389441, user.getLanguage()); + 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")) { + encodedFileName = URLEncoder.encode(encodedFileName, "utf-8"); + encodedFileName = encodedFileName.replace("+", "%20"); //IE下载文件名空格变+号问题 + } else { + encodedFileName = new String(encodedFileName.getBytes("utf-8"), "ISO_8859_1"); + } + writeLog("balanceofleaverp>>>ExportExcelCmd>>>encodedFileName="+encodedFileName); + response.setHeader("Content-disposition", "attachment;filename=" + encodedFileName + "excel.xls"); + response.setContentType("application/msexcel"); + response.setContentType("application/x-msdownload"); + OutputStream responseOutput = response.getOutputStream(); + workbook.write(responseOutput); + responseOutput.flush(); + } catch (Exception e) { + writeLog(e); + } + long endTime = System.currentTimeMillis(); + float seconds = (endTime - startTime) / 1000F; + System.out.println(Float.toString(seconds) + " seconds."); + return resultMap; + } +} diff --git a/src/com/engine/kq/cmd/balanceofleaverp/GetSearchListCmd.java b/src/com/engine/kq/cmd/balanceofleaverp/GetSearchListCmd.java new file mode 100644 index 0000000..fb4b2ab --- /dev/null +++ b/src/com/engine/kq/cmd/balanceofleaverp/GetSearchListCmd.java @@ -0,0 +1,426 @@ +package com.engine.kq.cmd.balanceofleaverp; + +import com.api.hrm.bean.HrmFieldBean; +import com.api.hrm.util.HrmFieldUtil; +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.KQTransMethod; +import com.engine.kq.util.UtilKQHS; +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.general.TimeUtil; +import weaver.general.Util; +import weaver.hrm.HrmUserVarify; +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.math.RoundingMode; +import java.util.*; + +/** + * 员工假期余额报表--获取查询列表 + */ +public class GetSearchListCmd extends AbstractCommonCommand> { + + public GetSearchListCmd(Map params, User user) { + this.user = user; + this.params = params; + } + + @Override + public BizLogContext getLogContext() { + return null; + } + + @Override + public Map execute(CommandContext commandContext) { + Map resultMap = new HashMap(); + /** + * 分页控件返回的值 + * currentPage:当前页数 + * pageSize:每页多少条数据 + */ + int currentPage = Util.getIntValue((String) params.get("currentPage"), 1); + int pageSize = Util.getIntValue((String) params.get("pageSize"), 10); + /** + * 时间范围选择的年份 + * 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")); + + try { + /** + * 获取考勤报表权限共享设置 + */ + KQReportBiz kqReportBiz = new KQReportBiz(); + String rightStr = kqReportBiz.getReportRight("4", "" + user.getUID(), "a"); + + /** + * 拼凑查询结果列表的表头 + */ + List> columnsList = new ArrayList>(); + List hrmFieldBeanList = new ArrayList(); + HrmFieldBean hrmFieldBean = null; + String[] tempArr = new String[]{"lastName,413", "subcom,141", "dept,124", "jobtitle,6086","workcode,714", "companyStartDate,1516"}; + for (int i = 0; i < tempArr.length; i++) { + String[] fieldInfo = tempArr[i].split(","); + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname(fieldInfo[0]); + hrmFieldBean.setFieldlabel(fieldInfo[1]); + hrmFieldBean.setFieldhtmltype("1"); + hrmFieldBean.setType("1"); + hrmFieldBean.setViewAttr(1); + hrmFieldBean.setIsFormField(true); + hrmFieldBeanList.add(hrmFieldBean); + } + + /**********************************************************************************************************/ + + /**获取假期类型的相关设置*/ + + /*请假类型的ID*/ + String leaveRulesId = ""; + + /*假期类型的名称,用作查询结果列表的表头显示*/ + String leaveName = ""; + + /*最小请假单位:1-按天请假、2-按半天请假、3-按小时请假、4-按整天请假*/ + int minimumUnit = 1; + + /*请假单位的显示名称是天还是小时*/ + String unitName = ""; + + /*是否开启假期余额,没有开启假期余额时需要提示“不限制余额*/ + int balanceEnable = 0; + + /**********************************************************************************************************/ + + /*是否是混合模式(福利年假+法定年假)*/ + boolean isMixMode = false; + + //是否是调休 + boolean isTiaoXiu = false; + + /**********************************************************************************************************/ + + /*获取当前日期*/ + String currentDate = DateUtil.getCurrentDate(); + + Map balanceMap = new HashMap(); + Map baseBalanceMap = new HashMap(); + KQLeaveRulesComInfo rulesComInfo = new KQLeaveRulesComInfo(); + rulesComInfo.setTofirstRow(); + while (rulesComInfo.next()) { + if (rulesComInfo.getIsEnable().equals("0")) { + continue;//此假期类型没有启用 + } + + /*获取假期类型的设置 start*/ + leaveRulesId = rulesComInfo.getId(); + leaveName = Util.formatMultiLang(rulesComInfo.getLeaveName(), "" + user.getLanguage()); + minimumUnit = Util.getIntValue(rulesComInfo.getMinimumUnit(), 1); + if (minimumUnit == 1 || minimumUnit == 2 || minimumUnit == 4) { + unitName = SystemEnv.getHtmlLabelName(389325, user.getLanguage());//(天) + } else { + unitName = SystemEnv.getHtmlLabelName(389326, user.getLanguage());//(小时) + } + String showName = leaveName + unitName; + balanceEnable = Util.getIntValue(rulesComInfo.getBalanceEnable(), 0); + + isMixMode = KQLeaveRulesBiz.isMixMode(leaveRulesId); + //isTiaoXiu = KQLeaveRulesBiz.isTiaoXiu(leaveRulesId); + isTiaoXiu = KQLeaveRulesBiz.isTiaoXiu2(leaveRulesId); + /*获取假期类型的设置 end*/ + + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname(rulesComInfo.getId()); + hrmFieldBean.setFieldlabelname(showName); + hrmFieldBean.setFieldhtmltype("1"); + hrmFieldBean.setType("1"); + hrmFieldBean.setViewAttr(1); + hrmFieldBean.setIsFormField(true); + hrmFieldBeanList.add(hrmFieldBean); + + /*判断该假期规则是否开启了假期余额,若没有开启,则无需查找该假期的余额,直接遍历下一个假期*/ + if (balanceEnable == 0) { + continue; + } + //如果是调休,获取假期余额的方式有些不同 + if(isTiaoXiu){ + params.put("leaveRulesId",leaveRulesId); + params.put("showAll","false"); + Map _balanceMap = KQBalanceOfLeaveBiz.getRestAmountMapByDis5(params,user); + balanceMap.putAll(_balanceMap); + continue; + } + + /*查询指定年份指定假期的余额数据,并放入集合中,用于后续拼凑查询结果数据*/ + KQTransMethod transMethod = new KQTransMethod(); + RecordSet recordSet = new RecordSet(); + String sql = "select a.id hrmResourceId,a.companyStartDate,a.workStartDate,b.* from HrmResource a left join kq_balanceOfLeave b on a.id=b.resourceId " + + "and belongYear='" + selectedYear + "' and b.leaveRulesId=" + leaveRulesId + " where 1=1 "; + if (recordSet.getDBType().equalsIgnoreCase("sqlserver")) { + sql = "select a.id hrmResourceId,a.companyStartDate,a.workStartDate,b.*,ROW_NUMBER() OVER(order by dspOrder,a.id) as rn from HrmResource a left join kq_balanceOfLeave b on a.id=b.resourceId " + + "and belongYear='" + selectedYear + "' and b.leaveRulesId=" + leaveRulesId + " where 1=1 "; + } else if (recordSet.getDBType().equalsIgnoreCase("mysql")) { + sql = "select a.id hrmResourceId,a.companyStartDate,a.workStartDate,b.* from HrmResource a left join kq_balanceOfLeave b on a.id=b.resourceId " + + "and belongYear='" + selectedYear + "' and b.leaveRulesId=" + leaveRulesId + " 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 (isNoAccount.equals("false")) { + if (recordSet.getDBType().equalsIgnoreCase("sqlserver") + || recordSet.getDBType().equalsIgnoreCase("mysql")) { + sql += " and (loginId is not null and loginId<>'')"; + }else if (recordSet.getDBType().equalsIgnoreCase("postgresql")) { + sql += " and (loginId is not null and loginId<>'')"; + } else { + sql += " and (loginId is not null)"; + } + } + + 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 (!rightStr.equals("") && !dataScope.equals("4")) { + sql += rightStr; + } + if (!recordSet.getDBType().equalsIgnoreCase("sqlserver")) { + sql += " order by dspOrder,hrmResourceId "; + } + + 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); + while (recordSet.next()) { + String hrmResourceId = recordSet.getString("hrmResourceId"); + //所属年份 + String belongYear = recordSet.getString("belongYear"); + //失效日期 + String effectiveDate = recordSet.getString("effectiveDate"); + //失效日期 + String expirationDate = recordSet.getString("expirationDate"); + /*判断假期余额的有效期*/ + boolean status = KQBalanceOfLeaveBiz.getBalanceStatus(leaveRulesId, hrmResourceId, belongYear, currentDate,effectiveDate,expirationDate); + if (!status) { + continue; + } + BigDecimal baseAmount = new BigDecimal(Util.getDoubleValue(recordSet.getString("baseAmount"), 0.00));//假期基数 + BigDecimal usedAmount = new BigDecimal(Util.getDoubleValue(recordSet.getString("usedAmount"), 0.00));//已用假期 + BigDecimal extraAmount = new BigDecimal(Util.getDoubleValue(recordSet.getString("extraAmount"), 0.00));//额外假期 + BigDecimal baseAmount2 = new BigDecimal(Util.getDoubleValue(recordSet.getString("baseAmount2"), 0.00));//用于混合模式时:福利年假基数 + BigDecimal usedAmount2 = new BigDecimal(Util.getDoubleValue(recordSet.getString("usedAmount2"), 0.00));//用于混合模式时:已用福利年假 + BigDecimal extraAmount2 = new BigDecimal(Util.getDoubleValue(recordSet.getString("extraAmount2"), 0.00));//用于混合模式时:额外福利年假 + + BigDecimal restAmount = new BigDecimal(0); + if (isMixMode) { + /*释放规则*/ + baseAmount = KQBalanceOfLeaveBiz.getCanUseAmount(hrmResourceId, leaveRulesId, belongYear, baseAmount, "legal", currentDate); + baseAmount2 = KQBalanceOfLeaveBiz.getCanUseAmount(hrmResourceId, leaveRulesId, belongYear, baseAmount2, "welfare", currentDate); + + restAmount = baseAmount.add(extraAmount).subtract(usedAmount).add(baseAmount2).add(extraAmount2).subtract(usedAmount2); + } else { + if ("36".equals(leaveRulesId)) { + //育儿假 + boolean isLastYearChildcareLeave = UtilKQHS.isLastYearChildcareLeave(resourceId, selectedYear); + + //根据释放规则获取已释放的天数/小时数 + baseAmount = KQBalanceOfLeaveBiz.getCanUseAmountChildcareLeave(resourceId, leaveRulesId, belongYear, baseAmount, "", currentDate, isLastYearChildcareLeave); + }else{ + /*释放规则*/ + baseAmount = KQBalanceOfLeaveBiz.getCanUseAmount(hrmResourceId, leaveRulesId, belongYear, baseAmount, "", currentDate); + } + + restAmount = baseAmount.add(extraAmount).subtract(usedAmount); + } + + baseBalanceMap.put(hrmResourceId + "_" + leaveRulesId, baseAmount); + balanceMap.put(hrmResourceId + "_" + leaveRulesId, restAmount); + } + } + + /** + * 用于拼凑查询结果列表的表数据 + */ + SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo(); + DepartmentComInfo departmentComInfo = new DepartmentComInfo(); + JobTitlesComInfo jobTitlesComInfo = new JobTitlesComInfo(); + List> dataList = new ArrayList>(); + Map dataMap = new HashMap(); + RecordSet recordSet = new RecordSet(); + String sql = "select * from HrmResource a where 1=1 "; + if (recordSet.getDBType().equalsIgnoreCase("sqlserver")) { + sql = "select *,ROW_NUMBER() OVER(order by dspOrder,id) as rn from HrmResource a 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 (isNoAccount.equals("false")) { + if (recordSet.getDBType().equalsIgnoreCase("sqlserver") + || recordSet.getDBType().equalsIgnoreCase("mysql")) { + sql += " and (a.loginId is not null and a.loginId<>'')"; + }else if (recordSet.getDBType().equalsIgnoreCase("postgresql")) { + sql += " and (a.loginId is not null and a.loginId<>'')"; + } else { + sql += " and (a.loginId is not null)"; + } + } + + 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 (!rightStr.equals("") && !dataScope.equals("4")) { + sql += rightStr; + } + if (!recordSet.getDBType().equalsIgnoreCase("sqlserver")) { + sql += " order by dspOrder,id "; + } + 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); + + // #1473334-概述:满足考勤报分部部门显示及导出时显示全路径 + String fullPathMainKey = "show_full_path"; + KQSettingsComInfo kqSettingsComInfo = new KQSettingsComInfo(); + String isShowFullPath = Util.null2String(kqSettingsComInfo.getMain_val(fullPathMainKey),"0"); + String departmentNameTmp = ""; + String subCompanyNameTmp = ""; + + while (recordSet.next()) { + dataMap = new HashMap(); + + String id = recordSet.getString("id"); + String lastName = Util.formatMultiLang(recordSet.getString("lastName"), "" + user.getLanguage()); + String departmentId = recordSet.getString("departmentId"); + String subcompanyId = recordSet.getString("subcompanyId1"); + String jobtitleId = recordSet.getString("jobtitle"); + String workcode = recordSet.getString("workcode"); + String companyStartdate = recordSet.getString("companyStartdate"); + + dataMap.put("id", id); + dataMap.put("lastName", lastName); + + // 根据开关决定是否显示分部部门全路径 + subCompanyNameTmp = "1".equals(isShowFullPath) ? + SubCompanyComInfo.getSubcompanyRealPath(subcompanyId, "/", "0") : + subCompanyComInfo.getSubCompanyname(subcompanyId); + + departmentNameTmp = "1".equals(isShowFullPath) ? + departmentComInfo.getDepartmentRealPath(departmentId, "/", "0") : + departmentComInfo.getDepartmentname(departmentId); + + dataMap.put("subcom", Util.formatMultiLang(subCompanyNameTmp, "" + user.getLanguage())); + dataMap.put("dept", Util.formatMultiLang(departmentNameTmp, "" + user.getLanguage())); + + // dataMap.put("subcom", Util.formatMultiLang(subCompanyComInfo.getSubcompanyname(subcompanyId), "" + user.getLanguage())); + // dataMap.put("dept", Util.formatMultiLang(departmentComInfo.getDepartmentname(departmentId), "" + user.getLanguage())); + dataMap.put("jobtitle", Util.formatMultiLang(jobTitlesComInfo.getJobTitlesname(jobtitleId), "" + user.getLanguage())); + dataMap.put("workcode", workcode); + dataMap.put("companyStartDate", companyStartdate); + dataMap.put("subcomId", subcompanyId); + dataMap.put("deptId", departmentId); + dataMap.put("jobtitleId", jobtitleId); + + rulesComInfo.setTofirstRow(); + while (rulesComInfo.next()) { + if (rulesComInfo.getIsEnable().equals("0")) { + continue; + } + /*该假期没有开启余额限制,显示不限制余额*/ + if (rulesComInfo.getBalanceEnable().equals("0")) { + dataMap.put(rulesComInfo.getId(), SystemEnv.getHtmlLabelName(389731, user.getLanguage()));//不限制余额 + continue; + } + BigDecimal restAmount = balanceMap.get(id + "_" + rulesComInfo.getId()); + dataMap.put(rulesComInfo.getId(), restAmount != null ? restAmount.setScale(2, RoundingMode.HALF_UP).toPlainString() : "0"); + } + dataList.add(dataMap); + } + + columnsList = HrmFieldUtil.getHrmDetailTable(hrmFieldBeanList, null, user); + resultMap.put("columns", columnsList); + resultMap.put("datas", dataList); + } catch (Exception e) { + e.printStackTrace(); + } + return resultMap; + } +} diff --git a/src/com/engine/kq/cmd/leaverules/GetLeaveRulesFormCmd.java b/src/com/engine/kq/cmd/leaverules/GetLeaveRulesFormCmd.java new file mode 100644 index 0000000..3d1e0ad --- /dev/null +++ b/src/com/engine/kq/cmd/leaverules/GetLeaveRulesFormCmd.java @@ -0,0 +1,808 @@ +package com.engine.kq.cmd.leaverules; + +import com.api.browser.bean.SearchConditionItem; +import com.api.browser.bean.SearchConditionOption; +import com.api.hrm.bean.HrmFieldBean; +import com.api.hrm.util.HrmFieldSearchConditionComInfo; +import com.engine.common.biz.AbstractCommonCommand; +import com.engine.common.entity.BizLogContext; +import com.engine.core.interceptor.CommandContext; +import com.engine.kq.biz.KQLeaveRulesComInfo; +import weaver.conn.RecordSet; +import weaver.filter.XssUtil; +import weaver.general.Util; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; +import weaver.systeminfo.SystemEnv; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 假期规则--获取新建编辑的表单 + */ +public class GetLeaveRulesFormCmd extends AbstractCommonCommand> { + + public GetLeaveRulesFormCmd(Map params, User user) { + this.user = user; + this.params = params; + } + + @Override + public BizLogContext getLogContext() { + return null; + } + + @Override + public Map execute(CommandContext commandContext) { + Map resultMap = new HashMap(); + try { + boolean canEdit = HrmUserVarify.checkUserRight("KQLeaveRulesEdit:Edit", user);//是否具有编辑权限 + if (!canEdit) { + resultMap.put("status", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage())); + return resultMap; + } + /**假期类型的相关信息:*/ + KQLeaveRulesComInfo rulesComInfo = new KQLeaveRulesComInfo(); + + /*新建假期规则时选择完请假类型后会再次请求此表单接口*/ + /*规则对应的假期类型的ID*/ + String ruleId = Util.null2String(params.get("typeId")); + + /*是否启用:0-未启用、1-启用*/ + int isEnable = 1; + + /*最小请假单位:1-按天请假、2-按半天请假、3-按小时请假、4-按整天请假*/ + int minimumUnit = 1; + + /******************************************************************************/ + + /**假期规则详情的相关信息:*/ + + /*是否是编辑*/ + boolean isEdit = false; + + /*假期规则详情的ID*/ + String ruleDetailId = Util.null2String(params.get("ruleId")); + + /*假期规则名称*/ + String ruleName = ""; + + /*应用范围:0-总部、1-分部*/ + int scopeType = 0; + + /*应用范围为分部时,选择的分部ID*/ + String scopeValue = ""; + + /*余额发放方式:1-手动发放、2-按司龄自动发放、3-按工龄自动发放、4-每年自动发放固定天数、5-加班时长自动计入余额、6-按工龄+司龄自动发放*/ + int distributionMode = 1; + + //年假基数计算方式: + // 0(精确计算)-假期基数发放日期和假期基数变动日期均为每年的01月01号(但是假期基数是结合 司龄/工龄 变化前后的值按天数比例折算出来的)、 + // 1(按最少的余额计算)-假期基数发放日期和假期基数变动日期均为每年的01月01号、 + // 2(按最多的余额计算)-假期基数发放日期发放日期为每年的01月01号,假期基数的变动日期为每年的 入职日期/参加工作日期 + int calcMethod = 1; + + //是否折算:0-不折算、1-四舍五入、2-向上取整、3-向下取整、4-向上取0.5的倍数、向下取0.5的倍数 + int convertMode = 1; + + //折算后的小数点位数 + int decimalDigit = 2; + + /*每人发放小时(天)数(当余额发放方式为是每年发放固定天数时有效)*/ + double annualAmount = 0; + + //法定年假规则:0-工龄、1-司龄、2-工龄+司龄 (当余额发放方式为按工龄+司龄自动发放时有效) + String legalKey = "0"; + + //福利年假规则:0-工龄、1司龄、2-工龄+司龄 (当余额发放方式为按工龄+司龄自动发放时有效) + String welfareKey = "1"; + + /*扣减优先级:1-法定年假、2-福利年假(当余额发放方式为按工龄+司龄自动发放时有效)*/ + int priority = 1; + + //有效期规则:0-永久有效、1-按自然年(1月1日-12月31日)、2-按入职日期起12个月、3-自定义次年失效日期、4、按天数失效、5-按季度失效、6-按月数失效 + int validityRule = 0; + + /*失效日期--月(当有效期规则选择自定义次年失效日期时有效)*/ + String expirationMonth = "1"; + + /*失效日期--日(当有效期规则选择自定义次年失效日期时有效)*/ + String expirationDay = "1"; + + //有效天数(当有效期规则选择自定义有效天数时) + String effectiveDays = "30"; + + //有效月数(当有效期规则选择自定义有效月数时) + String effectiveMonths = "1"; + + /*允许延长有效期:0-不允许、1-允许*/ + int extensionEnable = 0; + + /*允许超过有效期天数*/ + int extendedDays = 90; + + /*释放规则:0-不限制、1-按天释放、2-按月释放*/ + int releaseRule = 0; + + //是否需要排除次账号:0--不排除,即次账号正常享受年假、1--排除,即次账号不能享受年假 + int excludeSubAccount = 1; + + //转正之前是否允许发放假期余额:0-不允许、1-允许 + int beforeFormal = 1; + + /*入职时长--年假*/ + Map entryMap = new HashMap(); + List entryList = new ArrayList(); + + /*工龄--年假*/ + Map workingAgeMap = new HashMap(); + List workingAgeList = new ArrayList(); + + /*入职时长+工龄混合--年假*/ + Map mixedModeMap = new HashMap(); + List mixedModeList = new ArrayList(); + + if (!ruleDetailId.equals("")) { + String sql = "select * from kq_LeaveRulesDetail where (isDelete is null or isDelete != 1) and id=" + ruleDetailId; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql); + if (recordSet.next()) { + isEdit = true; + + ruleName = recordSet.getString("ruleName"); + ruleId = recordSet.getString("ruleId"); + scopeType = recordSet.getInt("scopeType"); + scopeValue = recordSet.getString("scopeValue"); + distributionMode = Util.getIntValue(recordSet.getString("distributionMode"), 1); + annualAmount = Util.getDoubleValue(recordSet.getString("annualAmount"), 0); + legalKey = "" + Util.getIntValue(recordSet.getString("legalKey"), 0); + welfareKey = "" + Util.getIntValue(recordSet.getString("welfareKey"), 1); + priority = Util.getIntValue(recordSet.getString("priority"), 1); + validityRule = Util.getIntValue(recordSet.getString("validityRule"), 0); + effectiveDays = Util.null2s(recordSet.getString("effectiveDays"), "30"); + effectiveMonths = Util.null2s(recordSet.getString("effectiveMonths"),"1"); + expirationMonth = Util.null2s(recordSet.getString("expirationMonth"), "1"); + expirationDay = Util.null2s(recordSet.getString("expirationDay"), "1"); + extensionEnable = Util.getIntValue(recordSet.getString("extensionEnable"), 0); + extendedDays = Util.getIntValue(recordSet.getString("extendedDays"), 90); + releaseRule = Util.getIntValue(recordSet.getString("releaseRule"), 0); + calcMethod = Util.getIntValue(recordSet.getString("calcMethod"), 1); + convertMode = Util.getIntValue(recordSet.getString("convertMode"), 1); + excludeSubAccount = Util.getIntValue(recordSet.getString("excludeSubAccount"), 1); + beforeFormal = Util.getIntValue(recordSet.getString("beforeFormal"), 1); + } + + if (distributionMode == 2 || distributionMode == 7) { + sql = "select * from kq_EntryToLeave where leaveRulesId = ? order by lowerLimit,upperLimit"; + recordSet.executeQuery(sql, ruleDetailId); + int lowerLimit = 0;//入职年限下限 + int upperLimit = 0;//入职年限上限 + double amount = 0;//假期天数 + while (recordSet.next()) { + lowerLimit = recordSet.getInt("lowerLimit"); + upperLimit = recordSet.getInt("upperLimit"); + amount = Util.getDoubleValue(recordSet.getString("amount"), 0); + + entryMap = new HashMap(); + entryMap.put("timePoint", lowerLimit); + entryMap.put("amount", String.format("%.2f", amount)); + entryList.add(entryMap); + } + resultMap.put("detailRule", entryList); + } + + if (distributionMode == 3) { + sql = "select * from kq_WorkingAgeToLeave where leaveRulesId = ? order by lowerLimit,upperLimit"; + recordSet.executeQuery(sql, ruleDetailId); + int lowerLimit = 0;//工龄下限 + int upperLimit = 0;//工龄上限 + double amount = 0;//假期天数 + while (recordSet.next()) { + lowerLimit = recordSet.getInt("lowerLimit"); + upperLimit = recordSet.getInt("upperLimit"); + amount = Util.getDoubleValue(recordSet.getString("amount"), 0); + + workingAgeMap = new HashMap(); + workingAgeMap.put("timePoint", lowerLimit); + workingAgeMap.put("amount", String.format("%.2f", amount)); + workingAgeList.add(workingAgeMap); + } + resultMap.put("detailRule", workingAgeList); + } + + if (distributionMode == 6) { + sql = "select * from kq_MixModeToLegalLeave where leaveRulesId=? order by id "; + recordSet.executeQuery(sql, ruleDetailId); + double limit1 = 0;//工龄下限 + double limit2 = 0;//司龄下限 + double amount = 0;//法定年假天数or福利年假天数 + while (recordSet.next()) { + limit1 = Util.getDoubleValue(recordSet.getString("limit1"), 0); + limit2 = Util.getDoubleValue(recordSet.getString("limit2"), 0); + amount = Util.getDoubleValue(recordSet.getString("amount"), 0); + + mixedModeMap = new HashMap(); + if (legalKey.equals("0") || legalKey.equals("2")) { + mixedModeMap.put("workYear", limit1); + } + if (legalKey.equals("1") || legalKey.equals("2")) { + mixedModeMap.put("entryTime", limit2); + } + mixedModeMap.put("legalAmount", String.format("%.2f", amount)); + mixedModeList.add(mixedModeMap); + } + resultMap.put("legalRule", mixedModeList); + resultMap.put("legalKey", legalKey); + + mixedModeList = new ArrayList(); + sql = "select * from kq_MixModeToWelfareLeave where leaveRulesId=? order by id "; + recordSet.executeQuery(sql, ruleDetailId); + while (recordSet.next()) { + limit1 = Util.getDoubleValue(recordSet.getString("limit1"), 0); + limit2 = Util.getDoubleValue(recordSet.getString("limit2"), 0); + amount = Util.getDoubleValue(recordSet.getString("amount"), 0); + + mixedModeMap = new HashMap(); + if (welfareKey.equals("0") || welfareKey.equals("2")) { + mixedModeMap.put("workYear", limit1); + } + if (welfareKey.equals("1") || welfareKey.equals("2")) { + mixedModeMap.put("entryTime", limit2); + } + mixedModeMap.put("welfareAmount", String.format("%.2f", amount)); + mixedModeList.add(mixedModeMap); + } + resultMap.put("welfareRule", mixedModeList); + resultMap.put("welfareKey", welfareKey); + } + } + + if (isEdit) { + isEnable = Util.getIntValue(rulesComInfo.getIsEnable(ruleId), 1); + } + + List> groupList = new ArrayList>(); + Map groupItem = new HashMap(); + List itemList = new ArrayList(); + HrmFieldSearchConditionComInfo hrmFieldSearchConditionComInfo = new HrmFieldSearchConditionComInfo(); + SearchConditionItem searchConditionItem = null; + HrmFieldBean hrmFieldBean = null; + + /****************************************************基本信息****************************************************/ + + groupItem.put("title", SystemEnv.getHtmlLabelName(1361, user.getLanguage())); + groupItem.put("defaultshow", true); + + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname("typeId");//假期类型 + hrmFieldBean.setFieldlabel("129811"); + hrmFieldBean.setFieldhtmltype("5"); + hrmFieldBean.setType("1"); + hrmFieldBean.setFieldvalue(ruleId); + hrmFieldBean.setIsFormField(true); + hrmFieldBean.setViewAttr(isEnable == 0 || isEdit ? 1 : 3); + searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + List optionsList = new ArrayList(); + if (!isEdit) { + rulesComInfo.setTofirstRow(); + while (rulesComInfo.next()) { + if (!rulesComInfo.getIsEnable().equals("1") || !rulesComInfo.getBalanceEnable().equals("1")) { + continue; + } + optionsList.add(new SearchConditionOption(rulesComInfo.getId(), Util.formatMultiLang(rulesComInfo.getLeaveName(), "" + user.getLanguage()), ruleId.equals(rulesComInfo.getId()))); + } + } else { + optionsList.add(new SearchConditionOption(ruleId, Util.formatMultiLang(rulesComInfo.getLeaveName(ruleId), "" + user.getLanguage()), true)); + } + searchConditionItem.setOptions(optionsList); + searchConditionItem.setHelpfulTip(SystemEnv.getHtmlLabelName(505298, user.getLanguage()));//只能选择启用状态下开启了假期余额的假期类型,并且编辑假期规则时不能变更假期类型 + searchConditionItem.setRules("required|string"); + if (hrmFieldBean.getViewAttr() == 1) { + Map OtherParamsMap = new HashMap(); + OtherParamsMap.put("hasBorder", true); + searchConditionItem.setOtherParams(OtherParamsMap); + } + itemList.add(searchConditionItem); + + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname("ruleName");//规则名称 + hrmFieldBean.setFieldlabel("19829"); + hrmFieldBean.setFieldhtmltype("1"); + hrmFieldBean.setType("1"); + hrmFieldBean.setFieldvalue(ruleName); + hrmFieldBean.setIsFormField(true); + hrmFieldBean.setViewAttr(isEnable == 0 ? 1 : 3); + searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + searchConditionItem.setRules("required|string"); + if (hrmFieldBean.getViewAttr() == 1) { + Map OtherParamsMap = new HashMap(); + OtherParamsMap.put("hasBorder", true); + searchConditionItem.setOtherParams(OtherParamsMap); + } + itemList.add(searchConditionItem); + + /*应用范围是否能够选择总部,如果已经新建过总部的假期规则,则无法新建总部的假期规则*/ + boolean canSelectCom = true; + /*已经新建过某分部的假期规则,则无法继续新建该分部的假期规则*/ + String selectedSubcomIds = ""; + /*新建假期规则的时候选择完假期类型后重亲请求了此接口*/ + if (!ruleId.equals("") && !isEdit) { + String sql = "select * from kq_LeaveRulesDetail where (isDelete is null or isDelete<>1) and ruleId=?"; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql, ruleId); + while (recordSet.next()) { + int scopeTypeTemp = Util.getIntValue(recordSet.getString("scopeType"), 0); + String scopeValueTemp = recordSet.getString("scopeValue"); + + if (scopeTypeTemp == 0) { + canSelectCom = false; + } + if (scopeTypeTemp == 1) { + selectedSubcomIds += "," + scopeValueTemp; + } + } + } + selectedSubcomIds = selectedSubcomIds.length() > 0 ? selectedSubcomIds.substring(1) : ""; + + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname("scopeType");//此规则适用范围 + hrmFieldBean.setFieldlabel("19374"); + hrmFieldBean.setFieldhtmltype("5"); + hrmFieldBean.setType("1"); + hrmFieldBean.setIsFormField(true); + hrmFieldBean.setViewAttr(isEnable == 0 || !canSelectCom ? 1 : 3); + searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + optionsList = new ArrayList(); + optionsList.add(new SearchConditionOption("0", SystemEnv.getHtmlLabelName(140, user.getLanguage()), scopeType == 0 || !canSelectCom)); + optionsList.add(new SearchConditionOption("1", SystemEnv.getHtmlLabelName(33553, user.getLanguage()), scopeType == 1)); + searchConditionItem.setOptions(optionsList); + //对于一个请假类型,各分部能够且仅能够设置一个属于本分部的假期规则,如果未设置本分部的假期规则,默认取总部的假期规则,如果总部也未设置,则假期基数视作0.00 + searchConditionItem.setHelpfulTip(SystemEnv.getHtmlLabelName(505299, user.getLanguage())); + searchConditionItem.setRules("required|string"); + if (hrmFieldBean.getViewAttr() == 1) { + Map OtherParamsMap = new HashMap(); + OtherParamsMap.put("hasBorder", true); + searchConditionItem.setOtherParams(OtherParamsMap); + } + itemList.add(searchConditionItem); + + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname("scopeValue");//分部 + hrmFieldBean.setFieldlabel("33553"); + hrmFieldBean.setFieldhtmltype("3"); + hrmFieldBean.setType("170"); + hrmFieldBean.setFieldvalue(scopeValue); + hrmFieldBean.setIsFormField(true); + hrmFieldBean.setViewAttr(isEnable == 0 ? 1 : 3); + searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + searchConditionItem.getBrowserConditionParam().getDataParams().put("rightStr", "KQLeaveRulesAdd:Add"); + if (selectedSubcomIds.length() > 0) { + XssUtil xssUtil = new XssUtil(); + String sqlWhere = " id not in (" + selectedSubcomIds + ") "; + searchConditionItem.getBrowserConditionParam().getDataParams().put("sqlWhere", xssUtil.put(sqlWhere)); + searchConditionItem.getBrowserConditionParam().getCompleteParams().put("sqlWhere", xssUtil.put(sqlWhere)); + searchConditionItem.getBrowserConditionParam().getDestDataParams().put("sqlWhere", xssUtil.put(sqlWhere)); + } + searchConditionItem.setRules("required|string"); + if (hrmFieldBean.getViewAttr() == 1) { + Map OtherParamsMap = new HashMap(); + OtherParamsMap.put("hasBorder", true); + searchConditionItem.setOtherParams(OtherParamsMap); + } + itemList.add(searchConditionItem); + + groupItem.put("items", itemList); + groupList.add(groupItem); + + /****************************************************发放规则****************************************************/ + + groupItem = new HashMap(); + itemList = new ArrayList(); + groupItem.put("title", SystemEnv.getHtmlLabelName(508539, user.getLanguage())); + groupItem.put("defaultshow", true); + + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname("distributionMode");//余额发放方式 + hrmFieldBean.setFieldlabel("388946"); + hrmFieldBean.setFieldhtmltype("5"); + hrmFieldBean.setType("1"); + hrmFieldBean.setIsFormField(true); + hrmFieldBean.setViewAttr((isEnable == 0 || (isEdit && distributionMode == 6)) ? 1 : 3); + searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + optionsList = new ArrayList(); + optionsList.add(new SearchConditionOption("1", SystemEnv.getHtmlLabelName(388947, user.getLanguage()), distributionMode == 1)); + optionsList.add(new SearchConditionOption("2", SystemEnv.getHtmlLabelName(390374, user.getLanguage()), distributionMode == 2)); + optionsList.add(new SearchConditionOption("3", SystemEnv.getHtmlLabelName(388949, user.getLanguage()), distributionMode == 3)); + optionsList.add(new SearchConditionOption("4", SystemEnv.getHtmlLabelName(390323, user.getLanguage()), distributionMode == 4)); + optionsList.add(new SearchConditionOption("5", SystemEnv.getHtmlLabelName(388951, user.getLanguage()), distributionMode == 5)); + SearchConditionOption searchConditionOption = new SearchConditionOption("6", SystemEnv.getHtmlLabelName(390822, user.getLanguage()), distributionMode == 6); + searchConditionOption.setDisabled((isEdit && distributionMode != 6) ? true : false); + optionsList.add(searchConditionOption); + optionsList.add(new SearchConditionOption("7", SystemEnv.getHtmlLabelName(514025, user.getLanguage()), distributionMode == 7)); + optionsList.add(new SearchConditionOption("8", SystemEnv.getHtmlLabelName(536880, user.getLanguage()), distributionMode == 8)); + + //增加加班调休规则 + optionsList.add(new SearchConditionOption("9", "工作日加班时长自动计入", distributionMode == 9)); + optionsList.add(new SearchConditionOption("10", "休息日加班时长自动计入", distributionMode == 10)); + + searchConditionItem.setOptions(optionsList); + searchConditionItem.setHelpfulTip("★" + SystemEnv.getHtmlLabelName(10000815,user.getLanguage()) + "★" + SystemEnv.getHtmlLabelName(501107, user.getLanguage())); + if (hrmFieldBean.getViewAttr() == 1) { + Map OtherParamsMap = new HashMap(); + OtherParamsMap.put("hasBorder", true); + searchConditionItem.setOtherParams(OtherParamsMap); + } + itemList.add(searchConditionItem); + + List distributionModeTips = new ArrayList(); + distributionModeTips.add(SystemEnv.getHtmlLabelName(389735, user.getLanguage()) + " " + SystemEnv.getHtmlLabelName(511045, user.getLanguage()) + ""); + distributionModeTips.add(SystemEnv.getHtmlLabelName(500952, user.getLanguage()) + " " + SystemEnv.getHtmlLabelName(511045, user.getLanguage()) + ""); + distributionModeTips.add(SystemEnv.getHtmlLabelName(500953, user.getLanguage()) + " " + SystemEnv.getHtmlLabelName(511046, user.getLanguage()) + ""); + distributionModeTips.add(SystemEnv.getHtmlLabelName(389736, user.getLanguage()) + " " + SystemEnv.getHtmlLabelName(511045, user.getLanguage()) + ""); + distributionModeTips.add(SystemEnv.getHtmlLabelName(389737, user.getLanguage()) + " " + SystemEnv.getHtmlLabelName(511045, user.getLanguage()) + ""); + distributionModeTips.add(SystemEnv.getHtmlLabelName(500954, user.getLanguage()) + " " + SystemEnv.getHtmlLabelName(511046, user.getLanguage()) + ""); + distributionModeTips.add(SystemEnv.getHtmlLabelName(514026, user.getLanguage()) + " " + SystemEnv.getHtmlLabelName(511045, user.getLanguage()) + ""); + distributionModeTips.add(SystemEnv.getHtmlLabelName(536881, user.getLanguage())); + resultMap.put("distributionMode", distributionModeTips); + + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname("calcMethod");//假期基数计算方式 + hrmFieldBean.setFieldlabel("501121"); + hrmFieldBean.setFieldhtmltype("5"); + hrmFieldBean.setType("1"); + hrmFieldBean.setIsFormField(true); + hrmFieldBean.setViewAttr(isEnable == 0 ? 1 : 3); + searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + optionsList = new ArrayList(); + optionsList.add(new SearchConditionOption("0", SystemEnv.getHtmlLabelName(505302, user.getLanguage()), calcMethod == 0)); + optionsList.add(new SearchConditionOption("1", SystemEnv.getHtmlLabelName(505303, user.getLanguage()), calcMethod == 1)); + optionsList.add(new SearchConditionOption("2", SystemEnv.getHtmlLabelName(505304, user.getLanguage()), calcMethod == 2)); + searchConditionItem.setOptions(optionsList); + if (hrmFieldBean.getViewAttr() == 1) { + Map OtherParamsMap = new HashMap(); + OtherParamsMap.put("hasBorder", true); + searchConditionItem.setOtherParams(OtherParamsMap); + } + itemList.add(searchConditionItem); + + List calcMethodTips = new ArrayList(); + //以入职日期(或参加工作日期)为分隔点将一年划分为上半年和下半年,全年可用假期天数=上半年天数/全年总天数*上半年司龄(或工龄)对应的假期天数+下半年天数/全年总天数*下半年司龄(或工龄)对应的假期天数。每年1月1日自动发放假期天数。 + calcMethodTips.add(SystemEnv.getHtmlLabelName(505305, user.getLanguage())); + //每年1月1日计算员工的司龄(或工龄),取对应的假期天数,于1月1日自动发放。 + calcMethodTips.add(SystemEnv.getHtmlLabelName(505306, user.getLanguage())); + //每年1月1日计算员工的司龄(或工龄),取对应的假期天数,于1月1日自动发放。若一年中员工司龄(或工龄)增加后,对应的假期天数也随之增加,则自动补发增加的假期天数。 + calcMethodTips.add(SystemEnv.getHtmlLabelName(505307, user.getLanguage())); + resultMap.put("calcMethod", calcMethodTips); + + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname("priority");//扣减优先级 + hrmFieldBean.setFieldlabel("2093"); + hrmFieldBean.setFieldhtmltype("5"); + hrmFieldBean.setType("1"); + hrmFieldBean.setIsFormField(true); + hrmFieldBean.setViewAttr(isEnable == 0 ? 1 : 3); + searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + optionsList = new ArrayList(); + optionsList.add(new SearchConditionOption("1", SystemEnv.getHtmlLabelName(129819, user.getLanguage()), priority == 1)); + optionsList.add(new SearchConditionOption("2", SystemEnv.getHtmlLabelName(132046, user.getLanguage()), priority == 2)); + searchConditionItem.setOptions(optionsList); + if (hrmFieldBean.getViewAttr() == 1) { + Map OtherParamsMap = new HashMap(); + OtherParamsMap.put("hasBorder", true); + searchConditionItem.setOtherParams(OtherParamsMap); + } + itemList.add(searchConditionItem); + + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname("annualAmount");//每人发放小时数 + hrmFieldBean.setFieldlabel("503237"); + hrmFieldBean.setFieldhtmltype("1"); + hrmFieldBean.setType("2"); + hrmFieldBean.setFieldvalue(annualAmount); + hrmFieldBean.setIsFormField(true); + hrmFieldBean.setViewAttr(isEnable == 0 ? 1 : 3); + searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + searchConditionItem.setRules("required|numeric"); + searchConditionItem.setPrecision(2); + searchConditionItem.setMin("0"); + if (hrmFieldBean.getViewAttr() == 1) { + Map OtherParamsMap = new HashMap(); + OtherParamsMap.put("hasBorder", true); + searchConditionItem.setOtherParams(OtherParamsMap); + } + itemList.add(searchConditionItem); + + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname("convertMode");//是否折算 + hrmFieldBean.setFieldlabel("508419"); + hrmFieldBean.setFieldhtmltype("5"); + hrmFieldBean.setType("1"); + hrmFieldBean.setIsFormField(true); + hrmFieldBean.setViewAttr(isEnable == 0 ? 1 : 3); + searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + optionsList = new ArrayList(); + optionsList.add(new SearchConditionOption("0", SystemEnv.getHtmlLabelName(508423, user.getLanguage()), convertMode == 0)); + optionsList.add(new SearchConditionOption("1", SystemEnv.getHtmlLabelName(389654, user.getLanguage()), convertMode == 1)); + optionsList.add(new SearchConditionOption("2", SystemEnv.getHtmlLabelName(508424, user.getLanguage()), convertMode == 2)); + optionsList.add(new SearchConditionOption("3", SystemEnv.getHtmlLabelName(508425, user.getLanguage()), convertMode == 3)); + optionsList.add(new SearchConditionOption("4", SystemEnv.getHtmlLabelName(508426, user.getLanguage()), convertMode == 4)); + optionsList.add(new SearchConditionOption("5", SystemEnv.getHtmlLabelName(508427, user.getLanguage()), convertMode == 5)); + searchConditionItem.setOptions(optionsList); + //当假期基数计算方式选择【精确计算】时,不能选择【不折算】 + searchConditionItem.setHelpfulTip(SystemEnv.getHtmlLabelName(510491, user.getLanguage())); + if (hrmFieldBean.getViewAttr() == 1) { + Map OtherParamsMap = new HashMap(); + OtherParamsMap.put("hasBorder", true); + searchConditionItem.setOtherParams(OtherParamsMap); + } + itemList.add(searchConditionItem); + + List convertModeTips = new ArrayList(); + //指不考虑是否是入职当年还是初始获得年(即年初01月01日的时候计算工龄或者司龄,得出对应的假期基数为0。但是当这一年的工龄或者司龄增加后,对应的假期基数就不再是0了,这样的年份称作初始获得年),通过工龄或司龄计算出对应的假期基数,不做任何扣减折算 + convertModeTips.add(SystemEnv.getHtmlLabelName(510131, user.getLanguage())); + //通过工龄或司龄计算出对应的假期基数后(若是入职当年或初始获得年会进行扣减折算),折算后四舍五入保留两位小数 + convertModeTips.add(SystemEnv.getHtmlLabelName(510132, user.getLanguage())); + //通过工龄或司龄计算出对应的假期基数后(若是入职当年或初始获得年会进行扣减折算),折算后的数值取整,例如:折算后的基数为3.21,取整后为4.0 + convertModeTips.add(SystemEnv.getHtmlLabelName(510133, user.getLanguage())); + //通过工龄或司龄计算出对应的假期基数后(若是入职当年或初始获得年会进行扣减折算),折算后的数值取整,例如:折算后的基数为3.21,取整后为3.0 + convertModeTips.add(SystemEnv.getHtmlLabelName(510134, user.getLanguage())); + //通过工龄或司龄计算出对应的假期基数后(若是入职当年或初始获得年会进行扣减折算),折算后的数值取0.5的倍数,例如:折算后的基数为3.21,最终为3.5 + convertModeTips.add(SystemEnv.getHtmlLabelName(510135, user.getLanguage())); + //通过工龄或司龄计算出对应的假期基数后(若是入职当年或初始获得年会进行扣减折算),折算后的数值取0.5的倍数,例如:折算后的基数为3.21,最终后为3.0 + convertModeTips.add(SystemEnv.getHtmlLabelName(510136, user.getLanguage())); + resultMap.put("convertModeTips", convertModeTips); + + groupItem.put("items", itemList); + groupList.add(groupItem); + + /****************************************************有效期****************************************************/ + + groupItem = new HashMap(); + itemList = new ArrayList(); + groupItem.put("title", SystemEnv.getHtmlLabelName(15030, user.getLanguage())); + groupItem.put("defaultshow", true); + + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname("validityRule");//有效期规则 + hrmFieldBean.setFieldlabel("388952"); + hrmFieldBean.setFieldhtmltype("5"); + hrmFieldBean.setType("1"); + hrmFieldBean.setIsFormField(true); + hrmFieldBean.setViewAttr(isEnable == 0 ? 1 : 3); + searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + optionsList = new ArrayList(); + optionsList.add(new SearchConditionOption("0", SystemEnv.getHtmlLabelName(22135, user.getLanguage()), validityRule == 0)); + optionsList.add(new SearchConditionOption("1", SystemEnv.getHtmlLabelName(388953, user.getLanguage()), validityRule == 1)); + optionsList.add(new SearchConditionOption("2", SystemEnv.getHtmlLabelName(388954, user.getLanguage()), validityRule == 2)); + optionsList.add(new SearchConditionOption("3", SystemEnv.getHtmlLabelName(389739, user.getLanguage()), validityRule == 3)); + optionsList.add(new SearchConditionOption("4", SystemEnv.getHtmlLabelName(508428, user.getLanguage()), validityRule == 4)); + optionsList.add(new SearchConditionOption("5", SystemEnv.getHtmlLabelName(513525, user.getLanguage()), validityRule == 5)); + optionsList.add(new SearchConditionOption("6", SystemEnv.getHtmlLabelName(515135, user.getLanguage()), validityRule == 6)); + optionsList.add(new SearchConditionOption("7", SystemEnv.getHtmlLabelName(536941, user.getLanguage()), validityRule == 7)); + searchConditionItem.setOptions(optionsList); + searchConditionItem.setHelpfulTip(SystemEnv.getHtmlLabelName(515354, user.getLanguage())); + if (hrmFieldBean.getViewAttr() == 1) { + Map OtherParamsMap = new HashMap(); + OtherParamsMap.put("hasBorder", true); + searchConditionItem.setOtherParams(OtherParamsMap); + } + itemList.add(searchConditionItem); + + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname("effectiveDays");//有效月数 + hrmFieldBean.setFieldlabel("132356"); + hrmFieldBean.setFieldhtmltype("1"); + hrmFieldBean.setType("2"); + hrmFieldBean.setFieldvalue(effectiveDays); + hrmFieldBean.setIsFormField(true); + hrmFieldBean.setViewAttr(isEnable == 0 ? 1 : 3); + searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + searchConditionItem.setRules("required|integer"); + searchConditionItem.setMin("1"); + if (hrmFieldBean.getViewAttr() == 1) { + Map OtherParamsMap = new HashMap(); + OtherParamsMap.put("hasBorder", true); + searchConditionItem.setOtherParams(OtherParamsMap); + } + itemList.add(searchConditionItem); + + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname("effectiveMonths");//有效月数 + hrmFieldBean.setFieldlabel("515174"); + hrmFieldBean.setFieldhtmltype("1"); + hrmFieldBean.setType("2"); + hrmFieldBean.setFieldvalue(effectiveMonths); + hrmFieldBean.setIsFormField(true); + hrmFieldBean.setViewAttr(isEnable == 0 ? 1 : 3); + searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + searchConditionItem.setRules("required|integer"); + searchConditionItem.setMin("1"); + if (hrmFieldBean.getViewAttr() == 1) { + Map OtherParamsMap = new HashMap(); + OtherParamsMap.put("hasBorder", true); + searchConditionItem.setOtherParams(OtherParamsMap); + } + itemList.add(searchConditionItem); + + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname("expirationMonth");//失效日期--月 + hrmFieldBean.setFieldlabel("390103"); + hrmFieldBean.setFieldhtmltype("5"); + hrmFieldBean.setType("1"); + hrmFieldBean.setFieldvalue(expirationMonth); + hrmFieldBean.setIsFormField(true); + hrmFieldBean.setViewAttr(isEnable == 0 ? 1 : 3); + searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + optionsList = new ArrayList(); + for (int i = 1; i <= 12; i++) { + if(user.getLanguage()==8){ + optionsList.add(new SearchConditionOption("" + i, i+"", Util.getIntValue(expirationMonth, 1) == i)); + }else { + optionsList.add(new SearchConditionOption("" + i, i + SystemEnv.getHtmlLabelName(383373, user.getLanguage()), Util.getIntValue(expirationMonth, 1) == i)); + } + } + searchConditionItem.setOptions(optionsList); + searchConditionItem.setRules("required|string"); + if (hrmFieldBean.getViewAttr() == 1) { + Map OtherParamsMap = new HashMap(); + OtherParamsMap.put("hasBorder", true); + searchConditionItem.setOtherParams(OtherParamsMap); + } + itemList.add(searchConditionItem); + + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname("expirationDay");//失效日期--日 + hrmFieldBean.setFieldlabel("390103"); + hrmFieldBean.setFieldhtmltype("5"); + hrmFieldBean.setType("1"); + hrmFieldBean.setFieldvalue(expirationDay); + hrmFieldBean.setIsFormField(true); + hrmFieldBean.setViewAttr(isEnable == 0 ? 1 : 3); + searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + optionsList = new ArrayList(); + for (int i = 1; i <= 31; i++) { + if(user.getLanguage()==8){ + optionsList.add(new SearchConditionOption("" + i, i+"", Util.getIntValue(expirationMonth, 1) == i)); + }else { + optionsList.add(new SearchConditionOption("" + i, i + SystemEnv.getHtmlLabelName(390, user.getLanguage()), Util.getIntValue(expirationDay, 1) == i)); + } + } + searchConditionItem.setOptions(optionsList); + searchConditionItem.setRules("required|string"); + if (hrmFieldBean.getViewAttr() == 1) { + Map OtherParamsMap = new HashMap(); + OtherParamsMap.put("hasBorder", true); + searchConditionItem.setOtherParams(OtherParamsMap); + } + itemList.add(searchConditionItem); + + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname("extensionEnable");//允许延长有效期 + hrmFieldBean.setFieldlabel("388955"); + hrmFieldBean.setFieldhtmltype("4"); + hrmFieldBean.setType("1"); + hrmFieldBean.setFieldvalue(extensionEnable); + hrmFieldBean.setIsFormField(true); + hrmFieldBean.setViewAttr(isEnable == 0 ? 1 : 2); + searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + Map otherParamsMap = new HashMap(); + otherParamsMap.put("display", "switch"); + searchConditionItem.setOtherParams(otherParamsMap); + if (hrmFieldBean.getViewAttr() == 1) { + Map OtherParamsMap = new HashMap(); + OtherParamsMap.put("hasBorder", true); + searchConditionItem.setOtherParams(OtherParamsMap); + } + itemList.add(searchConditionItem); + + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname("extendedDays");//允许延长的天数 + hrmFieldBean.setFieldlabel("389198"); + hrmFieldBean.setFieldhtmltype("1"); + hrmFieldBean.setType("2"); + hrmFieldBean.setFieldvalue(extendedDays); + hrmFieldBean.setIsFormField(true); + hrmFieldBean.setViewAttr(isEnable == 0 ? 1 : 3); + searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + searchConditionItem.setRules("required|integer"); + if (hrmFieldBean.getViewAttr() == 1) { + Map OtherParamsMap = new HashMap(); + OtherParamsMap.put("hasBorder", true); + searchConditionItem.setOtherParams(OtherParamsMap); + } + itemList.add(searchConditionItem); + + groupItem.put("items", itemList); + groupList.add(groupItem); + + /****************************************************其他设置****************************************************/ + + groupItem = new HashMap(); + itemList = new ArrayList(); + groupItem.put("title", SystemEnv.getHtmlLabelName(20824, user.getLanguage())); + groupItem.put("defaultshow", true); + + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname("releaseRule");//释放规则 + hrmFieldBean.setFieldlabel("389093"); + hrmFieldBean.setFieldhtmltype("5"); + hrmFieldBean.setType("1"); + hrmFieldBean.setIsFormField(true); + hrmFieldBean.setViewAttr(isEnable == 0 ? 1 : 3); + searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + optionsList = new ArrayList(); + optionsList.add(new SearchConditionOption("0", SystemEnv.getHtmlLabelName(32499, user.getLanguage()), releaseRule == 0)); + optionsList.add(new SearchConditionOption("1", SystemEnv.getHtmlLabelName(127263, user.getLanguage()), releaseRule == 1)); + optionsList.add(new SearchConditionOption("2", SystemEnv.getHtmlLabelName(127262, user.getLanguage()), releaseRule == 2)); + searchConditionItem.setOptions(optionsList); + if (hrmFieldBean.getViewAttr() == 1) { + Map OtherParamsMap = new HashMap(); + OtherParamsMap.put("hasBorder", true); + searchConditionItem.setOtherParams(OtherParamsMap); + } + searchConditionItem.setHelpfulTip(SystemEnv.getHtmlLabelName(510129, user.getLanguage())); + itemList.add(searchConditionItem); + + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname("excludeSubAccount");//次账号发放假期余额 + hrmFieldBean.setFieldlabel("510174"); + hrmFieldBean.setFieldhtmltype("4"); + hrmFieldBean.setType("1"); + hrmFieldBean.setFieldvalue(excludeSubAccount); + hrmFieldBean.setIsFormField(true); + hrmFieldBean.setViewAttr(isEnable == 0 ? 1 : 2); + searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + otherParamsMap = new HashMap(); + otherParamsMap.put("display", "switch"); + searchConditionItem.setOtherParams(otherParamsMap); + if (hrmFieldBean.getViewAttr() == 1) { + Map OtherParamsMap = new HashMap(); + OtherParamsMap.put("hasBorder", true); + searchConditionItem.setOtherParams(OtherParamsMap); + } + itemList.add(searchConditionItem); + + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname("beforeFormal");//转正之前发放假期余额 + hrmFieldBean.setFieldlabel("510175"); + hrmFieldBean.setFieldhtmltype("4"); + hrmFieldBean.setType("1"); + hrmFieldBean.setFieldvalue(beforeFormal); + hrmFieldBean.setIsFormField(true); + hrmFieldBean.setViewAttr(isEnable == 0 ? 1 : 2); + searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + otherParamsMap = new HashMap(); + otherParamsMap.put("display", "switch"); + searchConditionItem.setOtherParams(otherParamsMap); + if (hrmFieldBean.getViewAttr() == 1) { + Map OtherParamsMap = new HashMap(); + OtherParamsMap.put("hasBorder", true); + searchConditionItem.setOtherParams(OtherParamsMap); + } + itemList.add(searchConditionItem); + + groupItem.put("items", itemList); + groupList.add(groupItem); + resultMap.put("condition", groupList); + resultMap.put("isEnable", "" + isEnable); + if (isEdit) { + minimumUnit = Util.getIntValue(rulesComInfo.getMinimumUnit(ruleId), 1); + + String unitName = "";//单位名称,天/小时 + if (minimumUnit == 1 || minimumUnit == 2 || minimumUnit == 4) { + unitName = SystemEnv.getHtmlLabelName(1925, user.getLanguage());//天 + } else { + unitName = SystemEnv.getHtmlLabelName(391, user.getLanguage());//小时 + } + resultMap.put("unitName", unitName); + } + } catch (Exception e) { + e.printStackTrace(); + } + return resultMap; + } +} diff --git a/src/com/engine/kq/cmd/myattendance/GetHrmKQMonthReportInfoCmd.java b/src/com/engine/kq/cmd/myattendance/GetHrmKQMonthReportInfoCmd.java new file mode 100644 index 0000000..5c55aff --- /dev/null +++ b/src/com/engine/kq/cmd/myattendance/GetHrmKQMonthReportInfoCmd.java @@ -0,0 +1,1089 @@ +package com.engine.kq.cmd.myattendance; + +import com.api.hrm.bean.KQReportType; +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.entity.WorkTimeEntity; +import com.engine.kq.enums.KqSplitFlowTypeEnum; +import com.engine.kq.wfset.util.SplitActionUtil; +import com.engine.kq.wfset.util.SplitSelectSet; +import org.apache.commons.lang3.StringUtils; +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.Util; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; +import weaver.hrm.resource.ResourceComInfo; +import weaver.systeminfo.SystemEnv; + +import java.util.*; + +/** + * 前台--人事--我的考勤 + */ +public class GetHrmKQMonthReportInfoCmd extends AbstractCommonCommand> { + + public GetHrmKQMonthReportInfoCmd(Map params, User user) { + this.user = user; + this.params = params; + } + + private static boolean isIndirectSuperId(String id,String checkSuperId,ResourceComInfo info){ + + int loopBreakTimes = 20 ; + for(String loopId = id; + isRightResourceId(loopId) && (loopBreakTimes--)>0 ; + loopId = info.getManagerID(loopId)){ + if(isDirectSuperId(loopId,checkSuperId,info)) return true ; + } + return false ; + } + + private static boolean isDirectSuperId(String id,String checkSuperId,ResourceComInfo info){ + String superId = Util.null2String(info.getManagerID(id)) ; + return isRightResourceId(superId) && superId.equals(checkSuperId) ; + } + + private static boolean isRightResourceId(String id){ + return StringUtils.isNotBlank(id) && !"0".equals(id) ; + } + + /** + * 判断是否是组员或者考勤文员管理的人员 + * @param id + * @param checkSuperId + * @return + */ + private static boolean isTeamMembers(String id,String checkSuperId){ + boolean isMember = false; + String sql = " select id from cus_fielddata where id=? and field89=? "; + RecordSet rs = new RecordSet(); + rs.executeQuery(sql,id,checkSuperId); + if(rs.next()){ + isMember = true; + } + + String kqwySql = " select b.id from hrmdepartmentdefined a,hrmresource b " + + "where a.kqwy=? and a.deptid=b.departmentid and b.id=?"; + rs.executeQuery(kqwySql,checkSuperId,id); + if(rs.next()){ + isMember = true; + } + return isMember; + } + + @Override + public BizLogContext getLogContext() { + return null; + } + + @Override + public Map execute(CommandContext commandContext) { + Map resultMap = new HashMap(); + try { + String nowdate = DateUtil.getCurrentDate(); + String type = Util.null2String(params.get("type"));//是查看一年的数据还是一月的数据:1-年、2-月 + String typevalue = Util.null2String(params.get("typevalue"));//指定的年份或者指定的月份 + String fromDate = Util.null2String(params.get("fromDate"));//指定日期起点 + String toDate = Util.null2String(params.get("toDate"));//指定日期终点 + int subCompanyId = Util.getIntValue((String) params.get("subCompanyId"), 0);//指定查看的人员的所属分部 + int departmentId = Util.getIntValue((String) params.get("departmentId"), 0);//指定查看的人员的所属部门 + String resourceId = Util.null2String(params.get("resourceId"));//指定查看的人员ID + String status = Util.null2String(params.get("status"));//? + /** + * 若未指定查看人员,则默认为当前登录人员 + */ + if (resourceId.length() == 0) { + resourceId = "" + user.getUID(); + } + ResourceComInfo resourceComInfo = new ResourceComInfo(); + if (subCompanyId == 0 || departmentId == 0) { + subCompanyId = Util.getIntValue(resourceComInfo.getSubCompanyID(resourceId), 0); + departmentId = Util.getIntValue(resourceComInfo.getDepartmentID(resourceId), 0); + } + String lastName = resourceComInfo.getResourcename(resourceId); + if (resourceId.equals("" + user.getUID())) { + resultMap.put("title", SystemEnv.getHtmlLabelName(513535, user.getLanguage())); + } else { + resultMap.put("title", SystemEnv.getHtmlLabelName(515563, user.getLanguage()).replace("{name}", lastName)); + } + /** + * 判断是否有权限查看 + */ + //if (!resourceId.equals("" + user.getUID()) && !isIndirectSuperId(resourceId, user.getUID() + "", resourceComInfo) && !HrmUserVarify.checkUserRight("HrmResource:Absense", user, departmentId)) { + // resultMap.put("status", "-1"); + // resultMap.put("hasRight", false); + // return resultMap; + //} + + //二开线长查看组员考勤 + if (!resourceId.equals("" + user.getUID()) && !isTeamMembers(resourceId, user.getUID() + "") && !isIndirectSuperId(resourceId, user.getUID() + "", resourceComInfo) && !HrmUserVarify.checkUserRight("HrmResource:Absense", user, departmentId)) { + resultMap.put("status", "-1"); + resultMap.put("hasRight", false); + return resultMap; + } + + /** + * 获取指定日期范围的起点和终点 + */ + if (type.equals("1")) {//年 + if (typevalue.length() == 0 || typevalue.length() != 4) { + typevalue = DateUtil.getYear(); + } + fromDate = typevalue + "-01-01"; + toDate = DateUtil.getLastDayOfYear(DateUtil.parseToDate(fromDate)); + } else if (type.equals("2")) {//月 + if (typevalue.length() == 0) { + typevalue = DateUtil.getYear() + "-" + DateUtil.getMonth(); + } + fromDate = typevalue + "-01"; + toDate = DateUtil.getLastDayOfMonthToString(DateUtil.parseToDate(fromDate)); + } + + /**获取今天的日期*/ + 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); + + /**判断是否在考勤日历上显示签到签退数据*/ + boolean showSign = true; + String settingSql = "select * from KQ_SETTINGS where main_key='showSignOnCalendar'"; + RecordSet rs = new RecordSet(); + rs.executeQuery(settingSql); + if (rs.next()) { + String main_val = rs.getString("main_val"); + showSign = main_val.equals("1"); + } + + //签到签退明细 + Map signInfoMap = getSignInfo(); + List> signInfoList = new ArrayList>(); + //休息明细(统计工作日) + List isNotRestList = new ArrayList(); + //迟到明细 + List beLateList = new ArrayList(); + //早退明细 + List leaveEarlyList = new ArrayList(); + //旷工明细 + List absentList = new ArrayList(); + //漏签明细 + List noSignList = new ArrayList(); + //请假明细 + Map leaveMap = getFlowData(KqSplitFlowTypeEnum.LEAVE.getFlowtype()); + //出差明细 + Map evectionMap = getFlowData(KqSplitFlowTypeEnum.EVECTION.getFlowtype()); + //公出明细 + Map outDaysMap = getFlowData(KqSplitFlowTypeEnum.OUT.getFlowtype()); + //加班明细 + Map overtimeMap = getFlowData(KqSplitFlowTypeEnum.OVERTIME.getFlowtype()); + //调配工作日 + List workdayList = new ArrayList(); + //调配休息日、公众假日 + List holidayList = new ArrayList(); + + //二开 获取加班打卡数据 + Map overtimSignMap = getOvertimeSignInfo(fromDate,toDate); + + //获取节假日 + List> tempList = KQHolidaySetBiz.getHolidaySetListByScope(resourceId, fromDate, toDate); + for (Map tempMap : tempList) { + String date = Util.null2String(tempMap.get("date")); + int changeType = Util.getIntValue((String) tempMap.get("type"), 1); + if (changeType == 1 || changeType == 3) { + holidayList.add(date); + } else if (changeType == 2) { + workdayList.add(date); + } + } + + String sql = "select * from kq_format_detail where resourceId=" + resourceId + " and KQDate>='" + fromDate + "' and KQDate<='" + toDate + "' order by kqDate"; + RecordSet recordSet = new RecordSet(); + RecordSet detailRs = new RecordSet(); + recordSet.executeQuery(sql); + KQWorkTime kqWorkTime = new KQWorkTime(); + while (recordSet.next()) { + String kqDate = recordSet.getString("kqDate"); + String serialId = recordSet.getString("serialId"); + + WorkTimeEntity workTime = kqWorkTime.getWorkTime(resourceId,kqDate); + if (!isNotRestList.contains(kqDate) && !serialId.equals("")) { + isNotRestList.add(kqDate); + }else if(Util.null2String(workTime.getKQType()).equals("3")){ + if(workTime!=null&&Util.getIntValue(workTime.getWorkMins())>0) { + isNotRestList.add(kqDate); +// groupid = Util.null2String(workTime.getGroupId()); +// signstart = Util.null2String(workTime.getSignStart());//签到开始时间 +// workMins = Util.getIntValue(Util.null2String(workTime.getWorkMins()));//工作时长 + } + } + + int beLate = recordSet.getInt("beLateMins");//迟到 + int graveBeLate = recordSet.getInt("graveBeLateMins");//严重迟到 + int leaveEarly = recordSet.getInt("leaveEarlyMins");//早退 + int graveLeaveEarly = recordSet.getInt("graveLeaveEarlyMins");//严重早退 + int absenteeism = recordSet.getInt("absenteeismMins");//旷工 + int forgotCheck = recordSet.getInt("forgotCheckMins");//下班打卡漏签 + int forgotBeginWorkCheckMins = recordSet.getInt("forgotBeginWorkCheckMins");//上班打卡漏签 + if (absenteeism > 0) {//旷工 + absentList.add(kqDate); + } else { + if (beLate > 0 || graveBeLate > 0) { //迟到 + beLateList.add(kqDate); + } + if (leaveEarly > 0 || graveLeaveEarly > 0) {//早退 + leaveEarlyList.add(kqDate); + } + if (forgotCheck > 0 || forgotBeginWorkCheckMins > 0) {//漏签 + noSignList.add(kqDate); + } + } + } + + Map year = new HashMap(); + Map month = new HashMap(); + Map day = new HashMap(); + List types = new ArrayList(); + List> lsWorkflow = new ArrayList>(); + Map workflow = new HashMap(); + + boolean isEnd = false; + for (String date = fromDate; !isEnd; ) { + String tmpMonth = "" + Util.getIntValue(date.split("-")[1]); + String tmpDay = "" + Util.getIntValue(date.split("-")[2]); + if (date.compareTo(toDate) >= 0) { + isEnd = true; + } + /*如果是按年份查看*/ + if (type.equals("1")) { + if (!year.containsKey(tmpMonth)) { + month = new HashMap(); + year.put(tmpMonth, month); + } + } + + day = new HashMap(); + month.put(tmpDay, day); + if (isNotRestList.contains(date)) { + day.put("isWorkDay", true); + } else { + day.put("isWorkDay", false); + } + if (type.equals("1")) { + day.put("tip", ""); + } + if (holidayList.contains(date)) { + day.put("tip", SystemEnv.getHtmlLabelName(125806, user.getLanguage())); + day.put("isWorkDay", false); + } else if (workdayList.contains(date)) { + day.put("tip", SystemEnv.getHtmlLabelName(125807, user.getLanguage())); + day.put("isWorkDay", true); + } + day.put("date", date); + types = new ArrayList(); + if (type.equals("2")) { + day.put("types", types); + } + lsWorkflow = new ArrayList>(); + /*只有月视图才显示流程数据、只有月视图才把签到签退信息显示在日历上*/ + if (type.equals("2") && showSign) { + signInfoList = (List)signInfoMap.get(date); + if (signInfoList != null && signInfoList.size() > 0) { + day.put("signInfo", signInfoList); + } + } + /*只有月视图才显示流程数据*/ + if (type.equals("2")) { + day.put("workflow", lsWorkflow); + } + boolean isNormal = true; + //迟到明细 + if (beLateList.contains(date)) { + if (!types.contains(KQReportType.BELATE)) { + types.add(KQReportType.BELATE); + isNormal = false; + } + } + + //旷工明细 + if (absentList.contains(date)) { + if (!types.contains(KQReportType.ABSENT)) { + types.add(KQReportType.ABSENT); + isNormal = false; + } + } + + //早退明细 + if (leaveEarlyList.contains(date)) { + if (!types.contains(KQReportType.LEAVEEARLY)) { + types.add(KQReportType.LEAVEEARLY); + isNormal = false; + } + } + + //漏签明细 + if (noSignList.contains(date)) { + if (!types.contains(KQReportType.NOSIGN)) { + types.add(KQReportType.NOSIGN); + isNormal = false; + } + } + + //请假明细 + if (leaveMap.containsKey(resourceId + "|" + date)) { + if (!types.contains(KQReportType.LEAVE)) { + types.add(KQReportType.LEAVE); + isNormal = false; + } + tempList = (List>) leaveMap.get(resourceId + "|" + date); + for (Map tempMap : tempList) { + lsWorkflow.add(tempMap); + } + } + + //加班明细 二开增加打卡判断,有打卡才显示 + if (!Util.null2String(overtimeMap.get(resourceId + "|" + date)).equals("") && overtimSignMap.containsKey(resourceId + "|" + date) ) { + if (!types.contains(KQReportType.OVERTIME)) { + types.add(KQReportType.OVERTIME); + } + tempList = (List>) overtimeMap.get(resourceId + "|" + date); + for (Map tempMap : tempList) { + lsWorkflow.add(tempMap); + } + } + + //外出明细 + if (evectionMap.containsKey(resourceId + "|" + date)) { + if (!types.contains(KQReportType.EVECTION)) { + types.add(KQReportType.EVECTION); + isNormal = false; + } + tempList = (List>) evectionMap.get(resourceId + "|" + date); + for (Map tempMap : tempList) { + lsWorkflow.add(tempMap); + } + } + + //公出明细 + if (outDaysMap.containsKey(resourceId + "|" + date)) { + if (!types.contains(KQReportType.OUTDAYS)) { + types.add(KQReportType.OUTDAYS); + isNormal = false; + } + tempList = (List>) outDaysMap.get(resourceId + "|" + date); + for (Map tempMap : tempList) { + lsWorkflow.add(tempMap); + } + } + + if (isNotRestList.contains(date) && DateUtil.isInDateRange(date, fromDate, nowdate)) { + if (isNormal) { + types.add(KQReportType.NORMAL); + } + } + + if (type.equals("1")) { + day.put("type", types.size() > 0 ? types.get(0) : "NORMAL"); + } + date = DateUtil.getDate(date, 1); + } + if (type.equals("1")) { + resultMap.put("result", year); + } else { + resultMap.put("result", month); + } + resultMap.put("status", "1"); + } catch (Exception e) { + resultMap.put("api_status", false); + resultMap.put("api_errormsg", e.getMessage()); + writeLog(e); + } + return resultMap; + } + + /** + * 获取指定人员在指定时间范围内的流程集合 + * + * @return + */ + public Map getFlowData(int flowType) { + Map resultMap = new HashMap(); + try { + String nowdate = DateUtil.getCurrentDate(); + String type = Util.null2String(params.get("type"));//是查看一年的数据还是一月的数据:1-年、2-月 + String typevalue = Util.null2String(params.get("typevalue"));//指定的年份或者指定的月份 + String fromDate = Util.null2String(params.get("fromDate"));//指定日期起点 + String toDate = Util.null2String(params.get("toDate"));//指定日期终点 + int subCompanyId = Util.getIntValue((String) params.get("subCompanyId"), 0);//指定查看的人员的所属分部 + int departmentId = Util.getIntValue((String) params.get("departmentId"), 0);//指定查看的人员的所属部门 + String resourceId = Util.null2String(params.get("resourceId"));//指定查看的人员ID + String status = Util.null2String(params.get("status"));//? + + /** + * 若未指定查看人员,则默认为当前登录人员 + */ + if (resourceId.length() == 0) { + resourceId = "" + user.getUID(); + } + + /** + * 获取指定日期的起点和终点 + */ + if (type.equals("1")) {//年 + if (typevalue.length() == 0 || typevalue.length() != 4) { + typevalue = DateUtil.getYear(); + } + fromDate = typevalue + "-01-01"; + toDate = DateUtil.getLastDayOfYear(DateUtil.parseToDate(fromDate)); + } else if (type.equals("2")) {//月 + if (typevalue.length() == 0) { + typevalue = DateUtil.getYear() + "-" + DateUtil.getMonth(); + } + fromDate = typevalue + "-01"; + toDate = DateUtil.getLastDayOfMonthToString(DateUtil.parseToDate(fromDate)); + } + + /**获取销假*/ + List leaveBackList = getLeaveDate(); + + KQExitRulesComInfo exitRulesComInfo = new KQExitRulesComInfo(); + KQTravelRulesComInfo travelRulesComInfo = new KQTravelRulesComInfo(); + KQLeaveRulesComInfo rulesComInfo = new KQLeaveRulesComInfo(); + KQTimeSelectionComInfo kqTimeSelectionComInfo = new KQTimeSelectionComInfo(); + KQWorkTime kqWorkTime = new KQWorkTime(); + + boolean showOnHoliday = true;//非工作日是否显示流程(出差、公出、请假) + + String timeselection = "1"; + String selectiontype = ""; + String typeName = ""; + KQReportType workflowType = null; + switch (flowType) { + case 3://加班 + typeName = SystemEnv.getHtmlLabelName(6151, user.getLanguage()); + workflowType = KQReportType.OVERTIME; + selectiontype = ""+KqSplitFlowTypeEnum.OVERTIME.getFlowtype(); + timeselection = KQOvertimeRulesBiz.getTimeselection(); + break; + case 2://公出 + typeName = SystemEnv.getHtmlLabelName(24058, user.getLanguage()); + workflowType = KQReportType.OUTDAYS; + showOnHoliday = exitRulesComInfo.getComputingMode("1").equals("2"); + selectiontype = ""+KqSplitFlowTypeEnum.OUT.getFlowtype(); + timeselection = KQExitRulesBiz.getTimeselection(); + break; + case 1://出差 + typeName = SystemEnv.getHtmlLabelName(20084, user.getLanguage()); + workflowType = KQReportType.EVECTION; + showOnHoliday = travelRulesComInfo.getComputingMode("1").equals("2"); + selectiontype = ""+KqSplitFlowTypeEnum.EVECTION.getFlowtype(); + timeselection = KQTravelRulesBiz.getTimeselection(); + break; + case 0://请假 + typeName = SystemEnv.getHtmlLabelName(670, user.getLanguage()); + workflowType = KQReportType.LEAVE; + selectiontype = ""+KqSplitFlowTypeEnum.LEAVE.getFlowtype(); + break; + default: + break; + } + + /** + * 获取数据集合 + */ + List> workflowList = new ArrayList>(); + Map workflowMap = new HashMap(); + + Map paramsMap = new HashMap(); + paramsMap.put("typeselect", "6"); + paramsMap.put("tabKey", "1"); + paramsMap.put("kqtype", "" + flowType); + paramsMap.put("resourceId", resourceId); + paramsMap.put("fromDate", fromDate); + paramsMap.put("toDate", toDate); + paramsMap.put("isMyKQ", "1"); + paramsMap.put("isNoAccount","1"); + + KQAttFlowSetBiz kqAttFlowSetBiz = new KQAttFlowSetBiz(); + Map sqlMap = kqAttFlowSetBiz.getFLowSql(paramsMap, user); + String sqlFrom = sqlMap.get("from"); + String sqlWhere = sqlMap.get("where"); + + String sql = "select * " + sqlFrom + sqlWhere; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql); + while (recordSet.next()) { + String requestId = recordSet.getString("requestId"); + double duration = Util.getDoubleValue(recordSet.getString("duration"), 0.00); + double backDuration = 0.00; + int durationrule = recordSet.getInt("durationrule"); + String fromDateTemp = recordSet.getString("fromDate"); + String fromTimeTemp = recordSet.getString("fromTime"); + String toDateTemp = recordSet.getString("toDate"); + String toTimeTemp = recordSet.getString("toTime"); + String belongdate = Util.null2String(recordSet.getString("belongdate")); + String leaveRulesId = ""; + String filterholidays = ""; + String count = String.format("%.2f", duration) + "(" + ((durationrule == 3||durationrule == 5||durationrule == 6) ? SystemEnv.getHtmlLabelName(391, user.getLanguage()) : SystemEnv.getHtmlLabelName(1925, user.getLanguage())) + ")"; + if(flowType == 3){ + count = String.format("%.2f", duration) + "(" + ((durationrule == 3||durationrule == 5||durationrule == 6) ? SystemEnv.getHtmlLabelName(391, user.getLanguage()) : SystemEnv.getHtmlLabelName(1925, user.getLanguage())) + ")"; + } + if (flowType == 0) { + backDuration = Util.getDoubleValue(recordSet.getString("backDuraion"), 0.00); + if (backDuration > 0) { + count = String.format("%.2f", duration) + "(" + (SystemEnv.getHtmlLabelName(24473, user.getLanguage()) + ":" + String.format("%.2f", backDuration)) + ")" + ((durationrule == 3||durationrule == 5||durationrule == 6) ? SystemEnv.getHtmlLabelName(391, user.getLanguage()) : SystemEnv.getHtmlLabelName(1925, user.getLanguage())); + } + leaveRulesId = recordSet.getString("newleavetype"); + String computingMode = rulesComInfo.getComputingMode(leaveRulesId); + if("2".equalsIgnoreCase(computingMode)){ + //按照自然日计算 + showOnHoliday = true; + filterholidays= rulesComInfo.getFilterHolidays(leaveRulesId); + } else { + + showOnHoliday = false; + } + typeName = Util.formatMultiLang(rulesComInfo.getLeaveName(leaveRulesId), "" + user.getLanguage()); + } + String start = fromDateTemp + " " + fromTimeTemp; + String end = toDateTemp + " " + toTimeTemp; + if (2 == durationrule || 4 == durationrule) { + if (2 == durationrule) { + if(leaveRulesId.length() > 0){ + timeselection = rulesComInfo.getTimeSelection(leaveRulesId); + } + if("1".equalsIgnoreCase(timeselection)){ + Map half_map = kqTimeSelectionComInfo.getTimeselections(selectiontype,leaveRulesId,durationrule+""); + String cus_am = SystemEnv.getHtmlLabelName(16689, user.getLanguage()); + String cus_pm = SystemEnv.getHtmlLabelName(16690, user.getLanguage()); + if(half_map != null && !half_map.isEmpty()){ + cus_am = Util.null2String(half_map.get("half_on")); + cus_pm = Util.null2String(half_map.get("half_off")); + } + if (fromTimeTemp.equalsIgnoreCase(SplitSelectSet.forenoon_start)) { + start = fromDateTemp + " " + cus_am; + } else if (fromTimeTemp.equalsIgnoreCase(SplitSelectSet.forenoon_end)) { + start = fromDateTemp + " " + cus_pm; + } + + if (toTimeTemp.equalsIgnoreCase(SplitSelectSet.afternoon_start)) { + end = toDateTemp + " " + cus_am; + } else if (toTimeTemp.equalsIgnoreCase(SplitSelectSet.afternoon_end)) { + end = toDateTemp + " " + cus_pm; + } + } + } + if (4 == durationrule) { + if (fromTimeTemp.equalsIgnoreCase(SplitSelectSet.forenoon_start)) { + start = fromDateTemp + " " + SystemEnv.getHtmlLabelName(390728, user.getLanguage()); + } + + if (toTimeTemp.equalsIgnoreCase(SplitSelectSet.afternoon_end)) { + end = toDateTemp + " " + SystemEnv.getHtmlLabelName(390728, user.getLanguage()); + } + } + } + + //二开 修改加班归属,只判断flowType=3 加班类型,其他类型走原逻辑 + if(flowType==0 || flowType==1 || flowType==3 ){ + boolean isWorkDay = kqWorkTime.isWorkDay(resourceId, belongdate); + if (!leaveBackList.contains(resourceId + "|" + belongdate + "|" + requestId)) { + workflowList = (ArrayList>) resultMap.get(resourceId + "|" + belongdate); + + if (null == workflowList) { + workflowList = new ArrayList>(); + } + workflowMap = new HashMap(); + workflowMap.put("count", count); + workflowMap.put("start", start); + workflowMap.put("end", end); + workflowMap.put("type", typeName); + workflowMap.put("workflowtype", workflowType); + workflowMap.put("requestId", requestId); + workflowMap.put("belongdate", belongdate); + workflowMap.put("title", "" + typeName + ""); + workflowList.add(workflowMap); + + if (!(!isWorkDay && !showOnHoliday)) { + SplitActionUtil splitActionUtil = new SplitActionUtil(); + boolean is_filterholidays = splitActionUtil.check_filterholidays(filterholidays, resourceId, belongdate, 1); + if(!is_filterholidays){ + resultMap.put(resourceId + "|" + belongdate, workflowList); + } + } + } + }else { + boolean isEnd = false; + for (String date = fromDateTemp; !isEnd; ) { + if (date.equals(toDateTemp)) { + isEnd = true; + } + boolean isWorkDay = kqWorkTime.isWorkDay(resourceId, date); + if(!isWorkDay && !showOnHoliday) { + date = DateUtil.getDate(date, 1); + continue; + } + if (!leaveBackList.contains(resourceId + "|" + date + "|" + requestId)) { + workflowList = (ArrayList>) resultMap.get(resourceId + "|" + date); + if (null == workflowList) { + workflowList = new ArrayList>(); + } + workflowMap = new HashMap(); + workflowMap.put("count", count); + workflowMap.put("start", start); + workflowMap.put("end", end); + workflowMap.put("type", typeName); + workflowMap.put("workflowtype", workflowType); + workflowMap.put("requestId", requestId); + workflowMap.put("belongdate", belongdate); + workflowMap.put("title", "" + typeName + ""); + workflowList.add(workflowMap); + + if (!(!isWorkDay && !showOnHoliday)) { + SplitActionUtil splitActionUtil = new SplitActionUtil(); + boolean is_filterholidays = splitActionUtil.check_filterholidays(filterholidays, resourceId, date, 1); + if(!is_filterholidays){ + resultMap.put(resourceId + "|" + date, workflowList); + } + } + } + + date = DateUtil.getDate(date, 1); + } + } + } + } catch (Exception e) { + writeLog(e); + } + return resultMap; + } + + /** + * 获取请完假之后又销掉的日期 + * + * @return + */ + private List getLeaveDate() { + List resultList = new ArrayList(); + try { + String nowdate = DateUtil.getCurrentDate(); + String type = Util.null2String(params.get("type"));//是查看一年的数据还是一月的数据:1-年、2-月 + String typevalue = Util.null2String(params.get("typevalue"));//指定的年份或者指定的月份 + String fromDate = Util.null2String(params.get("fromDate"));//指定日期起点 + String toDate = Util.null2String(params.get("toDate"));//指定日期终点 + int subCompanyId = Util.getIntValue((String) params.get("subCompanyId"), 0);//指定查看的人员的所属分部 + int departmentId = Util.getIntValue((String) params.get("departmentId"), 0);//指定查看的人员的所属部门 + String resourceId = Util.null2String(params.get("resourceId"));//指定查看的人员ID + String status = Util.null2String(params.get("status"));//? + + /** + * 若未指定查看人员,则默认为当前登录人员 + */ + if (resourceId.length() == 0) { + resourceId = "" + user.getUID(); + } + + /** + * 获取指定日期的起点和终点 + */ + if (type.equals("1")) {//年 + if (typevalue.length() == 0 || typevalue.length() != 4) { + typevalue = DateUtil.getYear(); + } + fromDate = typevalue + "-01-01"; + toDate = DateUtil.getLastDayOfYear(DateUtil.parseToDate(fromDate)); + } else if (type.equals("2")) {//月 + if (typevalue.length() == 0) { + typevalue = DateUtil.getYear() + "-" + DateUtil.getMonth(); + } + fromDate = typevalue + "-01"; + toDate = DateUtil.getLastDayOfMonthToString(DateUtil.parseToDate(fromDate)); + } + + String leaveBackTableName = KqSplitFlowTypeEnum.LEAVEBACK.getTablename(); + String leaveTableName = KqSplitFlowTypeEnum.LEAVE.getTablename(); + String sql = " select requestId,resourceId,belongDate,duration,durationRule," + + " (select sum(duration) from " + leaveBackTableName + " where " + leaveBackTableName + ".leavebackrequestid=" + leaveTableName + ".requestid " + + " and " + leaveBackTableName + ".newleavetype=" + leaveTableName + ".newleavetype " + + " and " + leaveBackTableName + ".belongdate=" + leaveTableName + ".belongDate ) as backDuration " + + " from " + leaveTableName + " where 1=1 "; + if (!resourceId.equals("")) { + sql += " and " + leaveTableName + ".resourceId=" + resourceId; + } + if (fromDate.length() > 0 && toDate.length() > 0) { + sql += " and " + leaveTableName + ".belongdate between'" + fromDate + "' and '" + toDate + "' "; + } + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql); + while (recordSet.next()) { + String requestId = recordSet.getString("requestId"); + String belongDate = recordSet.getString("belongDate"); + double duration = Util.getDoubleValue(recordSet.getString("duration"), 0.00); + if (duration <= 0) { + continue; + } + double backDuration = Util.getDoubleValue(recordSet.getString("backDuration"), 0.00); + if (backDuration >= duration) { + resultList.add(resourceId + "|" + belongDate + "|" + requestId); + } + } + } catch (Exception e) { + writeLog(e); + } + return resultList; + } + + /** + * 获取某段时间内的所有签到签退信息 + * + * @return + */ + private Map getSignInfo() { + Map resultMap = new HashMap(); + try { + String type = Util.null2String(params.get("type"));//是查看一年的数据还是一月的数据:1-年、2-月 + String typevalue = Util.null2String(params.get("typevalue"));//指定的年份或者指定的月份 + String fromDate = Util.null2String(params.get("fromDate"));//指定日期起点 + String toDate = Util.null2String(params.get("toDate"));//指定日期终点 + String resourceId = Util.null2String(params.get("resourceId"));//指定查看的人员ID + + /** + * 若未指定查看人员,则默认为当前登录人员 + */ + if (resourceId.length() == 0) { + resourceId = "" + user.getUID(); + } + + /** + * 获取指定日期的起点和终点 + */ + if (type.equals("1")) {//年 + if (typevalue.length() == 0 || typevalue.length() != 4) { + typevalue = DateUtil.getYear(); + } + fromDate = typevalue + "-01-01"; + toDate = DateUtil.getLastDayOfYear(DateUtil.parseToDate(fromDate)); + } else if (type.equals("2")) {//月 + if (typevalue.length() == 0) { + typevalue = DateUtil.getYear() + "-" + DateUtil.getMonth(); + } + fromDate = typevalue + "-01"; + toDate = DateUtil.getLastDayOfMonthToString(DateUtil.parseToDate(fromDate)); + } + /** + * 判断是否显示补打卡数据 + */ + RecordSet recordSet = new RecordSet(); + boolean showCard = false; + String settingSql = "select * from KQ_SETTINGS where main_key='showSignFromCard'"; + recordSet.executeQuery(settingSql); + if (recordSet.next()) { + String main_val = recordSet.getString("main_val"); + showCard = main_val.equals("1"); + } + + SignInfo signInfo = null; + Map signInfoMap = new LinkedHashMap(); + + String sql = "SELECT a.kqdate,a.resourceId,a.serialNumber,a.serialId,'signIn' signType,a.signInDate signDate,a.signInTime signTime,b.clientAddress,b.addr FROM KQ_FORMAT_DETAIL a LEFT JOIN HrmScheduleSign b ON a.signInId=b.id WHERE 1=1 AND resourceId=" + resourceId + "\n "; + if (!showCard) { + sql += " AND (signFrom is null or signFrom not like 'card%') "; + } + if (!"".equals(fromDate)) { + sql += " AND kqDate>='" + fromDate + "' "; + } + if (!"".equals(toDate)) { + sql += " AND kqDate<='" + toDate + "' "; + } + sql += " UNION ALL\n " + + "SELECT a.kqdate,a.resourceId,a.serialNumber,a.serialId,'signOut' signType,a.signOutDate signDate,a.signOutTime signTime,b.clientAddress,b.addr FROM KQ_FORMAT_DETAIL a LEFT JOIN HrmScheduleSign b ON a.signOutId=b.id WHERE 1=1 AND resourceId=" + resourceId + "\n "; + if (!showCard) { + sql += " AND (signFrom is null or signFrom not like 'card%') "; + } + if (!"".equals(fromDate)) { + sql += " AND kqDate>='" + fromDate + "' "; + } + if (!"".equals(toDate)) { + sql += " AND kqDate<='" + toDate + "' "; + } + sql += "ORDER BY kqDate,resourceId,serialNumber,signType "; + recordSet.executeQuery(sql); + while (recordSet.next()) { + String kqDate = Util.null2String(recordSet.getString("kqDate")); + String signType = Util.null2String(recordSet.getString("signType")); + String signDate = Util.null2String(recordSet.getString("signDate")); + String signTime = Util.null2String(recordSet.getString("signTime")); + String serialId = Util.null2String(recordSet.getString("serialId")); + int serialNumber = Util.getIntValue(recordSet.getString("serialNumber"), 0); + + + signInfo = signInfoMap.get(kqDate); + if (signInfo == null) { + signInfo = new SignInfo(); + } + signInfo.setSerialId("" + serialId); + if ("signIn".equals(signType)) { + if (serialNumber == 2) { + signInfo.setNeedSign3(true); + signInfo.setSignInTime3(signTime); + } else if (serialNumber == 1) { + signInfo.setNeedSign2(true); + signInfo.setSignInTime2(signTime); + } else { + signInfo.setNeedSign1(true); + signInfo.setSignInTime1(signTime); + } + } else { + if (serialNumber == 2) { + signInfo.setNeedSign3(true); + signInfo.setSignOutTime3(signTime); + } else if (serialNumber == 1) { + signInfo.setNeedSign2(true); + signInfo.setSignOutTime2(signTime); + } else { + signInfo.setNeedSign1(true); + signInfo.setSignOutTime1(signTime); + } + } + signInfoMap.put(kqDate,signInfo); + } + + Map itemMap = null; + List> itemList = null; + for (Map.Entry entry : signInfoMap.entrySet()) { + String kqDate = (String) entry.getKey(); + signInfo = (SignInfo) entry.getValue(); + String serialId = Util.null2String(signInfo.getSerialId()); + boolean needSign1 = signInfo.isNeedSign1(); + String signInTime1 = Util.null2String(signInfo.getSignInTime1()); + String signOutTime1 = Util.null2String(signInfo.getSignOutTime1()); + boolean needSign2 = signInfo.isNeedSign2(); + String signInTime2 = Util.null2String(signInfo.getSignInTime2()); + String signOutTime2 = Util.null2String(signInfo.getSignOutTime2()); + boolean needSign3 = signInfo.isNeedSign3(); + String signInTime3 = Util.null2String(signInfo.getSignInTime3()); + String signOutTime3 = Util.null2String(signInfo.getSignOutTime3()); + + itemList = new ArrayList>(); + + if (serialId.equals("") || serialId.equals("0")) { + if (signInTime1.equals("") && signOutTime1.equals("")) { + continue; + } else { + itemMap = new HashMap(); + itemMap.put("title", SystemEnv.getHtmlLabelName(512504, user.getLanguage())); + if (signInTime1.equals("")) { + itemMap.put("signTime", SystemEnv.getHtmlLabelName(25994, user.getLanguage())); + } else { + itemMap.put("signTime", signInTime1); + } + itemList.add(itemMap); + + itemMap = new HashMap(); + itemMap.put("title", SystemEnv.getHtmlLabelName(512505, user.getLanguage())); + if (signOutTime1.equals("")) { + itemMap.put("signTime", SystemEnv.getHtmlLabelName(25994, user.getLanguage())); + } else { + itemMap.put("signTime", signOutTime1); + } + itemList.add(itemMap); + resultMap.put(kqDate,itemList); + } + } else { + itemMap = new HashMap(); + itemMap.put("title", SystemEnv.getHtmlLabelName(512504, user.getLanguage())); + if (signInTime1.equals("")) { + itemMap.put("signTime", SystemEnv.getHtmlLabelName(25994, user.getLanguage())); + } else { + itemMap.put("signTime", signInTime1); + } + itemList.add(itemMap); + + itemMap = new HashMap(); + itemMap.put("title", SystemEnv.getHtmlLabelName(512505, user.getLanguage())); + if (signOutTime1.equals("")) { + itemMap.put("signTime", SystemEnv.getHtmlLabelName(25994, user.getLanguage())); + } else { + itemMap.put("signTime", signOutTime1); + } + itemList.add(itemMap); + + if (needSign2) { + itemMap = new HashMap(); + itemMap.put("title", SystemEnv.getHtmlLabelName(512504, user.getLanguage())); + if (signInTime2.equals("")) { + itemMap.put("signTime", SystemEnv.getHtmlLabelName(25994, user.getLanguage())); + } else { + itemMap.put("signTime", signInTime2); + } + itemList.add(itemMap); + + itemMap = new HashMap(); + itemMap.put("title", SystemEnv.getHtmlLabelName(512505, user.getLanguage())); + if (signOutTime2.equals("")) { + itemMap.put("signTime", SystemEnv.getHtmlLabelName(25994, user.getLanguage())); + } else { + itemMap.put("signTime", signOutTime2); + } + itemList.add(itemMap); + } + + if (needSign3) { + itemMap = new HashMap(); + itemMap.put("title", SystemEnv.getHtmlLabelName(512504, user.getLanguage())); + if (signInTime3.equals("")) { + itemMap.put("signTime", SystemEnv.getHtmlLabelName(25994, user.getLanguage())); + } else { + itemMap.put("signTime", signInTime3); + } + itemList.add(itemMap); + + itemMap = new HashMap(); + itemMap.put("title", SystemEnv.getHtmlLabelName(512505, user.getLanguage())); + if (signOutTime3.equals("")) { + itemMap.put("signTime", SystemEnv.getHtmlLabelName(25994, user.getLanguage())); + } else { + itemMap.put("signTime", signOutTime3); + } + itemList.add(itemMap); + } + + BaseBean bb = new BaseBean(); + //所有的休息班次id + String xxrSerialId = bb.getPropValue("hskq_main","xxrSerialId"); + if(Arrays.asList(xxrSerialId.split(",")).contains(serialId)){ + //是休息班的班次 + if("".equals(signInTime1) && "".equals(signOutTime1)){ + //休息班且无上下班打卡记录时,不显示未打卡字样 + itemList = new ArrayList>(); + } + } + + resultMap.put(kqDate,itemList); + } + } + } catch (Exception e) { + writeLog(e); + } + return resultMap; + } + + /** + * 判断是否有加班打卡 + * @param fromDate + * @param toDate + * @return + */ + public Map getOvertimeSignInfo(String fromDate,String toDate){ + Map overtiemInfo = new HashMap<>(); + RecordSet rs = new RecordSet(); + rs.executeQuery(" select resourceid,belongdate,duration_min from kq_flow_overtime " + + "where belongdate>=? and belongdate<=? and fromtimedb is not null ",fromDate,toDate); + while(rs.next()){ + String resourceid = Util.null2String(rs.getString("resourceid")); + String belongdate = Util.null2String(rs.getString("belongdate")); + String duration_min = Util.null2String(rs.getString("duration_min")); + overtiemInfo.put(resourceid+"|"+belongdate,duration_min); + } + return overtiemInfo; + } + + class SignInfo { + private String serialId; + private boolean needSign1 = false; + private String signInTime1; + private String signOutTime1; + private boolean needSign2 = false; + private String signInTime2; + private String signOutTime2; + private boolean needSign3 = false; + private String signInTime3; + private String signOutTime3; + + public SignInfo() { + } + + public String getSerialId() { + return serialId; + } + + public void setSerialId(String serialId) { + this.serialId = serialId; + } + + public boolean isNeedSign1() { + return needSign1; + } + + public void setNeedSign1(boolean needSign1) { + this.needSign1 = needSign1; + } + + public String getSignInTime1() { + return signInTime1; + } + + public void setSignInTime1(String signInTime1) { + this.signInTime1 = signInTime1; + } + + public String getSignOutTime1() { + return signOutTime1; + } + + public void setSignOutTime1(String signOutTime1) { + this.signOutTime1 = signOutTime1; + } + + public boolean isNeedSign2() { + return needSign2; + } + + public void setNeedSign2(boolean needSign2) { + this.needSign2 = needSign2; + } + + public String getSignInTime2() { + return signInTime2; + } + + public void setSignInTime2(String signInTime2) { + this.signInTime2 = signInTime2; + } + + public String getSignOutTime2() { + return signOutTime2; + } + + public void setSignOutTime2(String signOutTime2) { + this.signOutTime2 = signOutTime2; + } + + public boolean isNeedSign3() { + return needSign3; + } + + public void setNeedSign3(boolean needSign3) { + this.needSign3 = needSign3; + } + + public String getSignInTime3() { + return signInTime3; + } + + public void setSignInTime3(String signInTime3) { + this.signInTime3 = signInTime3; + } + + public String getSignOutTime3() { + return signOutTime3; + } + + public void setSignOutTime3(String signOutTime3) { + this.signOutTime3 = signOutTime3; + } + } +} diff --git a/src/com/engine/kq/cmd/myattendance/GetHrmKQReportInfoCmd.java b/src/com/engine/kq/cmd/myattendance/GetHrmKQReportInfoCmd.java new file mode 100644 index 0000000..827d175 --- /dev/null +++ b/src/com/engine/kq/cmd/myattendance/GetHrmKQReportInfoCmd.java @@ -0,0 +1,430 @@ +package com.engine.kq.cmd.myattendance; + +import com.engine.common.biz.AbstractCommonCommand; +import com.engine.common.entity.BizLogContext; +import com.engine.core.interceptor.CommandContext; +import com.engine.kq.biz.*; +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; +import weaver.hrm.resource.ResourceComInfo; +import weaver.systeminfo.SystemEnv; +import org.apache.commons.lang3.StringUtils; + +import java.util.*; + +/** + * 前台--人事--我的考勤 + */ +public class GetHrmKQReportInfoCmd extends AbstractCommonCommand> { + + public GetHrmKQReportInfoCmd(Map params, User user) { + this.user = user; + this.params = params; + } + + @Override + public BizLogContext getLogContext() { + return null; + } + + private static boolean isIndirectSuperId(String id,String checkSuperId,ResourceComInfo info){ + + int loopBreakTimes = 20 ; + for(String loopId = id; + isRightResourceId(loopId) && (loopBreakTimes--)>0 ; + loopId = info.getManagerID(loopId)){ + if(isDirectSuperId(loopId,checkSuperId,info)) return true ; + } + return false ; + } + + private static boolean isDirectSuperId(String id,String checkSuperId,ResourceComInfo info){ + String superId = Util.null2String(info.getManagerID(id)) ; + return isRightResourceId(superId) && superId.equals(checkSuperId) ; + } + + /** + * 判断是否是组员或者考勤文员管理的人员 + * @param id + * @param checkSuperId + * @return + */ + private static boolean isTeamMembers(String id,String checkSuperId){ + boolean isMember = false; + String sql = " select id from cus_fielddata where id=? and field89=? "; + RecordSet rs = new RecordSet(); + rs.executeQuery(sql,id,checkSuperId); + if(rs.next()){ + isMember = true; + } + + String kqwySql = " select b.id from hrmdepartmentdefined a,hrmresource b " + + "where a.kqwy=? and a.deptid=b.departmentid and b.id=?"; + rs.executeQuery(kqwySql,checkSuperId,id); + if(rs.next()){ + isMember = true; + } + return isMember; + } + + private static boolean isRightResourceId(String id){ + return StringUtils.isNotBlank(id) && !"0".equals(id) ; + } + + @Override + public Map execute(CommandContext commandContext) { + Map resultMap = new HashMap(); + try { + ResourceComInfo resourceComInfo = new ResourceComInfo(); + /** + * 判断是否有权限 + */ + int subCompanyId = Util.getIntValue((String) params.get("subCompanyId"), 0); + int departmentId = Util.getIntValue((String) params.get("departmentId"), 0); + String resourceId = Util.null2String(params.get("resourceId")); + if (resourceId.equals("")) { + resourceId = "" + user.getUID(); + } + String lastName = resourceComInfo.getResourcename(resourceId); + if (resourceId.equals("" + user.getUID())) { + resultMap.put("title", SystemEnv.getHtmlLabelName(513095, user.getLanguage())); + } else { + resultMap.put("title", SystemEnv.getHtmlLabelName(515562, user.getLanguage()).replace("{name}", lastName)); + } + if (subCompanyId == 0 || departmentId == 0) { + subCompanyId = Util.getIntValue(resourceComInfo.getSubCompanyID(resourceId), 0); + departmentId = Util.getIntValue(resourceComInfo.getDepartmentID(resourceId), 0); + } + //if (!resourceId.equals("" + user.getUID()) && !isIndirectSuperId(resourceId, user.getUID() + "", resourceComInfo) && !HrmUserVarify.checkUserRight("HrmResource:Absense", user, departmentId)) { + // resultMap.put("status", "-1"); + // resultMap.put("hasRight", false); + // return resultMap; + //} + //二开线长查看组员考勤 + if (!resourceId.equals("" + user.getUID()) && !isTeamMembers(resourceId, user.getUID() + "") && !isIndirectSuperId(resourceId, user.getUID() + "", resourceComInfo) + && !HrmUserVarify.checkUserRight("HrmResource:Absense", user, departmentId)) { + resultMap.put("status", "-1"); + resultMap.put("hasRight", false); + return resultMap; + } + + + String fromDate = Util.null2String(params.get("fromDate")); + String toDate = Util.null2String(params.get("toDate")); + + 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 lastYearDate = Util.add0(today.get(Calendar.YEAR) - 1, 4) + "-12-31"; + + /** + * 拼凑前端所属数据格式 + */ + Map groupMap = new HashMap(); + List groupItemList = new ArrayList(); + Map groupItem = new HashMap(); + List itemList = new ArrayList(); + Map itemMap = new HashMap(); + List itemList5 = new ArrayList(); + Map groupItem5 = new HashMap(); + /** + * 出勤统计 + * workDays:应出勤天数 + * realWorkDays:实际出勤天数 + * leaveDays:缺勤天数 + */ + double workDays = 0.00; + double realWorkDays = 0.00; + double leaveDays = 0.00; + /** + * beLate:迟到次数 + * graveBeLate;严重迟到次数 + * leaveEearly:早退次数 + * graveLeaveEarly:严重迟到次数 + * absenteeism:旷工次数 + * forgotCheck:漏签次数 + */ + int beLate = 0; + int graveBeLate = 0; + int leaveEearly = 0; + int graveLeaveEarly = 0; + int absenteeism = 0; + int forgotCheck = 0; + /** + * or_minimumUnit:最小加班单位 + * or_unitName:(小时)/(天) + * tr_minimumUnit:最小出差单位 + * tr_unitName:(小时)/(天) + * er_minimumUnit:最小公出单位 + * er_unitName:(小时)/(天) + */ + int or_minimumUnit = KQOvertimeRulesBiz.getMinimumUnit();//最小加班单位 + String or_unitName = (or_minimumUnit == 3 || or_minimumUnit == 5 || or_minimumUnit == 6) ? SystemEnv.getHtmlLabelName(389326, user.getLanguage()) : SystemEnv.getHtmlLabelName(389325, user.getLanguage()); + KQTravelRulesComInfo kqTravelRulesComInfo = new KQTravelRulesComInfo(); + int tr_minimumUnit = Util.getIntValue(kqTravelRulesComInfo.getMinimumUnit("1"));//最小出差单位 + String tr_unitName = tr_minimumUnit == 3 ? SystemEnv.getHtmlLabelName(389326, user.getLanguage()) : SystemEnv.getHtmlLabelName(389325, user.getLanguage()); + KQExitRulesComInfo kqExitRulesComInfo = new KQExitRulesComInfo(); + int er_minimumUnit = Util.getIntValue(kqExitRulesComInfo.getMinimumUnit("1"));//最小公出单位 + String er_unitName = er_minimumUnit == 3 ? SystemEnv.getHtmlLabelName(389326, user.getLanguage()) : SystemEnv.getHtmlLabelName(389325, user.getLanguage()); + /** + * overtimeTotal:加班时长 + * businessLeave:出差时长 + * officialBusiness:公出时长 + */ + double overtimeTotal = 0.00;//加班时长 + double businessLeave = 0.00;//出差时长 + double officialBusiness = 0.00;//公出时长 + /** + * 记录请假时长(考虑到人员调整部门之后,考勤汇总报表会存在两条记录,用于累计请假时长) + */ + KQLeaveRulesComInfo rulesComInfo = new KQLeaveRulesComInfo(); + Map leaveMap = new HashMap(); + /** + * 获取考勤的相关统计数据,数据来源于考勤汇总报表,在service层调用了考勤汇总报表的接口重新封装了数据传入此接口 + * 调用的考勤汇总报表的接口为:com/engine/kq/cmd/report/GetKQReportCmd.java + */ + List> datasList = new ArrayList>(); + Map datasMap = new HashMap<>(); + + datasList = (List>) params.get("datas"); + for (int i = 0; datasList != null && i < datasList.size(); i++) { + datasMap = (Map) datasList.get(i); + + workDays += Util.getDoubleValue((String) datasMap.get("workdays"), 0.00);//应出勤天数 + realWorkDays += Util.getDoubleValue((String) datasMap.get("attendancedays"), 0.00);//实际出勤天数 + leaveDays = workDays - realWorkDays;//缺勤天数 + + beLate += Util.getIntValue((String) datasMap.get("beLate"), 0);//迟到次数 + graveBeLate += Util.getIntValue((String) datasMap.get("graveBeLate"), 0);//严重迟到次数 + leaveEearly += Util.getIntValue((String) datasMap.get("leaveEearly"), 0);//早退次数 + graveLeaveEarly += Util.getIntValue((String) datasMap.get("graveLeaveEarly"), 0);//严重迟到次数 + absenteeism += Util.getIntValue((String) datasMap.get("absenteeism"), 0);//旷工次数 + forgotCheck += Util.getIntValue((String) datasMap.get("forgotCheck"), 0);//漏签次数 + + overtimeTotal += Util.getDoubleValue((String) datasMap.get("overtimeTotal"), 0.00);//加班时长 + businessLeave += Util.getDoubleValue((String) datasMap.get("businessLeave"), 0.00);//出差时长 + officialBusiness += Util.getDoubleValue((String) datasMap.get("officialBusiness"), 0.00);//公出时长 + + rulesComInfo.setTofirstRow(); + while (i == 0 && rulesComInfo.next()) { + double value = Util.getDoubleValue(String.valueOf(leaveMap.get("leaveType_" + rulesComInfo.getId())), 0.00); + value += Util.getDoubleValue((String) datasMap.get("leaveType_" + rulesComInfo.getId()), 0.00);//请假时长 + leaveMap.put("leaveType_" + rulesComInfo.getId(), value); + } + } + + /**统计应出勤天数*/ + KQWorkTime kqWorkTime = new KQWorkTime(); + if (!toDate.equals("") && toDate.compareTo(currentDate) > 0 && Util.getIntValue(resourceComInfo.getStatus(resourceId), 0) < 4) { + workDays = 0.00; + if (!fromDate.equals("") && fromDate.compareTo(currentDate) > 0) { + //查询没有到的月份,缺勤天数以及出勤天数应该都为0 + realWorkDays = 0.00; + leaveDays = 0.00; + } + + boolean isEnd = false; + for (String date = fromDate; !isEnd; ) { + if (date.compareTo(toDate)>=0) { + isEnd = true; + } + + boolean isWorkDay = kqWorkTime.isWorkDay(resourceId, date); + if (isWorkDay) { + workDays += 1.00; + } + + date = DateUtil.getDate(date, 1); + } + } + + /**********************************************************************************************************/ + + itemList = new ArrayList(); + itemMap = new HashMap(); + itemMap.put("id", "leaveDays"); + itemMap.put("name", SystemEnv.getHtmlLabelName(506345, user.getLanguage()));//未出勤 + itemMap.put("title", SystemEnv.getHtmlLabelName(506345, user.getLanguage())); + itemMap.put("type", "ABSENT"); + itemMap.put("value", String.format("%.2f", leaveDays)); + itemList.add(itemMap); + + itemMap = new HashMap(); + itemMap.put("id", "realWorkDays"); + itemMap.put("name", SystemEnv.getHtmlLabelName(130566, user.getLanguage()));//实际出勤 + itemMap.put("title", SystemEnv.getHtmlLabelName(130566, user.getLanguage())); + itemMap.put("type", "REALWORKDAYS"); + itemMap.put("value", String.format("%.2f", realWorkDays)); + itemList.add(itemMap); + + groupItem = new HashMap(); + groupItem.put("id", "workDays"); + groupItem.put("name", SystemEnv.getHtmlLabelName(513089, user.getLanguage()));//应出勤(天) + groupItem.put("title", SystemEnv.getHtmlLabelName(16732, user.getLanguage())); + groupItem.put("value", String.format("%.2f", workDays)); + groupItem.put("items", itemList); + resultMap.put("groupitem1", groupItem); + + /**********************************************************************************************************/ + + itemList = new ArrayList(); + itemMap = new HashMap(); + itemMap.put("name", "evection"); + itemMap.put("title", SystemEnv.getHtmlLabelName(20084, user.getLanguage()) + tr_unitName);//出差 + itemMap.put("type", "EVECTION"); + itemMap.put("value", String.format("%.2f",businessLeave)); + itemList.add(itemMap); + + itemMap = new HashMap(); + itemMap.put("name", "outDays"); + itemMap.put("title", SystemEnv.getHtmlLabelName(24058, user.getLanguage()) + er_unitName);//公出 + itemMap.put("type", "OUTDAYS"); + itemMap.put("value",String.format("%.2f",officialBusiness)); + itemList.add(itemMap); + + itemMap = new HashMap(); + itemMap.put("name", "overTimes"); + itemMap.put("title", SystemEnv.getHtmlLabelName(6151, user.getLanguage()) + or_unitName);//加班 + itemMap.put("type", "OVERTIME"); + itemMap.put("value", String.format("%.2f",overtimeTotal)); + itemList.add(itemMap); + + groupItem = new HashMap(); + groupItem.put("items", itemList); + resultMap.put("groupitem2", groupItem); + + /**********************************************************************************************************/ + + itemList = new ArrayList(); + itemMap = new HashMap(); + itemMap.put("name", "beLate"); + itemMap.put("title", SystemEnv.getHtmlLabelName(34089, user.getLanguage()));//迟到 + itemMap.put("type", "BELATE"); + itemMap.put("value", beLate); + itemList.add(itemMap); + + itemMap = new HashMap(); + itemMap.put("name", "graveBeLate"); + itemMap.put("title", SystemEnv.getHtmlLabelName(535131, user.getLanguage()));//严重迟到 + itemMap.put("type", "graveBeLate"); + itemMap.put("value", graveBeLate); + itemList.add(itemMap); + + itemMap = new HashMap(); + itemMap.put("name", "leaveEarly"); + itemMap.put("title", SystemEnv.getHtmlLabelName(34098, user.getLanguage()));//早退 + itemMap.put("type", "LEAVEEARLY"); + itemMap.put("value", leaveEearly); + itemList.add(itemMap); + + itemMap = new HashMap(); + itemMap.put("name", "graveLeaveEarly"); + itemMap.put("title", SystemEnv.getHtmlLabelName(535132, user.getLanguage()));//严重早退 + itemMap.put("type", "graveLeaveEarly"); + itemMap.put("value", graveLeaveEarly); + itemList.add(itemMap); + + itemMap = new HashMap(); + itemMap.put("name", "absentFromWork"); + itemMap.put("title", SystemEnv.getHtmlLabelName(10000344, user.getLanguage()));//旷工 + itemMap.put("type", "ABSENT"); + itemMap.put("value", absenteeism); + itemList.add(itemMap); + + itemMap = new HashMap(); + itemMap.put("name", "noSign"); + itemMap.put("title", SystemEnv.getHtmlLabelName(34099, user.getLanguage()));//漏签 + itemMap.put("type", "noSign"); + itemMap.put("value", forgotCheck); + itemList.add(itemMap); + + groupItem = new HashMap(); + groupItem.put("items", itemList); + resultMap.put("groupitem3", groupItem); + + /**********************************************************************************************************/ + + rulesComInfo.setTofirstRow(); + while (rulesComInfo.next()) { + if (!rulesComInfo.getIsEnable().equals("1") || !rulesComInfo.getBalanceEnable().equals("1")) { + continue; + } + String scopeType = rulesComInfo.getScopeType(); + if (scopeType.equals("1")) { + String scopeValue = rulesComInfo.getScopeValue(); + List scopeValueList = Util.TokenizerString(scopeValue, ","); + if (scopeValueList.indexOf("" + resourceComInfo.getSubCompanyID(resourceId)) < 0) { + continue; + } + } + + String allRestAmount = KQBalanceOfLeaveBiz.getRestAmount("" + resourceId, rulesComInfo.getId(), currentDate, true, true); + String currentRestAmount = KQBalanceOfLeaveBiz.getRestAmount("" + resourceId, rulesComInfo.getId(), currentDate, true, false); + String beforeRestAmount = String.format("%.2f", Util.getDoubleValue(allRestAmount, 0) - Util.getDoubleValue(currentRestAmount, 0)); + itemList = new ArrayList(); + if(KQSettingsBiz.show_split_balance()) { + itemMap = new HashMap(); + itemMap.put("title", (KQUnitBiz.isLeaveHour(rulesComInfo.getMinimumUnit())) ? SystemEnv.getHtmlLabelName(513286, user.getLanguage()) : SystemEnv.getHtmlLabelName(513287, user.getLanguage())); + itemMap.put("value", beforeRestAmount); + itemList.add(itemMap); + + itemMap = new HashMap(); + itemMap.put("title", (KQUnitBiz.isLeaveHour(rulesComInfo.getMinimumUnit())) ? SystemEnv.getHtmlLabelName(504395, user.getLanguage()) : SystemEnv.getHtmlLabelName(504394, user.getLanguage())); + itemMap.put("value", currentRestAmount); + itemList.add(itemMap); + + itemMap = new HashMap(); + itemMap.put("title", (KQUnitBiz.isLeaveHour(rulesComInfo.getMinimumUnit())) ? SystemEnv.getHtmlLabelName(513288, user.getLanguage()) : SystemEnv.getHtmlLabelName(513289, user.getLanguage())); + itemMap.put("value", allRestAmount); + itemList.add(itemMap); + }else{ + itemMap = new HashMap(); + itemMap.put("title", (KQUnitBiz.isLeaveHour(rulesComInfo.getMinimumUnit())) ? SystemEnv.getHtmlLabelName(513288, user.getLanguage()) : SystemEnv.getHtmlLabelName(513289, user.getLanguage())); + itemMap.put("value", allRestAmount); + itemList.add(itemMap); + } + + groupItem = new HashMap(); + groupItem.put("color", "#25C6DA"); + groupItem.put("icon", "icon-Human-resources-adjustment"); + groupItem.put("title", rulesComInfo.getLeaveName()); + groupItem.put("item", itemList); + groupItemList.add(groupItem); + } + groupMap.put("items", groupItemList); + groupMap.put("title", SystemEnv.getHtmlLabelName(132058, user.getLanguage())); + resultMap.put("groupitem4", groupMap); + + /**********************************************************************************************************/ + + rulesComInfo.setTofirstRow(); + while (rulesComInfo.next()) { + double value = Util.getDoubleValue(String.valueOf(leaveMap.get("leaveType_" + rulesComInfo.getId())), 0.00);//请假时长 + if (value > 0) { + String leaveName = Util.formatMultiLang(rulesComInfo.getLeaveName(), "" + user.getLanguage()); + int le_minimumUnit = Util.getIntValue(rulesComInfo.getMinimumUnit(), 1);//最小请假单位 + String le_unitName = (le_minimumUnit == 3 || le_minimumUnit == 5 || le_minimumUnit == 6) ? SystemEnv.getHtmlLabelName(389326, user.getLanguage()) : SystemEnv.getHtmlLabelName(389325, user.getLanguage()); + + itemMap = new HashMap(); + itemMap.put("name", "leaveType_" + rulesComInfo.getId()); + itemMap.put("title", leaveName + le_unitName); + itemMap.put("type", "leaveType_" + rulesComInfo.getId()); + itemMap.put("value", Util.toDecimalDigits("" + value, 2)); + itemList5.add(itemMap); + } + } + groupItem5.put("items", itemList5); + resultMap.put("groupitem5", groupItem5); + resultMap.put("status", "1"); + } catch (Exception e) { + writeLog(e); + } + return resultMap; + } +} diff --git a/src/com/engine/kq/cmd/myattendance/GetHrmKQSignInfoCmd.java b/src/com/engine/kq/cmd/myattendance/GetHrmKQSignInfoCmd.java new file mode 100644 index 0000000..4cc8486 --- /dev/null +++ b/src/com/engine/kq/cmd/myattendance/GetHrmKQSignInfoCmd.java @@ -0,0 +1,466 @@ +package com.engine.kq.cmd.myattendance; + +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.cmd.shiftmanagement.toolkit.ShiftManagementToolKit; +import com.engine.kq.entity.WorkTimeEntity; +import com.engine.kq.enums.KqSplitFlowTypeEnum; +import com.engine.kq.wfset.util.KQSignUtil; +import org.checkerframework.checker.units.qual.K; +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.Util; +import weaver.hrm.User; +import weaver.systeminfo.SystemEnv; + +import java.text.SimpleDateFormat; +import java.util.*; + +/** + * 获取签到签退信息 + */ +public class GetHrmKQSignInfoCmd extends AbstractCommonCommand> { + + public GetHrmKQSignInfoCmd(Map params, User user) { + this.user = user; + this.params = params; + } + + @Override + public BizLogContext getLogContext() { + return null; + } + + @Override + public Map execute(CommandContext commandContext) { + Map resultMap = new HashMap(); + try { + String date = Util.null2String(params.get("date")); + String resourceId = Util.null2String(params.get("resourceId")); + if (resourceId.equals("")) { + resourceId = String.valueOf(user.getUID()); + } + String isMobile = Util.null2String(params.get("isMobile"));//是否是移动端的【我的考勤】 + + /**判断是否显示补打卡数据*/ + boolean showCard = false; + String settingSql = "select * from KQ_SETTINGS where main_key='showSignFromCard'"; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(settingSql); + if (recordSet.next()) { + String main_val = recordSet.getString("main_val"); + showCard = main_val.equals("1"); + } + + Map signStatusInfo = new HashMap(); + + List dataList = new ArrayList<>(); + Map dataMap = new HashMap<>(); + List dataItemList = new ArrayList<>(); + Map dataItemMap = new HashMap<>(); + BaseBean bb = new BaseBean(); + //所有的休息班次id + String xxrSerialId = bb.getPropValue("hskq_main","xxrSerialId"); + Boolean checkXxr = false; + + String serialId = ""; + String sql = "SELECT a.RESOURCEID, a.KQDATE, a.GROUPID, a.SERIALID, a.SERIALNUMBER, a.WORKBEGINDATE,\n " + + "a.WORKBEGINTIME, a.WORKENDDATE, a.WORKENDTIME, a.WORKMINS, a.SIGNINDATE, a.SIGNINTIME,\n " + + "a.SIGNINID, a.SIGNOUTDATE, a.SIGNOUTTIME, a.SIGNOUTID, a.ATTENDANCEMINS, a.BELATEMINS,\n " + + "a.GRAVEBELATEMINS, a.LEAVEEARLYMINS, a.GRAVELEAVEEARLYMINS, a.ABSENTEEISMMINS, a.LEAVEMINS,\n " + + "a.EVECTIONMINS, a.OUTMINS, a.FORGOTCHECKMINS, a.SIGNMINS, a.LEAVEINFO, a.FORGOTBEGINWORKCHECKMINS,\n " + + "'signIn' signType,a.signInDate signDate,a.signInTime signTime,b.clientAddress,b.addr\n " + + "FROM KQ_FORMAT_DETAIL a LEFT JOIN HrmScheduleSign b ON a.signInId=b.id " + + "WHERE kqDate='" + date + "' AND resourceId=" + resourceId + "\n "; + if (!showCard) { + sql += " AND (signFrom is null or signFrom not like 'card%') "; + } + sql += "UNION ALL\n " + + "SELECT a.RESOURCEID, a.KQDATE, a.GROUPID, a.SERIALID, a.SERIALNUMBER, a.WORKBEGINDATE,\n " + + "a.WORKBEGINTIME, a.WORKENDDATE, a.WORKENDTIME, a.WORKMINS, a.SIGNINDATE, a.SIGNINTIME,\n " + + "a.SIGNINID, a.SIGNOUTDATE, a.SIGNOUTTIME, a.SIGNOUTID, a.ATTENDANCEMINS, a.BELATEMINS,\n " + + "a.GRAVEBELATEMINS, a.LEAVEEARLYMINS, a.GRAVELEAVEEARLYMINS, a.ABSENTEEISMMINS, a.LEAVEMINS,\n " + + "a.EVECTIONMINS, a.OUTMINS, a.FORGOTCHECKMINS, a.SIGNMINS, a.LEAVEINFO, a.FORGOTBEGINWORKCHECKMINS,\n " + + "'signOut' signType,a.signOutDate signDate,a.signOutTime signTime,b.clientAddress,b.addr\n " + + "FROM KQ_FORMAT_DETAIL a LEFT JOIN HrmScheduleSign b ON a.signOutId=b.id " + + "WHERE kqDate='" + date + "' AND resourceId=" + resourceId + "\n "; + if (!showCard) { + sql += " AND (signFrom is null or signFrom not like 'card%') "; + } + sql += "ORDER BY kqDate,resourceId,serialNumber,signType "; + recordSet.executeQuery(sql); + while (recordSet.next()) { + String signType = recordSet.getString("signType"); + String signDate = recordSet.getString("signDate"); + String signTime = recordSet.getString("signTime"); + String clientAddress = recordSet.getString("clientAddress"); + String addr = recordSet.getString("addr"); + + serialId = Util.null2String(recordSet.getString("serialId")); + int serialNumber = recordSet.getInt("serialnumber") + 1; + String workBeginTime = Util.null2String(recordSet.getString("workbegintime")).trim(); + String workEndTime = Util.null2String(recordSet.getString("workendtime")).trim(); + int workMins = recordSet.getInt("workMins"); + int attendanceMins = recordSet.getInt("attendanceMins"); + String beLateMins = Util.null2String(recordSet.getString("beLateMins")).trim(); + String graveBeLateMins = Util.null2String(recordSet.getString("graveBeLateMins")).trim(); + String leaveEarlyMins = Util.null2String(recordSet.getString("leaveEarlyMins")).trim(); + String graveLeaveEarlyMins = Util.null2String(recordSet.getString("graveLeaveEarlyMins")).trim(); + String absenteeismMins = Util.null2String(recordSet.getString("absenteeismMins")).trim(); + String forgotCheckMins = Util.null2String(recordSet.getString("forgotcheckMins")).trim(); + String forgotBeginWorkCheckMins = Util.null2String(recordSet.getString("forgotBeginWorkCheckMins")).trim(); + int leaveMins = recordSet.getInt("leaveMins"); + String leaveInfo = Util.null2String(recordSet.getString("leaveInfo")); + int evectionMins = recordSet.getInt("evectionMins"); + int outMins = recordSet.getInt("outMins"); + + signStatusInfo = new HashMap(); + signStatusInfo.put("worktime", workBeginTime); + signStatusInfo.put("absenteeismMins", absenteeismMins); + signStatusInfo.put("leaveMins", leaveMins); + signStatusInfo.put("leaveInfo", leaveInfo); + signStatusInfo.put("evectionMins", evectionMins); + signStatusInfo.put("outMins", outMins); + String signStatus = ""; + boolean needWorkFlow = false;//是否需要提交考勤异常流程 + if ("signIn".equals(signType)) { + signStatusInfo.put("beLateMins", beLateMins); + signStatusInfo.put("graveBeLateMins", graveBeLateMins); + signStatusInfo.put("forgotBeginWorkCheckMins", forgotBeginWorkCheckMins); + signStatus = "on"; + if (Util.getDoubleValue(beLateMins, 0) > 0 || Util.getDoubleValue(graveBeLateMins, 0) > 0 || Util.getDoubleValue(forgotBeginWorkCheckMins, 0) > 0 || Util.getDoubleValue(absenteeismMins, 0) > 0) { + needWorkFlow = true; + } + } else { + signStatusInfo.put("leaveEarlyMins", leaveEarlyMins); + signStatusInfo.put("graveLeaveEarlyMins", graveLeaveEarlyMins); + signStatusInfo.put("forgotCheckMins", forgotCheckMins); + signStatusInfo.put("forgotBeginWorkCheckMins", forgotBeginWorkCheckMins); + signStatus = "off"; + if (Util.getDoubleValue(leaveEarlyMins, 0) > 0 || Util.getDoubleValue(graveLeaveEarlyMins, 0) > 0 || Util.getDoubleValue(forgotCheckMins, 0) > 0 || Util.getDoubleValue(absenteeismMins, 0) > 0) { + needWorkFlow = true; + } + } + if (!resourceId.equals("" + user.getUID())) { + needWorkFlow = false; + } + String status = KQReportBiz.getSignStatus2(signStatusInfo, user, signStatus); +// if (serialId.equalsIgnoreCase("")) { +// continue; +// } + + + if ("signIn".equals(signType)) { + //签到 start + String signDateTime = signDate + " " + signTime; + if (signTime.trim().length() <= 0) { + signDateTime = SystemEnv.getHtmlLabelName(25994, user.getLanguage()); + }else{ + if(Arrays.asList(xxrSerialId.split(",")).contains(serialId)){ + //是休息班的班次,并且有打卡记录 + checkXxr = true; + } + } + + dataMap = new HashMap<>(); + dataItemList = new ArrayList(); + + dataItemMap = new HashMap(); + dataItemMap.put("title", SystemEnv.getHtmlLabelName(512504, user.getLanguage())); + dataItemMap.put("value", signDateTime); + dataItemList.add(dataItemMap); + + dataItemMap = new HashMap(); + dataItemMap.put("title", SystemEnv.getHtmlLabelName(20032, user.getLanguage()) + "IP"); + dataItemMap.put("value", clientAddress); + dataItemList.add(dataItemMap); + + dataItemMap = new HashMap(); + dataItemMap.put("title", SystemEnv.getHtmlLabelName(125531, user.getLanguage())); + dataItemMap.put("value", addr); + dataItemList.add(dataItemMap); + + dataMap.put("item", dataItemList); + dataMap.put("status", status); + dataMap.put("needWorkFlow", needWorkFlow); + + + dataList.add(dataMap); + //签到 end + } else { + //签退 start + String signDateTime = signDate + " " + signTime; + if (signTime.trim().length() <= 0) { + signDateTime = SystemEnv.getHtmlLabelName(25994, user.getLanguage()); + }else{ + if(Arrays.asList(xxrSerialId.split(",")).contains(serialId)){ + //是休息班的班次,并且有打卡记录 + checkXxr = true; + } + } + + dataMap = new HashMap<>(); + dataItemList = new ArrayList(); + + dataItemMap = new HashMap(); + dataItemMap.put("title", SystemEnv.getHtmlLabelName(512505, user.getLanguage())); + dataItemMap.put("value", signDateTime); + dataItemList.add(dataItemMap); + + dataItemMap = new HashMap(); + dataItemMap.put("title", SystemEnv.getHtmlLabelName(20033, user.getLanguage()) + "IP"); + dataItemMap.put("value", clientAddress); + dataItemList.add(dataItemMap); + + dataItemMap = new HashMap(); + dataItemMap.put("title", SystemEnv.getHtmlLabelName(132060, user.getLanguage())); + dataItemMap.put("value", addr); + dataItemList.add(dataItemMap); + + dataMap.put("item", dataItemList); + dataMap.put("status", status); + dataMap.put("needWorkFlow", needWorkFlow); + dataList.add(dataMap); + //签退 end + } + } + + if(Arrays.asList(xxrSerialId.split(",")).contains(serialId)){ + //是休息班的班次 + if(!checkXxr){ + //不存在打卡记录 + dataList = new ArrayList<>(); + } + } + + Map signDateMap = new HashMap(); + signDateMap.put("date", date); + signDateMap.put("signInfo", dataList); + //班次时间 + ShiftManagementToolKit shiftManagementToolKit = new ShiftManagementToolKit(); +// String serialInfo = shiftManagementToolKit.getShiftOnOffWorkSections(serialId, user.getLanguage()); + + //移动端显示未到日期班次 + String freeserial = ""; + if ("".equals(serialId) && "true".equals(isMobile)){ + try { + KQWorkTime kqWorkTime = new KQWorkTime(); + WorkTimeEntity workTime = kqWorkTime.getWorkTime(resourceId, date); + serialId = workTime == null ? "" : Util.null2String(workTime.getSerialId()); + if (Util.getIntValue(serialId,-1)>0){ + signDateMap.put("isWork",1); + } + + if("3".equals(workTime.getKQType())){ + if(!"0".equals(Util.null2String(workTime.getWorkMins()))){ + freeserial = SystemEnv.getHtmlLabelName(389129, user.getLanguage()); + signDateMap.put("isWork",1); + } + } + }catch (Exception e){ + new BaseBean().writeLog("========hb=======e:"+e); + } + } + //班次信息--加入自由班制的判断 + String serialInfo = shiftManagementToolKit.getShiftOnOffWorkSections(serialId, user.getLanguage(),date,resourceId); + + if (freeserial.length()>0){ + serialInfo = freeserial; + } + + + signDateMap.put("serialInfo", SystemEnv.getHtmlLabelName(24803, user.getLanguage()) + ":" + serialInfo); + resultMap.put("data", signDateMap); + new BaseBean().writeLog("GetHrmKQSignInfoCmd>>isMobile="+isMobile+";date="+date); + //只有移动端的【我的考勤】才需要显示流程相关的数据 + if ("true".equals(isMobile)) { + //获取考勤流程的相关数据 + List> workflowList = new ArrayList>(); + //请假 + workflowList = getFlowData(KqSplitFlowTypeEnum.LEAVE.getFlowtype()); + if (workflowList == null) { + workflowList = new ArrayList>(); + } + //出差 + workflowList.addAll(getFlowData(KqSplitFlowTypeEnum.EVECTION.getFlowtype())); + if (workflowList == null) { + workflowList = new ArrayList>(); + } + //公出 + workflowList.addAll(getFlowData(KqSplitFlowTypeEnum.OUT.getFlowtype())); + if (workflowList == null) { + workflowList = new ArrayList>(); + } + //加班 + workflowList.addAll(getFlowData(KqSplitFlowTypeEnum.OVERTIME.getFlowtype())); + resultMap.put("workflowInfo", workflowList); + } + } catch (Exception e) { + e.printStackTrace(); + } + return resultMap; + } + + public List> getFlowData(int flowType) { + List> resultList = new ArrayList>(); + try { + String resourceId = Util.null2String(params.get("resourceId")); + if ("".equals(resourceId)) { + resourceId = "" + user.getUID(); + } + String date = Util.null2String(params.get("date")); + if ("".equals(date)) { + date = DateUtil.getCurrentDate(); + } + String firstDateOfMonth = DateUtil.getFirstDayOfMonth(date); + String lastDateOfMonth = DateUtil.getLastDayOfMonth(date); + + /**获取销假*/ + List leaveBackList = getLeaveDate(); + + Map dataMap = new HashMap(); + Map workflowMap = new HashMap(); + List> workflowList = new ArrayList>(); + + boolean showOnHoliday = true;//非工作日是否显示流程(出差、公出、请假) + KQExitRulesComInfo exitRulesComInfo = new KQExitRulesComInfo(); + KQTravelRulesComInfo travelRulesComInfo = new KQTravelRulesComInfo(); + KQLeaveRulesComInfo rulesComInfo = new KQLeaveRulesComInfo(); + KQWorkTime kqWorkTime = new KQWorkTime(); + + if (flowType == 2) { + showOnHoliday = exitRulesComInfo.getComputingMode("1").equals("2"); + } else if (flowType == 1) { + showOnHoliday = travelRulesComInfo.getComputingMode("1").equals("2"); + } + + Map paramsMap = new HashMap(); + paramsMap.put("typeselect", "6"); + paramsMap.put("tabKey", "1"); + paramsMap.put("kqtype", "" + flowType); + paramsMap.put("resourceId", resourceId); + paramsMap.put("fromDate", firstDateOfMonth); + paramsMap.put("toDate", lastDateOfMonth); + paramsMap.put("isMyKQ", "1"); + + KQAttFlowSetBiz kqAttFlowSetBiz = new KQAttFlowSetBiz(); + Map sqlMap = kqAttFlowSetBiz.getFLowSql(paramsMap, user); + String sqlFrom = sqlMap.get("from"); + String sqlWhere = sqlMap.get("where"); + + String sql = "select * " + sqlFrom + sqlWhere; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql); + while (recordSet.next()) { + String requestId = recordSet.getString("requestId"); + double duration = Util.getDoubleValue(recordSet.getString("duration"), 0.00); + double backDuration = 0.00; + String requestName = recordSet.getString("requestName"); + int durationRule = Util.getIntValue(recordSet.getString("durationrule")); + String unitName = ""; + if (durationRule == 3 || durationRule == 5 || durationRule == 6) { + unitName = SystemEnv.getHtmlLabelName(389326, user.getLanguage()); + } else { + unitName = SystemEnv.getHtmlLabelName(389325, user.getLanguage()); + } + String fromDateTemp = recordSet.getString("fromDate"); + String fromTimeTemp = recordSet.getString("fromTime"); + String toDateTemp = recordSet.getString("toDate"); + String toTimeTemp = recordSet.getString("toTime"); + String leaveRulesId = ""; + String period = SystemEnv.getHtmlLabelName(506047, user.getLanguage()) + ":" + String.format("%.2f", duration) + unitName; + if (flowType == 0) { + backDuration = Util.getDoubleValue(recordSet.getString("backDuraion"), 0.00); + if (backDuration > 0) { + period = SystemEnv.getHtmlLabelName(506047, user.getLanguage()) + ":" + String.format("%.2f", duration) + "(" + SystemEnv.getHtmlLabelName(24473, user.getLanguage()) + ":" + String.format("%.2f", backDuration) + ")" + unitName; + } + leaveRulesId = recordSet.getString("newleavetype"); + showOnHoliday = rulesComInfo.getComputingMode(leaveRulesId).equals("2"); + } + + boolean isEnd = false; + for (String dateTemp = fromDateTemp; !isEnd; ) { + if (dateTemp.equals(toDateTemp)) { + isEnd = true; + } + if (!leaveBackList.contains(resourceId + "|" + date + "|" + requestId)) { + workflowList = (ArrayList>) dataMap.get(resourceId + "|" + dateTemp); + if (null == workflowList) { + workflowList = new ArrayList>(); + } + workflowMap = new HashMap(); + workflowMap.put("title", requestName); + workflowMap.put("period", period); + workflowMap.put("requestId", requestId); + workflowList.add(workflowMap); + + boolean isWorkDay = kqWorkTime.isWorkDay(resourceId, date); + if (!(!isWorkDay && !showOnHoliday)) { + dataMap.put(resourceId + "|" + dateTemp, workflowList); + } + } + + dateTemp = DateUtil.getDate(dateTemp, 1); + } + } + if (dataMap.get(resourceId + "|" + date) != null) { + resultList = (ArrayList>) dataMap.get(resourceId + "|" + date); + } + } catch (Exception e) { + e.printStackTrace(); + } + return resultList; + } + + /** + * 获取请完假之后又销掉的日期 + * + * @return + */ + private List getLeaveDate() { + List resultList = new ArrayList(); + try { + String resourceId = Util.null2String(params.get("resourceId")); + if ("".equals(resourceId)) { + resourceId = "" + user.getUID(); + } + String date = Util.null2String(params.get("date")); + if ("".equals(date)) { + date = DateUtil.getCurrentDate(); + } + String firstDateOfMonth = DateUtil.getFirstDayOfMonth(date); + String lastDateOfMonth = DateUtil.getLastDayOfMonth(date); + + String leaveBackTableName = KqSplitFlowTypeEnum.LEAVEBACK.getTablename(); + String leaveTableName = KqSplitFlowTypeEnum.LEAVE.getTablename(); + String sql = " select requestId,resourceId,belongDate,duration,durationRule," + + " (select sum(duration) from " + leaveBackTableName + " where " + leaveBackTableName + ".leavebackrequestid=" + leaveTableName + ".requestid " + + " and " + leaveBackTableName + ".newleavetype=" + leaveTableName + ".newleavetype " + + " and " + leaveBackTableName + ".belongdate=" + leaveTableName + ".belongDate ) as backDuration " + + " from " + leaveTableName + " where 1=1 "; + if (!resourceId.equals("")) { + sql += " and " + leaveTableName + ".resourceId=" + resourceId; + } + if (firstDateOfMonth.length() > 0 && lastDateOfMonth.length() > 0) { + sql += " and " + leaveTableName + ".belongdate between'" + firstDateOfMonth + "' and '" + lastDateOfMonth + "' "; + } + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql); + while (recordSet.next()) { + String requestId = recordSet.getString("requestId"); + String belongDate = recordSet.getString("belongDate"); + double duration = Util.getDoubleValue(recordSet.getString("duration"), 0.00); + double backDuration = Util.getDoubleValue(recordSet.getString("backDuration"), 0.00); + if (backDuration >= duration) { + resultList.add(resourceId + "|" + belongDate + "|" + requestId); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + return resultList; + } +} diff --git a/src/com/engine/kq/cmd/report/ExportExcelCmd.java b/src/com/engine/kq/cmd/report/ExportExcelCmd.java new file mode 100644 index 0000000..92d4cc5 --- /dev/null +++ b/src/com/engine/kq/cmd/report/ExportExcelCmd.java @@ -0,0 +1,941 @@ +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 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 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; + + 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(); + KQReportBiz kqReportBiz = new KQReportBiz(); + + 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); + + 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 = "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()); + Map flowData = new KQReportBiz().getFlowData(params, user); + //System.out.println("end" + DateUtil.getFullDate()); + + // #1475814-概述:满足考勤报分部部门显示及导出时显示全路径 + String fullPathMainKey = "show_full_path"; + KQSettingsComInfo kqSettingsComInfo = new KQSettingsComInfo(); + String isShowFullPath = Util.null2String(kqSettingsComInfo.getMain_val(fullPathMainKey),"0"); + + + rs.execute(sql); + while (rs.next()) { + data = new ArrayList<>(); + String id = rs.getString("id"); + String deptid = rs.getString("departmentid"); + 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(); + 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)); + + String valueOverTimeTotal = getFieldValueByUnitType(fieldValue,kqReportFieldComInfo.getUnittype(KQReportFieldComInfo.field2Id.get("overtimeTotal"))); + data.add(valueOverTimeTotal); + 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 if (fieldName.equals("jiabancishu")) { + // 计算加班次数(晚餐次数) + //fieldValue = StringUtil.isEmpty(Util.null2String(flowData.get(id + "|" + fieldName))) ? "0" : Util.null2String(flowData.get(id + "|" + fieldName)); + fieldValue = getDinnerCount(id,fromDate,toDate)+""; + } else if (fieldName.equals("jiabancishuYb")) { + // 计算加班次数(晚餐次数)(含夜班) + //fieldValue = StringUtil.isEmpty(Util.null2String(flowData.get(id + "|" + fieldName))) ? "0" : Util.null2String(flowData.get(id + "|" + fieldName)); + fieldValue = getDinnerCountOfNight(id,fromDate,toDate)+""; + } else if (fieldName.equals("yebancishu")) { + // 计算夜班次数 + fieldValue = getYbcsNew(id,fromDate,toDate)+""; + }else if (fieldName.equals("wucancishu")) { + // 午餐次数 + // fieldValue = StringUtil.isEmpty(Util.null2String(flowData.get(id + "|" + fieldName))) ? "0" : Util.null2String(flowData.get(id + "|" + fieldName)); + fieldValue = getLanchCount(id,fromDate,toDate)+""; + } else if (fieldName.equals("wucancishuYb")) { + // 午餐次数(含夜班) + // fieldValue = StringUtil.isEmpty(Util.null2String(flowData.get(id + "|" + fieldName))) ? "0" : Util.null2String(flowData.get(id + "|" + fieldName)); + fieldValue = getLanchCountOfNight(id,fromDate,toDate)+""; + } else if (fieldName.equals("deptcode")) { + fieldValue = departmentComInfo.getDepartmentCode(deptid); + } else if (fieldName.equals("supdept")) { + //fieldValue = departmentComInfo.getDepartmentRealPath(deptid, "/", "0",false) ; + fieldValue = departmentComInfo.getDepartmentname(departmentComInfo.getDepartmentsupdepid(deptid)); + } else if (fieldName.equals("ofr08name")) { + fieldValue = getCusFieldData(id,"field36",-1); + fieldValue = getCusSelectName(36,fieldValue); + } else if (fieldName.equals("ofr07name")) { + fieldValue = getCusFieldData(id,"field35",-1); + fieldValue = getCusSelectName(35,fieldValue); + }else if (fieldName.equals("attendanceMins")) { + String attendanceMinsN = Util.formatMultiLang(Util.null2String(rs.getString("attendanceMins")),""+user.getLanguage()); + attendanceMinsN = getFieldValueByUnitType(attendanceMinsN,kqReportFieldComInfo.getUnittype(fieldid)); + fieldValue = attendanceMinsN; + attendanceMinsN = Util.formatMultiLang(fieldValue,""+user.getLanguage()); + //二开,重新计算工作时长(包含加班) + 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)); + + String valueOverTimeTotal = getFieldValueByUnitType(fieldValue,kqReportFieldComInfo.getUnittype(KQReportFieldComInfo.field2Id.get("overtimeTotal"))); + double attendanceMins = Util.getDoubleValue((String) attendanceMinsN,0)+Util.getDoubleValue((String) valueOverTimeTotal,0); + fieldValue = KQDurationCalculatorUtil.getDurationRound(attendanceMins+""); + + } 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); + } + + //二开,重新计算工作时长(包含加班) +// double attendanceMins = Util.getDoubleValue((String) data.get(11),0)+Util.getDoubleValue((String) data.get(57),0); +// data.set(11,KQDurationCalculatorUtil.getDurationRound(attendanceMins+"")); + +// if(showColumns.contains("kqCalendar")) { +// Map detialDatas = kqReportBiz.getDetialDatasOnlyTime(id, fromDate, toDate, user); +// isEnd = false; +// for (String date = fromDate; !isEnd; ) { +// if (date.equals(toDate)) isEnd = true; +// if (DateUtil.compDate(today, date) > 0) { +// data.add(""); +// } else { +// if (detialDatas.get(id + "|" + date) != null) { +// String atttimeNew = getTimesByDay(id,date); +// //从建模取数据 +// double atttime = Double.valueOf(atttimeNew); +// data.add(atttime); +// } else { +// data.add(SystemEnv.getHtmlLabelName(26593, user.getLanguage())); +// } +// } +// cal.setTime(DateUtil.parseToDate(date)); +// date = DateUtil.getDate(cal.getTime(), 1); +// } +// } + + if(showColumns.contains("kqCalendar")) { + Map detialDatas = kqReportBiz.getDetialDatasOnlyTime(id, fromDate, toDate, user); + Map detialOvtimeDatas = kqReportBiz.getDetialOvtimeData(id, fromDate, toDate); + isEnd = false; + for (String date = fromDate; !isEnd; ) { + if (date.equals(toDate)) isEnd = true; + if (DateUtil.compDate(today, date) > 0) { + data.add(""); + } else { + if (detialDatas.get(id + "|" + date) != null) { + double atttime = Util.getDoubleValue((String) detialDatas.get(id + "|" + date),0); + if(detialOvtimeDatas.get(id + "|" + date) !=null ){ + atttime += (double) detialOvtimeDatas.get(id + "|" + date); + } + data.add(atttime); + } else { + data.add(SystemEnv.getHtmlLabelName(26593, user.getLanguage())); + } + } + cal.setTime(DateUtil.parseToDate(date)); + date = DateUtil.getDate(cal.getTime(), 1); + } + } + dataList.add(data); + } + sheet.put("dataList", dataList); + 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); + 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; + 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(); + 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; + } + + /** + * 查询自定义字段的值 + * @param id + * @param fieldname + * @param scopeid + * @return + */ + public String getCusFieldData(String id,String fieldname,int scopeid){ + String fieldVal = ""; + RecordSet rs = new RecordSet(); + String sql = "select "+fieldname+" from cus_fielddata where id=? and scopeid=? and scope='HrmCustomFieldByInfoType' "; + rs.executeQuery(sql,id,scopeid); + if(rs.next()){ + fieldVal = Util.null2String(rs.getString(fieldname)); + } + return fieldVal; + } + + /** + * 获取自定义下拉框值 + * @param fieldid + * @param selectvalue + * @return + */ + public String getCusSelectName(int fieldid,String selectvalue){ + String selectname = ""; + if(!"".equals(selectvalue)){ + RecordSet rs = new RecordSet(); + String sql = " select selectname from cus_selectitem where fieldid=? and selectvalue=? "; + rs.executeQuery(sql,fieldid,selectvalue); + if(rs.next()){ + selectname = Util.null2String(rs.getString("selectname")); + } + } + return selectname; + } + + /** + * 查询夜班次数 + * @param resourceid + * @param fromDate + * @param toDate + * @return + */ + public int getYbcs(String resourceid,String fromDate,String toDate){ + int ybcs = 0; + RecordSet rs = new RecordSet(); + rs.executeQuery(" select field35 from cus_fielddata where id = ? ",resourceid); + rs.next(); + int field35 = rs.getInt("field35"); + + //有加班流程且打卡时间在第二天0点-6点30之间才算夜班次数 + String jbSql = "select count(1) ybcs from kq_flow_overtime where resourceid =? " + + " and belongdate>=? and belongdate<=? " + + " and totimedb>='00:00' and totimedb<='06:30'"; + rs.executeQuery(jbSql,resourceid,fromDate,toDate); + if(rs.next()){ + ybcs += Util.getIntValue(rs.getString("ybcs"),0); + } + + //制造人员、劳务人员、实习生(2,3,4)需要加上正常的夜班和特殊夜班 + if(field35==2 || field35==4 || field35==4){ + String ybSql = " select count(1) ybcs from kq_format_detail " + + " where resourceid=? and serialid in(3,4) and attendanceMins>0 " + + " and kqdate>=? and kqdate<=? "; + rs.executeQuery(ybSql,resourceid,fromDate,toDate); + if(rs.next()){ + ybcs += Util.getIntValue(rs.getString("ybcs"),0); + } + } + return ybcs; + } + + + + /** + * 获取午餐次数 + * @param resourceid + * @param fromDate + * @param toDate + * @return + */ + public int getLanchCount(String resourceid, String fromDate, String toDate){ + int dinnerCount = 0; + RecordSet rs = new RecordSet(); + String sql = "select sum(wuccs) as wuccsAll from uf_zdyzdgsh where xm = "+resourceid+" and rq>='"+fromDate+"' and rq<= '"+toDate+"'"; + rs.executeQuery(sql); + if(rs.next()){ + dinnerCount = Util.getIntValue(rs.getString("wuccsAll"),0); + } + return dinnerCount; + } + + + + + /** + * 查询午餐次数(含夜班)次数 + * @param resourceid + * @param fromDate + * @param toDate + * @return + */ + public int getLanchCountOfNight(String resourceid,String fromDate,String toDate){ + int dinnerCount = 0; + RecordSet rs = new RecordSet(); + String sql = "select sum(wccshyb) as wccshybAll from uf_zdyzdgsh where xm = "+resourceid+" and rq>='"+fromDate+"' and rq<= '"+toDate+"'"; + rs.executeQuery(sql); + if(rs.next()){ + dinnerCount = Util.getIntValue(rs.getString("wccshybAll"),0); + } + return dinnerCount; + } + + /** + * 获取晚餐信息 + * @param resourceid + * @param fromDate + * @param toDate + * @return + */ + public int getDinnerCount(String resourceid,String fromDate,String toDate){ + int dinnerCount = 0; + RecordSet rs = new RecordSet(); + String sql = "select sum(wccs) as jiabancishu from uf_zdyzdgsh where xm = "+resourceid+" and rq>='"+fromDate+"' and rq<= '"+toDate+"'"; + rs.executeQuery(sql); + if(rs.next()){ + dinnerCount = Util.getIntValue(rs.getString("jiabancishu"),0); + } + return dinnerCount; + } + + /** + * 查询晚餐次数(当天有夜班) + * @param resourceid + * @param fromDate + * @param toDate + * @return + */ + public int getDinnerCountOfNight(String resourceid,String fromDate,String toDate){ + int dinnerCount = 0; + RecordSet rs = new RecordSet(); + String sql = "select sum(waccshyb) as jiabancishuYb from uf_zdyzdgsh where xm = "+resourceid+" and rq>='"+fromDate+"' and rq<= '"+toDate+"'"; + rs.executeQuery(sql); + if(rs.next()){ + dinnerCount = Util.getIntValue(rs.getString("jiabancishuYb"),0); + } + return dinnerCount; + } + + + /** + * 查询晚餐次数(当天有夜班) + * @param resourceid + * @param fromDate + * @param toDate + * @return + */ + public int getYbcsNew(String resourceid,String fromDate,String toDate){ + int dinnerCount = 0; + RecordSet rs = new RecordSet(); + String sql = "select sum(ybcs) as ybcsAll from uf_zdyzdgsh where xm = "+resourceid+" and rq>='"+fromDate+"' and rq<= '"+toDate+"'"; + rs.executeQuery(sql); + if(rs.next()){ + dinnerCount = Util.getIntValue(rs.getString("ybcsAll"),0); + } + return dinnerCount; + } + + /** + * 获取人员夜班情况 + * @param resourceid + * @param fromDate + * @param toDate + * @return + */ + public Map getNightShiftInfo(String resourceid,String fromDate,String toDate){ + Map ybInfo = new HashMap<>(); + RecordSet rs = new RecordSet(); + //1.夜班、特殊夜班班次,判断在班次内是否有过零点的打卡记录 ,记1次;(2023-9-13)下班卡最晚到次日9:00、当日有效出勤>=3.5H; + String ybSql = " select * from kq_format_detail " + + " where resourceid=? and kqdate>=? and kqdate<=? " + + " and serialid in(3,4) and attendanceMins/60>=3.5 and signouttime>='00:00:00' and signouttime<='12:00:00' "; + rs.executeQuery(ybSql,resourceid,fromDate,toDate); + while(rs.next()){ + ybInfo.put(Util.null2String(rs.getString("kqdate")),1); + } + + //2.白班班次(加班情况,白班不存在跨0点),加班下班卡最晚到次日9:00,且有效出勤>=3.5H,记1次; + // 休息日/法定节假日加班有效出勤时长>=3.5H(非工作日跨0点加班必须提外出流程),且下班卡过0点,记1次 + //0913修改,不用考虑加班流程,只看打卡时间和出勤时长 + //String jbSql = " select a.*,b.signindate ,b.signintime ,b.signoutdate ,b.signouttime from kq_flow_overtime a " + + // " left join kq_format_detail b on a.resourceid=b.resourceid and a.belongdate =b.kqdate " + + // " where a.resourceid =? and a.belongdate >=? and a.belongdate <=? " + + // " and (b.signouttime >='00:00:00' and b.signouttime <='09:00:00') and (attendanceMins+duration_min)/60>=3.5 "; + // + String ybsql = " select a.* from kq_format_detail a " + + " left join kq_flow_overtime b on a.resourceid=b.resourceid and a.kqdate =b.belongdate " + + " where a.resourceid=? and kqdate>=? and kqdate<=? " + + " and signouttime >='00:00:00' and signouttime <='12:00:00' and (ifnull(attendanceMins,0)+ifnull(duration_min,0)) /60>=3.5 "; + rs.executeQuery(ybsql,resourceid,fromDate,toDate); + while(rs.next()){ + ybInfo.put(Util.null2String(rs.getString("kqdate")),1); + } + return ybInfo; + } + + + + + /** + * 判断是否是不定时人员 + * @param userid + * @return + */ + public boolean timingStaff(String userid){ + RecordSet rs = new RecordSet(); + String sql = " select 1 from cus_fielddata where field112 in(1,2) and id=? "; + rs.executeQuery(sql,userid); + return rs.next(); + } + + /** + * 判断是否是不定时人员 + * @param userid + * @return + */ + public String getTimesByDay(String userid,String date){ + RecordSet rs = new RecordSet(); + String times = ""; + String ny = date.substring(0,7); + String ts = date.substring(8,10); + String fieldDay = "h" + Integer.valueOf(ts); + String sql = "select "+fieldDay+" from uf_kqhzbx where xm = "+userid+" and ny = '"+ny+"'"; + rs.executeQuery(sql); + if(rs.next()){ + times = Util.null2String(rs.getString(fieldDay)); + } + return times; + } + + /** + * 判断是否是保洁人员 + * @param userid + * @return + */ + public boolean cleanStaff(String userid){ + RecordSet rs = new RecordSet(); + String sql = " select 1 from hrmroles a, hrmrolemembers b where a.rolesmark='保洁人员' and a.id=b.roleid and b.resourceid=? "; + rs.executeQuery(sql,userid); + return rs.next(); + } + + + + @Override + public BizLogContext getLogContext() { + return null; + } + +} diff --git a/src/com/engine/kq/cmd/report/GetKQReportCmd.java b/src/com/engine/kq/cmd/report/GetKQReportCmd.java new file mode 100644 index 0000000..663c405 --- /dev/null +++ b/src/com/engine/kq/cmd/report/GetKQReportCmd.java @@ -0,0 +1,906 @@ +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.KQDurationCalculatorUtil; +import com.engine.kq.util.PageUidFactory; +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +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(); + + 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()); + 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", 65); + 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()*65); + column.put("children", childColumns); + } + columns.add(column); + + 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 = "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) "; + } + } + + 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"; + KQSettingsComInfo kqSettingsComInfo = new KQSettingsComInfo(); + String isShowFullPath = Util.null2String(kqSettingsComInfo.getMain_val(fullPathMainKey),"0"); + + Map flowData = kqReportBiz.getFlowData(params,user); + rs.execute(sql); + while (rs.next()) { + data = new HashMap<>(); + kqReportFieldComInfo.setTofirstRow(); + String id = rs.getString("id"); + String deptid = rs.getString("departmentid"); + 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(); + 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); + } + + //二开,重新计算工作时长(包含加班) + double attendanceMins = Util.getDoubleValue((String) data.get("attendanceMins"),0)+Util.getDoubleValue((String) data.get("overtimeTotal"),0); + data.put("attendanceMins",KQDurationCalculatorUtil.getDurationRound(attendanceMins+"")); + + Map detialDatas = kqReportBiz.getDetialDatas(id,fromDate,toDate,user); +// new KQLog().info("id:"+id+":detialDatas:"+detialDatas); + isEnd = false; + for(String date=fromDate; !isEnd;) { + if(date.equals(toDate)) isEnd = true; + if(DateUtil.compDate(today, date)>0){ + data.put(date,""); + }else{ +// new KQLog().info("id:date:"+(id+"|"+date)+":detialDatas.get:"+detialDatas.get(id+"|"+date)); + 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); + } + datas.add(data); + } + + List lsHolidays = KQHolidaySetBiz.getHolidaySetListByScope(""+user.getUID(),fromDate,toDate); + retmap.put("holidays", lsHolidays); + + retmap.put("columns",columns); + retmap.put("datas",datas); + retmap.put("pagesize", pageSize); + retmap.put("pageindex", pageIndex); + retmap.put("count", count); + retmap.put("pagecount", pageCount); + retmap.put("ishavepre", isHavePre); + retmap.put("ishavenext", isHaveNext); + }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; + 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(); + 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 belongdate<=? " + + " and totimedb>='00:00' and totimedb<='06:30'"; + rs.executeQuery(jbSql,resourceid,fromDate,toDate); + if(rs.next()){ + ybcs += Util.getIntValue(rs.getString("ybcs"),0); + } + + String ybSql = " select count(1) ybcs from kq_format_detail " + + " where resourceid=? and serialid in(3,4) and attendanceMins>0 " + + " and kqdate>=? and kqdate<=? "; + rs.executeQuery(ybSql,resourceid,fromDate,toDate); + if(rs.next()){ + ybcs += Util.getIntValue(rs.getString("ybcs"),0); + } + + return ybcs; + } + + + /** + * 获取午餐次数 + * @param resourceid + * @param fromDate + * @param toDate + * @return + */ + public int getLanchCount(String resourceid, String fromDate, String toDate){ + int dinnerCount = 0; + RecordSet rs = new RecordSet(); + String sql = "select sum(wuccs) as wuccsAll from uf_zdyzdgsh where xm = "+resourceid+" and rq>='"+fromDate+"' and rq<= '"+toDate+"'"; + rs.executeQuery(sql); + if(rs.next()){ + dinnerCount = Util.getIntValue(rs.getString("wuccsAll"),0); + } + return dinnerCount; + } + + + + + /** + * 查询午餐次数(含夜班)次数 + * @param resourceid + * @param fromDate + * @param toDate + * @return + */ + public int getLanchCountOfNight(String resourceid,String fromDate,String toDate){ + int dinnerCount = 0; + RecordSet rs = new RecordSet(); + String sql = "select sum(wccshyb) as wccshybAll from uf_zdyzdgsh where xm = "+resourceid+" and rq>='"+fromDate+"' and rq<= '"+toDate+"'"; + rs.executeQuery(sql); + if(rs.next()){ + dinnerCount = Util.getIntValue(rs.getString("wccshybAll"),0); + } + return dinnerCount; + } + + /** + * 获取晚餐信息 + * @param resourceid + * @param fromDate + * @param toDate + * @return + */ + public int getDinnerCount(String resourceid,String fromDate,String toDate){ + int dinnerCount = 0; + RecordSet rs = new RecordSet(); + String sql = "select sum(wccs) as jiabancishu from uf_zdyzdgsh where xm = "+resourceid+" and rq>='"+fromDate+"' and rq<= '"+toDate+"'"; + rs.executeQuery(sql); + if(rs.next()){ + dinnerCount = Util.getIntValue(rs.getString("jiabancishu"),0); + } + return dinnerCount; + } + + /** + * 查询晚餐次数(当天有夜班) + * @param resourceid + * @param fromDate + * @param toDate + * @return + */ + public int getDinnerCountOfNight(String resourceid,String fromDate,String toDate){ + int dinnerCount = 0; + RecordSet rs = new RecordSet(); + String sql = "select sum(waccshyb) as jiabancishuYb from uf_zdyzdgsh where xm = "+resourceid+" and rq>='"+fromDate+"' and rq<= '"+toDate+"'"; + rs.executeQuery(sql); + if(rs.next()){ + dinnerCount = Util.getIntValue(rs.getString("jiabancishuYb"),0); + } + return dinnerCount; + } + + + /** + * 查询晚餐次数(当天有夜班) + * @param resourceid + * @param fromDate + * @param toDate + * @return + */ + public int getYbcsNew(String resourceid,String fromDate,String toDate){ + int dinnerCount = 0; + RecordSet rs = new RecordSet(); + String sql = "select sum(ybcs) as ybcsAll from uf_zdyzdgsh where xm = "+resourceid+" and rq>='"+fromDate+"' and rq<= '"+toDate+"'"; + rs.executeQuery(sql); + if(rs.next()){ + dinnerCount = Util.getIntValue(rs.getString("ybcsAll"),0); + } + return dinnerCount; + } + + + /** + * 获取人员夜班情况 + * @param resourceid + * @param fromDate + * @param toDate + * @return + */ + public Map getNightShiftInfo(String resourceid,String fromDate,String toDate){ + Map ybInfo = new HashMap<>(); + RecordSet rs = new RecordSet(); + //1.夜班、特殊夜班班次,判断在班次内是否有过零点的打卡记录 ,记1次;(2023-9-13)下班卡最晚到次日9:00、当日有效出勤>=3.5H; + String ybSql = " select * from kq_format_detail " + + " where resourceid=? and kqdate>=? and kqdate<=? " + + " and serialid in(3,4) and attendanceMins/60>=3.5 and signouttime>='00:00:00' and signouttime<='12:00:00' "; + rs.executeQuery(ybSql,resourceid,fromDate,toDate); + while(rs.next()){ + ybInfo.put(Util.null2String(rs.getString("kqdate")),1); + } + + //2.白班班次(加班情况,白班不存在跨0点),加班下班卡最晚到次日9:00,且有效出勤>=3.5H,记1次; + // 休息日/法定节假日加班有效出勤时长>=3.5H(非工作日跨0点加班必须提外出流程),且下班卡过0点,记1次 + //0913修改,不用考虑加班流程,只看打卡时间和出勤时长 + //String jbSql = " select a.*,b.signindate ,b.signintime ,b.signoutdate ,b.signouttime from kq_flow_overtime a " + + // " left join kq_format_detail b on a.resourceid=b.resourceid and a.belongdate =b.kqdate " + + // " where a.resourceid =? and a.belongdate >=? and a.belongdate <=? " + + // " and (b.signouttime >='00:00:00' and b.signouttime <='09:00:00') and (attendanceMins+duration_min)/60>=3.5 "; + // + String jbsql = " select a.* from kq_format_detail a " + + " left join kq_flow_overtime b on a.resourceid=b.resourceid and a.kqdate =b.belongdate " + + " where a.resourceid=? and kqdate>=? and kqdate<=? " + + " and signouttime >='00:00:00' and signouttime <='12:00:00' and (ifnull(attendanceMins,0)+ifnull(duration_min,0)) /60>=3.5 "; + rs.executeQuery(jbsql,resourceid,fromDate,toDate); + while(rs.next()){ + ybInfo.put(Util.null2String(rs.getString("kqdate")),1); + } + return ybInfo; + } + + + + + /** + * 判断是否是不定时人员 + * @param userid + * @return + */ + public boolean timingStaff(String userid){ + RecordSet rs = new RecordSet(); + String sql = " select 1 from cus_fielddata where field112 in(1,2) and id=? "; + rs.executeQuery(sql,userid); + return rs.next(); + } + + /** + * 判断是否是保洁人员 + * @param userid + * @return + */ + public boolean cleanStaff(String userid){ + RecordSet rs = new RecordSet(); + String sql = " select 1 from hrmroles a, hrmrolemembers b where a.rolesmark='保洁人员' and a.id=b.roleid and b.resourceid=? "; + rs.executeQuery(sql,userid); + return rs.next(); + } + + + + + @Override + public BizLogContext getLogContext() { + return null; + } + +} diff --git a/src/com/engine/kq/cmd/shiftmanagement/GetShiftManagementBaseFormCmd.java b/src/com/engine/kq/cmd/shiftmanagement/GetShiftManagementBaseFormCmd.java new file mode 100644 index 0000000..f6ec2fe --- /dev/null +++ b/src/com/engine/kq/cmd/shiftmanagement/GetShiftManagementBaseFormCmd.java @@ -0,0 +1,424 @@ +package com.engine.kq.cmd.shiftmanagement; + +import com.api.browser.bean.SearchConditionItem; +import com.api.browser.bean.SearchConditionOption; +import com.api.hrm.bean.HrmFieldBean; +import com.api.hrm.util.HrmFieldSearchConditionComInfo; +import com.engine.common.biz.AbstractCommonCommand; +import com.engine.common.entity.BizLogContext; +import com.engine.core.interceptor.CommandContext; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; +import weaver.hrm.company.SubCompanyComInfo; +import weaver.hrm.moduledetach.ManageDetachComInfo; +import weaver.systeminfo.SystemEnv; +import weaver.systeminfo.systemright.CheckSubCompanyRight; + +/** + * 获取班次管理基本信息表单 + * @author pzy + * + */ +public class GetShiftManagementBaseFormCmd extends AbstractCommonCommand>{ + + public GetShiftManagementBaseFormCmd(Map params, User user) { + this.user = user; + this.params = params; + } + + @Override + public BizLogContext getLogContext() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Map execute(CommandContext commandContext) { + Map retmap = new HashMap(); + List> grouplist = new ArrayList>(); + Map groupitem = null; + List itemlist = null; + RecordSet rs = new RecordSet(); + RecordSet rs1 = new RecordSet(); + String sql = ""; + try { + if(!HrmUserVarify.checkUserRight("KQClass:Management",user)) { + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage())); + return retmap; + } + CheckSubCompanyRight newCheck=new CheckSubCompanyRight(); + ManageDetachComInfo manageDetachComInfo = new ManageDetachComInfo(); + boolean hrmdetachable = manageDetachComInfo.isUseHrmManageDetach();//是否开启了人力资源模块的管理分权 + String hrmdftsubcomid = manageDetachComInfo.getHrmdftsubcomid();//分权默认分部 + + SubCompanyComInfo sc = new SubCompanyComInfo(); + String _id = Util.null2String(params.get("id")); + String subcompanyid = Util.null2String(params.get("subcompanyid")); + boolean isEdit = false; + + List workSectionList = new ArrayList<>(); + Map groupSectionMaps = new HashMap<>();//分组用的map + Map sectionMaps = new HashMap<>(); + Map sectionMap = new HashMap<>(); + + //现在休息时段还是只能设置一个的,对于以后可能出现的多个休息时段预留这个map + List restSectionsList = new ArrayList<>(); + Map restSectionsMap = new HashMap<>(); + + String[] fields = new String[]{"serial,125818,1,1","subcompanyid,141,3,169","shiftonoffworkcount,388563,5,3","punchsettings,388564,4,1", + "rest_shift,536771,4,2", + "isresttimeopen,388565,4,2","restbeigin,388566,3,19","restend,388567,3,19","halfcalrule,513090,5,1","cardRemind,507833,4,2","cardRemOfSignIn,507835,5,1", + "minsBeforeSignIn,510106,1,2","cardRemOfSignOut,507837,5,1","minsAfterSignOut,510108,1,2","remindMode,501471,5,3","remindOnPC,513233,4,2", + "isoffdutyfreecheck,388568,4,2","halfcalpoint,513145,3,19","halfcalpoint2cross,513090,5,1"}; + + Map shiftValMap = new HashMap<>(); + if(_id.length() > 0){ + String getShiftInfo = "select * from kq_ShiftManagement where (isdelete is null or isdelete <> '1') and id = ?"; + rs.executeQuery(getShiftInfo, _id); + if(rs.next()){ + for(int i = 0 ; i < fields.length ; i++){ + String[] tmpField = Util.null2String(fields[i]).split(","); + String fieldname = tmpField[0]; + String fieldvalue = rs.getString(fieldname); + if("shiftonoffworkcount".equalsIgnoreCase(fieldname) || + "punchsettings".equalsIgnoreCase(fieldname) || + "cardRemOfSignIn".equalsIgnoreCase(fieldname) || + "cardRemOfSignOut".equalsIgnoreCase(fieldname) || + "remindMode".equalsIgnoreCase(fieldname)){ + fieldvalue = Util.null2s(fieldvalue, "1"); + }else if("isresttimeopen".equalsIgnoreCase(fieldname) || + "halfcalrule".equalsIgnoreCase(fieldname) || + "cardRemind".equalsIgnoreCase(fieldname) || + "minsAfterSignOut".equalsIgnoreCase(fieldname) || + "remindOnPC".equalsIgnoreCase(fieldname) || + "isoffdutyfreecheck".equalsIgnoreCase(fieldname) || + "halfcalpoint".equalsIgnoreCase(fieldname) || + "halfcalpoint2cross".equalsIgnoreCase(fieldname)|| + "rest_shift".equalsIgnoreCase(fieldname)){ + fieldvalue = Util.null2s(fieldvalue, "0"); + }else if("minsBeforeSignIn".equalsIgnoreCase(fieldname)){ + fieldvalue = Util.null2s(fieldvalue, "10"); + }else if("subcompanyid".equalsIgnoreCase(fieldname)){ + subcompanyid = fieldvalue; + } + shiftValMap.put(fieldname, fieldvalue); + } + } + + String getWorkSections = "select * from kq_ShiftOnOffWorkSections where (isdelete is null or isdelete <> '1') and serialid = ? order by record "; + rs.executeQuery(getWorkSections, _id); + while(rs.next()){ + String record = rs.getString("record"); + if(record.length() == 0) { + continue; + } + + String onoffworktype = Util.null2String(rs.getString("onoffworktype")); + String across = Util.null2String(rs.getString("across")); + String times = Util.null2String(rs.getString("times")); + String mins = Util.null2String(rs.getString("mins")); + String mins_next = Util.null2String(rs.getString("mins_next")); + sectionMap = new HashMap<>(); + sectionMaps = new HashMap<>(); + sectionMap.put("across", across); + sectionMap.put("times", times); + sectionMap.put("mins", mins); + sectionMap.put("mins_next", mins_next); + sectionMaps.put(onoffworktype, sectionMap); + if(groupSectionMaps.get(record) != null){ + List tmpSections = (List) groupSectionMaps.get(record); + ((Map)tmpSections.get(tmpSections.size()-1)).putAll(sectionMaps); + }else{ + sectionMaps.put("record", record); + workSectionList.add(sectionMaps); + groupSectionMaps.put(record, workSectionList); + } + } + + String getRestSections = "select * from kq_ShiftRestTimeSections where (isdelete is null or isdelete <> '1') and serialid = ? "; + rs.executeQuery(getRestSections, _id); + while(rs.next()){ + String resttype = Util.null2String(rs.getString("resttype")); + String across = Util.null2String(rs.getString("across")); + String times = Util.null2String(rs.getString("time")); + restSectionsMap = new HashMap<>(); + restSectionsMap.put("resttype", resttype); + restSectionsMap.put("time", times); + restSectionsMap.put("across", across); + restSectionsList.add(restSectionsMap); + if("start".equalsIgnoreCase(resttype)){ + shiftValMap.put("restbeigin", times); + }else if("end".equalsIgnoreCase(resttype)){ + shiftValMap.put("restend", times); + } + } + isEdit = true; + } + + //班次名称 所属机构(开启分权有所属机构) 一天内上下班次数 打卡时段是否开启 排除休息时间是否开启 休息开始时间 休息结束时间 允许下班不打卡 + HrmFieldBean hrmFieldBean = null; + + HrmFieldSearchConditionComInfo hrmFieldSearchConditionComInfo = new HrmFieldSearchConditionComInfo(); + SearchConditionItem searchConditionItem = null; + List options = new ArrayList(); + + groupitem = new HashMap(); + + itemlist = new ArrayList(); + for (int j = 0; j < fields.length; j++) { + options = new ArrayList(); + String[] tmpField = Util.null2String(fields[j]).split(","); + String fieldname = tmpField[0]; + String beanVal = Util.null2String(shiftValMap.get(fieldname)); + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname(fieldname); + hrmFieldBean.setFieldlabel(tmpField[1]); + hrmFieldBean.setFieldhtmltype(tmpField[2]); + hrmFieldBean.setType(tmpField[3]); + hrmFieldBean.setIsFormField(true); + + if("serial".equalsIgnoreCase(tmpField[0]) || "restbeigin".equalsIgnoreCase(tmpField[0]) || "restend".equalsIgnoreCase(tmpField[0])){ + hrmFieldBean.setViewAttr(3); + hrmFieldBean.setRules("required|string"); + } + if("shiftonoffworkcount".equalsIgnoreCase(tmpField[0]) || "restbeigin".equalsIgnoreCase(tmpField[0]) || "restend".equalsIgnoreCase(tmpField[0])){ + hrmFieldBean.setRules("required|string"); + if(!isEdit){ + if("restbeigin".equalsIgnoreCase(tmpField[0])){ + hrmFieldBean.setFieldvalue("12:00"); + } + if("restend".equalsIgnoreCase(tmpField[0])){ + hrmFieldBean.setFieldvalue("13:00"); + } + } + } +// if("color".equalsIgnoreCase(tmpField[0])){ +// hrmFieldBean.setTip(SystemEnv.getHtmlLabelName(389509, user.getLanguage())); +// } + if(!isEdit){ + if("isresttimeopen".equalsIgnoreCase(tmpField[0])){ + hrmFieldBean.setFieldvalue("0"); + } + if("isoffdutyfreecheck".equalsIgnoreCase(tmpField[0])){ + hrmFieldBean.setFieldvalue("0"); + } + if("punchsettings".equalsIgnoreCase(tmpField[0])){ + hrmFieldBean.setFieldvalue("1"); + } +// if("color".equalsIgnoreCase(tmpField[0])){ +// hrmFieldBean.setFieldvalue("#000"); +// } + if("cardRemOfSignIn".equals(hrmFieldBean.getFieldname())){ + beanVal = "1"; + } + if("minsBeforeSignIn".equals(hrmFieldBean.getFieldname())){ + beanVal = "10"; + } + if("cardRemOfSignOut".equals(hrmFieldBean.getFieldname())){ + beanVal = "1"; + } + if("minsAfterSignOut".equals(hrmFieldBean.getFieldname())){ + beanVal = "0"; + } + if("remindMode".equals(hrmFieldBean.getFieldname())){ + beanVal = "1"; + } + if("halfcalrule".equals(hrmFieldBean.getFieldname())){ + hrmFieldBean.setFieldvalue("0"); + } + if("halfcalpoint2cross".equals(hrmFieldBean.getFieldname())){ + hrmFieldBean.setFieldvalue("0"); + } + if("rest_shift".equals(hrmFieldBean.getFieldname())){ + hrmFieldBean.setFieldvalue("0"); + } + } + + if("shiftonoffworkcount".equals(tmpField[0])){ + SearchConditionOption SearchConditionOption_1 = new SearchConditionOption("1",SystemEnv.getHtmlLabelName(388569, user.getLanguage())); + SearchConditionOption SearchConditionOption_2 = new SearchConditionOption("2",SystemEnv.getHtmlLabelName(388570, user.getLanguage())); + SearchConditionOption SearchConditionOption_3 = new SearchConditionOption("3",SystemEnv.getHtmlLabelName(388571, user.getLanguage())); + if(isEdit){ + if("1".equalsIgnoreCase(beanVal)){ + SearchConditionOption_1.setSelected(true); + }else if("2".equalsIgnoreCase(beanVal)){ + SearchConditionOption_2.setSelected(true); + }else if("3".equalsIgnoreCase(beanVal)){ + SearchConditionOption_3.setSelected(true); + } + }else{ + SearchConditionOption_1.setSelected(true); + } + options.add(SearchConditionOption_1); + options.add(SearchConditionOption_2); + options.add(SearchConditionOption_3); + hrmFieldBean.setSelectOption(options); + } + if(isEdit){ + hrmFieldBean.setFieldvalue(beanVal); + } + if("subcompanyid".equals(tmpField[0])){ + if(hrmdetachable){ + hrmFieldBean.setViewAttr(3); + hrmFieldBean.setRules("required|string"); + String defaultSubcompanyid = ""; + int[] subcomids = newCheck.getSubComByUserRightId(user.getUID(),"KQClass:Management",0); + ManageDetachComInfo detachComInfo = new ManageDetachComInfo(); + if(detachComInfo.isUseHrmManageDetach()){ + defaultSubcompanyid = detachComInfo.getHrmdftsubcomid(); + }else{ + rs.executeProc("SystemSet_Select",""); + if(rs.next()){ + if(subcompanyid.length()==0||subcompanyid.equals("0")){ + defaultSubcompanyid = Util.null2String(rs.getString("dftsubcomid")); + } + } + } + + boolean hasRight = false; + for (int i = 0; subcomids!=null&& i < subcomids.length; i++) { + if((""+subcomids[i]).equals(defaultSubcompanyid)){ + hasRight = true; + break; + } + } + + if(!hasRight){ + defaultSubcompanyid = ""; + } + //表示左侧分部树选择了 + if(Util.getIntValue(Util.null2String(subcompanyid)) > 0){ + hrmFieldBean.setFieldvalue(subcompanyid); + }else{ + hrmFieldBean.setFieldvalue(defaultSubcompanyid); + } + + }else{ + //不开启分权的话,不显示分部 + continue; + } + } + if("punchsettings".equalsIgnoreCase(tmpField[0])){ + hrmFieldBean.setFieldvalue("1"); + } + searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + if("shiftonoffworkcount".equals(tmpField[0])){ +// searchConditionItem.setHelpfulTip(SystemEnv.getHtmlLabelName(388574, user.getLanguage())); + } + if("isoffdutyfreecheck".equals(tmpField[0])){ + searchConditionItem.setHelpfulTip(SystemEnv.getHtmlLabelName(388573, user.getLanguage())); + } + if(hrmdetachable && "subcompanyid".equals(tmpField[0])){ + searchConditionItem.getBrowserConditionParam().getDataParams().put("rightStr", "KQClass:Management"); + searchConditionItem.getBrowserConditionParam().getCompleteParams().put("rightStr", "KQClass:Management"); + } + if("cardRemOfSignIn".equals(hrmFieldBean.getFieldname())){ + List optionsList = new ArrayList(); + optionsList.add(new SearchConditionOption("0", SystemEnv.getHtmlLabelName(19782, user.getLanguage()), "0".equals(beanVal))); + optionsList.add(new SearchConditionOption("1", SystemEnv.getHtmlLabelName(510106, user.getLanguage()), "1".equals(beanVal))); + searchConditionItem.setOptions(optionsList); + searchConditionItem.setValue(beanVal); + } + if("minsBeforeSignIn".equals(hrmFieldBean.getFieldname())||"minsAfterSignOut".equals(hrmFieldBean.getFieldname())){ + searchConditionItem.setValue(beanVal); + searchConditionItem.setMin("0"); + searchConditionItem.setViewAttr(3); + searchConditionItem.setRules("required|integer"); + } + if("cardRemOfSignOut".equals(hrmFieldBean.getFieldname())){ + List optionsList = new ArrayList(); + optionsList.add(new SearchConditionOption("0", SystemEnv.getHtmlLabelName(19782, user.getLanguage()), "0".equals(beanVal))); + optionsList.add(new SearchConditionOption("1", SystemEnv.getHtmlLabelName(510108, user.getLanguage()), "1".equals(beanVal))); + searchConditionItem.setOptions(optionsList); + searchConditionItem.setValue(beanVal); + } + if("remindMode".equals(hrmFieldBean.getFieldname())){ + List optionsList = new ArrayList(); + optionsList.add(new SearchConditionOption("1", SystemEnv.getHtmlLabelName(383607, user.getLanguage()), "1".equals(beanVal))); + optionsList.add(new SearchConditionOption("2", SystemEnv.getHtmlLabelName(18845, user.getLanguage()), "2".equals(beanVal))); + optionsList.add(new SearchConditionOption("3", SystemEnv.getHtmlLabelName(17586, user.getLanguage()), "3".equals(beanVal))); + searchConditionItem.setOptions(optionsList); + searchConditionItem.setValue(beanVal); + } + if("halfcalrule".equals(hrmFieldBean.getFieldname())){ + List optionsList = new ArrayList(); + optionsList.add(new SearchConditionOption("0", SystemEnv.getHtmlLabelName(513091, user.getLanguage()), "0".equals(beanVal))); + optionsList.add(new SearchConditionOption("1", SystemEnv.getHtmlLabelName(513092, user.getLanguage()), "1".equals(beanVal))); + searchConditionItem.setOptions(optionsList); + } + if("halfcalpoint2cross".equals(hrmFieldBean.getFieldname())){ + List optionsList = new ArrayList(); + optionsList.add(new SearchConditionOption("0", SystemEnv.getHtmlLabelName(509159, user.getLanguage()), "0".equals(beanVal))); + optionsList.add(new SearchConditionOption("1", SystemEnv.getHtmlLabelName(388785, user.getLanguage()), "1".equals(beanVal))); + searchConditionItem.setOptions(optionsList); + } + searchConditionItem.setColSpan(1); + + itemlist.add(searchConditionItem); + } + groupitem.put("items", itemlist); + grouplist.add(groupitem); + int operatelevel = -1; + if(hrmdetachable){ + if(subcompanyid.length()>0 && !subcompanyid.equalsIgnoreCase("0")){ + CheckSubCompanyRight checkSubCompanyRight = new CheckSubCompanyRight(); + operatelevel=checkSubCompanyRight.ChkComRightByUserRightCompanyId(user.getUID(),"KQClass:Management",Util.getIntValue(subcompanyid,-1)); + } + }else{ + operatelevel = 2; + } + if(!isEdit){ + operatelevel = 2; + } + + if(user.getUID() == 1){ + operatelevel = 2; + } + if(operatelevel > 0){ + retmap.put("canAdd", true); + }else{ + retmap.put("canAdd", false); + } + retmap.put("status", "1"); + retmap.put("condition", grouplist); + retmap.put("workSections", workSectionList); + retmap.put("restTimeSections", restSectionsList); + if(shift_24()){ + retmap.put("shift_24", "1"); + }else{ + retmap.put("shift_24", "0"); + } + retmap.put("id", _id); + } catch (Exception e) { + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(382661,user.getLanguage())); + writeLog(e); + } + return retmap; + } + + /** + * 班次是否放开24小时制 + * @return + */ + public boolean shift_24() { + boolean shift_24 = false; + RecordSet rs = new RecordSet(); + String settingSql = "select * from KQ_SETTINGS where main_key='shift_24'"; + rs.executeQuery(settingSql); + if(rs.next()){ + String main_val = rs.getString("main_val"); + if("1".equalsIgnoreCase(main_val)){ + shift_24 = true; + } + } + return shift_24; + } +} diff --git a/src/com/engine/kq/cmd/shiftmanagement/SaveShiftManagementBaseFormCmd.java b/src/com/engine/kq/cmd/shiftmanagement/SaveShiftManagementBaseFormCmd.java new file mode 100644 index 0000000..8c2ba9e --- /dev/null +++ b/src/com/engine/kq/cmd/shiftmanagement/SaveShiftManagementBaseFormCmd.java @@ -0,0 +1,489 @@ +package com.engine.kq.cmd.shiftmanagement; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.engine.common.biz.AbstractCommonCommand; +import com.engine.common.biz.SimpleBizLogger; +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.kq.biz.KQConfigComInfo; +import com.engine.kq.biz.KQGroupBiz; +import com.engine.kq.biz.KQGroupComInfo; +import com.engine.kq.biz.KQShiftManagementComInfo; +import com.engine.kq.biz.KQShiftOnOffWorkSectionComInfo; +import com.engine.kq.biz.KQShiftRestTimeSectionComInfo; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.UUID; +import weaver.common.StringUtil; +import weaver.conn.RecordSet; +import weaver.conn.RecordSetTrans; +import weaver.general.Util; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.Reminder.KQAutoCardTask; +import weaver.hrm.User; +import weaver.hrm.common.database.dialect.DbDialectFactory; +import weaver.hrm.common.database.dialect.IDbDialectSql; +import weaver.systeminfo.SystemEnv; + +/** + * 保存班次管理基本信息表单 + * @author pzy + * + */ +public class SaveShiftManagementBaseFormCmd extends AbstractCommonCommand>{ + + private SimpleBizLogger logger; + + public SaveShiftManagementBaseFormCmd() { + } + + public SaveShiftManagementBaseFormCmd(Map params, User user) { + this.user = user; + this.params = params; + this.logger = new SimpleBizLogger(); + BizLogContext logContext = new BizLogContext(); + logContext.setDateObject(new Date()); + logContext.setLogType(BizLogType.HRM_ENGINE); + logContext.setBelongType(BizLogSmallType4Hrm.HRM_ENGINE_SHIFTMANAGER); + logContext.setLogSmallType(BizLogSmallType4Hrm.HRM_ENGINE_SHIFTMANAGER); + logContext.setParams(params); + logger.setUser(user);//当前操作人 + if(params != null && params.containsKey("data")){ + String datas = Util.null2String(params.get("data")); + JSONObject jsonObj = JSON.parseObject(datas); + String serialid = Util.null2String(jsonObj.get("id")); + + if(serialid.length() > 0){ + String mainSql = " select * from kq_ShiftManagement where id= "+serialid +" "; + logger.setMainSql(mainSql);//主表sql + logger.setMainPrimarykey("id");//主日志表唯一key + logger.setMainTargetNameColumn("serial"); + + SimpleBizLogger.SubLogInfo subLogInfo1 = logger.getNewSubLogInfo(); + String subSql1 = "select * from kq_ShiftOnOffWorkSections where serialid="+serialid; + subLogInfo1.setSubTargetNameColumn("times"); + subLogInfo1.setGroupId("0"); //所属分组, 按照groupid排序显示在详情中, 不设置默认按照add的顺序。 + subLogInfo1.setSubGroupNameLabel(27961); //在详情中显示的分组名称,不设置默认显示明细x + subLogInfo1.setSubSql(subSql1); + logger.addSubLogInfo(subLogInfo1); + + SimpleBizLogger.SubLogInfo subLogInfo = logger.getNewSubLogInfo(); + String subSql = " select * from kq_ShiftRestTimeSections where serialid = "+serialid; + subLogInfo.setSubSql(subSql); + subLogInfo.setSubTargetNameColumn("time"); + subLogInfo.setGroupId("1"); //所属分组, 按照groupid排序显示在详情中, 不设置默认按照add的顺序。 + subLogInfo.setSubGroupNameLabel(505603); //在详情中显示的分组名称,不设置默认显示明细x + logger.addSubLogInfo(subLogInfo); + logger.before(logContext); + } + } + + } + + @Override + public BizLogContext getLogContext() { + // TODO Auto-generated method stub + return null; + } + + @Override + public List getLogContexts() { + return logger.getBizLogContexts(); + } + + /** + * 获取日志对象的名称 + * @param id + * @param para2 + * @return + */ + public String getTargetName(String id,String para2){ + try { + return para2; + } catch (Exception e) { + e.printStackTrace(); + return ""; + } + } + + @Override + public Map execute(CommandContext commandContext) { + Map retmap = new HashMap(); + String datas = Util.null2String(params.get("data")); + JSONObject jsonObj = JSON.parseObject(datas); + String serialid = Util.null2String(jsonObj.get("id")); + if(!HrmUserVarify.checkUserRight("KQClass:Management",user)) { + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage())); + return retmap; + } + + try{ + if(serialid.length() > 0){ + edit(retmap,jsonObj); + }else{ + add(retmap,jsonObj); + } + KQShiftManagementComInfo kqShiftManagementComInfo = new KQShiftManagementComInfo(); + kqShiftManagementComInfo.removeShiftManagementCache(); + + if(retmap.containsKey("id")){ + KQConfigComInfo kqConfigComInfo = new KQConfigComInfo(); + String auto_card_cominfo = Util.null2String(kqConfigComInfo.getValue("auto_card_cominfo"),"0"); + if("1".equalsIgnoreCase(auto_card_cominfo)){ + String serial_id = Util.null2String(retmap.get("id")); + KQGroupBiz kqGroupBiz = new KQGroupBiz(); + List groupList = kqGroupBiz.getGroupIdByUesedSerialId(serial_id); + KQGroupComInfo kqGroupComInfo = new KQGroupComInfo(); + if(!groupList.isEmpty()){ + for(String groupId : groupList){ + String auto_checkin = kqGroupComInfo.getAuto_checkin(groupId); + String auto_checkout = kqGroupComInfo.getAuto_checkout(groupId); + if("1".equalsIgnoreCase(auto_checkout) || "1".equalsIgnoreCase(auto_checkin)){ + //当前班次存在自动打卡设置,修改班次后,不影响当天的自动打卡时间,变更后的班次自动打卡需要第二天才起作用 + retmap.put("message", "当前班次存在自动打卡设置,修改班次后,不影响当天的自动打卡时间,变更后的班次自动打卡需要第二天才起作用"); + break; + } + } + } + } + } + + }catch (Exception e){ + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(382661,user.getLanguage())); + writeLog(e); + } + + return retmap; + } + + /** + * 编辑班次基本信息 + * @param retmap + * @param jsonObj + */ + public void edit(Map retmap,JSONObject jsonObj) throws Exception{ + RecordSetTrans rst = new RecordSetTrans(); + rst.setAutoCommit(true); + RecordSet rs = new RecordSet(); + String serialid = Util.null2String(jsonObj.get("id")); + String serial = Util.null2String(jsonObj.get("serial"));//班次名称 + String subcompanyid = Util.null2o(Util.null2String(jsonObj.get("subcompanyid"))); + int rest_shift = StringUtil.parseToInt(jsonObj.getString("rest_shift"),0);//休息班 + String shiftOnOffWorkCount = Util.null2o(Util.null2String(jsonObj.get("shiftonoffworkcount")));//一天内上下班次数 + String punchSettings = "1";//打卡时段是否开启 1表示开启 + String isOffDutyFreeCheck = Util.null2o(Util.null2String(jsonObj.get("isoffdutyfreecheck")));//允许下班不打卡 1表示开启 + String isRestTimeOpen = Util.null2o(Util.null2String(jsonObj.get("isresttimeopen")));//排除休息时间是否开启 1表示开启 + String worktime = Util.null2o(Util.null2String(jsonObj.get("worktime")));//工作时长 +// String color = Util.null2o(Util.null2String(jsonObj.get("color")));//工作时长 + String color = "#000"; + String cardRemind = Util.null2s(jsonObj.getString("cardRemind"),"0");//是否开启打卡提醒:0-不开启、1-开启。默认不开启 + String cardRemOfSignIn = Util.null2s(jsonObj.getString("cardRemOfSignIn"),"1");//上班打卡提醒:0-不提醒、1-自定义提前提醒分钟数。默认为1 + String minsBeforeSignIn = Util.null2s(jsonObj.getString("minsBeforeSignIn"),"10");//自定义提前提醒分钟数。默认10分钟 + String cardRemOfSignOut = Util.null2s(jsonObj.getString("cardRemOfSignOut"),"1");//下班打卡提醒:0-不提醒、1-自定义延后提醒分钟数。默认为1 + String minsAfterSignOut = Util.null2s(jsonObj.getString("minsAfterSignOut"),"0");//自定义延后提醒分钟数。默认0分钟 + String remindMode = Util.null2s(jsonObj.getString("remindMode"),"1");//提醒方式:1-消息中心提醒、2-邮件提醒、3-短信提醒。默认消息中心提醒 + String remindOnPC = Util.null2s(jsonObj.getString("remindOnPC"),"0");//登陆PC端弹窗提醒:0-不开启、1-开启 + + String halfcalrule = Util.null2s(jsonObj.getString("halfcalrule"),"0");//半天计算规则 + String halfcalpoint = Util.null2s(jsonObj.getString("halfcalpoint"),"");//半天分界点 + String halfcalpoint2cross = Util.null2s(jsonObj.getString("halfcalpoint2cross"),"0");//当日 + + + if(duplicationCheck(serial,serialid)){ + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(389019,user.getLanguage())); + return ; + } + String[] works = new String[]{"start","end"}; + JSONArray workSections = (JSONArray)jsonObj.get("workSections"); + checkRule(retmap,workSections,works); + + if(!retmap.isEmpty()){ + return ; + } + + String mainSql = "update kq_ShiftManagement set serial=?,subcompanyid=?,shiftonoffworkcount=?,punchsettings=?,isoffdutyfreecheck=?,isresttimeopen=?,worktime=?,color=?," + + "cardRemind=? ,cardRemOfSignIn=? ,minsBeforeSignIn=? ,cardRemOfSignOut=? ,minsAfterSignOut=? ,remindMode=? ,remindOnPC=?,halfcalrule=?,halfcalpoint=?,halfcalpoint2cross=?,rest_shift= ? where id = ? "; + + boolean isUpdated = rst.executeUpdate(mainSql, serial,subcompanyid,shiftOnOffWorkCount,punchSettings,isOffDutyFreeCheck,isRestTimeOpen,worktime,color, + cardRemind ,cardRemOfSignIn ,minsBeforeSignIn ,cardRemOfSignOut ,minsAfterSignOut ,remindMode ,remindOnPC,halfcalrule,halfcalpoint,halfcalpoint2cross,rest_shift,serialid); + + if(isUpdated){ + //对于休息时间和工作时间,直接删除后重新创建 + String delRestSql = "delete from kq_ShiftRestTimeSections where serialid = ? "; + rs = new RecordSet(); + rst.executeUpdate(delRestSql, serialid); + String delWorkSql = "delete from kq_ShiftOnOffWorkSections where serialid = ? "; + rs = new RecordSet(); + rst.executeUpdate(delWorkSql, serialid); + + //休息时间 resttype:start开始时间,end结束时间 + JSONArray restTimeSections = (JSONArray)jsonObj.get("restTimeSections"); + //工作时间 across是否跨天,1表示跨天;beginMin上班前分钟数开始签到,endMin下班后分钟数停止签退;times具体上下班时间;onOffWorkType:start开始时间,end结束时间 + + String restSql = "insert into kq_ShiftRestTimeSections(serialid,resttype,time,across) values(?,?,?,?)"; + int restCount = restTimeSections.size(); + rs = new RecordSet(); + for(int i = 0 ; i < restCount ; i++){ + JSONObject jsonRest = ((JSONObject)restTimeSections.get(i)); + String time=Util.null2String(jsonRest.get("time")); + String resttype=Util.null2String(jsonRest.get("resttype")); + String across=Util.null2String(jsonRest.get("across")); + rst.executeUpdate(restSql, serialid,resttype,time,across); + } + rs = new RecordSet(); + String workSql = "insert into kq_ShiftOnOffWorkSections(serialid,across,mins,times,onoffworktype,record,mins_next) values(?,?,?,?,?,?,?)"; + int workCount = workSections.size(); + for(int i = 0 ; i < workCount ; i++){ + JSONObject jsonWork = ((JSONObject)workSections.get(i)); + String record = Util.null2String(jsonWork.get("record")); + for(int j = 0 ; j < works.length ; j++){ + String onOffWorkType=works[j]; + JSONObject inWork=(JSONObject)jsonWork.get(onOffWorkType); + String across=Util.null2String(inWork.get("across")); + String mins = Util.null2s(Util.null2String(inWork.get("mins")),"0"); + String times=Util.null2String(inWork.get("times")); + String mins_next=Util.null2String(inWork.get("mins_next")); + rst.executeUpdate(workSql, serialid,across,mins,times,onOffWorkType,record,mins_next); + } + } + retmap.put("id", serialid); + retmap.put("status", "1"); + retmap.put("message", SystemEnv.getHtmlLabelName(18758, user.getLanguage())); + }else{ + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(382661,user.getLanguage())); + } + + } + + /** + * 新增班次基本信息 + * @param retmap + * @param jsonObj + */ + public void add(Map retmap,JSONObject jsonObj) throws Exception{ + RecordSetTrans rst = new RecordSetTrans(); + rst.setAutoCommit(true); + RecordSet rs = new RecordSet(); + String subcompanyid = Util.null2o(Util.null2String(jsonObj.get("subcompanyid"))); + int rest_shift = StringUtil.parseToInt(jsonObj.getString("rest_shift"),0);//休息班 + String serial = Util.null2String(jsonObj.get("serial"));//班次名称 + String shiftOnOffWorkCount = Util.null2o(Util.null2String(jsonObj.get("shiftonoffworkcount")));//一天内上下班次数 + String punchSettings = "1";//打卡时段是否开启 1表示开启 + String isOffDutyFreeCheck = Util.null2o(Util.null2String(jsonObj.get("isoffdutyfreecheck")));//允许下班不打卡 1表示开启 + String isRestTimeOpen = Util.null2o(Util.null2String(jsonObj.get("isresttimeopen")));//排除休息时间是否开启 1表示开启 + String worktime = Util.null2o(Util.null2String(jsonObj.get("worktime")));//工作时长 +// String color = Util.null2o(Util.null2String(jsonObj.get("color")));//工作时长 + String color = "#000"; + String uuid = UUID.randomUUID().toString();//uuid供查询使用 + String cardRemind = Util.null2s(jsonObj.getString("cardRemind"),"0");//是否开启打卡提醒:0-不开启、1-开启。默认不开启 + String cardRemOfSignIn = Util.null2s(jsonObj.getString("cardRemOfSignIn"),"1");//上班打卡提醒:0-不提醒、1-自定义提前提醒分钟数。默认为1 + String minsBeforeSignIn = Util.null2s(jsonObj.getString("minsBeforeSignIn"),"10");//自定义提前提醒分钟数。默认10分钟 + String cardRemOfSignOut = Util.null2s(jsonObj.getString("cardRemOfSignOut"),"1");//下班打卡提醒:0-不提醒、1-自定义延后提醒分钟数。默认为1 + String minsAfterSignOut = Util.null2s(jsonObj.getString("minsAfterSignOut"),"0");//自定义延后提醒分钟数。默认0分钟 + String remindMode = Util.null2s(jsonObj.getString("remindMode"),"1");//提醒方式:1-消息中心提醒、2-邮件提醒、3-短信提醒。默认消息中心提醒 + String remindOnPC = Util.null2s(jsonObj.getString("remindOnPC"),"0");//登陆PC端弹窗提醒:0-不开启、1-开启 + + String halfcalrule = Util.null2s(jsonObj.getString("halfcalrule"),"0");//半天计算规则 + String halfcalpoint = Util.null2s(jsonObj.getString("halfcalpoint"),"");//半天分界点 + String halfcalpoint2cross = Util.null2s(jsonObj.getString("halfcalpoint2cross"),"0");//当日 + + if(duplicationCheck(serial,"")){ + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(389019,user.getLanguage())); + return ; + } + //工作时间 across是否跨天,1表示跨天;beginMin上班前分钟数开始签到,endMin下班后分钟数停止签退;times具体上下班时间;onOffWorkType:start开始时间,end结束时间 + + JSONArray workSections = (JSONArray)jsonObj.get("workSections"); + String[] works = new String[]{"start","end"}; + checkRule(retmap,workSections,works); + + if(!retmap.isEmpty()){ + return ; + } + //color改为前台获取 +// String color = getRandomColor(); + boforeLog(uuid); + + String mainSql = "insert into kq_ShiftManagement(serial,subcompanyid,shiftonoffworkcount,punchsettings,isoffdutyfreecheck,isresttimeopen,worktime,uuid,color," + + "cardRemind ,cardRemOfSignIn ,minsBeforeSignIn ,cardRemOfSignOut ,minsAfterSignOut ,remindMode ,remindOnPC,halfcalrule,halfcalpoint,halfcalpoint2cross,rest_shift)" + + " values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + + boolean isUpdated = rst.executeUpdate(mainSql, serial,subcompanyid,shiftOnOffWorkCount,punchSettings,isOffDutyFreeCheck,isRestTimeOpen,worktime,uuid,color, + cardRemind ,cardRemOfSignIn ,minsBeforeSignIn ,cardRemOfSignOut ,minsAfterSignOut ,remindMode ,remindOnPC,halfcalrule,halfcalpoint,halfcalpoint2cross,rest_shift); + + if(isUpdated){ + int serialid = 0; + String idSql = "select id from kq_ShiftManagement where uuid=? and (isdelete is null or isdelete <> '1') "; + rs = new RecordSet(); + rs.executeQuery(idSql,uuid); + if(rs.next()) { + serialid = rs.getInt("id"); + } + + if(serialid > 0){ + + //休息时间 resttype:start开始时间,end结束时间 + JSONArray restTimeSections = (JSONArray)jsonObj.get("restTimeSections"); + + String restSql = "insert into kq_ShiftRestTimeSections(serialid,resttype,time,across) values(?,?,?,?)"; + int restCount = restTimeSections.size(); + rs = new RecordSet(); + for(int i = 0 ; i < restCount ; i++){ + JSONObject jsonRest = ((JSONObject)restTimeSections.get(i)); + String time=Util.null2String(jsonRest.get("time")); + String resttype=Util.null2String(jsonRest.get("resttype")); + String across=Util.null2String(jsonRest.get("across")); + rst.executeUpdate(restSql, serialid,resttype,time,across); + } + rs = new RecordSet(); + String workSql = "insert into kq_ShiftOnOffWorkSections(serialid,across,mins,times,onoffworktype,record,mins_next) values(?,?,?,?,?,?,?)"; + int workCount = workSections.size(); + for(int i = 0 ; i < workCount ; i++){ + JSONObject jsonWork = ((JSONObject)workSections.get(i)); + String record = Util.null2String(jsonWork.get("record")); + for(int j = 0 ; j < works.length ; j++){ + String onOffWorkType=works[j]; + JSONObject inWork=(JSONObject)jsonWork.get(onOffWorkType); + String across=Util.null2String(inWork.get("across")); + String mins = Util.null2s(Util.null2String(inWork.get("mins")),"1"); + String times=Util.null2String(inWork.get("times")); + String mins_next=Util.null2String(inWork.get("mins_next")); + rst.executeUpdate(workSql, serialid,across,mins,times,onOffWorkType,record,mins_next); + } + } + retmap.put("status", "1"); + retmap.put("id", serialid); + retmap.put("message", SystemEnv.getHtmlLabelName(18758, user.getLanguage())); + }else{ + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(382661,user.getLanguage())); + } + }else{ + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(382661,user.getLanguage())); + } + } + + private void checkRule(Map retmap, + JSONArray workSections, String[] works) { + for(int i = 0 ; i < workSections.size() ; i++) { + JSONObject jsonWork = ((JSONObject) workSections.get(i)); + for(int j = 0 ; j < works.length ; j++){ + String onOffWorkType=works[j]; + JSONObject inWork=(JSONObject)jsonWork.get(onOffWorkType); + String mins = Util.null2String(inWork.get("mins")); + if(mins.length() == 0 || Util.getIntValue(mins) == 0){ + retmap.put("status", "-1"); + retmap.put("message", ""+weaver.systeminfo.SystemEnv.getHtmlLabelName(10005343,weaver.general.ThreadVarLanguage.getLang())+""); + break; + } + } + } + } + + /** + * 判断是否重名 + * @param serial + * @param serialid 为空表示新增 + * @return + */ + private boolean duplicationCheck(String serial,String serialid){ + boolean isDuplicated = false; + RecordSet rs = new RecordSet(); + String checkSql = "select 1 from kq_ShiftManagement where serial=? and (isdelete is null or isdelete <> '1') "; + if(serialid.length() > 0){ + checkSql += " and id != "+serialid; + } + rs.executeQuery(checkSql, Util.null2s(serial, "").trim()); + if(rs.next()){ + isDuplicated = true; + } + return isDuplicated; + } + + /** + * 生成随机的颜色 + * @return + */ + private String getRandomColor(){ + + RecordSet rs = new RecordSet(); + List colorLists = new ArrayList<>(); + String hasSameColor = "select color from kq_ShiftManagement group by color "; + rs.executeQuery(hasSameColor); + while (rs.next()){ + colorLists.add(rs.getString("color")); + } + + String color = ""; + Random random = null; + + int i = 0 ; +// while(true){ +// random = new Random(); +// //颜色就要深色的 +// String[] colors = new String[]{"0","1","2","3","4","5","6"}; +// int not_r = random.nextInt(16); +// int not_g = random.nextInt(16); +// int not_b = random.nextInt(16); +// int not_r1 = random.nextInt(16); +// int not_g1 = random.nextInt(16); +// int not_b1 = random.nextInt(16); +// color = "#"+colors[not_r]+colors[not_g]+colors[not_b]+colors[not_r1]+colors[not_g1]+colors[not_b1]; +// //以防死锁 +// if(i > 1000){ +// break; +// } +// if(!colorLists.contains(color)){ +// break; +// } +// i++; +// } + + return color; + } + + public void boforeLog(String uuid){ + BizLogContext logContext = new BizLogContext(); + logContext.setDateObject(new Date()); + logContext.setLogType(BizLogType.HRM_ENGINE); + logContext.setBelongType(BizLogSmallType4Hrm.HRM_ENGINE_SHIFTMANAGER); + logContext.setLogSmallType(BizLogSmallType4Hrm.HRM_ENGINE_SHIFTMANAGER); + logContext.setParams(params); + + String log_mainSql = " select * from kq_ShiftManagement where uuid in('"+uuid+"')"; + logger.setMainSql(log_mainSql);//主表sql + logger.setMainPrimarykey("id");//主日志表唯一key + logger.setMainTargetNameColumn("serial"); + + SimpleBizLogger.SubLogInfo subLogInfo1 = logger.getNewSubLogInfo(); + String subSql1 = "select * from kq_ShiftOnOffWorkSections where serialid in (select id from kq_ShiftManagement where uuid in('"+uuid+"'))" ; + subLogInfo1.setSubTargetNameColumn("times"); + subLogInfo1.setGroupId("0"); //所属分组, 按照groupid排序显示在详情中, 不设置默认按照add的顺序。 + subLogInfo1.setSubGroupNameLabel(27961); //在详情中显示的分组名称,不设置默认显示明细x + subLogInfo1.setSubSql(subSql1); + logger.addSubLogInfo(subLogInfo1); + + SimpleBizLogger.SubLogInfo subLogInfo = logger.getNewSubLogInfo(); + String subSql = " select * from kq_ShiftRestTimeSections where serialid in (select id from kq_ShiftManagement where uuid in('"+uuid+"'))" ; + subLogInfo.setSubSql(subSql); + subLogInfo.setSubTargetNameColumn("time"); + subLogInfo.setGroupId("1"); //所属分组, 按照groupid排序显示在详情中, 不设置默认按照add的顺序。 + subLogInfo.setSubGroupNameLabel(505603); //在详情中显示的分组名称,不设置默认显示明细x + logger.addSubLogInfo(subLogInfo); + logger.before(logContext); + } +} diff --git a/src/com/engine/kq/cmd/shiftschedule/GetShiftScheduleCmd.java b/src/com/engine/kq/cmd/shiftschedule/GetShiftScheduleCmd.java new file mode 100644 index 0000000..27fabeb --- /dev/null +++ b/src/com/engine/kq/cmd/shiftschedule/GetShiftScheduleCmd.java @@ -0,0 +1,313 @@ +package com.engine.kq.cmd.shiftschedule; + +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.KQGroupComInfo; +import com.engine.kq.biz.KQHolidaySetBiz; +import com.engine.kq.biz.KQShiftManagementComInfo; +import com.engine.kq.cmd.shiftmanagement.toolkit.ShiftManagementToolKit; +import com.engine.kq.log.KQLog; +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; +import weaver.hrm.company.DepartmentComInfo; +import weaver.hrm.resource.ResourceComInfo; +import weaver.systeminfo.SystemEnv; + +import java.util.*; + +public class GetShiftScheduleCmd extends AbstractCommonCommand> { + + public GetShiftScheduleCmd(Map params, User user) { + this.user = user; + this.params = params; + } + + @Override + public Map execute(CommandContext commandContext) { + Map retmap = new HashMap(); + Map shiftSchedule = new HashMap(); + List lsDatas = null; + List lsKeyDatas = null; + Map data = null; + RecordSet rs = new RecordSet(); + + String sql = ""; + try{ + //必要的权限判断 + if(!HrmUserVarify.checkUserRight("HrmKQGroup:Add",user)) { + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage())); + return retmap; + } + + int count = 0; + int pageCount = 0; + int isHavePre = 0; + int isHaveNext = 0; + + KQGroupComInfo kQGroupComInfo = new KQGroupComInfo(); + KQShiftManagementComInfo kQShiftManagementComInfo = new KQShiftManagementComInfo(); + ShiftManagementToolKit shiftManagementToolKit = new ShiftManagementToolKit(); + ResourceComInfo resourceComInfo = new ResourceComInfo(); + DepartmentComInfo departmentComInfo = new DepartmentComInfo(); + String status = Util.null2String(params.get("status")); + + String groupId = Util.null2String(params.get("groupId"));//考勤组id + String kqMonth = Util.null2String(params.get("kqMonth"));//月份 + String viewscope = Util.null2String(params.get("viewscope"));//0:总部 1:分部 2:部门 3:人员 4:我的下属 + int pageIndex = Util.getIntValue(Util.null2String(params.get("pageIndex")), 1); + int pageSize = Util.getIntValue(Util.null2String(params.get("pageSize")), 20); + String year = kqMonth.substring(0,4); + String month = kqMonth.substring(5,7); + String monthBeginDate = DateUtil.getFirstDayOfMonth(kqMonth+"-01"); + String monthEndDate = DateUtil.getLastDayOfMonth(kqMonth+"-01"); + + String serialidStr = Util.null2String(kQGroupComInfo.getSerialids(groupId)); + List serialids = new ArrayList<>(); + List lsSerialDatas = new ArrayList<>(); + if(serialidStr.length() > 0){ + serialids = Util.splitString2List(serialidStr,","); + for(int i=0;i(); + data.put("id",serialids.get(i)); + data.put("name",shiftManagementToolKit.getShiftOnOffWorkSections(serialids.get(i),user.getLanguage())); + data.put("bgColor",kQShiftManagementComInfo.getColor(serialids.get(i))); + lsSerialDatas.add(data); + } + } + + lsDatas = new ArrayList<>(); + sql = "select id,shiftcyclename,shiftcycleserialids from kq_group_shiftcycle where groupid = ? order by id asc "; + rs.executeQuery(sql,groupId); + while(rs.next()){ + data = new HashMap<>(); + data.put("name",Util.null2String(rs.getString("shiftcyclename")));//周期名称, + data.put("serial",Util.splitString(Util.null2String(rs.getString("shiftcycleserialids")),","));//周期顺序,例7天一周期 + lsDatas.add(data); + } + retmap.put("serialInfo", lsDatas); + lsDatas = KQHolidaySetBiz.getGroupHolidaySetList(groupId,year,month); + retmap.put("holidays", lsDatas); + + String sqlWhere = " "; + if(viewscope.length()>0){ + if(viewscope.equals("1")){//分部 + String subCompanyId = Util.null2String(params.get("subCompanyId")); + sqlWhere += " and t.subcompanyid1 in ("+subCompanyId+") "; + }else if(viewscope.equals("2")){//部门 + String departmentId = Util.null2String(params.get("departmentId")); + sqlWhere += " and t.departmentid in ("+departmentId+") "; + }else if(viewscope.equals("3")){//人员 + String resourceId = Util.null2String(params.get("resourceId")); + sqlWhere += " and t.resourceid in ("+resourceId+") "; + } + } + + String isNoAccount = Util.null2String(params.get("isNoAccount"));// 是否显示无账号人员 + if (!"1".equals(isNoAccount)) { + sqlWhere += " and t.status in(0,1,2,3) and t.loginid is not null "+(rs.getDBType().equals("oracle")?"":" and t.loginid<>'' "); + } + if(status.length()>0){ + if (!status.equals("8") && !status.equals("9")) { + sqlWhere += " and t.status = "+status+ ""; + }else if (status.equals("8")) { + sqlWhere += " and (t.status = 0 or t.status = 1 or t.status = 2 or t.status = 3) "; + } + } + + if(!Util.null2String(kQGroupComInfo.getExcludecount(groupId)).equals("1")) { + //剔除无需排班人员 + String excludeid = Util.null2String(kQGroupComInfo.getExcludeid(groupId)); + if (excludeid.length() > 0) { + sqlWhere += " and t.resourceid not in (" + excludeid + ")"; + } + } + + //二开 2023年06月19日09:37:14 增加分权功能 start + String roleSql = " select a.id from hrmroles a,hrmrolemembers b " + + "where a.id=b.roleid and a.rolesmark='考勤管理员' and resourceid=? "; + rs.executeQuery(roleSql,user.getUID()); + if(!user.isAdmin() && !rs.next()){ + sqlWhere += " and t.departmentid in( select deptid from hrmdepartmentdefined where kqwy="+user.getUID()+") "; + } + //end + + + String backFields = " t.resourceid, t.groupid, t.status, t.dsporder,t.lastname,t.subcompanyid1, t.departmentid, t.loginid "; + String sqlFrom = " from (SELECT distinct t.resourceid, t.groupid, t.status, t.dsporder,t.lastname,t.subcompanyid1, t.departmentid, t.loginid FROM ( \n" + + " SELECT a.id AS resourceid, b.groupid, a.status,a.dsporder,a.lastname,a.subcompanyid1, a.departmentid, a.loginid FROM HrmResource a, kq_groupmember b \n" + + " WHERE a.id=b.typevalue and b.type =1 and (b.isdelete is null or b.isdelete <> '1') \n" + + " UNION ALL \n" + + " SELECT a.id AS resourceid, b.groupid, a.status,a.dsporder,a.lastname,a.subcompanyid1, a.departmentid, a.loginid FROM HrmResource a, kq_groupmember b \n" + + " WHERE a.subcompanyid1 = b.typevalue AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto AND b.type=2 and (b.isdelete is null or b.isdelete <> '1') \n" + + " UNION ALL \n" + + " SELECT a.id AS resourceid, b.groupid, a.status,a.dsporder,a.lastname,a.subcompanyid1, a.departmentid, a.loginid FROM HrmResource a, kq_groupmember b \n" + + " WHERE a.departmentid = b.typevalue AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto AND b.type=3 and (b.isdelete is null or b.isdelete <> '1') \n" + + " UNION ALL \n" + + " SELECT a.id AS resourceid, b.groupid, a.status,a.dsporder,a.lastname,a.subcompanyid1, a.departmentid, a.loginid FROM HrmResource a, kq_groupmember b \n" + + " WHERE (a.jobtitle = b.typevalue AND b.type=5 and (b.isdelete is null or b.isdelete <> '1') AND (b.jobtitlelevel=1 OR (b.jobtitlelevel=2 AND a.subcompanyid1 IN(b.jobtitlelevelvalue)) OR (b.jobtitlelevel=3 AND a.departmentid IN(b.jobtitlelevelvalue)))) \n" + + " UNION ALL " + + " SELECT a.id AS resourceid, b.groupid, a.status,a.dsporder,a.lastname,a.subcompanyid1, a.departmentid, a.loginid FROM HrmResource a, kq_groupmember b \n" + + " WHERE b.type=6 AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto and (b.isdelete is null or b.isdelete <> '1')" + + " )t ) t where t.groupid = "+groupId; + String groupBy = " "; + + + lsKeyDatas = new ArrayList<>(); + lsDatas = new ArrayList<>(); +// sql = " select b.id, b.kqdate, b.serialid, t.resourceid, t.subcompanyid1, t.departmentid, t.loginid from (\n" + +// " SELECT distinct t.resourceid, t.groupid, t.status, t.dsporder,t.lastname,t.subcompanyid1, t.departmentid, t.loginid FROM ( \n" + +// " SELECT a.id AS resourceid, b.groupid, a.status,a.dsporder,a.lastname,a.subcompanyid1, a.departmentid, a.loginid FROM HrmResource a, kq_groupmember b \n" + +// " WHERE a.id=b.typevalue and b.type =1 and (b.isdelete is null or b.isdelete <> '1') \n" + +// " UNION ALL \n" + +// " SELECT a.id AS resourceid, b.groupid, a.status,a.dsporder,a.lastname,a.subcompanyid1, a.departmentid, a.loginid FROM HrmResource a, kq_groupmember b \n" + +// " WHERE a.subcompanyid1 = b.typevalue AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto AND b.type=2 and (b.isdelete is null or b.isdelete <> '1') \n" + +// " UNION ALL \n" + +// " SELECT a.id AS resourceid, b.groupid, a.status,a.dsporder,a.lastname,a.subcompanyid1, a.departmentid, a.loginid FROM HrmResource a, kq_groupmember b \n" + +// " WHERE a.departmentid = b.typevalue AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto AND b.type=3 and (b.isdelete is null or b.isdelete <> '1') \n" + +// " UNION ALL \n" + +// " SELECT a.id AS resourceid, b.groupid, a.status,a.dsporder,a.lastname,a.subcompanyid1, a.departmentid, a.loginid FROM HrmResource a, kq_groupmember b \n" + +// " WHERE (a.jobtitle = b.typevalue AND b.type=5 and (b.isdelete is null or b.isdelete <> '1') AND (b.jobtitlelevel=1 OR (b.jobtitlelevel=2 AND a.subcompanyid1 IN(b.jobtitlelevelvalue)) OR (b.jobtitlelevel=3 AND a.departmentid IN(b.jobtitlelevelvalue)))) \n" + +// " UNION ALL " + +// " SELECT a.id AS resourceid, b.groupid, a.status,a.dsporder,a.lastname,a.subcompanyid1, a.departmentid, a.loginid FROM HrmResource a, kq_groupmember b \n" + +// " WHERE b.type=6 AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto and (b.isdelete is null or b.isdelete <> '1')" + +// " )t ) t left join kq_shiftschedule b on t.resourceid=b.resourceid and t.groupid = b.groupid and (b.isdelete is null or b.isdelete <> '1') and b.kqdate>=? and b.kqdate<=? where t.groupid=? \n " + +// sqlWhere + +// " order by t.dsporder,t.lastname"; + + 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 "; + + 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; + } + new KQLog().info("GetShiftScheduleCmd:"+sql); + rs.executeQuery(sql); + while(rs.next()){ + String resourceid = Util.null2String(rs.getString("resourceid")); + data = new HashMap<>(); + data.put("resourceid",resourceid); + data.put("name",resourceComInfo.getLastname(resourceid)); + data.put("department",departmentComInfo.getDepartmentname(resourceComInfo.getDepartmentID(resourceid))); + List shiftScheduleDatas = this.getShiftSchedule(groupId, resourceid, monthBeginDate,monthEndDate); + for(int i=0;shiftScheduleDatas!=null&&i shiftScheduleData = (Map)shiftScheduleDatas.get(i); + String id = Util.null2String(shiftScheduleData.get("id")); + String kqdate = Util.null2String(shiftScheduleData.get("kqdate")); + String serialid = Util.null2String(shiftScheduleData.get("serialid")); + if(!serialids.contains(serialid) && !serialid.equals("-1")){ + serialids.add(serialid); + Map serialdata = new HashMap<>(); + serialdata.put("id",serialid); + serialdata.put("name",shiftManagementToolKit.getShiftOnOffWorkSections(serialid,user.getLanguage())); + serialdata.put("bgColor",kQShiftManagementComInfo.getColor(serialid)); + serialdata.put("isDelete",1); + lsSerialDatas.add(serialdata); + } + data.put(kqdate,serialid); + lsKeyDatas.add(resourceid+"|"+kqdate+"|"+id); + } + lsDatas.add(data); + } + retmap.put("pagesize", pageSize); + retmap.put("pageindex", pageIndex); + retmap.put("count", count); + retmap.put("pagecount", pageCount); + retmap.put("ishavepre", isHavePre); + retmap.put("ishavenext", isHaveNext); + retmap.put("datas", lsDatas); + retmap.put("keyDatas", lsKeyDatas); + retmap.put("shiftList", lsSerialDatas); + retmap.put("groupName", kQGroupComInfo.getGroupname(groupId)); + retmap.put("today", DateUtil.getCurrentDate()); + if(Util.null2String(kQGroupComInfo.getValidity(groupId)).equals("1")){//考勤组设置了有效期 + retmap.put("validityFromDate", kQGroupComInfo.getValidityfromdate(groupId)); + retmap.put("validityEndDate", kQGroupComInfo.getValidityenddate(groupId)); + } + retmap.put("status", "1"); + }catch (Exception e) { + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(382661,user.getLanguage())); + writeLog(e); + } + return retmap; + } + + private List getShiftSchedule(String groupid, String resourceid, String monthBeginDate,String monthEndDate){ + List datas = new ArrayList<>(); + Map data = null; + String sql = ""; + RecordSet rs = new RecordSet(); + sql = " select id,kqdate, serialid from kq_shiftschedule where groupid= '"+groupid+"' and resourceid="+resourceid+" " + + " and kqdate>='"+monthBeginDate+"' and kqdate<='"+monthEndDate+"' and (isdelete is null or isdelete <> '1')"; + rs.executeQuery(sql); + while(rs.next()){ + String id = Util.null2String(rs.getString("id")); + String kqdate = Util.null2String(rs.getString("kqdate")); + String serialid = Util.null2String(rs.getString("serialid")); + + data = new HashMap<>(); + data.put("id",id); + data.put("kqdate",kqdate); + data.put("serialid",serialid); + datas.add(data); + } + return datas; + } + + @Override + public BizLogContext getLogContext() { + return null; + } + +} diff --git a/src/com/engine/kq/cmd/shiftschedule/GetShiftScheduleTotalCmd.java b/src/com/engine/kq/cmd/shiftschedule/GetShiftScheduleTotalCmd.java new file mode 100644 index 0000000..68528c8 --- /dev/null +++ b/src/com/engine/kq/cmd/shiftschedule/GetShiftScheduleTotalCmd.java @@ -0,0 +1,119 @@ +package com.engine.kq.cmd.shiftschedule; + +import com.engine.common.biz.AbstractCommonCommand; +import com.engine.common.entity.BizLogContext; +import com.engine.core.interceptor.CommandContext; +import com.engine.kq.biz.KQGroupComInfo; +import com.engine.kq.biz.KQHolidaySetBiz; +import com.engine.kq.biz.KQShiftManagementComInfo; +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; +import weaver.hrm.company.DepartmentComInfo; +import weaver.hrm.resource.ResourceComInfo; +import weaver.systeminfo.SystemEnv; + +import java.util.*; + +public class GetShiftScheduleTotalCmd extends AbstractCommonCommand> { + + public GetShiftScheduleTotalCmd(Map params, User user) { + this.user = user; + this.params = params; + } + + @Override + public Map execute(CommandContext commandContext) { + Map retmap = new HashMap(); + List lsColumns = new ArrayList<>(); + Map column = null; + List lsDatas = null; + Map data = null; + String sql = ""; + RecordSet rs = new RecordSet(); + + try{ + //必要的权限判断 + if(!HrmUserVarify.checkUserRight("HrmKQGroup:Add",user)) { + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage())); + return retmap; + } + + Calendar cal = DateUtil.getCalendar(); + KQGroupComInfo kQGroupComInfo = new KQGroupComInfo(); + KQShiftManagementComInfo kQShiftManagementComInfo = new KQShiftManagementComInfo(); + String groupId = Util.null2String(params.get("groupId"));//考勤组id + String kqMonth = Util.null2String(params.get("kqMonth"));//月份 + String monthBeginDate = DateUtil.getFirstDayOfMonth(kqMonth+"-01"); + String monthEndDate = DateUtil.getLastDayOfMonth(kqMonth+"-01"); + + boolean hasRestShift = false; + Map mapShiftSchedule = new HashMap<>(); + sql = " select kqdate,serialid,count(resourceid) as num from kq_shiftschedule " + + " where (isdelete is null or isdelete <> '1') and kqdate>=? and kqdate<=? and groupid=? " + + " group by kqdate,serialid "; + rs.executeQuery(sql,monthBeginDate,monthEndDate,groupId); + while(rs.next()){ + if(Util.null2String(rs.getString("serialid")).equals("-1")){ + hasRestShift=true; + } + mapShiftSchedule.put(rs.getString("kqdate")+"|"+rs.getInt("serialid"),rs.getInt("num")); + } + + column = new HashMap(); + column.put("title", SystemEnv.getHtmlLabelName(389646,user.getLanguage())); + column.put("dataIndex", "serialName"); + lsColumns.add(column); + boolean isEnd = false; + for(String date=monthBeginDate; !isEnd;) { + if (date.equals(monthEndDate)) isEnd = true; + column = new HashMap(); + column.put("title", date); + column.put("dataIndex", date); + lsColumns.add(column); + cal.setTime(DateUtil.parseToDate(date)); + date = DateUtil.getDate(cal.getTime(), 1); + } + + List lsSerialId = Util.splitString2List(Util.null2String(kQGroupComInfo.getSerialids(groupId)),","); + if(hasRestShift && !lsSerialId.contains("-1"))lsSerialId.add("-1");//统计休息班 + lsDatas = new ArrayList<>(); + for(int i=0;lsSerialId!=null&&i(); + data.put("serialId",lsSerialId.get(i)); + if(lsSerialId.get(i).equals("-1")){ + data.put("serialName",SystemEnv.getHtmlLabelName(26593,user.getLanguage())); + }else{ + data.put("serialName",kQShiftManagementComInfo.getSerial(lsSerialId.get(i))); + } + data.put("bgColor",kQShiftManagementComInfo.getColor(lsSerialId.get(i))); + isEnd = false; + for(String date=monthBeginDate; !isEnd;) { + if (date.equals(monthEndDate)) isEnd = true; + data.put(date,mapShiftSchedule.get(date+"|"+lsSerialId.get(i))); + cal.setTime(DateUtil.parseToDate(date)); + date = DateUtil.getDate(cal.getTime(), 1); + } + lsDatas.add(data); + } + retmap.put("columns", lsColumns); + retmap.put("datas", lsDatas); + retmap.put("groupName", kQGroupComInfo.getGroupname(groupId)); + retmap.put("status", "1"); + }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; + } + +} diff --git a/src/com/engine/kq/cmd/shiftschedule/ImportExcelCmd.java b/src/com/engine/kq/cmd/shiftschedule/ImportExcelCmd.java new file mode 100644 index 0000000..4e4446a --- /dev/null +++ b/src/com/engine/kq/cmd/shiftschedule/ImportExcelCmd.java @@ -0,0 +1,309 @@ +package com.engine.kq.cmd.shiftschedule; + +import com.engine.common.biz.AbstractCommonCommand; +import com.engine.common.biz.SimpleBizLogger; +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.kq.biz.*; +import org.apache.poi.ss.usermodel.*; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import weaver.conn.BatchRecordSet; +import weaver.conn.RecordSet; +import weaver.file.ImageFileManager; +import weaver.general.Util; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.Reminder.KQAutoCardTask; +import weaver.hrm.User; +import weaver.hrm.resource.ResourceComInfo; +import weaver.systeminfo.SystemEnv; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class ImportExcelCmd extends AbstractCommonCommand> { + private String today = weaver.common.DateUtil.getCurrentDate(); + private SimpleBizLogger logger; + public ImportExcelCmd(Map params, User user) { + this.user = user; + this.params = params; + this.logger = new SimpleBizLogger(); + + String groupId = Util.null2String(params.get("groupId")); + BizLogContext bizLogContext = new BizLogContext(); + bizLogContext.setLogType(BizLogType.HRM_ENGINE);//模块类型 + bizLogContext.setBelongType(BizLogSmallType4Hrm.HRM_ENGINE_Schedule_Set);//所属大类型 + bizLogContext.setLogSmallType(BizLogSmallType4Hrm.HRM_ENGINE_Schedule_Set);//当前小类型 + bizLogContext.setParams(params);//当前request请求参数 + logger.setUser(user);//当前操作人 + String mainSql = "select * from kq_group where id = " + groupId + " and (isdelete is null or isdelete <> '1') "; + logger.setMainSql(mainSql, "id");//主表sql + logger.setMainPrimarykey("id");//主日志表唯一key + logger.setMainTargetNameColumn("groupname"); + SimpleBizLogger.SubLogInfo subLogInfo1 = logger.getNewSubLogInfo(); + String subSql1 = "select * from kq_shiftschedule where groupid = " + groupId + " and (isdelete is null or isdelete <> '1') "; + subLogInfo1.setSubSql(subSql1,"id"); + logger.addSubLogInfo(subLogInfo1); + logger.before(bizLogContext); + } + + @Override + public Map execute(CommandContext commandContext) { + Map retmap = new HashMap(); + RecordSet rs = new RecordSet(); + BatchRecordSet bRs = new BatchRecordSet(); + String sql = ""; + try { + //必要的权限判断 + if (!HrmUserVarify.checkUserRight("HrmKQGroup:Add", user)) { + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage())); + return retmap; + } + ResourceComInfo resourceComInfo = new ResourceComInfo(); + KQGroupComInfo kqGroupComInfo = new KQGroupComInfo(); + KQGroupBiz kqGroupBiz = new KQGroupBiz(); + KQShiftManagementComInfo kqShiftManagementComInfo = new KQShiftManagementComInfo(); + + String groupId = Util.null2String(params.get("groupId")); + String filename = Util.null2String(params.get("filename")); + + List lsColumn = null; + List> paramInsert = new ArrayList>(); + List> paramUpdate = new ArrayList>(); + List param = null; + List> lsFormatParams = new ArrayList<>(); + List formatParams = null; + + List> lscheckSerialParams = new ArrayList<>(); + List checkSerialParams = null; + + Map mapShiftSchedule = new HashMap<>(); + Map mapSerial = new HashMap<>(); + Map mapGroupMembersWorkCode = new HashMap<>(); + Map mapGroupMembersLastName = new HashMap<>(); + List serialids=Util.splitString2List(kqGroupComInfo.getSerialids(groupId),","); + if(!serialids.contains("-1"))serialids.add("-1"); + for(String serialid : serialids){ + if(serialid.equals("-1")){ + mapSerial.put(SystemEnv.getHtmlLabelName(26593, user.getLanguage()),serialid); + }else{ + mapSerial.put(Util.formatMultiLang(kqShiftManagementComInfo.getSerial(serialid),""+user.getLanguage()),serialid); + } + } + + Map params = new HashMap<>(); + params.put("groupId",groupId); + params.put("isNoAccount","1"); + List kqGroupMembers = kqGroupBiz.getGroupMembers(params); + List excludeidList = new ArrayList<>(); + if(!Util.null2String(kqGroupComInfo.getExcludecount(groupId)).equals("1")) { + String excludeid = Util.null2String(kqGroupComInfo.getExcludeid(groupId)); + if (excludeid.length() > 0) { + excludeidList = Util.splitString2List(excludeid,","); + } + } + for(String resourceid : kqGroupMembers){ + // 排除无需考勤人员 + if(excludeidList != null && excludeidList.contains(resourceid)) { + continue; + } + String workCode = Util.formatMultiLang(Util.null2String(resourceComInfo.getWorkcode(resourceid)),""+user.getLanguage()); + String lastName = Util.formatMultiLang(Util.null2String(resourceComInfo.getLastname(resourceid)),""+user.getLanguage()); + if(workCode.length()>0){ + mapGroupMembersWorkCode.put(workCode,resourceid); + }else if(lastName.length()>0){ + mapGroupMembersLastName.put(lastName,resourceid); + } + } + sql = " delete from kq_shiftschedule where groupid=? and isdelete='1' "; + rs.executeUpdate(sql,groupId); + + sql = " select id, resourceid, kqdate from kq_shiftschedule where groupid=? "; + rs.executeQuery(sql,groupId); + while(rs.next()){ + mapShiftSchedule.put(rs.getString("kqdate")+"|"+rs.getString("resourceid"),rs.getString("id")); + } + + int firstRow = 6; + int firstCol = 3; + ImageFileManager manager = new ImageFileManager(); + manager.getImageFileInfoById(Util.getIntValue(filename)); + //Workbook workbook = WorkbookFactory.create(manager.getInputStream()); + Workbook workbook = new XSSFWorkbook(manager.getInputStream()); + for (int idx = 0; idx < workbook.getNumberOfSheets(); idx++) { + Sheet sheet = workbook.getSheetAt(idx); + if(sheet.getSheetName().indexOf("constraintDataSheet")>-1)continue; + Row row = null; + Cell cell = null; + + row = sheet.getRow(firstRow); + lsColumn = new ArrayList(); + for (int cellIndex = firstCol; cellIndex < row.getLastCellNum(); cellIndex++) { + cell = row.getCell((short) cellIndex); + lsColumn.add(Util.null2String(getCellValue(cell)).trim()); + } + firstRow++; + + for (int i = firstRow; firstRow<=sheet.getLastRowNum() && i <= sheet.getLastRowNum(); i++) { + row = sheet.getRow(i); + if (row == null) { + continue; + } + String workCode = Util.null2String(row.getCell(1));//编号 + String lastName = Util.null2String(row.getCell(2));//姓名 + if(workCode.length()==0 && lastName.length()==0){ + continue; + } + String resourceId = Util.null2String(mapGroupMembersWorkCode.get(workCode));//人员id + if(resourceId.length()==0){ + resourceId = Util.null2String(mapGroupMembersLastName.get(lastName));//人员id + } + if(resourceId.length()==0)continue; + for (int cellIndex = firstCol; cellIndex < row.getLastCellNum(); cellIndex++) { + cell = row.getCell((short) cellIndex); + if (cell == null) continue; + String serialId = ""; + String serialName = Util.null2String(getCellValue(cell)).trim(); + if(serialName.length()==0)continue; + String kqdate = Util.null2String(lsColumn.get(cellIndex-firstCol)); + //if(weaver.common.DateUtil.timeInterval(kqdate,today)>0)continue;//今天之前的无需处理 + serialId = Util.null2String(mapSerial.get(serialName)); + if(serialId.length()==0)continue; + + String id = Util.null2String(mapShiftSchedule.get(kqdate+"|"+resourceId)); + if(id.length()>0){ + param = new ArrayList(); + param.add(serialId); + param.add(id); + paramUpdate.add(param); + }else{ + param = new ArrayList(); + param.add(kqdate); + param.add(serialId); + param.add(resourceId); + param.add(groupId); + paramInsert.add(param); + } + + formatParams = new ArrayList<>(); + formatParams.add(resourceId); + formatParams.add(kqdate); + lsFormatParams.add(formatParams); + + checkSerialParams = new ArrayList<>(); + checkSerialParams.add(resourceId); + checkSerialParams.add(kqdate); + checkSerialParams.add(serialId); + lscheckSerialParams.add(checkSerialParams); + } + } + sql = " update kq_shiftschedule set serialid=?, isDelete=0 where id = ? "; + for (int i = 0; paramUpdate != null && i < paramUpdate.size(); i++) { + List update_params = paramUpdate.get(i); + String serialid = Util.null2String(update_params.get(0)); + String id = Util.null2String(update_params.get(1)); + rs.executeUpdate(sql, serialid,id); + } + + sql = "insert into kq_shiftschedule (kqdate,serialid,resourceid,groupid,isDelete) values(?,?,?,?,0)"; + for (int i = 0; paramInsert != null && i < paramInsert.size(); i++) { + List insert_params = paramInsert.get(i); + String kqdate = Util.null2String(insert_params.get(0)); + String serialid = Util.null2String(insert_params.get(1)); + String resourceid = Util.null2String(insert_params.get(2)); + String groupid = Util.null2String(insert_params.get(3)); + rs.executeUpdate(sql, kqdate,serialid,resourceid,groupid); + } + } + + //删除之前的排的班次,一天只能有一个班次 + sql = " update kq_shiftschedule set isdelete =1 where (isdelete is null or isdelete <> '1') and resourceid = ? and kqdate = ? and groupid != "+groupId; + for (int i = 0; lsFormatParams != null && i < lsFormatParams.size(); i++) { + List delete_params = lsFormatParams.get(i); + String resourceid = Util.null2String(delete_params.get(0)); + String kqdate = Util.null2String(delete_params.get(1)); + rs.executeUpdate(sql, resourceid,kqdate); + } + + sql = " update kq_shiftschedule set isdelete =1 where (isdelete is null or isdelete <> '1') and resourceid = ? and kqdate = ? and serialid != ? "; + for (int i = 0; lscheckSerialParams != null && i < lscheckSerialParams.size(); i++) { + List check_params = lscheckSerialParams.get(i); + String resourceid = Util.null2String(check_params.get(0)); + String kqdate = Util.null2String(check_params.get(1)); + String serialid = Util.null2String(check_params.get(2)); + rs.executeUpdate(sql, resourceid,kqdate,serialid); + } + + new KQShiftScheduleComInfo().removeCache(); + + //刷新报表数据 + sql = " insert into kq_format_pool (resourceid, kqdate) values (?,?)"; + bRs.executeBatchSql(sql, lsFormatParams); + + KQGroupComInfo kQGroupComInfo = new KQGroupComInfo(); + String auto_checkout = kQGroupComInfo.getAuto_checkout(groupId); + String auto_checkin = kQGroupComInfo.getAuto_checkin(groupId); + if("1".equalsIgnoreCase(auto_checkin) || "1".equalsIgnoreCase(auto_checkout)){ + //如果开启了自动打卡,保存考勤组成员之后需要格式化下缓存 + KQAutoCardTask kqAutoCardTask = new KQAutoCardTask(); + kqAutoCardTask.initAutoCardTask(groupId); + } + + retmap.put("status", "1"); + } 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(); + } + /** + * /** + * 获取excel单元格值 + * + * @param cell 要读取的单元格对象 + * @return + */ + public 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 (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/src/com/engine/kq/entity/WorkTimeEntity.java b/src/com/engine/kq/entity/WorkTimeEntity.java new file mode 100644 index 0000000..b358c44 --- /dev/null +++ b/src/com/engine/kq/entity/WorkTimeEntity.java @@ -0,0 +1,136 @@ +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 restShift; + + 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 getRestShift() { + return restShift; +} + +public void setRestShift(int restShift) { + this.restShift = restShift; +} +} diff --git a/src/com/engine/kq/util/KQDurationCalculatorUtil.java b/src/com/engine/kq/util/KQDurationCalculatorUtil.java new file mode 100644 index 0000000..6100904 --- /dev/null +++ b/src/com/engine/kq/util/KQDurationCalculatorUtil.java @@ -0,0 +1,633 @@ +package com.engine.kq.util; + +import com.alibaba.fastjson.JSONObject; +import com.engine.kq.biz.KQLeaveRulesBiz; +import com.engine.kq.biz.KQLeaveRulesComInfo; +import com.engine.kq.biz.KQShiftManagementComInfo; +import com.engine.kq.biz.KQWorkTime; +import com.engine.kq.biz.chain.cominfo.ShiftInfoCominfoBean; +import com.engine.kq.biz.chain.duration.NonDayUnitSplitChain; +import com.engine.kq.biz.chain.duration.NonHalfUnitSplitChain; +import com.engine.kq.biz.chain.duration.NonHourUnitSplitChain; +import com.engine.kq.biz.chain.duration.NonWholeUnitSplitChain; +import com.engine.kq.biz.chain.duration.NonWorkDurationChain; +import com.engine.kq.biz.chain.duration.WorkDayUnitSplitChain; +import com.engine.kq.biz.chain.duration.WorkDurationChain; +import com.engine.kq.biz.chain.duration.WorkHalfUnitSplitChain; +import com.engine.kq.biz.chain.duration.WorkHourUnitSplitChain; +import com.engine.kq.biz.chain.duration.WorkWholeUnitSplitChain; +import com.engine.kq.biz.chain.shiftinfo.ShiftInfoBean; +import com.engine.kq.enums.DurationTypeEnum; +import com.engine.kq.log.KQLog; +import com.engine.kq.wfset.bean.SplitBean; +import com.engine.kq.wfset.util.KQFlowUtil; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import weaver.common.StringUtil; +import weaver.general.BaseBean; +import weaver.general.Util; +import weaver.hrm.User; +import weaver.hrm.report.schedulediff.HrmScheduleDiffUtil; + +public class KQDurationCalculatorUtil extends BaseBean { + private KQLog kqLog = new KQLog(); + + private final String resourceid; + private String fromDate; + private String toDate; + private String fromTime; + private String toTime; + private String newLeaveType; + /** + * 获取最小计算单位 + * 1-按天计算 + * 2-按半天计算 + * 3-按小时计算 + * 4-按整天计算 + */ + private String durationrule; + /** + * 1-按工作日计算计算时长 + * 2-按自然日计算计算时长 + */ + private String computingMode; + + /** + * 加班类型 + */ + private String overtime_type; + + private DurationTypeEnum durationTypeEnum; + + //外部类的构造函数 + private KQDurationCalculatorUtil(DurationParamBuilder build){ + this.resourceid = build.resourceid; + this.fromDate = build.fromDate; + this.toDate = build.toDate; + this.fromTime = build.fromTime; + this.toTime = build.toTime; + this.newLeaveType = build.newLeaveType; + this.durationrule = build.durationrule; + this.computingMode = build.computingMode; + this.durationTypeEnum = build.durationTypeEnum; + this.overtime_type = build.overtime_type; + } + + /** + * 根据人和指定的日期获取办公时段 + * @param resourceid + * @param date + * @param containYesterday + * @return + */ + public static ShiftInfoBean getWorkTime(String resourceid, String date,boolean containYesterday){ + User user = User.getUser(Util.getIntValue(resourceid), 0); + if(user == null){ + return null; + } + return getWorkTime(user, date,containYesterday); + } + + public static ShiftInfoBean getWorkTimeNew(String resourceid, String date,boolean containYesterday){ + User user = User.getUser(Util.getIntValue(resourceid), 0); + if(user == null){ + return null; + } + return getWorkTime(user, date, containYesterday, true, false); + } + + /** + * 不记录日志的,流程的超时提醒日志太大 + * @param resourceid + * @param date + * @param containYesterday + * @param isLog + * @return + */ + public static ShiftInfoBean getWorkTime(String resourceid, String date,boolean containYesterday,boolean isLog){ + User user = User.getUser(Util.getIntValue(resourceid), 0); + if(user == null){ + return null; + } + return getWorkTime(user, date,containYesterday,isLog); + } + + public static ShiftInfoCominfoBean getShiftInfoCominfoBean(String resourceid, String date){ + KQWorkTime kqWorkTime = new KQWorkTime(); + Map kqWorkTimeMap = new HashMap<>(); + ShiftInfoCominfoBean shiftInfoCominfoBean = kqWorkTime.getShiftInfoCominfoBean(resourceid, date); + return shiftInfoCominfoBean; + } + + /** + * 直接根据user来获取 + * @param user + * @param date + * @param containYesterday + * @param isLog + * @return + */ + public static ShiftInfoBean getWorkTime(User user, String date,boolean containYesterday,boolean isLog){ + return getWorkTime(user, date, containYesterday, isLog, true); + } + + public static ShiftInfoBean getWorkTime(User user, String date,boolean containYesterday,boolean isLog, boolean isUsedRestShift){ + KQWorkTime kqWorkTime = new KQWorkTime(); + Map kqWorkTimeMap = new HashMap<>(); + kqWorkTimeMap = kqWorkTime.getWorkDuration(""+user.getUID(), date,containYesterday,isLog); + boolean isfree = "1".equalsIgnoreCase(Util.null2String(kqWorkTimeMap.get("isfree"))); + if(isfree){ + ShiftInfoBean shiftInfoBean = new ShiftInfoBean(); + shiftInfoBean.setIsfree(true); + String signStart = Util.null2String(kqWorkTimeMap.get("signStart")); + String workMins = Util.null2String(kqWorkTimeMap.get("workMins")); + shiftInfoBean.setFreeSignStart(signStart); + shiftInfoBean.setFreeWorkMins(workMins); + shiftInfoBean.setSplitDate(date); + if(signStart.length() > 0 && workMins.length() > 0){ + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm"); + LocalTime signLocalTime = LocalTime.parse(signStart, dateTimeFormatter); + shiftInfoBean.setFreeSignEnd(signLocalTime.plusMinutes(Util.getIntValue(workMins)).format(dateTimeFormatter)); + shiftInfoBean.setFreeSignMiddle(signLocalTime.plusMinutes(Util.getIntValue(workMins)/2).format(dateTimeFormatter)); + } + + return shiftInfoBean; + }else{ + if(kqWorkTimeMap.get("shiftInfoBean") != null){ + ShiftInfoBean shiftInfoBean = (ShiftInfoBean)kqWorkTimeMap.get("shiftInfoBean"); + if(isUsedRestShift) { + int serialid = Util.getIntValue(Util.null2String(shiftInfoBean.getSerialid()), 0); + KQShiftManagementComInfo kQShiftManagementComInfo = new KQShiftManagementComInfo(); + int restShift = StringUtil.parseToInt(kQShiftManagementComInfo.getRestShift(String.valueOf(serialid)), 0); + if(restShift == 1) { + return null; + } + } + return shiftInfoBean; + }else{ + return null; + } + } + } + + /** + * 直接根据user来获取 + * @param user + * @param date + * @param containYesterday + * @return + */ + public static ShiftInfoBean getWorkTime(User user, String date,boolean containYesterday){ + return getWorkTime(user, date, containYesterday, true); + } + + public static Map getWorkButton(String resourceid, String date, boolean containYesterday){ + User user = User.getUser(Util.getIntValue(resourceid), 0); + return getWorkButton(user,date,containYesterday); + } + + public static Map getWorkButton(User user, String date, boolean containYesterday){ + KQWorkTime kqWorkTime = new KQWorkTime(); + Map kqWorkTimeMap = new HashMap<>(); + kqWorkTimeMap = kqWorkTime.getWorkButton(""+user.getUID(), date,containYesterday); + + return kqWorkTimeMap; + } + + /** + * 根据传入的用户和时段返回非工作时长 + * @return + */ + public Map getNonWorkDuration(){ + + Map durationMap = new HashMap<>(); + try{ + double D_Duration = 0.0; + double Min_Duration = 0.0; + //公众假日加班时长 + double D_Pub_Duration = 0.0; + double D_Pub_Mins = 0.0; + //工作日加班时长 + double D_Work_Duration = 0.0; + double D_Work_Mins = 0.0; + //休息日加班时长 + double D_Rest_Duration = 0.0; + double D_Rest_Mins = 0.0; + + SplitBean splitBean = new SplitBean(); + splitBean.setFromDate(fromDate); + splitBean.setFromTime(fromTime); + splitBean.setToDate(toDate); + splitBean.setToTime(toTime); + splitBean.setResourceId(resourceid); + splitBean.setFromdatedb(fromDate); + splitBean.setTodatedb(toDate); + splitBean.setFromtimedb(fromTime); + splitBean.setTotimedb(toTime); + splitBean.setDurationrule(durationrule); + splitBean.setComputingMode(computingMode); + splitBean.setDurationTypeEnum(DurationTypeEnum.OVERTIME); + splitBean.setOvertime_type(overtime_type); + + List splitBeans = new ArrayList<>(); + + NonWorkDurationChain hourUnitSplitChain = new NonHourUnitSplitChain(splitBeans); + NonWorkDurationChain dayUnitSplitChain = new NonDayUnitSplitChain(splitBeans); + NonWorkDurationChain halfUnitSplitChain = new NonHalfUnitSplitChain(splitBeans); + NonWorkDurationChain wholeUnitSplitChain = new NonWholeUnitSplitChain(splitBeans); + + //设置执行链 + hourUnitSplitChain.setDurationChain(dayUnitSplitChain); + dayUnitSplitChain.setDurationChain(halfUnitSplitChain); + halfUnitSplitChain.setDurationChain(wholeUnitSplitChain); + //把初始数据设置进去 + hourUnitSplitChain.handleDuration(splitBean); + + //每一天的流程时长都在这里了,搞吧 + for(SplitBean sb : splitBeans){ +// * 1-公众假日、2-工作日、3-休息日 + int changeType = sb.getChangeType(); + double durations = Util.getDoubleValue(sb.getDuration(), 0.0); + double durationMins = sb.getD_Mins(); + if(1 == changeType){ + D_Pub_Duration += durations; + D_Pub_Mins += durationMins; + } + if(2 == changeType){ + D_Work_Duration += durations; + D_Work_Mins += durationMins; + } + if(3 == changeType){ + D_Rest_Duration += durations; + D_Rest_Mins += durationMins; + } + } + Min_Duration = D_Pub_Mins+D_Work_Mins+D_Rest_Mins; + + if("3".equalsIgnoreCase(durationrule) || "5".equalsIgnoreCase(durationrule) || "6".equalsIgnoreCase(durationrule)){ + double d_hour = Min_Duration/60.0; + durationMap.put("duration", KQDurationCalculatorUtil.getDurationRound(""+d_hour)); + }else { + double oneDayHour = KQFlowUtil.getOneDayHour(DurationTypeEnum.OVERTIME,""); + double d_day = Min_Duration/(oneDayHour * 60); + durationMap.put("duration", KQDurationCalculatorUtil.getDurationRound(""+d_day)); + } + + durationMap.put("min_duration", KQDurationCalculatorUtil.getDurationRound(""+Min_Duration)); + + }catch (Exception e){ + e.printStackTrace(); + } + return durationMap; + } + + /** + * 根据传入的用户和时段返回工作时长 + * @return + */ + public Map getWorkDuration(){ + + Map durationMap = new HashMap<>(); + try{ + if(!isValidate(fromDate,toDate,fromTime,toTime)){ + durationMap.put("duration", "0.0"); + return durationMap; + } + if(durationTypeEnum != DurationTypeEnum.COMMON_CAL){ + kqLog.info("resourceid="+resourceid+",getWorkDuration:"+durationTypeEnum.getDurationType()+":fromDate:"+fromDate+":toDate:"+toDate+":fromTime:"+fromTime+":toTime:"+toTime+":durationrule:"+durationrule+":computingMode:"+computingMode); + } + //如果是加班 + if(durationTypeEnum ==DurationTypeEnum.OVERTIME){ + return getNonWorkDuration(); + } + //时长 + double D_Duration = 0.0; + //分钟数 + double Min_Duration = 0.0; + + SplitBean splitBean = new SplitBean(); + splitBean.setFromDate(fromDate); + splitBean.setFromTime(fromTime); + splitBean.setToDate(toDate); + splitBean.setToTime(toTime); + splitBean.setResourceId(resourceid); + splitBean.setFromdatedb(fromDate); + splitBean.setTodatedb(toDate); + splitBean.setFromtimedb(fromTime); + splitBean.setTotimedb(toTime); + splitBean.setDurationrule(durationrule); + splitBean.setDurationTypeEnum(durationTypeEnum); + splitBean.setComputingMode(computingMode); + splitBean.setNewLeaveType(newLeaveType); + if("2".equalsIgnoreCase(computingMode)){ + double oneDayHour = KQFlowUtil.getOneDayHour(durationTypeEnum,newLeaveType); + splitBean.setOneDayHour(oneDayHour); + if(durationTypeEnum == DurationTypeEnum.LEAVE){ + //只有自然日 请假才有这个排除节假日、休息日的功能 + splitBean.setFilterholidays(KQLeaveRulesBiz.getFilterHolidays(splitBean.getNewLeaveType())); + } + } + if(durationTypeEnum ==DurationTypeEnum.LEAVE || durationTypeEnum ==DurationTypeEnum.LEAVEBACK){ + if(newLeaveType.length() > 0){ + KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo(); + String conversion = kqLeaveRulesComInfo.getConversion(newLeaveType); + splitBean.setConversion(conversion); + } + } + + List splitBeans = new ArrayList<>(); + + WorkDurationChain hourUnitSplitChain = new WorkHourUnitSplitChain(splitBeans); + WorkDurationChain dayUnitSplitChain = new WorkDayUnitSplitChain(splitBeans); + WorkDurationChain halfUnitSplitChain = new WorkHalfUnitSplitChain(splitBeans); + WorkDurationChain wholeUnitSplitChain = new WorkWholeUnitSplitChain(splitBeans); + + //设置执行链 + hourUnitSplitChain.setDurationChain(dayUnitSplitChain); + dayUnitSplitChain.setDurationChain(halfUnitSplitChain); + halfUnitSplitChain.setDurationChain(wholeUnitSplitChain); + //把初始数据设置进去 + hourUnitSplitChain.handleDuration(splitBean); + + kqLog.info("getWorkDuration--resourceid="+resourceid+",durationType="+durationTypeEnum.getDurationType()+",splitBeans="+ JSONObject.toJSONString(splitBeans)); + //每一天的流程时长都在这里了,搞吧 + for(SplitBean sb : splitBeans){ + double durations = Util.getDoubleValue(sb.getDuration(), 0.0); + double min_durations = sb.getD_Mins(); + D_Duration += durations; + Min_Duration += min_durations; + } + kqLog.info("getWorkDuration--resourceid=" + resourceid + ",durationType=" + durationTypeEnum.getDurationType() + ",D_Duration=" + D_Duration); + durationMap.put("duration", KQDurationCalculatorUtil.getDurationRound(""+D_Duration)); + durationMap.put("min_duration", KQDurationCalculatorUtil.getDurationRound(""+Min_Duration)); + kqLog.info("getWorkDuration--resourceid=" + resourceid + ",durationType=" + durationTypeEnum.getDurationType() + ",durationMap=" + durationMap.toString()); + }catch (Exception e){ + e.printStackTrace(); + } + return durationMap; + } + + /** + * 校验是传入的参数数据是否正常 + * @return false 表示数据有误 + */ + private boolean isValidate(String fromDate,String toDate,String fromTime,String toTime) { + + if(fromDate.length() == 0 || toDate.length() == 0){ + return false; + } + if(fromTime.length() == 0 || toTime.length() == 0){ + return false; + } + + DateTimeFormatter fullFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + + String fromDateTime = fromDate+" "+fromTime+":00"; + String toDateTime = toDate+" "+toTime+":00"; + + LocalDateTime localFromDateTime = LocalDateTime.parse(fromDateTime,fullFormatter); + LocalDateTime localToDateTime = LocalDateTime.parse(toDateTime,fullFormatter); + + if(localFromDateTime.isAfter(localToDateTime) || localFromDateTime.isEqual(localToDateTime)){ + return false; + } + return true; + } + + /** + * 得到排除非工作时间的时长 + * @param fromDate + * @param fromTime + * @param toDate + * @param toTime + * @param resourceid + * @return + */ + public Map getTotalWorkingDurations(String fromDate,String fromTime,String toDate,String toTime,String resourceid){ + KQDurationCalculatorUtil kqDurationCalculatorUtil =new KQDurationCalculatorUtil.DurationParamBuilder(resourceid). + fromDateParam(fromDate).toDateParam(toDate).fromTimeParam(fromTime).toTimeParam(toTime).durationRuleParam("1") + .computingModeParam("1").durationTypeEnumParam(DurationTypeEnum.COMMON_CAL).build(); + + Map durationMap = kqDurationCalculatorUtil.getWorkDuration(); + return durationMap; + } + + /** + * 得到排除非工作时间的天数 + * @param fromDate + * @param fromTime + * @param toDate + * @param toTime + * @param resourceid + * @return + */ + public String getTotalWorkingDays(String fromDate,String fromTime,String toDate,String toTime,String resourceid){ + Map durationMap = getTotalWorkingDurations(fromDate,fromTime,toDate,toTime,resourceid); + + String duration4day = Util.null2s(Util.null2String(durationMap.get("duration")),"0"); + return KQDurationCalculatorUtil.getDurationRound(duration4day); + } + + /** + * 得到排除非工作时间的小时 + * @param fromDate + * @param fromTime + * @param toDate + * @param toTime + * @param resourceid + * @return + */ + public String getTotalWorkingHours(String fromDate,String fromTime,String toDate,String toTime,String resourceid){ + Map durationMap = getTotalWorkingDurations(fromDate,fromTime,toDate,toTime,resourceid); + String duration4min = Util.null2s(Util.null2String(durationMap.get("min_duration")),"0"); + double duration4hour = Util.getDoubleValue(duration4min)/60.0; + + return KQDurationCalculatorUtil.getDurationRound(duration4hour+""); + } + + /** + * 得到排除非工作时间的分钟 + * @param fromDate + * @param fromTime + * @param toDate + * @param toTime + * @param resourceid + * @return + */ + public String getTotalWorkingMins(String fromDate,String fromTime,String toDate,String toTime,String resourceid){ + Map durationMap = getTotalWorkingDurations(fromDate,fromTime,toDate,toTime,resourceid); + String duration4min = Util.null2s(Util.null2String(durationMap.get("min_duration")),"0"); + + return KQDurationCalculatorUtil.getDurationRound(duration4min+""); + } + + /** + * 得到非工作时间的天数 + * @param fromDate + * @param fromTime + * @param toDate + * @param toTime + * @param resourceid + * @return + */ + public String getTotalNonWorkingDays(String fromDate,String fromTime,String toDate,String toTime,String resourceid){ + KQDurationCalculatorUtil kqDurationCalculatorUtil =new KQDurationCalculatorUtil.DurationParamBuilder(resourceid). + fromDateParam(fromDate).toDateParam(toDate).fromTimeParam(fromTime).toTimeParam(toTime).computingModeParam("1"). + durationRuleParam("1").durationTypeEnumParam(DurationTypeEnum.OVERTIME).build(); + Map durationMap = kqDurationCalculatorUtil.getNonWorkDuration(); + + String duration = Util.null2String(durationMap.get("duration")); + return KQDurationCalculatorUtil.getDurationRound(duration); + } + + /** + * 得到非工作时间的小时 + * @param fromDate + * @param fromTime + * @param toDate + * @param toTime + * @param resourceid + * @return + */ + public String getTotalNonWorkingHours(String fromDate,String fromTime,String toDate,String toTime,String resourceid){ + KQDurationCalculatorUtil kqDurationCalculatorUtil =new KQDurationCalculatorUtil.DurationParamBuilder(resourceid). + fromDateParam(fromDate).toDateParam(toDate).fromTimeParam(fromTime).toTimeParam(toTime).computingModeParam("1"). + durationRuleParam("3").durationTypeEnumParam(DurationTypeEnum.OVERTIME).build(); + Map durationMap = kqDurationCalculatorUtil.getNonWorkDuration(); + + String duration = Util.null2String(durationMap.get("duration")); + return KQDurationCalculatorUtil.getDurationRound(duration); + } + + /** + * 考勤通用精度 2 + * @param duration + * @return + */ + public static String getDurationRound(String duration){ + if(HrmScheduleDiffUtil.isFromFlow()){ + return Util.round(duration,5) ; + } + return Util.round(duration, 2); + } + + /** + * 考勤流程中间表精度 5 + * @param duration + * @return + */ + public static String getDurationRound5(String duration){ + return Util.round(duration, 5); + } + + /** + * 针对可能存在的多种参数类型 创建参数静态内部类Builder + */ + public static class DurationParamBuilder { + + //必选变量 人员看怎么都是需要的 + private final String resourceid; + + //可选变量 + private String fromDate = ""; + private String toDate = ""; + private String fromTime = ""; + private String toTime = ""; + /** + * 请假用的请假类型 + */ + private String newLeaveType = ""; + /** + * 单位 + * 1-按天出差 + * 2-按半天出差 + * 3-按小时出差 + * 4-按整天出差 + */ + private String durationrule = ""; + /** + * 时长计算方式 + * 1-按照工作日计算请假时长 + * 2-按照自然日计算请假时长 + */ + private String computingMode = ""; + + /** + * 加班类型 + */ + private String overtime_type = ""; + + /** + * 哪种类型的时长计算,请假还是出差还是公出还是加班 + */ + private DurationTypeEnum durationTypeEnum; + + public DurationParamBuilder(String resourceid) { + this.resourceid = resourceid; + //初始化的时候需要把其他参数先清空下 + this.fromDate = ""; + this.toDate = ""; + this.fromTime = ""; + this.toTime = ""; + this.newLeaveType = ""; + this.durationrule = ""; + this.computingMode = ""; + this.overtime_type = ""; + } + + //成员方法返回其自身,所以可以链式调用 + public DurationParamBuilder fromDateParam(final String fromDate) { + this.fromDate = fromDate; + return this; + } + + public DurationParamBuilder toDateParam(final String toDate) { + this.toDate = toDate; + return this; + } + + public DurationParamBuilder fromTimeParam(final String fromTime) { + this.fromTime = fromTime; + return this; + } + + public DurationParamBuilder toTimeParam(final String toTime) { + this.toTime = toTime; + return this; + } + + public DurationParamBuilder newLeaveTypeParam(final String newLeaveType) { + this.newLeaveType = newLeaveType; + return this; + } + + public DurationParamBuilder durationRuleParam(final String durationrule) { + this.durationrule = durationrule; + return this; + } + public DurationParamBuilder computingModeParam(final String computingMode) { + this.computingMode = computingMode; + return this; + } + public DurationParamBuilder overtime_typeParam(final String overtime_type) { + this.overtime_type = overtime_type; + return this; + } + public DurationParamBuilder durationTypeEnumParam(final DurationTypeEnum durationTypeEnum) { + this.durationTypeEnum = durationTypeEnum; + return this; + } + + //Builder的build方法,返回外部类的实例 + public KQDurationCalculatorUtil build() { + return new KQDurationCalculatorUtil(this); + } + } + +} diff --git a/src/com/engine/kq/util/KQTransMethod.java b/src/com/engine/kq/util/KQTransMethod.java new file mode 100644 index 0000000..1a3c1ce --- /dev/null +++ b/src/com/engine/kq/util/KQTransMethod.java @@ -0,0 +1,1384 @@ +package com.engine.kq.util; + +import com.alibaba.fastjson.JSONObject; +import com.engine.kq.biz.*; +import com.google.common.collect.Lists; +import weaver.common.DateUtil; +import weaver.common.StringUtil; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.Util; +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.math.RoundingMode; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.List; + +import weaver.workflow.workflow.WorkflowRequestComInfo; + +/** + * 列表的显示转换方法 + */ +public class KQTransMethod { + + /***************************************假期的相关方法***************************************/ + /** + * 判断假期类型能否进行编辑、删除、查看日志 + * (被流程引用过的假期类型不可删除,新建过假期规则的假期类型不可删除、未启用的假期类型不可编辑) + * + * @param ruleId 假期类型的ID + * @param param canEdit:canDelete:canLog + * @return + */ + public ArrayList getLeaveRulesOperate(String ruleId, String param) { + ArrayList resultList = new ArrayList(); + String[] allParam = param.split(":"); + String canEdit = allParam[0]; + String canDelete = allParam[1]; + String canLog = allParam[2]; + boolean leaveTypeUsed = false; + boolean isEnable = true; + boolean hasLeaveRules = false; + try { + String sql = "select * from kq_LeaveRulesDetail where (isDelete is null or isDelete<>1) and ruleId=?"; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql, ruleId); + if (recordSet.next()) { + hasLeaveRules = true; + } + + leaveTypeUsed = KQFlowDataBiz.leaveTypeUsed(ruleId);//判断是否有发起过该请假类型的请假流程 + KQLeaveRulesComInfo rulesComInfo = new KQLeaveRulesComInfo(); + isEnable = rulesComInfo.getIsEnable(ruleId).equals("1");//判断该请假是否启用 + } catch (Exception e) { + e.printStackTrace(); + } + resultList.add(isEnable ? canEdit : "false");//是否可以编辑 + resultList.add((leaveTypeUsed || hasLeaveRules) ? "false" : canDelete);//是否可以删除 + resultList.add(canLog);//是否可以查看日志 + return resultList; + } + + /** + * 判断假期类型是否可以勾选,即是否可以删除 + * (被流程引用过的假期类型不可删除、新建过假期规则的假期类型不可删除) + * + * @param ruleId 假期类型ID + * @return + */ + public String getLeaveRulesCheckbox(String ruleId) { + boolean leaveTypeUsed = false; + boolean hasLeaveRules = false; + try { + String sql = "select * from kq_LeaveRulesDetail where (isDelete is null or isDelete<>1) and ruleId=?"; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql, ruleId); + if (recordSet.next()) { + hasLeaveRules = true; + } + + leaveTypeUsed = KQFlowDataBiz.leaveTypeUsed(ruleId);//判断是否有发起过该请假类型的请假流程 + } catch (Exception e) { + e.printStackTrace(); + } + return String.valueOf(!leaveTypeUsed && !hasLeaveRules); + } + + /** + * 获取最小请假单位 + * 1-按天请假 + * 2-按半天请假 + * 3-按小时请假 + * 4-按整天请假 + * + * @param minimumUnit + * @param languageId + * @return + */ + public String getMinimumUnitName4Browser(String minimumUnit, String languageId) { + String minimumUnitName = ""; + int language = Util.getIntValue(languageId, 7); + switch (minimumUnit) { + case "1": + minimumUnitName = SystemEnv.getHtmlLabelName(1925, language); + break; + case "2": + minimumUnitName = SystemEnv.getHtmlLabelName(128559, language); + break; + case "3": + minimumUnitName = SystemEnv.getHtmlLabelName(391, language); + break; + case "4": + minimumUnitName = SystemEnv.getHtmlLabelName(390728, language); + break; + case "5": + minimumUnitName = SystemEnv.getHtmlLabelName(124952, language); + break; + case "6": + minimumUnitName = SystemEnv.getHtmlLabelName(529675, language); + break; + default: + minimumUnitName = ""; + break; + } + return minimumUnitName; + } + + /** + * 获取最小请假单位 + * 1-按天请假 + * 2-按半天请假 + * 3-按小时请假 + * 4-按整天请假 + * + * @param minimumUnit + * @param languageId + * @return + */ + public String getMinimumUnitName(String minimumUnit, String languageId) { + String minimumUnitName = ""; + int language = Util.getIntValue(languageId, 7); + switch (minimumUnit) { + case "1": + minimumUnitName = SystemEnv.getHtmlLabelName(388885, language); + break; + case "2": + minimumUnitName = SystemEnv.getHtmlLabelName(388886, language); + break; + case "3": + minimumUnitName = SystemEnv.getHtmlLabelName(388887, language); + break; + case "4": + minimumUnitName = SystemEnv.getHtmlLabelName(389680, language); + break; + case "5": + minimumUnitName = SystemEnv.getHtmlLabelName(514712, language); + break; + case "6": + minimumUnitName = SystemEnv.getHtmlLabelName(514786, language); + break; + default: + minimumUnitName = ""; + break; + } + return minimumUnitName; + } + + /** + * 计算请假时长方式 + * 1-按工作日计算请假时长 + * 2-按自然日计算请假时长 + * + * @param computingMode + * @param languageId + * @return + */ + public String getComputingModeName(String computingMode, String languageId) { + String computingModeName = ""; + int language = Util.getIntValue(languageId, 7); + switch (computingMode) { + case "1": + computingModeName = SystemEnv.getHtmlLabelName(388889, language); + break; + case "2": + computingModeName = SystemEnv.getHtmlLabelName(388890, language); + break; + default: + computingModeName = ""; + break; + } + return computingModeName; + } + + /** + * 获取余额规则 + * 1-手动发放 + * 2-按司龄自动发放 + * 3-按工龄自动发放 + * 4-每年自动发放固定天数 + * 5-加班时长自动计入余额 + * 6-按工龄+司龄自动发放 + * + * @param distributionMode + * @return + */ + public String getDistributionModName(String distributionMode, String languageId) { + int language = Util.getIntValue(languageId, 7); + + String distributionModeName = ""; + switch (distributionMode) { + case "1": + distributionModeName = SystemEnv.getHtmlLabelName(388947, language); + break; + case "2": + distributionModeName = SystemEnv.getHtmlLabelName(390374, language); + break; + case "3": + distributionModeName = SystemEnv.getHtmlLabelName(388949, language); + break; + case "4": + distributionModeName = SystemEnv.getHtmlLabelName(388950, language); + break; + case "5": + distributionModeName = SystemEnv.getHtmlLabelName(388951, language); + break; + case "6": + distributionModeName = SystemEnv.getHtmlLabelName(390822, language); + break; + case "7": + distributionModeName = SystemEnv.getHtmlLabelName(514025, language); + break; + case "8": + distributionModeName = SystemEnv.getHtmlLabelName(536880, language); + break; + default: + distributionModeName = ""; + break; + } + return distributionModeName; + } + + /** + * 获取应用范围的显示名称 + * + * @param scopeType + * @param languageId + * @return + */ + public String getScopeTypeName(String scopeType, String languageId) { + int language = Util.getIntValue(languageId, 7); + String scopeTypeName = ""; + if (scopeType.equals("0")) { + scopeTypeName = SystemEnv.getHtmlLabelName(140, language); + } else if (scopeType.equals("1")) { + scopeTypeName = SystemEnv.getHtmlLabelName(33553, language); + } + return scopeTypeName; + } + + /** + * 获取分部的名称 + * + * @param organizationType + * @param organizationId + * @return + */ + public String getOrganizationIdName(String organizationId, String organizationType) { + SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo(); + String showName = ""; + if (organizationType.equals("1")) { + showName = subCompanyComInfo.getSubCompanyname(organizationId); + } + return showName; + } + + /** + * 获取应用范围的显示名称 + * + * @param organizationType + * @param languageId + * @return + */ + public String getOrganizationTypeName(String organizationType, String languageId) { + int language = Util.getIntValue(languageId, 7); + String showName = ""; + if (organizationType.equals("0")) { + showName = SystemEnv.getHtmlLabelName(140, language); + } else { + showName = SystemEnv.getHtmlLabelName(141, language); + } + return showName; + } + + /** + * 获取释放规则的显示名称 + * + * @param releaseRule + * @param languageId + * @return + */ + public String getReleaseRuleName(String releaseRule, String languageId) { + String releaseRuleName = ""; + int language = Util.getIntValue(languageId, 7); + if (releaseRule.equals("0")) { + releaseRuleName = SystemEnv.getHtmlLabelName(32499, language); + } else if (releaseRule.equals("1")) { + releaseRuleName = SystemEnv.getHtmlLabelName(390280, language); + } else if (releaseRule.equals("2")) { + releaseRuleName = SystemEnv.getHtmlLabelName(390281, language); + } + return releaseRuleName; + } + + /** + * 获取有效期规则的显示名称 + * + * @param validityRule + * @param languageId + * @return + */ + public String getValidityRuleShow(String validityRule, String languageId) { + String validityRuleShow = ""; + int language = Util.getIntValue(languageId, 7); + if (validityRule.equals("0")) { + validityRuleShow = SystemEnv.getHtmlLabelName(22135, language); + } else if (validityRule.equals("1")) { + validityRuleShow = SystemEnv.getHtmlLabelName(388953, language); + } else if (validityRule.equals("2")) { + validityRuleShow = SystemEnv.getHtmlLabelName(388954, language); + } else if (validityRule.equals("3")) { + validityRuleShow = SystemEnv.getHtmlLabelName(389739, language); + } else if (validityRule.equals("4")) { + validityRuleShow = SystemEnv.getHtmlLabelName(508428, language); + } else if (validityRule.equals("5")) { + validityRuleShow = SystemEnv.getHtmlLabelName(513525, language); + } else if (validityRule.equals("6")) { + validityRuleShow = SystemEnv.getHtmlLabelName(515135, language); + } else if (validityRule.equals("7")) { + validityRuleShow = SystemEnv.getHtmlLabelName(536941, language); + } + return validityRuleShow; + } + + /** + * 获取是否启用假期余额的显示名称 + * + * @param balanceEnable 是否显示假期余额 + * @param languageId 系统语言 + * @return + */ + public String getBalanceEnableShow(String balanceEnable, String languageId) { + String balanceEnableShow = ""; + try { + int language = Util.getIntValue(languageId, 7); + if (balanceEnable.equals("1")) { + balanceEnableShow = SystemEnv.getHtmlLabelName(18095, language); + } else { + balanceEnableShow = SystemEnv.getHtmlLabelName(32386, language); + } + } catch (Exception e) { + e.printStackTrace(); + } + return balanceEnableShow; + } + + /** + * 获取假期类型的显示名称 + * + * @param typeId 假期类型的ID(对应于数据库表kq_leaveRules的主键ID) + * @param languageId 系统语言 + * @return + */ + public String getLeaveTypesName(String typeId, String languageId) { + String leaveTypesName = ""; + try { + KQLeaveRulesComInfo rulesComInfo = new KQLeaveRulesComInfo(); + leaveTypesName = Util.formatMultiLang(rulesComInfo.getLeaveName(typeId), languageId); + } catch (Exception e) { + e.printStackTrace(); + } + return leaveTypesName; + } + + /***************************************员工假期余额的相关方法***************************************/ + + /** + * 为了前端校验时取值,故将分页控件的值做一下转换显示 + * + * @param value + * @return + */ + public String getOriginalShow(String value) { + BigDecimal bigDecimal = new BigDecimal(Util.null2s(value.trim(), "0")); + return bigDecimal.setScale(2, RoundingMode.HALF_UP).toPlainString(); + } + + /** + * 获取当前可用的假期余额(假期余额基数*释放比例) + * + * @param balanceId 假期余额表的主键ID + * @param otherPara 指定的人员ID+指定的假期规则ID+指定的所属年份+假期基数+是计算法定年假还是计算福利年假('neither'-非混合模式、legal-法定年假、welfare-福利年假) + * @return + */ + public String getCanUseAmount(String balanceId, String otherPara) { + BigDecimal canUseAmount = new BigDecimal(0); + String otherParaArr[] = otherPara.split("\\+", 5); + String resourceId = otherParaArr[0]; + String leaveRulesId = otherParaArr[1]; + String belongYear = otherParaArr[2]; + BigDecimal baseAmount = new BigDecimal(Util.null2s(otherParaArr[3].trim(), "0")); + try { + + + String legalOrWelfare = Util.null2String(otherParaArr[4]); + + /*获取当前日期*/ + String date = DateUtil.getCurrentDate(); + + //判断查询年份是否是小孩出生日期的第三年 + new BaseBean().writeLog("-KQTransMethod-belongYear:"+belongYear); + boolean isLastYearChildcareLeave = UtilKQHS.isLastYearChildcareLeave(resourceId, belongYear); + new BaseBean().writeLog("-KQTransMethod-isLastYearChildcareLeave:"+isLastYearChildcareLeave); + if(isLastYearChildcareLeave && "36".equals(leaveRulesId)){ + canUseAmount = KQBalanceOfLeaveBiz.getCanUseAmountChildcareLeave(resourceId, leaveRulesId, belongYear, baseAmount, legalOrWelfare, date, isLastYearChildcareLeave); + }else{ + canUseAmount = KQBalanceOfLeaveBiz.getCanUseAmount(resourceId, leaveRulesId, belongYear, baseAmount, legalOrWelfare, date); + } + + } catch (Exception e) { + e.printStackTrace(); + } + String canUseAmountStr = canUseAmount.setScale(2, RoundingMode.HALF_UP).toPlainString(); + //36:育儿假 37:独生子女护理假 + if("36".equals(leaveRulesId) || "37".equals(leaveRulesId)){ + canUseAmountStr = UtilKQHS.handleAmount(canUseAmountStr,baseAmount.toPlainString()); + } + return canUseAmountStr; + } + + /** + * 获取剩余的假期余额(假期余额基数*释放比例+额外余额-已用余额) + * + * @param balanceId 假期余额表的主键ID + * @param otherPara 指定的人员ID+指定的假期规则ID+指定的所属年份+假期基数+额外假期余额+已休假期余额+是计算法定年假还是计算福利年假(neither-非混合模式、legal-法定年假、welfare-福利年假) + * @return + */ + public String getRestAmount(String balanceId, String otherPara) { + String restAmount = "0.00"; + try { + String otherParaArr[] = otherPara.split("\\+", 7); + String resourceId = otherParaArr[0]; + String leaveRulesId = otherParaArr[1]; + String belongYear = otherParaArr[2]; + double baseAmount = Util.getDoubleValue(otherParaArr[3], 0.00); + double extraAmount = Util.getDoubleValue(otherParaArr[4], 0.00); + double usedAmount = Util.getDoubleValue(otherParaArr[5], 0.00); + String legalOrWelfare = Util.null2s(otherParaArr[6], ""); + + String str = resourceId + "+" + leaveRulesId + "+" + belongYear + "+" + baseAmount + "+" + legalOrWelfare; + double canUseAmount = Util.getDoubleValue(getCanUseAmount(balanceId, str), 0.00); + + restAmount = String.format("%.2f", canUseAmount + extraAmount - usedAmount); + } catch (Exception e) { + e.printStackTrace(); + } + return restAmount; + } + + /** + * 判断假期余额是否有效 + * + * @param leaveRulesId + * @param otherParams + * @return + */ + public String getBalanceStatusShow(String leaveRulesId, String 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); + + boolean status = KQBalanceOfLeaveBiz.getBalanceStatus(leaveRulesId, resourceId, belongYear, currentDate, effectiveDate, expirationDate); + 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; + } + + public String getTotalAmountShow(String baseAmount, String otherParams) { + String extraAmount = otherParams; + BigDecimal _baseAmount = new BigDecimal(Util.null2s(baseAmount.trim(), "0")); + BigDecimal _extraAmount = new BigDecimal(Util.null2s(extraAmount.trim(), "0")); + BigDecimal _totalAmount = _baseAmount.add(_extraAmount); + String totalAmount = _totalAmount.setScale(2, RoundingMode.HALF_UP).toPlainString(); + return totalAmount; + } + + public String getTiaoxiuamountShow(String tiaoxiuamount) { + BigDecimal _tiaoxiuamount = new BigDecimal(Util.null2s(tiaoxiuamount, "0")); + String totalAmount = _tiaoxiuamount.setScale(2, RoundingMode.HALF_UP).toPlainString(); + return totalAmount; + } + + /** + * 获取已经失效的调休值(针对单条记录而言的,不是汇总的) + * + * @param invalidAmount + * @param otherParams + * @return + */ + public String getInvalidAmountShow(String invalidAmount, String otherParams) { + /*获取当前日期,当前时间*/ + 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); +// tiaoxiuamount + String[] otherParamArr = otherParams.split("\\+", 5); + BigDecimal baseAmount = new BigDecimal(Util.null2s(otherParamArr[0].trim(), "0"));//基数 + BigDecimal extraAmount = new BigDecimal(Util.null2s(otherParamArr[1].trim(), "0"));//额外 + BigDecimal tiaoxiuAmount = new BigDecimal(Util.null2s(otherParamArr[4].trim(), "0"));//加班生成的调休 + BigDecimal totalAmount = baseAmount.add(extraAmount).add(tiaoxiuAmount); + BigDecimal usedAmount = new BigDecimal(Util.null2s(otherParamArr[2].trim(), "0"));//已休 + String expirationDate = Util.null2String(otherParamArr[3]).trim(); + if ("".equals(expirationDate) || expirationDate.compareTo(currentDate) >= 0) { + invalidAmount = "0.00"; + } else { + invalidAmount = totalAmount.subtract(usedAmount).setScale(2, RoundingMode.HALF_UP).toPlainString(); + } + + return invalidAmount; + } + + /** + * 获取剩余的调休值(针对单条记录而言的,不是汇总的) + * + * @param restAmount + * @param otherParam + * @return + */ + public String getRestAmountShow(String restAmount, String otherParam) { + /*获取当前日期,当前时间*/ + 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[] otherParamArr = otherParam.split("\\+", 5); + BigDecimal baseAmount = new BigDecimal(Util.null2s(otherParamArr[0].trim(), "0"));//基数 + BigDecimal extraAmount = new BigDecimal(Util.null2s(otherParamArr[1].trim(), "0"));//额外 + BigDecimal usedAmount = new BigDecimal(Util.null2s(otherParamArr[2].trim(), "0"));//已休 + BigDecimal tiaoxiuamount = new BigDecimal(Util.null2s(otherParamArr[4].trim(), "0"));//加班生成调休 + BigDecimal totalAmount = baseAmount.add(extraAmount).add(tiaoxiuamount); + String expirationDate = Util.null2String(otherParamArr[3]).trim(); + if ("".equals(expirationDate) || expirationDate.compareTo(currentDate) >= 0) { + restAmount = totalAmount.subtract(usedAmount).setScale(2, RoundingMode.HALF_UP).toPlainString(); + } else { + restAmount = "0.00"; + } + + return restAmount; + } + + /** + * 获取加班类型 + * + * @param overtimeType + * @param language + * @return + */ + public String getOvertimeTypeShow(String overtimeType, String language) { + if (overtimeType.equals("3")) { + //打卡生成的调休 + return SystemEnv.getHtmlLabelName(509982, Util.getIntValue(language, 7)); + } else if (overtimeType.equals("4")) { + //加班流程生成的调休 + return SystemEnv.getHtmlLabelName(509981, Util.getIntValue(language, 7)); + } else if (overtimeType.equals("7")) { + //Excel导入生成的调休 + return SystemEnv.getHtmlLabelName(509980, Util.getIntValue(language, 7)); + } else { + //原有的调休 + return SystemEnv.getHtmlLabelName(509983, Util.getIntValue(language, 7)); + } + } + + public String getAllTotalAmount(String allTotalAmount, String otherParams) { + String[] otherParamArr = otherParams.split("\\+", 6); + BigDecimal allBaseAmountB = new BigDecimal(Util.null2s(otherParamArr[0].trim(), "0")); + BigDecimal allExtraAmountB = new BigDecimal(Util.null2s(otherParamArr[1].trim(), "0")); + BigDecimal allBaseAmountC = new BigDecimal(Util.null2s(otherParamArr[2].trim(), "0")); + BigDecimal allExtraAmountC = new BigDecimal(Util.null2s(otherParamArr[3].trim(), "0")); + BigDecimal alltiaoxiuamountB = new BigDecimal(Util.null2s(otherParamArr[4].trim(), "0")); + BigDecimal alltiaoxiuamountC = new BigDecimal(Util.null2s(otherParamArr[5].trim(), "0")); + allTotalAmount = allBaseAmountB.add(allExtraAmountB).add(allBaseAmountC).add(allExtraAmountC) + .add(alltiaoxiuamountB).add(alltiaoxiuamountC).setScale(2, RoundingMode.HALF_UP).toPlainString(); + return allTotalAmount; + } + + public String getAllUsedAmount(String allUsedAmount, String otherParams) { + String[] otherParamArr = otherParams.split("\\+", 2); + BigDecimal allUsedAmountB = new BigDecimal(Util.null2s(otherParamArr[0].trim(), "0")); + BigDecimal allUsedAmountC = new BigDecimal(Util.null2s(otherParamArr[1].trim(), "0")); + allUsedAmount = allUsedAmountB.add(allUsedAmountC).setScale(2, RoundingMode.HALF_UP).toString(); + return allUsedAmount; + } + + public String getAllInvalidAmount(String allInvalidAmount, String otherParams) { + String[] otherParamArr = otherParams.split("\\+", 4); + BigDecimal allBaseAmountC = new BigDecimal(Util.null2s(otherParamArr[0].trim(), "0")); + BigDecimal allExtraAmountC = new BigDecimal(Util.null2s(otherParamArr[1].trim(), "0")); + BigDecimal alltiaoxiuAmountC = new BigDecimal(Util.null2s(otherParamArr[3].trim(), "0")); + BigDecimal allUsedAmountC = new BigDecimal(Util.null2s(otherParamArr[2].trim(), "0")); + allInvalidAmount = allBaseAmountC.add(allExtraAmountC).add(alltiaoxiuAmountC).subtract(allUsedAmountC).setScale(2, RoundingMode.HALF_UP).toPlainString(); + return allInvalidAmount; + } + + public String getAllRestAmount(String allRestAmount, String otherParams) { + String[] otherParamArr = otherParams.split("\\+", 4); + BigDecimal allBaseAmountB = new BigDecimal(Util.null2s(otherParamArr[0].trim(), "0")); + BigDecimal allExtraAmountB = new BigDecimal(Util.null2s(otherParamArr[1].trim(), "0")); + BigDecimal allUsedAmountB = new BigDecimal(Util.null2s(otherParamArr[2].trim(), "0")); + BigDecimal alltiaoxiuamountB = new BigDecimal(Util.null2s(otherParamArr[3].trim(), "0")); + allRestAmount = allBaseAmountB.add(allExtraAmountB).add(alltiaoxiuamountB).subtract(allUsedAmountB).setScale(2, RoundingMode.HALF_UP).toPlainString(); + return allRestAmount; + } + + /** + * 获取明细列的转换显示 + * + * @param detaiShow + * @param language + * @return + */ + public String getDetailShow(String detaiShow, String language) { + return SystemEnv.getHtmlLabelName(17463, Util.getIntValue(language, 7)); + } + + /** + * 获取有效期的显示 + * + * @param expirationDate + * @param language + * @return + */ + public String getExpirationDateShow(String expirationDate, String language) { + String expirationDateShow = ""; + if ("2222-12-31".equals(expirationDate)) { + expirationDateShow = SystemEnv.getHtmlLabelName(10000846, Util.getIntValue(Util.getIntValue(language, 7))); + } else { + expirationDateShow = expirationDate; + } + return expirationDateShow; + } + + /** + * 获取员工假期余额明细操作日志中对象的显示名称 + * + * @param id + * @param params + * @return + */ + public String getTargetName4BalanceDetail(String id, String params) { + String targetName = ""; + try { + String[] paramArr = params.split("\\+"); + String resourceId = paramArr[0]; + String belongYear = paramArr[1]; + String belongMonth = paramArr[2]; + String languageId = paramArr[3]; + + //人力资源缓存类 + ResourceComInfo resourceComInfo = new ResourceComInfo(); + String lastName = Util.formatMultiLang(resourceComInfo.getResourcename(resourceId), languageId); + targetName = SystemEnv.getHtmlLabelName(512690, Util.getIntValue(languageId, 7)); + targetName = targetName.replace("${lastName}", lastName).replace("${belongYear}", belongYear).replace("${belongMonth}", belongMonth).replace("${ID}", id); + } catch (Exception e) { + e.printStackTrace(); + } + return targetName; + } + + /** + * 员工假期余额的右键日志对象名称 + * + * @param id + * @param otherParams + * @return + */ + public String getTargetName4Balance(String id, String otherParams) { + String targetName = ""; + try { + String[] otherParaArr = otherParams.split("\\+"); + String resourceId = otherParaArr[0]; + String leaveRulesId = otherParaArr[1]; + + ResourceComInfo resourceComInfo = new ResourceComInfo(); + KQLeaveRulesComInfo rulesComInfo = new KQLeaveRulesComInfo(); + String lastName = resourceComInfo.getResourcename(resourceId); + String ruleName = rulesComInfo.getLeaveName(leaveRulesId); + targetName = lastName + "-" + ruleName; + } catch (Exception e) { + e.printStackTrace(); + } + return targetName; + } + + /***************************************加班的相关方法***************************************/ + + /** + * 获取加班规则的具体的规则内容 + * + * @param ruleId 加班规则的ID + * @return + */ + public String getRuleContent(String ruleId, String languageId) { + if (ruleId.equals("")) { + return ""; + } + int language = Util.getIntValue(languageId, 7); + /*需要显示的内容*/ + String resultStr = ""; + /*日期类型:1-工作日、2-周末、3-节假日*/ + int dayType = 0; + /*是否允许加班:0-不允许、1-允许*/ + int overtimeEnable = 0; + /*加班方式:1-需审批,以审批单为准、2-需审批,以打卡为准,但是不能超过审批时长、3-无需审批,根据打卡时间计算加班时长*/ + int computingMode = 0; + List dayTypeList = Lists.newArrayList(); + String sql = "select * from kq_OvertimeRulesDetail where ruleId=" + ruleId + " order by id"; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql); + while (recordSet.next()) { + dayType = recordSet.getInt("dayType"); + overtimeEnable = recordSet.getInt("overtimeEnable"); + computingMode = recordSet.getInt("computingMode"); + + if (dayTypeList.contains(("" + dayType))) { + continue; + } else { + dayTypeList.add(("" + dayType)); + } + + if (dayType == 2) {//工作日 + resultStr += SystemEnv.getHtmlLabelName(28387, language) + ":"; + if (overtimeEnable == 0) { + resultStr += SystemEnv.getHtmlLabelName(389562, language);//不允许加班 + } else if (computingMode == 1) { + resultStr += SystemEnv.getHtmlLabelName(500382, language);//需审批,以加班流程为准 + } else if (computingMode == 2) { + resultStr += SystemEnv.getHtmlLabelName(500383, language);//需审批,以打卡为准,但是不能超过加班流程时长 + } else if (computingMode == 3) { + resultStr += SystemEnv.getHtmlLabelName(390837, language);//无需审批,根据打卡时间计算加班时长 + } else if (computingMode == 4) { + resultStr += SystemEnv.getHtmlLabelName(524827, language);//流程和打卡取交集 + } + } else if (dayType == 3) {//休息日 + resultStr += "
" + SystemEnv.getHtmlLabelName(458, language) + ":"; + if (overtimeEnable == 0) { + resultStr += SystemEnv.getHtmlLabelName(389562, language);//不允许加班 + } else if (computingMode == 1) { + resultStr += SystemEnv.getHtmlLabelName(500382, language);//需审批,以加班流程为准 + } else if (computingMode == 2) { + resultStr += SystemEnv.getHtmlLabelName(500383, language);//需审批,以打卡为准,但是不能超过加班流程时长 + } else if (computingMode == 3) { + resultStr += SystemEnv.getHtmlLabelName(390837, language);//无需审批,根据打卡时间计算加班时长 + } else if (computingMode == 4) { + resultStr += SystemEnv.getHtmlLabelName(524827, language);//流程和打卡取交集 + } + } else if (dayType == 1) {//节假日 + resultStr += "
" + SystemEnv.getHtmlLabelName(28386, language) + ":"; + if (overtimeEnable == 0) { + resultStr += SystemEnv.getHtmlLabelName(389562, language);//不允许加班 + } else if (computingMode == 1) { + resultStr += SystemEnv.getHtmlLabelName(500382, language);//需审批,以加班流程为准 + } else if (computingMode == 2) { + resultStr += SystemEnv.getHtmlLabelName(500383, language);//需审批,以打卡为准,但是不能超过加班流程时长 + } else if (computingMode == 3) { + resultStr += SystemEnv.getHtmlLabelName(390837, language);//无需审批,根据打卡时间计算加班时长 + } else if (computingMode == 4) { + resultStr += SystemEnv.getHtmlLabelName(524827, language);//流程和打卡取交集 + } + } + } + System.out.println("getRuleContent resultStr:::" + resultStr); + return resultStr; + } + + /** + * 获取加班规则的应用范围列的显示名称 + * + * @param groupIds + * @param languageId + * @return + */ + public String getGroupName(String groupIds, String languageId) { + String groupName = ""; + int language = Util.getIntValue(languageId, 7); + if (groupIds.equals("")) { + groupName = SystemEnv.getHtmlLabelName(165, language); + return groupName; + } + KQGroupComInfo kqGroupComInfo = new KQGroupComInfo(); + String[] groupIdArr = groupIds.split(","); + groupName = kqGroupComInfo.getGroupname(groupIdArr[0]); + if (groupIdArr.length > 1) { + groupName = SystemEnv.getHtmlLabelName(516131, language).replace("{groupname}", groupName).replace("{count}", "" + groupIdArr.length); + } + return groupName; + } + + /** + * 获取加班计算单位的日志的对象名 + * + * @param targetId + * @param otherParams + * @return + */ + public String getTargetName4OvertimeUnit(String targetId, String otherParams) { + String targetName = ""; + String languageId = otherParams.split("\\+")[0]; + targetName = SystemEnv.getHtmlLabelName(505608, Util.getIntValue(languageId, 7)); + return targetName; + } + + + /***************************************节假日设置的相关方法***************************************/ + + /** + * 根据changeType获取显示名 + * + * @param changeType + * @return + */ + public String getChangeTypeName(String changeType, String languageId) { + int language = Util.getIntValue(languageId, 7); + String changeTypeName = ""; + if (changeType.equals("1")) { + changeTypeName = SystemEnv.getHtmlLabelName(16478, language); + } else if (changeType.equals("2")) { + changeTypeName = SystemEnv.getHtmlLabelName(16751, language); + } else if (changeType.equals("3")) { + changeTypeName = SystemEnv.getHtmlLabelName(16752, language); + } + return changeTypeName; + } + + /** + * 获取对应工作日的显示名称 + * + * @param relatedDay 对应工作日:0-星期一、1-星期二、2-星期三、3-星期四、4-星期五、5-星期六、6-星期日 + * @return + */ + public String getRelatedDayName(String relatedDay, String languageId) { + String relatedDayName = ""; + int language = Util.getIntValue(languageId, 7); + switch (relatedDay) { + case "6": + relatedDayName = SystemEnv.getHtmlLabelName(398, language); + break; + case "0": + relatedDayName = SystemEnv.getHtmlLabelName(392, language); + break; + case "1": + relatedDayName = SystemEnv.getHtmlLabelName(393, language); + break; + case "2": + relatedDayName = SystemEnv.getHtmlLabelName(394, language); + break; + case "3": + relatedDayName = SystemEnv.getHtmlLabelName(395, language); + break; + case "4": + relatedDayName = SystemEnv.getHtmlLabelName(396, language); + break; + case "5": + relatedDayName = SystemEnv.getHtmlLabelName(397, language); + break; + default: + relatedDayName = ""; + break; + } + return relatedDayName; + } + + /** + * 获取节假日设置的日志的对象名 + * + * @param targetId + * @param otherParams + * @return + */ + public String getTargetName4HolidaySet(String targetId, String otherParams) { + String targetName = ""; + try { + String groupId = otherParams.split("\\+")[0]; + String holidayDate = otherParams.split("\\+")[1]; + String languageId = otherParams.split("\\+")[2]; + + KQGroupComInfo groupComInfo = new KQGroupComInfo(); + String groupName = Util.formatMultiLang(groupComInfo.getGroupname(groupId), languageId); + targetName = groupName + " " + holidayDate; + } catch (Exception e) { + e.printStackTrace(); + } + return targetName; + } + + /***************************************原始打卡记录的相关方法***************************************/ + + /** + * 获取考勤日期显示 + * + * @param belongDate + * @param languageId + * @return + */ + public String getBelongDateShow(String belongDate, String languageId) { + String belongDateShow = belongDate + " "; + int index = DateUtil.getWeek(belongDate); + if (index == 1) { + belongDateShow += getRelatedDayName("0", languageId); + } else if (index == 2) { + belongDateShow += getRelatedDayName("1", languageId); + } else if (index == 3) { + belongDateShow += getRelatedDayName("2", languageId); + } else if (index == 4) { + belongDateShow += getRelatedDayName("3", languageId); + } else if (index == 5) { + belongDateShow += getRelatedDayName("4", languageId); + } else if (index == 6) { + belongDateShow += getRelatedDayName("5", languageId); + } else if (index == 7) { + belongDateShow += getRelatedDayName("6", languageId); + } + return belongDateShow; + } + + /** + * 获取考勤时间显示 + * + * @param belongTime + * @param belongDate + * @return + */ + public String getBelongTimeShow(String belongTime, String belongDate, String languageId) { + String belongTimeShow = belongDate + " " + new KQTimesArrayComInfo().turn48to24Time(belongTime); + int language = Util.getIntValue(languageId, 7); + if (belongTime.equals("free")) { + belongTimeShow = belongDate + " " + SystemEnv.getHtmlLabelName(500375, language); + } + return belongTimeShow; + } + + /** + * 获取打卡时间显示 + * + * @param signDate + * @param signTime + * @return + */ + public String getSignDateShow(String signDate, String signTime) { + String tmpsignDate = signDate.replaceAll("-", "/"); + return tmpsignDate + " " + signTime; + } + + public String getSignDateShowNew(String signDate, String signTime) { + String tmpsignDate = signDate.replaceAll("-", "/"); + return tmpsignDate + " " + signTime; + } + + /** + * 获取原始打卡记录的数据来源列的显示名称 + * + * @param signFrom + * @return + */ + public String getSignFromShow(String signFrom, String languageId) { + String signFromShow = ""; + int language = Util.getIntValue(languageId, 7); + if (signFrom.equalsIgnoreCase("e9pc")) { + signFromShow = SystemEnv.getHtmlLabelName(503612, language); + } else if (signFrom.equalsIgnoreCase("e9mobile")) { + signFromShow = SystemEnv.getHtmlLabelName(503613, language); + } else if (signFrom.equalsIgnoreCase("e9e")) { + signFromShow = SystemEnv.getHtmlLabelName(503614, language); + } else if (signFrom.equalsIgnoreCase("e9ewx")) { + signFromShow = SystemEnv.getHtmlLabelName(503615, language); + } else if (signFrom.startsWith("card")) { + signFromShow = SystemEnv.getHtmlLabelName(503616, language); + } else if (signFrom.equalsIgnoreCase("e9_mobile_out")) { + signFromShow = SystemEnv.getHtmlLabelName(82634, language); + } else if (signFrom.equalsIgnoreCase("importExcel")) { + signFromShow = SystemEnv.getHtmlLabelName(503617, language); + } else if (signFrom.equalsIgnoreCase("EMSyn")) { + signFromShow = SystemEnv.getHtmlLabelName(503618, language); + } else if (signFrom.equalsIgnoreCase("EMSyn_out")) { + signFromShow = SystemEnv.getHtmlLabelName(517845, language); + } else if (signFrom.equalsIgnoreCase("OutDataSourceSyn")) { + signFromShow = SystemEnv.getHtmlLabelName(503619, language); + } else if (signFrom.equalsIgnoreCase("DingTalk")) { + signFromShow = SystemEnv.getHtmlLabelName(506318, language); + } else if (signFrom.equalsIgnoreCase("DingTalk_out")) { + signFromShow = SystemEnv.getHtmlLabelName(506319, language); + } else if (signFrom.equalsIgnoreCase("Wechat_out")) { + signFromShow = SystemEnv.getHtmlLabelName(506652, language); + } else if (signFrom.equalsIgnoreCase("Wechat")) { + signFromShow = SystemEnv.getHtmlLabelName(506653, language); + } else if (signFrom.equalsIgnoreCase("auto_card")) { + signFromShow = SystemEnv.getHtmlLabelName(521191, language); + } else if (signFrom.equalsIgnoreCase("null")) { + signFromShow = ""; + } else { + signFromShow = signFrom; + } + return signFromShow; + } + + /***************************************考勤报表权限共享的相关方法***************************************/ + + /** + * 获取考勤报表名称的显示 + * + * @param reportName + * @param languageId + * @return + */ + public String getReportNameShow(String reportName, String languageId) { + String reportNameShow = ""; + int language = Util.getIntValue(languageId, 7); + if (reportName.equals("0")) { + reportNameShow = SystemEnv.getHtmlLabelName(332, language); + } else if (reportName.equals("1")) { + reportNameShow = SystemEnv.getHtmlLabelName(390351, language); + } else if (reportName.equals("2")) { + reportNameShow = SystemEnv.getHtmlLabelName(390352, language); + } else if (reportName.equals("3")) { + reportNameShow = SystemEnv.getHtmlLabelName(390248, language); + } else if (reportName.equals("4")) { + reportNameShow = SystemEnv.getHtmlLabelName(389441, language); + } + return reportNameShow; + } + + /** + * 获取共享级别的显示 + * + * @param shareLevel 0-分部、1-部门、2-人员、3-岗位、4-所有人 + * @param languageId + * @return + */ + public String getShareLevelShow(String shareLevel, String languageId) { + String shareLevelShow = ""; + int language = Util.getIntValue(languageId, 7); + if (shareLevel.equals("0")) { + shareLevelShow = SystemEnv.getHtmlLabelName(33553, language); + } else if (shareLevel.equals("1")) { + shareLevelShow = SystemEnv.getHtmlLabelName(27511, language); + } else if (shareLevel.equals("2")) { + shareLevelShow = SystemEnv.getHtmlLabelName(179, language); + } else if (shareLevel.equals("3")) { + shareLevelShow = SystemEnv.getHtmlLabelName(6086, language); + } else if (shareLevel.equals("4")) { + shareLevelShow = SystemEnv.getHtmlLabelName(1340, language); + } + return shareLevelShow; + } + + /** + * 获取共享对象的显示 + * + * @param id + * @param languageId + * @return + */ + public String getReportShareShow(String id, String languageId) { + String showName = ""; + try { + int language = Util.getIntValue(languageId, 7); + String sql = "select * from kq_ReportShare where id=" + id; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql); + if (recordSet.next()) { + String shareLevel = recordSet.getString("shareLevel"); + String subcomId = Util.null2String(recordSet.getString("subcomId")); + String deptId = Util.null2String(recordSet.getString("deptId")); + String jobtitleId = Util.null2String(recordSet.getString("jobtitleId")); + String userId = Util.null2String(recordSet.getString("userId")); + + if (shareLevel.equals("0")) { + SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo(); + showName = subCompanyComInfo.getSubcompanynames(subcomId); + } else if (shareLevel.equals("1")) { + DepartmentComInfo departmentComInfo = new DepartmentComInfo(); + showName = departmentComInfo.getDepartmentNames(deptId); + } else if (shareLevel.equals("2")) { + ResourceComInfo resourceComInfo = new ResourceComInfo(); + List tempList = Util.TokenizerString(userId, ","); + for (int i = 0; i < tempList.size(); i++) { + showName += "," + resourceComInfo.getResourcename(tempList.get(i)); + } + showName = showName.startsWith(",") ? showName.substring(1) : showName; + } else if (shareLevel.equals("3")) { + JobTitlesComInfo jobTitlesComInfo = new JobTitlesComInfo(); + List tempList = Util.TokenizerString(jobtitleId, ","); + for (int i = 0; i < tempList.size(); i++) { + showName += "," + jobTitlesComInfo.getJobTitlesname(tempList.get(i)); + } + showName = showName.length() > 0 ? showName.substring(1) : showName; + } else if (shareLevel.equals("4")) { + showName = SystemEnv.getHtmlLabelName(1340, language); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + return showName; + } + + /** + * 获取考勤报表权限共享日志的对象名 + * + * @param targetId + * @param otherParams + * @return + */ + public String getTargetName4ReportShare(String targetId, String otherParams) { + String targetName = ""; + try { + String reportName = otherParams.split("\\+")[0]; + String resourceType = otherParams.split("\\+")[1]; + String resourceId = otherParams.split("\\+", 4)[2]; + String languageId = otherParams.split("\\+", 4)[3]; + + switch (reportName) { + case "1": + targetName += SystemEnv.getHtmlLabelName(16559, Util.getIntValue(languageId, 7)); + break; + case "2": + targetName += SystemEnv.getHtmlLabelName(82801, Util.getIntValue(languageId, 7)); + break; + case "3": + targetName += SystemEnv.getHtmlLabelName(390248, Util.getIntValue(languageId, 7)); + break; + case "4": + targetName += SystemEnv.getHtmlLabelName(389441, Util.getIntValue(languageId, 7)); + break; + } + + ResourceComInfo resourceComInfo = new ResourceComInfo(); + targetName += " " + Util.formatMultiLang(resourceComInfo.getLastnames(resourceId), languageId); + } catch (Exception e) { + e.printStackTrace(); + } + return targetName; + } + + /***************************************公出出差规则的相关方法***************************************/ + + /** + * 获取出差公出规则的日志的对象名 + * + * @param targetId + * @param otherParams + * @return + */ + public String getTargetName4TravelRules(String targetId, String otherParams) { + String targetName = ""; + String languageId = otherParams.split("\\+")[0]; + targetName = SystemEnv.getHtmlLabelName(390004, Util.getIntValue(languageId, 7)); + return targetName; + } + + /***************************************一键已用考勤的相关方法***************************************/ + + /** + * 获取目前新考勤的请假类型表的ID字段的下一个值 + * 考虑到历史数据迁移,过去的请假类型表和目前的请假类型表不是同一张,所以新考勤请假类型表kq_leaveRules的id(非自增)对应于旧的老考勤请假类型表HrmLeaveTypeColor的Id,并作为主键使用 + * + * @return + */ + public int getNextId() { + int nextId = 0; + int maxId = 0; + String maxColorIdSql = "select max(id) maxId from kq_leaveRules"; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(maxColorIdSql); + if (recordSet.next()) { + maxId = Util.getIntValue(recordSet.getString("maxId"), 1); + } + nextId = maxId <= 0 ? 1 : (maxId + 1); + return nextId; + } + + /***************************************正式系统会用到的相关方法***************************************/ + + /** + * 获取人员的年假计算开始日期 + * + * @param companyStartDate + * @param resourceId + * @return + */ + public String getCompanyStartDate(String companyStartDate, String resourceId) { + return companyStartDate; + } + + /** + * 获取考勤流程校验规则的 校验规则 + * + * @return + */ + public String get_rules(String rule_type_uuid, String otherparam) { + List otherparams = Util.splitString2List(otherparam, "+"); + if (otherparams.size() == 4 && rule_type_uuid.length() > 0) { + String ruleid = otherparams.get(0); + String rule_table = otherparams.get(1); + String key_fieldname = otherparams.get(2); + String fieldname = ""; + RecordSet rs = new RecordSet(); + if (key_fieldname.length() > 0) { + String sql = "select * from kq_att_checkrule_fields where rule_type_uuid=? and key_fieldname=? "; + rs.executeQuery(sql, rule_type_uuid, key_fieldname); + if (rs.next()) { + fieldname = rs.getString("fieldname"); + } else { + fieldname = key_fieldname; + } + } else { + return ""; + } + String lanid = otherparams.get(3); + String sql = "select * from " + rule_table + " where id = ? "; + rs.executeQuery(sql, ruleid); + if (rs.next()) { + String val = rs.getString(fieldname); + if ("check_rule".equalsIgnoreCase(key_fieldname)) { + if ("kq_att_frequency_rule".equalsIgnoreCase(rule_table)) { + //次数校验需要单独处理 + String val_count = rs.getString(fieldname + "_count"); + String frequencyContent = getFrequencyContent(val, Util.getIntValue(lanid)); + String content = frequencyContent + SystemEnv.getHtmlLabelName(516776, Util.getIntValue(Util.getIntValue(lanid))) + val_count + SystemEnv.getHtmlLabelName(18083, Util.getIntValue(Util.getIntValue(lanid))); + return content; + } else { + if ("1".equalsIgnoreCase(val)) { + return SystemEnv.getHtmlLabelName(516104, Util.getIntValue(Util.getIntValue(lanid))); + } else { + return SystemEnv.getHtmlLabelName(516103, Util.getIntValue(Util.getIntValue(lanid))); + } + } + } else if ("check_level".equalsIgnoreCase(key_fieldname)) { + if ("0".equalsIgnoreCase(val)) { + return SystemEnv.getHtmlLabelName(32137, Util.getIntValue(Util.getIntValue(lanid))); + } else if ("1".equalsIgnoreCase(val)) { + return SystemEnv.getHtmlLabelName(32138, Util.getIntValue(Util.getIntValue(lanid))); + } else if ("2".equalsIgnoreCase(val)) { + return SystemEnv.getHtmlLabelName(26009, Util.getIntValue(Util.getIntValue(lanid))); + } else { + return ""; + } + } else if ("check_message".equalsIgnoreCase(key_fieldname)) { + return val; + } else { + return ""; + } + } + } + return ""; + } + + public String getCheckRuleName(String labelids, String lanid) { + return SystemEnv.getHtmlLabelNames(labelids, Util.getIntValue(lanid, 7)); + } + + public String getFrequencyContent(String val, int lanid) { + if ("0".equalsIgnoreCase(val)) { + return SystemEnv.getHtmlLabelName(539, Util.getIntValue(lanid)); + } else if ("1".equalsIgnoreCase(val)) { + return SystemEnv.getHtmlLabelName(545, Util.getIntValue(lanid)); + } else if ("2".equalsIgnoreCase(val)) { + return SystemEnv.getHtmlLabelName(541, Util.getIntValue(lanid)); + } else if ("3".equalsIgnoreCase(val)) { + return SystemEnv.getHtmlLabelName(543, Util.getIntValue(lanid)); + } else if ("4".equalsIgnoreCase(val)) { + return SystemEnv.getHtmlLabelName(546, Util.getIntValue(lanid)); + } + return ""; + } + + /** + * 获取设备信息 + * + * @param deviceinfo + * @return + */ + public String getDeviceinfo(String deviceinfo) { + String info = ""; + try { + if (deviceinfo.length() > 0) { + JSONObject jsonObject = JSONObject.parseObject(deviceinfo); + if (jsonObject != null && !jsonObject.isEmpty()) { + String deviceId = Util.null2String(jsonObject.get("deviceId")); + if (deviceId.length() > 0) { + info = deviceId; + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + return info; + } + + /** + * 判断是否在地理范围内 + * + * @param isincom + * @param otherParam + * @return + */ + public String getIsincom(String isincom, String otherParam) { + String info = ""; + try { + if (isincom.length() > 0) { + int lan = Util.getIntValue(otherParam); + if ("1".equalsIgnoreCase(isincom)) { + info = SystemEnv.getHtmlLabelName(163, lan); + } else { + info = SystemEnv.getHtmlLabelName(161, lan); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + return info; + } + + public String getWorkFlowUrl4mobile(String requestid) { + WorkflowRequestComInfo workflowRequestComInfo = new WorkflowRequestComInfo(); + String flowName = workflowRequestComInfo.getRequestName(requestid); + if (StringUtil.isNotNull(flowName)) { + String url = weaver.general.GCONST.getContextPath() + "/spa/workflow/static4mobileform/index.html#/req?ismonitor=1&requestid=" + requestid; + String a_href = "" + flowName + " "; + return a_href; + } else { + return ""; + } + } + + public String getWorkFlowUrl(String requestid) { + WorkflowRequestComInfo workflowRequestComInfo = new WorkflowRequestComInfo(); + String flowName = workflowRequestComInfo.getRequestName(requestid); + if (StringUtil.isNotNull(flowName)) { + return "" + flowName + " "; + } else { + return ""; + } + } + + public String getLabelName(String id, String otherPara) { + String otherParaArr[] = otherPara.split("\\+", 5); + String labelId = otherParaArr[0]; + String LanId = otherParaArr[1]; + return SystemEnv.getHtmlLabelNames(labelId, LanId); + } +} diff --git a/src/com/engine/kq/util/UtilKQHS.java b/src/com/engine/kq/util/UtilKQHS.java new file mode 100644 index 0000000..c910e63 --- /dev/null +++ b/src/com/engine/kq/util/UtilKQHS.java @@ -0,0 +1,148 @@ +package com.engine.kq.util; + +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.general.Util; + +import java.math.BigDecimal; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; + +/** + * hansang考勤假期计算相关工具类 + * + * @author wangj + * @version 1.00版本 + * @Date 2023/9/12 + */ + +public class UtilKQHS { + /** + * 判断是否查询年份是育儿假最后一年(即第三年) + * @return + */ + public static boolean isLastYearChildcareLeave(String userid,String searchYear) { + boolean flag = false; + RecordSet rs = new RecordSet(); + rs.executeQuery("select csrq from uf_jt where gx = 2 and ry = ? ORDER BY csrq desc limit 1",userid); + String csrq = ""; + while (rs.next()){ + csrq = Util.null2String(rs.getString("csrq")); + } + if(!"".equals(csrq)){ + String year = Util.object2String(Util.getIntValue(csrq.substring(0,4))+3); + if(year.equals(searchYear)){ + flag = true; + } + } + return flag; + } + + + + + /** + * 获取人员的小孩满三周岁日期 + * @param userid + * @param searchDate + * @return + */ + public static String getLastDateChildcareLeave(String userid,String searchDate){ + RecordSet rs = new RecordSet(); + rs.executeQuery("select csrq from uf_jt where gx = 2 and ry = ? ORDER BY csrq desc limit 1",userid); + String date = ""; + while (rs.next()){ + String csrq = Util.null2String(rs.getString("csrq")); + if("".equals(csrq)){ + date = searchDate; + }else{ + try { + date = dealDate(csrq); + }catch (ParseException e) { + e.getMessage(); + } + } + } + + return date; + } + + + public static String dealDate(String date) throws ParseException { + SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); + Date dt=sdf.parse(date); + Calendar rightNow = Calendar.getInstance(); + rightNow.setTime(dt); + rightNow.add(Calendar.YEAR,+3);//日期减1年 +// rightNow.add(Calendar.MONTH,3);//日期加3个月 +// rightNow.add(Calendar.DAY_OF_YEAR ,10);//日期加10天 + Date dt1=rightNow.getTime(); + + Calendar calendar = Calendar.getInstance(); + calendar.setTime(dt1); + calendar.add(Calendar.DAY_OF_MONTH, -1); //当前时间减去一天,即一天前的时间 + + // 获取减一天后的日期 + int year = calendar.get(Calendar.YEAR); + int month = calendar.get(Calendar.MONTH) + 1; + int day = calendar.get(Calendar.DAY_OF_MONTH); + String months = ""; + String days = ""; + if(month < 10){ + months = "0"+month; + }else{ + months = month+""; + } + if(day < 10){ + days = "0"+day; + }else{ + days = day + ""; + } + return year+"-"+months+"-"+days; + } + + //比较时间大小 + public static boolean compareDate(String start, String end) { + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); + try { + Date date1 = simpleDateFormat.parse(start); + Date date2 = simpleDateFormat.parse(end); + if (date1.getTime() < date2.getTime()) { + return true; + } + } catch (ParseException e) { + throw new RuntimeException(e); + } + return false; + } + +// public static void main(String[] args) { +// System.out.println(handleAmount("7.60","7.89")); +// } + + public static String handleAmount(String restAmount,String baseAmount){ + + String[] arr = restAmount.split("\\."); + + String restPart0 = arr[0]; + String restPart1 = arr[1]; + System.out.println("restPart0:"+restPart0); + System.out.println("restPart1:"+restPart1); + double a = 0.00; + double base = Util.getDoubleValue(baseAmount); + + if(Util.getIntValue(restPart1) > 50){ + a = Util.getIntValue(restPart0) + 1.00; + if(a > base){ + a = Util.getIntValue(restPart0) + 0.5; + } + }else{ + a = Util.getIntValue(restPart0) + 0.00; + } + return Util.object2String(a); + } + + +} diff --git a/src/com/engine/kq/wfset/util/KQFlowUtil.java b/src/com/engine/kq/wfset/util/KQFlowUtil.java new file mode 100644 index 0000000..d51192b --- /dev/null +++ b/src/com/engine/kq/wfset/util/KQFlowUtil.java @@ -0,0 +1,471 @@ +package com.engine.kq.wfset.util; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.engine.kq.biz.KQExitRulesBiz; +import com.engine.kq.biz.KQFormatData; +import com.engine.kq.biz.KQLeaveRulesBiz; +import com.engine.kq.biz.KQOvertimeRulesBiz; +import com.engine.kq.biz.KQTravelRulesBiz; +import com.engine.kq.enums.DurationTypeEnum; +import com.engine.kq.enums.KqSplitFlowTypeEnum; +import com.engine.kq.log.KQLog; +import com.engine.kq.wfset.bean.SplitBean; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.locks.ReentrantLock; + +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.resource.ResourceComInfo; +import weaver.workflow.workflow.WorkflowRequestComInfo; + +public class KQFlowUtil { + private KQLog kqLog = new KQLog(); + + /** + * 把通用的bean部分在这里进行填充 + * @param splitBean + * @param rs1 + * @param requestId + * @param rci + * @param workflowId + * @param durationTypeEnum + * @param key + * @param result + * @param datetimeFormatter + * @param uuid + */ + public boolean fillSplitBean(SplitBean splitBean, RecordSet rs1, String requestId, + ResourceComInfo rci, String workflowId, DurationTypeEnum durationTypeEnum, String key, + Map result, DateTimeFormatter datetimeFormatter, String uuid){ + + boolean isFillRight = true; + String concort = "###" ; + int usedetail = Util.getIntValue(key.split(concort)[2], 0); + String tableDetailName= key.split(concort)[1] ; + String tableName= key.split(concort)[0] ; + String prefix = ""; + String id = "dataId"; + if(usedetail == 1){ + prefix = "detail_"; + id = "detailId"; + } + + boolean isLeaveBack = false; + if(durationTypeEnum == DurationTypeEnum.LEAVEBACK){ + isLeaveBack = true; + } + boolean isProcessChange = false; + boolean isProcessDrawBack = false; + if(durationTypeEnum == DurationTypeEnum.PROCESSCHANGE){ + isProcessChange = true; + String changetype = Util.null2s(rs1.getString("changetype"), ""); + if("1".equalsIgnoreCase(changetype)){ + //如果是撤销的话,没有开始日期时间和结束日期时间 + isProcessDrawBack = true; + } + } + + String resourceId = ""; + //查询到的requestid + String requestId_rs = ""; + + String idVal = Util.null2s(rs1.getString(id), "0"); + String fromDate = Util.null2s(rs1.getString(prefix+"fromDate"), ""); + String toDate = Util.null2s(rs1.getString(prefix+"toDate"), ""); + String fromTime = Util.null2s(rs1.getString(prefix+"fromTime"), ""); + String toTime = Util.null2s(rs1.getString(prefix+"toTime"), ""); + String durationDB = Util.null2s(rs1.getString(prefix+"duration"), ""); + if(isLeaveBack || isProcessChange){ + resourceId = Util.null2s(rs1.getString("resourceId"), ""); + }else{ + resourceId = Util.null2s(rs1.getString(prefix+"resourceId"), ""); + } + if(Util.getIntValue(requestId,0) <= 0){ + requestId_rs = Util.null2s(rs1.getString("requestId"), "0"); + } + + boolean isVal = checkActionValidate(result, fromDate, toDate, fromTime, toTime, datetimeFormatter); + if(isProcessDrawBack){ + result.clear(); + result.put("isProcessDrawBack", "1"); + isVal = true; + } + if(!isVal){ + isFillRight = false; + return isFillRight; + } + if(isLeaveBack){ + LocalDateTime localFromDateTime = LocalDateTime.parse(fromDate+" "+fromTime,datetimeFormatter); + LocalDateTime localToDateTime = LocalDateTime.parse(toDate+" "+toTime,datetimeFormatter); + + isFillRight = KQFlowLeaveBackUtil.leaveBackCheck(rs1 ,datetimeFormatter,prefix,localFromDateTime,localToDateTime,result); + if(!isFillRight){ + return isFillRight; + } + } + if(isProcessChange){ + isFillRight = KQFlowProcessChangeUtil.processChangeCheck(rs1 ,requestId_rs,result); + if(!isFillRight){ + return isFillRight; + } + } + + if(usedetail == 1){ + splitBean.setDataId("0"); + splitBean.setDetailId(idVal); + splitBean.setTablenamedb(tableDetailName); + }else{ + splitBean.setDataId(idVal); + splitBean.setDetailId("0"); + splitBean.setTablenamedb(tableName); + } + splitBean.setFromdatedb(fromDate); + splitBean.setFromtimedb(fromTime); + splitBean.setTodatedb(toDate); + splitBean.setTotimedb(toTime); + + if(requestId_rs.length() > 0){ + WorkflowRequestComInfo workflowRequestComInfo = new WorkflowRequestComInfo(); + splitBean.setRequestId(requestId_rs); + splitBean.setWorkflowId(workflowRequestComInfo.getWorkflowId(requestId_rs)); + }else{ + splitBean.setRequestId(requestId); + splitBean.setWorkflowId(workflowId); + } + splitBean.setUsedetail(""+usedetail); + splitBean.setResourceId(resourceId); + splitBean.setSubcompanyid(Util.null2s(rci.getSubCompanyID(resourceId),"0")); + splitBean.setDepartmentid(Util.null2s(rci.getDepartmentID(resourceId),"0")); + splitBean.setJobtitle(Util.null2s(rci.getJobTitle(resourceId),"0")); + splitBean.setFromDate(fromDate); + splitBean.setFromTime(fromTime); + splitBean.setToDate(toDate); + splitBean.setToTime(toTime); + splitBean.setDurationDB(durationDB); + //默认记录的状态都为0 + splitBean.setStatus("0"); + splitBean.setDurationTypeEnum(durationTypeEnum); + + switch (durationTypeEnum){ + case LEAVE: + KQFlowLeaveUtil.bean4Leave(prefix,rs1,splitBean); + break; + case EVECTION: + KQFlowEvectionUtil.bean4Evection(prefix,rs1,splitBean); + break; + case OUT: + KQFlowOutUtil.bean4Out(splitBean); + break; + case OVERTIME: + KQFlowOvertimeUtil.bean4Overtime(prefix,rs1,splitBean); + break; + case LEAVEBACK: + KQFlowLeaveBackUtil.bean4LeaveBack(prefix,rs1,splitBean); + break; + case OTHER: + bean4Other(prefix,rs1,splitBean); + break; + case PROCESSCHANGE: + KQFlowProcessChangeUtil.bean4ProcessChange(prefix,rs1,splitBean); + break; + default: + break; + } + String computingMode = splitBean.getComputingMode(); + String newLeaveType = splitBean.getNewLeaveType(); + if("2".equalsIgnoreCase(computingMode)){ + if(durationTypeEnum == DurationTypeEnum.PROCESSCHANGE){ + double oneDayHour = getOneDayHour(splitBean.getDurationTypeEnum(),newLeaveType); + splitBean.setOneDayHour(oneDayHour); + }else{ + double oneDayHour = getOneDayHour(durationTypeEnum,newLeaveType); + splitBean.setOneDayHour(oneDayHour); + } + } + return isFillRight; + + } + + private void bean4Other(String prefix, RecordSet rs1, SplitBean splitBean) { + String minimumUnit = "1"; + String computingMode = "1"; + splitBean.setDurationrule(minimumUnit); + splitBean.setComputingMode(computingMode); + } + + + /** + * 获取按照自然日计算的时候,按天/半天计算的时候一天对应的小时数 + * @param durationTypeEnum + * @param newLeaveType + * @return + */ + public static double getOneDayHour(DurationTypeEnum durationTypeEnum,String newLeaveType){ + double oneDayHour = 0.0; + //TODO KQLeaveRulesBiz.getHoursToDay如果单位是小时的时候取不到日折算时长 + switch (durationTypeEnum){ + case LEAVE: + oneDayHour = Util.getDoubleValue(KQLeaveRulesBiz.getHoursToDay(newLeaveType), 0.0); + break; + case EVECTION: + oneDayHour = Util.getDoubleValue(KQTravelRulesBiz.getHoursToDay(), 0.0); + break; + case OUT: + oneDayHour = Util.getDoubleValue(KQExitRulesBiz.getHoursToDay(), 0.0); + break; + case OVERTIME: + oneDayHour = KQOvertimeRulesBiz.getHoursToDay(); + break; + case LEAVEBACK: + oneDayHour = Util.getDoubleValue(KQLeaveRulesBiz.getHoursToDay(newLeaveType), 0.0); + break; + default: + } + return oneDayHour; + } + + public boolean checkActionValidate(Map result,String fromDate,String toDate,String fromTime,String toTime, DateTimeFormatter datetimeFormatter){ + + boolean isVal = true; + + if(Util.null2String(fromDate,"").length() == 0 || + Util.null2String(toDate,"").length() == 0 || + Util.null2String(fromTime,"").length() == 0 || + Util.null2String(toTime,"").length() == 0){ + result.put("status", "-1"); + result.put("message", ""+weaver.systeminfo.SystemEnv.getHtmlLabelName(10005411,weaver.general.ThreadVarLanguage.getLang())+""); + isVal = false; + return isVal; + } + if((fromDate+" "+fromTime).length() != 16 || (toDate+" "+toTime).length() != 16){ + result.put("status", "-1"); + result.put("message", ""+weaver.systeminfo.SystemEnv.getHtmlLabelName(10005412,weaver.general.ThreadVarLanguage.getLang())+""+(fromDate+" "+fromTime)+":"+(toDate+" "+toTime)); + isVal = false; + return isVal; + } + LocalDate localFromDate = LocalDate.parse(fromDate); + LocalDate localToDate = LocalDate.parse(toDate); + LocalDateTime localFromDateTime = LocalDateTime.parse(fromDate+" "+fromTime,datetimeFormatter); + LocalDateTime localToDateTime = LocalDateTime.parse(toDate+" "+toTime,datetimeFormatter); + + if(localFromDateTime.isAfter(localToDateTime)){ + result.put("status", "-1"); + result.put("message", ""+weaver.systeminfo.SystemEnv.getHtmlLabelName(511480,weaver.general.ThreadVarLanguage.getLang())+""); + isVal = false; + return isVal; + } + + if (localFromDate.isAfter(localToDate)) { + result.put("status", "-1"); + result.put("message", ""+weaver.systeminfo.SystemEnv.getHtmlLabelName(10005413,weaver.general.ThreadVarLanguage.getLang())+""); + isVal = false; + return isVal; + } + return isVal; + } + + + /** + * 插入数据到中间表 + * @param splitBeans + * @param flowTypeEnum + * @param rci + * @param result + * @param isForce + * @param requestId + * @param workflowId + * @param isUpgrade 是否是升级,升级的话不需要处理假期余额数据 + * @throws Exception + */ + public void handleSplitFLowActionData( + List splitBeans, KqSplitFlowTypeEnum flowTypeEnum, + ResourceComInfo rci, Map result, boolean isForce, int requestId, + int workflowId,boolean isUpgrade) throws Exception{ + + RecordSet rs = new RecordSet(); + RecordSet rs1 = new RecordSet(); + Map custome_map = Maps.newHashMap(); + List custome_field = Lists.newArrayList(); + if(flowTypeEnum == KqSplitFlowTypeEnum.OVERTIME){ + custome_field.add("overtime_type"); + } + kqLog.info("splitBeans="+(null!=splitBeans?JSON.toJSON(null!=splitBeans):"is null")); + + String batchSql = "insert into "+flowTypeEnum.getTablename()+" (" + + "requestid,workflowid,dataid,detailid,resourceid,fromdate,fromtime," + + "todate,totime,newleavetype,duration,usedetail,durationrule,tablenamedb,fromdatedb," + + "fromtimedb,todatedb,totimedb,durationdb,status,belongDate,D_Mins,serialid," + + "changeType,subcompanyid,departmentid,jobtitle,companion,iscompanion"+getCustomField(custome_field,"field",null, + custome_map)+")"+ + " values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?"+getCustomField(custome_field,"param",null, + custome_map)+") "; + List params = new ArrayList(); + + List formateList = new ArrayList<>(); + for(SplitBean bean : splitBeans){ + List beanParams = new ArrayList(); + beanParams.add(bean.getRequestId()); + beanParams.add(bean.getWorkflowId()); + beanParams.add(bean.getDataId()); + beanParams.add(bean.getDetailId()); + beanParams.add(bean.getResourceId()); + beanParams.add(bean.getFromDate()); + beanParams.add(bean.getFromTime()); + beanParams.add(bean.getToDate()); + beanParams.add(bean.getToTime()); + beanParams.add(bean.getNewLeaveType()); + beanParams.add(Util.null2s(bean.getDuration(),"0")); + beanParams.add(bean.getUsedetail()); + beanParams.add(bean.getDurationrule()); + beanParams.add(bean.getTablenamedb()); + beanParams.add(bean.getFromdatedb()); + beanParams.add(bean.getFromtimedb()); + beanParams.add(bean.getTodatedb()); + beanParams.add(bean.getTotimedb()); + beanParams.add(bean.getDurationDB()); + beanParams.add(bean.getStatus()); + beanParams.add(bean.getBelongDate()); + beanParams.add(bean.getD_Mins()); + beanParams.add(bean.getSerialid()); + beanParams.add(bean.getChangeType()); + beanParams.add(bean.getSubcompanyid()); + beanParams.add(bean.getDepartmentid()); + beanParams.add(bean.getJobtitle()); + beanParams.add(bean.getCompanion()); + beanParams.add(bean.getIscompanion()); + if(!custome_field.isEmpty()){ + if(flowTypeEnum == KqSplitFlowTypeEnum.OVERTIME){ + custome_map.put("overtime_type", bean.getOvertime_type()); + } + getCustomField(custome_field, "value",beanParams,custome_map); + } + + String format = bean.getResourceId()+"_"+bean.getBelongDate(); + formateList.add(format); + + params.add(beanParams); + + if(flowTypeEnum == KqSplitFlowTypeEnum.EVECTION && false){ + //qc898997 已经改成根据每个人的班次来计算了,这里就屏蔽了 + KQFlowEvectionUtil kqFlowEvectionUtil = new KQFlowEvectionUtil(); + String companion = Util.null2s(bean.getCompanion(), ""); + if(companion.length() > 0){ + kqFlowEvectionUtil.splitEvectionCompanion(companion,bean,params,rci,formateList); + } + } + } + kqLog.info("params="+ JSONObject.toJSONString(params)); + if(!params.isEmpty()){ + ReentrantLock lock = new ReentrantLock(); + + //先根据requestid删除中间表里的数据,再做啥插入操作 + try { + lock.lock(); + String delSql = "delete from "+flowTypeEnum.getTablename()+" where requestid = "+requestId; + boolean isok1 = rs.executeUpdate(delSql); + kqLog.info("isok1="+ isok1); + + for(int i = 0 ; i < params.size() ; i++){ + List beanParams = params.get(i); + boolean isOk = rs1.executeUpdate(batchSql, beanParams); + kqLog.info("isOk="+ isOk); + if(!isOk){ + delSql = "delete from "+flowTypeEnum.getTablename()+" where requestid = "+requestId; + rs.executeUpdate(delSql); + result.put("status", "-1"); + result.put("message", ""+weaver.systeminfo.SystemEnv.getHtmlLabelName(10005408,weaver.general.ThreadVarLanguage.getLang())+":"+flowTypeEnum.getTablename()+""+weaver.systeminfo.SystemEnv.getHtmlLabelName(10005414,weaver.general.ThreadVarLanguage.getLang())+""); + kqLog.info("handleSplitFLowActionData:"+flowTypeEnum.getTablename()+"拆分保存失败:"+params); + return ; + } + } + } finally { + lock.unlock(); + } + kqLog.info("handleSplitFLowActionData:formateList:"+formateList+":flowTypeEnum:"+flowTypeEnum); + for(String format: formateList){ + kqLog.info("handleSplitFLowActionData:format:"+ JSON.toJSONString(format)+":flowTypeEnum:"+flowTypeEnum); + String[] formats = format.split("_"); + if(!isUpgrade){ + //考勤设置升级的话 流程数据就不需要格式化考勤了 + new KQFormatData().formatKqDate(formats[0],formats[1]); + } + } + if(!isUpgrade){ + if(isForce){ + if(flowTypeEnum == KqSplitFlowTypeEnum.LEAVE){ + //先在这里执行扣减动作 + SplitActionUtil.handleLeaveAction(splitBeans,""+requestId); + //然后再把扣减的了数据更新下KQ_ATT_VACATION表 + String updateFreezeSql = "update KQ_ATT_VACATION set status=0 where requestId=? and workflowId = ? "; + boolean isUpdate = rs.executeUpdate(updateFreezeSql,requestId,""+workflowId); + if(!isUpdate){ + result.put("status", "-1"); + result.put("message", (""+weaver.systeminfo.SystemEnv.getHtmlLabelName(82823,weaver.general.ThreadVarLanguage.getLang())+"action"+weaver.systeminfo.SystemEnv.getHtmlLabelName(10005361,weaver.general.ThreadVarLanguage.getLang())+""+updateFreezeSql+"(0,"+requestId+","+workflowId+")")); + kqLog.info("扣减action保存失败:"+updateFreezeSql+"(0,"+requestId+","+workflowId+")"); + return ; + } + }else if(flowTypeEnum == KqSplitFlowTypeEnum.OVERTIME){ + // 强制归档,加班数据第一第二种规则都需要处理 + SplitActionUtil.handleOverTimeAction(splitBeans, ""+requestId,true, ""); + } + }else{ + if(flowTypeEnum == KqSplitFlowTypeEnum.OVERTIME){ + //正常归档的时候 单独针对加班规则的第一 第二种模式 生成加班数据 + SplitActionUtil.handleOverTimeActionMode2(splitBeans, ""+requestId); + } + } + }else{ + if(flowTypeEnum == KqSplitFlowTypeEnum.OVERTIME){ + if(!splitBeans.isEmpty()){ + for (SplitBean splitBean : splitBeans) { + String sql = "delete from kq_flow_overtime where requestid=? "; + rs.executeUpdate(sql, splitBean.getRequestId()); + } + } + SplitActionUtil.handleOverTimeActionMode2(splitBeans, ""+requestId); + } + } + }else{ + rs1.writeLog(flowTypeEnum.getTablename()+"生成的params是空:"); + return ; + } + } + + /** + * 考勤流程中间表针对某个流程扩展字段 + * @param custome_field + * @param key + * @param beanParams + * @param custome_map + * @return + */ + public String getCustomField(List custome_field, String key, List beanParams, + Map custome_map) { + String fieldValue = ""; + if(!custome_field.isEmpty()){ + for(int i = 0 ; i < custome_field.size() ; i++){ + String tmp_value = Util.null2String(custome_field.get(i)); + if(tmp_value.length() > 0){ + if("field".equalsIgnoreCase(key)){ + fieldValue += ","+tmp_value; + }else if("param".equalsIgnoreCase(key)){ + fieldValue += ",?"; + }else if("value".equalsIgnoreCase(key)){ + String value = custome_map.get(tmp_value); + beanParams.add(value); + } + } + } + } + return fieldValue; + } + +} diff --git a/src/com/engine/leshanvc/cmd/EntryWorkflowSaveEventCmd.java b/src/com/engine/leshanvc/cmd/EntryWorkflowSaveEventCmd.java new file mode 100644 index 0000000..5c5c9fc --- /dev/null +++ b/src/com/engine/leshanvc/cmd/EntryWorkflowSaveEventCmd.java @@ -0,0 +1,42 @@ +package com.engine.leshanvc.cmd; + +import com.engine.common.biz.AbstractCommonCommand; +import com.engine.common.entity.BizLogContext; +import com.engine.core.interceptor.CommandContext; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.User; + +import java.util.HashMap; +import java.util.Map; + +/** + * @Author weaver_cl + * @Description: + * @Date 2023/2/21 + * @Version V1.0 + **/ +public class EntryWorkflowSaveEventCmd extends AbstractCommonCommand> { + + public EntryWorkflowSaveEventCmd(Map params, User user) { + this.user = user; + this.params = params; + } + + @Override + public BizLogContext getLogContext() { + return null; + } + + @Override + public Map execute(CommandContext commandContext) { + Map apidatas = new HashMap<>(16); + RecordSet rs = new RecordSet(); + String tableName = Util.null2String(params.get("tableName")); + String status = Util.null2String(params.get("status")); + String billId = Util.null2String(params.get("billId")); + rs.executeUpdate("update "+tableName+" set rzzt = ? where id = ?",status,billId); + apidatas.put("msg","success"); + return apidatas; + } +} diff --git a/src/com/engine/leshanvc/cmd/KqWorkflowRangeLimitCmd.java b/src/com/engine/leshanvc/cmd/KqWorkflowRangeLimitCmd.java new file mode 100644 index 0000000..d2115ca --- /dev/null +++ b/src/com/engine/leshanvc/cmd/KqWorkflowRangeLimitCmd.java @@ -0,0 +1,60 @@ +package com.engine.leshanvc.cmd; + +import com.engine.common.biz.AbstractCommonCommand; +import com.engine.common.entity.BizLogContext; +import com.engine.core.interceptor.CommandContext; +import com.engine.kq.biz.chain.shiftinfo.ShiftInfoBean; +import com.engine.kq.util.KQDurationCalculatorUtil; +import weaver.hrm.User; +import weaver.wechat.util.Utils; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +/** + * @Author weaver_cl + * @Description: + * @Date 2023/3/3 + * @Version V1.0 + **/ +public class KqWorkflowRangeLimitCmd extends AbstractCommonCommand> { + + + public KqWorkflowRangeLimitCmd(Map params, User user) { + this.user = user; + this.params = params; + } + + @Override + public BizLogContext getLogContext() { + return null; + } + + @Override + public Map execute(CommandContext commandContext) { + Map data = new HashMap<>(16); + boolean result = false; + String resourceId = Utils.null2String(params.get("resourceId")); + String fromDate = Utils.null2String(params.get("fromDate")); + String fromTime = Utils.null2String(params.get("fromTime")); + String toDate = Utils.null2String(params.get("toDate")); + String toTime = Utils.null2String(params.get("toTime")); + + User user1 = new User(); + user1.setUid(Integer.valueOf(resourceId)); + ShiftInfoBean shiftInfoBean = KQDurationCalculatorUtil.getWorkTime(user1, fromDate, false, false); + ShiftInfoBean shiftInfoBean1 = KQDurationCalculatorUtil.getWorkTime(user1, toDate, false, false); + if (Objects.nonNull(shiftInfoBean) && Objects.nonNull(shiftInfoBean1)) { + List workAcrossTime = shiftInfoBean.getWorkAcrossTime(); + List workAcrossTime1 = shiftInfoBean1.getWorkAcrossTime(); + if (fromTime.compareTo(workAcrossTime.get(0)[0]) >= 0 && fromTime.compareTo(workAcrossTime.get(0)[1]) < 0 + && toTime.compareTo(workAcrossTime1.get(0)[0]) > 0 && toTime.compareTo(workAcrossTime1.get(0)[1]) <= 0) { + result = true; + } + } + data.put("result",result); + return data; + } +} diff --git a/src/com/engine/leshanvc/cmd/WorkflowCheckCmd.java b/src/com/engine/leshanvc/cmd/WorkflowCheckCmd.java new file mode 100644 index 0000000..414b22e --- /dev/null +++ b/src/com/engine/leshanvc/cmd/WorkflowCheckCmd.java @@ -0,0 +1,56 @@ +package com.engine.leshanvc.cmd; + +import com.engine.common.biz.AbstractCommonCommand; +import com.engine.common.entity.BizLogContext; +import com.engine.core.interceptor.CommandContext; +import lombok.SneakyThrows; +import weaver.conn.RecordSet; +import weaver.hrm.User; +import weaver.hrm.resource.ResourceComInfo; +import weaver.wechat.util.Utils; + +import java.util.HashMap; +import java.util.Map; + +/** + * @Author weaver_cl + * @Description: + * @Date 2023/3/8 + * @Version V1.0 + **/ +public class WorkflowCheckCmd extends AbstractCommonCommand> { + + public WorkflowCheckCmd(Map params, User user) { + this.user = user; + this.params = params; + } + + @Override + public BizLogContext getLogContext() { + return null; + } + + @SneakyThrows + @Override + public Map execute(CommandContext commandContext) { + Map data = new HashMap<>(16); + String workflowId = Utils.null2String(params.get("workflowId")); + String resourceId = Utils.null2String(params.get("resourceId")); + String requestId = Utils.null2String(params.get("requestid")); + + RecordSet rs = new RecordSet(); + ResourceComInfo resourceComInfo = new ResourceComInfo(); + rs.executeQuery("select requestname,creater from workflow_requestbase where workflowid = ? and creater = ? " + + " and requestid != ? and currentnodetype not in (0,3)",workflowId,resourceId,requestId); + if (rs.next()) { + String requestName = Utils.null2String(rs.getString("requestname")); + String creater = Utils.null2String(rs.getString("creater")); + String lastname = resourceComInfo.getLastname(creater); + data.put("result",true); + data.put("requestName",requestName); + data.put("lastname",lastname); + } + + return data; + } +} diff --git a/src/com/engine/leshanvc/enums/MessageContentEnum.java b/src/com/engine/leshanvc/enums/MessageContentEnum.java new file mode 100644 index 0000000..983b283 --- /dev/null +++ b/src/com/engine/leshanvc/enums/MessageContentEnum.java @@ -0,0 +1,42 @@ +package com.engine.leshanvc.enums; + +/** + * @Author weaver_cl + * @Description: + * @Date 2023/2/13 + * @Version V1.0 + **/ +public enum MessageContentEnum { + + ONE(3,3,11), + TWO(11,11,36), + THREE(36,36,60), + FOUR(60,60,80), + FIVE(80,80,12) + ; + + private int value; + + private int min; + + private int max; + + + MessageContentEnum(int value, int min, int max) { + this.value = value; + this.min = min; + this.max = max; + } + + public int getValue() { + return value; + } + + public int getMin() { + return min; + } + + public int getMax() { + return max; + } +} diff --git a/src/com/engine/leshanvc/exception/CustomizeRunTimeException.java b/src/com/engine/leshanvc/exception/CustomizeRunTimeException.java new file mode 100644 index 0000000..cee8ef1 --- /dev/null +++ b/src/com/engine/leshanvc/exception/CustomizeRunTimeException.java @@ -0,0 +1,22 @@ +package com.engine.leshanvc.exception; + +/** + * @Author weaver_cl + * @Description: + * @Date 2023/2/21 + * @Version V1.0 + **/ +public class CustomizeRunTimeException extends RuntimeException{ + + public CustomizeRunTimeException(String message) { + super(message); + } + + public CustomizeRunTimeException(Throwable cause) { + super(cause); + } + + public CustomizeRunTimeException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/com/engine/leshanvc/service/EntryCommitFormModeService.java b/src/com/engine/leshanvc/service/EntryCommitFormModeService.java new file mode 100644 index 0000000..923fd55 --- /dev/null +++ b/src/com/engine/leshanvc/service/EntryCommitFormModeService.java @@ -0,0 +1,21 @@ +package com.engine.leshanvc.service; + +import java.util.Map; + +/** + * @Author ml + * @Date 2023/3/1 11:13 + * @Description This is description of class + * @Since version-1.0 + */ +public interface EntryCommitFormModeService { + + /** + * @Author ml + * @Date 2023/3/1 11:14 + * @Description 入职提交 + * @Param [params] + * @Return java.util.Map + */ + Map entryCommit(Map params); +} diff --git a/src/com/engine/leshanvc/service/EntryWorkflowSaveEventService.java b/src/com/engine/leshanvc/service/EntryWorkflowSaveEventService.java new file mode 100644 index 0000000..92b56ce --- /dev/null +++ b/src/com/engine/leshanvc/service/EntryWorkflowSaveEventService.java @@ -0,0 +1,19 @@ +package com.engine.leshanvc.service; + +import java.util.Map; + +/** + * @Author weaver_cl + * @Description: + * @Date 2023/2/21 + * @Version V1.0 + **/ +public interface EntryWorkflowSaveEventService { + + /** + * 入职流程保存修改建模(uf_rzgl)人员状态信息 + * @param params + * @return + */ + Map changeStatus(Map params); +} diff --git a/src/com/engine/leshanvc/service/KqWorkflowRangeLimitService.java b/src/com/engine/leshanvc/service/KqWorkflowRangeLimitService.java new file mode 100644 index 0000000..c65daaf --- /dev/null +++ b/src/com/engine/leshanvc/service/KqWorkflowRangeLimitService.java @@ -0,0 +1,19 @@ +package com.engine.leshanvc.service; + +import java.util.Map; + +/** + * @Author weaver_cl + * @Description: + * @Date 2023/3/3 + * @Version V1.0 + **/ +public interface KqWorkflowRangeLimitService { + + /** + * 考勤流程 控制选择范围在排版日期内 + * @param params + * @return + */ + Map rangeLimit(Map params); +} diff --git a/src/com/engine/leshanvc/service/LeaverWorkflowService.java b/src/com/engine/leshanvc/service/LeaverWorkflowService.java new file mode 100644 index 0000000..f8968d8 --- /dev/null +++ b/src/com/engine/leshanvc/service/LeaverWorkflowService.java @@ -0,0 +1,19 @@ +package com.engine.leshanvc.service; + +import java.util.Map; + +/** + * @author:dxfeng + * @createTime: 2023/04/19 + * @version: 1.0 + */ +public interface LeaverWorkflowService { + + /** + * 获取根据假期类型、开始日期,获取假期结束日期 + * + * @param params + * @return + */ + Map getEndDate(Map params); +} diff --git a/src/com/engine/leshanvc/service/LzWorkflowManageService.java b/src/com/engine/leshanvc/service/LzWorkflowManageService.java new file mode 100644 index 0000000..9a6787b --- /dev/null +++ b/src/com/engine/leshanvc/service/LzWorkflowManageService.java @@ -0,0 +1,13 @@ +package com.engine.leshanvc.service; + +import java.util.Map; + +/** + * @Author ml + * @Date 2023/3/16 9:22 + * @Since version-1.0 + */ +public interface LzWorkflowManageService { + + Map getHrmInfoByLinSup(Map params); +} diff --git a/src/com/engine/leshanvc/service/ResourceCardService.java b/src/com/engine/leshanvc/service/ResourceCardService.java new file mode 100644 index 0000000..5be6450 --- /dev/null +++ b/src/com/engine/leshanvc/service/ResourceCardService.java @@ -0,0 +1,17 @@ +package com.engine.leshanvc.service; + +import java.util.Map; + +/** + * @author:dxfeng + * @createTime: 2023/04/20 + * @version: 1.0 + */ +public interface ResourceCardService { + /** + * 后台补充人员卡片相关信息 + * + * @param params + */ + void editResourceCard(Map params); +} diff --git a/src/com/engine/leshanvc/service/SyncXcDataService.java b/src/com/engine/leshanvc/service/SyncXcDataService.java new file mode 100644 index 0000000..f459a39 --- /dev/null +++ b/src/com/engine/leshanvc/service/SyncXcDataService.java @@ -0,0 +1,39 @@ +package com.engine.leshanvc.service; + +import java.util.Map; + +/** + * @Author ml + * @Date 2023/3/29 11:22 + * @Description 线内分组管理页 + * @Since version-1.0 + */ +public interface SyncXcDataService { + + /** + * @Author ml + * @Date 2023/3/29 11:22 + * @Description 线长数据同步 + * @Param [] + * @Return java.util.Map + */ + Map syncXcData(Map params); + + /** + * @Author ml + * @Date 2023/4/4 17:18 + * @Description 非办公上岗数据花名册 + * @Param [params] + * @Return java.util.Map + */ + Map nonOfficeUpload(Map params); + + /** + * @Author ml + * @Date 2023/4/6 17:31 + * @Description 身份证读取 + * @Param [params] + * @Return java.lang.Long + */ + Map saveIDCard(Map params); +} diff --git a/src/com/engine/leshanvc/service/WorkflowCheckService.java b/src/com/engine/leshanvc/service/WorkflowCheckService.java new file mode 100644 index 0000000..b48ba35 --- /dev/null +++ b/src/com/engine/leshanvc/service/WorkflowCheckService.java @@ -0,0 +1,19 @@ +package com.engine.leshanvc.service; + +import java.util.Map; + +/** + * @Author weaver_cl + * @Description: + * @Date 2023/3/8 + * @Version V1.0 + **/ +public interface WorkflowCheckService { + + /** + * 流程保存提交时判断是否有审批中流程 + * @param params + * @return + */ + Map workflowController(Map params); +} diff --git a/src/com/engine/leshanvc/service/impl/EntryCommitFormModeServiceImpl.java b/src/com/engine/leshanvc/service/impl/EntryCommitFormModeServiceImpl.java new file mode 100644 index 0000000..20551c5 --- /dev/null +++ b/src/com/engine/leshanvc/service/impl/EntryCommitFormModeServiceImpl.java @@ -0,0 +1,247 @@ +package com.engine.leshanvc.service.impl; + +import com.engine.core.impl.Service; +import com.engine.leshanvc.service.EntryCommitFormModeService; +import org.apache.commons.lang3.StringUtils; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.PasswordUtil; +import weaver.general.Util; +import weaver.hrm.HrmUserVarify; +import weaver.interfaces.leshanvc.workflow.entity.FieldMapEntity; +import weaver.interfaces.leshanvc.workflow.util.ResourceSyncUtil; +import weaver.soa.workflow.request.Property; +import weaver.systeminfo.SystemEnv; + +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.stream.Collectors; + +/** + * @Author ml + * @Date 2023/3/3 17:46 + * @Description This is description of class + * @Since version-1.0 + */ +public class EntryCommitFormModeServiceImpl extends Service implements EntryCommitFormModeService { + BaseBean baseBean = new BaseBean(); + @Override + public Map entryCommit(Map params) { + Map result = new HashMap<>(); + RecordSet rs = new RecordSet(); + // 查询字段预处理 + List fieldNameList = new ArrayList<>(); + String fieldsSql = "select wf_field,ec_type from uf_hs_field_map"; + baseBean.writeLog("fieldsSql:" + fieldsSql); + rs.executeQuery(fieldsSql); + while (rs.next()) { + fieldNameList.add(rs.getString("wf_field")); + } + String fieldNames = fieldNameList.stream().collect(Collectors.joining(",")); + List propertyList = new ArrayList<>(); + Property[] properties; + + String sql = "select " + fieldNames + " from uf_rzgl where id=" + Util.null2String(params.get("id")); + baseBean.writeLog("动态拼接字段查询sql:" + sql); + rs.executeQuery(sql); + if (rs.next()) { + for (String s : fieldNameList) { + Property property = new Property(); + property.setName(s); + property.setValue(rs.getString(s)); + propertyList.add(property); + } + } + + if (propertyList.size() == 0) { + result.put("type", 2); + result.put("msg", "未查询到入职管理表中对应数据"); + baseBean.writeLog("未查询到入职管理表中对应数据"); + return result; + } + properties = new Property[propertyList.size()]; + properties = propertyList.toArray(properties); + + // 根据手机号+姓名校验数据存在 + String sjhm = null; + String xm = null; + for (Property property : properties) { + if ("sjhm".equals(property.getName())) { + sjhm = property.getValue(); + } + if ("xm".equals(property.getName())) { + xm = property.getValue(); + } + } + rs.execute("select * from hrmresource where mobile='" + sjhm + "' and lastname='" + xm + "'"); + if (rs.next()) { + result.put("type", 2); + result.put("msg", "当前人员已存在,无法重复添加"); + baseBean.writeLog("当前人员已存在,无法重复添加"); + return result; + } + // 获取人员主表(系统表)字段 + String sysSql = "select ec_field,wf_field,ec_type from uf_hs_field_map where ec_type=0"; + rs.executeQuery(sysSql); + // 系统字段 + Map fieldsMap = new HashMap<>(); + StringBuilder updateSysFields = new StringBuilder(); + while (rs.next()) { + fieldsMap.put(rs.getString("wf_field"), rs.getString("ec_field")); + } + //取系统字段对应字段数据 + Map resMap = new HashMap<>(); + for (Property p : properties) { + if (fieldsMap.containsKey(p.getName())) { + resMap.put(fieldsMap.get(p.getName()), p.getValue()); + baseBean.writeLog("resMap参数值:"+fieldsMap.get(p.getName()) + "++" + p.getValue()); + updateSysFields.append(fieldsMap.get(p.getName())).append("=").append("'").append(p.getValue()).append("'").append(","); + } + } + baseBean.writeLog("updateSysFields="+updateSysFields); + boolean flag = false; + //人员表数据插入 + resMap.put("status","0"); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + String currentDate = sdf.format(new Date()); + resMap.put("companystartdate",currentDate); + boolean canEdit = HrmUserVarify.checkUserRight("HrmResourceEdit:Edit", user); + if (!canEdit) { + result.put("msg", "人员新增失败,当前用户没有权限"); + baseBean.writeLog("人员新增失败,当前用户没有权限"); + return result; + } + Map retMap = ResourceSyncUtil.addResource(user, resMap); + if (!"1".equals(retMap.get("status"))) { + result.put("type", 2); + result.put("msg", "人员新增失败,请联系管理员"); + baseBean.writeLog("人员新增失败,请联系管理员"); + return result; + } + //查询拼接 + String defId = ""; + //查询新增成功的人员id + String queryHrmSql = "select id, workcode from hrmresource h where h.lastname = '" + resMap.get("lastname") + "' and h.mobile = '" + resMap.get("mobile") + "'"; + flag = rs.executeQuery(queryHrmSql); + RecordSet recordSet = new RecordSet(); + baseBean.writeLog("查询新增人员sql:" + queryHrmSql); + if (rs.next()) { + defId = rs.getString("id"); + String encrptPassword = ""; + String salt = ""; + if (org.apache.commons.lang3.StringUtils.isNotBlank(rs.getString("workcode"))) { + String[] encrypts = PasswordUtil.encrypt(rs.getString("workcode")); + encrptPassword = encrypts[0]; + salt = encrypts[1]; + } + String updateSql = "update hrmresource set "+updateSysFields+" loginid='" + rs.getString("workcode") + "',password='" + encrptPassword + "',salt='" + salt + "',certificatenum='"+Util.null2String(resMap.get("certificatenum"))+"' where id=" + defId; + recordSet.execute(updateSql); + + } else { + result.put("type", 2); + result.put("msg", "未查到对应人员Id,请联系管理员"); + baseBean.writeLog("未查到对应人员Id,请联系管理员"); + return result; + } + Map defMap; + rs.execute("select DISTINCT(ec_type) as ec_type from uf_hs_field_map where ec_type!=0"); + List ecTypes = new ArrayList<>(); + while (rs.next()) { + ecTypes.add(rs.getString("ec_type")); + } + // 自定义表数据插入 + for (String s : ecTypes) { + defMap = getFields(s, properties); + if (defMap != null) { + String defFields = "id, " + defMap.get("defFields"); + String defFieldsValue = defId + ", " + defMap.get("defFieldsValue"); + String insertSql = "insert into cus_fielddata(" + defFields + ") values (" + defFieldsValue + ")"; + flag = rs.execute(insertSql); + if (!flag) { + recordSet.execute("delete from hrmresource where id=" + defId); + recordSet.execute("delete from cus_fielddata where id=" + defId); + result.put("type", 2); + result.put("msg", "自定义字段类型" + s + "数据插入失败,请联系管理员检查字段"); + baseBean.writeLog("自定义字段类型" + s + "数据插入失败,请联系管理员检查字段"); + return result; + } + } + } + //修改建模表中人员状态 + if (flag) { + recordSet.execute("update uf_rzgl set rzzt='3' where xm='" + resMap.get("lastname") + "' and sfzh='" + resMap.get("certificatenum") + "'"); + result.put("type", 3); + result.put("msg", "入职提交成功!"); + baseBean.writeLog("入职提交成功!"); + } + + return result; + + } + + + /** + * 自定义字段分类获取 + * @param type + * @param properties + */ + private Map getFields(String type,Property[] properties) { + String ecType = "1"; + switch (type){ + case "2": + ecType = "-1"; + break; + case "3": + ecType = "1"; + break; + case "4": + ecType = "3"; + break; + default: break; + } + RecordSet rs = new RecordSet(); + List fieldsList = new ArrayList<>(); + List propertyListWf = new ArrayList<>(); + Map fieldsMapDef = new HashMap<>(); + // 自定义表字段 + String defSql = "select ec_field,wf_field,ec_type from uf_hs_field_map where ec_type='" + type +"'"; + rs.execute(defSql); + while (rs.next()) { + FieldMapEntity fieldMapEntity = new FieldMapEntity(); + fieldMapEntity.setEcField(rs.getString("ec_field")); + fieldMapEntity.setWfField(rs.getString("wf_field")); + fieldMapEntity.setEcType(rs.getString("ec_type")); + fieldsList.add(fieldMapEntity); + Property property = new Property(); + property.setName(rs.getString("wf_field")); + propertyListWf.add(property); + } + if (fieldsList.size()<1){ + return null; + } + // 拼接sql字段 + String defFields = fieldsList.stream().map(FieldMapEntity::getEcField).collect(Collectors.joining(",")); + defFields = " scope, scopeid," + defFields; + //交集字段和数据 + List propertyListFront = Arrays.asList(properties); + Map frontMap = propertyListFront.stream().collect(Collectors.toMap(Property::getName,(p) -> p)); + for (FieldMapEntity f : fieldsList) { + if (frontMap.containsKey(f.getWfField())) { + f.setEcValue(Util.null2String(frontMap.get(f.getWfField()).getValue())); + } + } + String defFieldsValue2 = fieldsList.stream().map(fieldMapEntity -> StringUtils.isBlank(fieldMapEntity.getEcValue()) ? "null" : "'"+fieldMapEntity.getEcValue()+"'").collect(Collectors.joining(",")); + System.out.println(defFieldsValue2); + List propertyListBack = propertyListFront.stream() + .filter(property -> propertyListWf.stream() + .map(Property::getName) + .anyMatch(name -> Objects.equals(property.getName(), name))) + .collect(Collectors.toList()); + String defFieldsValue = propertyListBack.stream().map(property -> "".equals(property.getValue()) ? "null" : property.getValue()).collect(Collectors.joining(",")); + defFieldsValue2 = " 'HrmCustomFieldByInfoType', " + ecType + "," + defFieldsValue2; + Map resFieldMap = new HashMap<>(); + resFieldMap.put("defFields",defFields); + resFieldMap.put("defFieldsValue",defFieldsValue2); + return resFieldMap; + } +} diff --git a/src/com/engine/leshanvc/service/impl/EntryWorkflowSaveEventServiceImpl.java b/src/com/engine/leshanvc/service/impl/EntryWorkflowSaveEventServiceImpl.java new file mode 100644 index 0000000..0998597 --- /dev/null +++ b/src/com/engine/leshanvc/service/impl/EntryWorkflowSaveEventServiceImpl.java @@ -0,0 +1,21 @@ +package com.engine.leshanvc.service.impl; + +import com.engine.core.impl.Service; +import com.engine.leshanvc.cmd.EntryWorkflowSaveEventCmd; +import com.engine.leshanvc.service.EntryWorkflowSaveEventService; + +import java.util.Map; + +/** + * @Author weaver_cl + * @Description: + * @Date 2023/2/21 + * @Version V1.0 + **/ +public class EntryWorkflowSaveEventServiceImpl extends Service implements EntryWorkflowSaveEventService { + + @Override + public Map changeStatus(Map params) { + return commandExecutor.execute(new EntryWorkflowSaveEventCmd(params, user)); + } +} diff --git a/src/com/engine/leshanvc/service/impl/KqWorkflowRangeLimitServiceImpl.java b/src/com/engine/leshanvc/service/impl/KqWorkflowRangeLimitServiceImpl.java new file mode 100644 index 0000000..669ce2c --- /dev/null +++ b/src/com/engine/leshanvc/service/impl/KqWorkflowRangeLimitServiceImpl.java @@ -0,0 +1,21 @@ +package com.engine.leshanvc.service.impl; + +import com.engine.core.impl.Service; +import com.engine.leshanvc.cmd.KqWorkflowRangeLimitCmd; +import com.engine.leshanvc.service.KqWorkflowRangeLimitService; + +import java.util.Map; + +/** + * @Author weaver_cl + * @Description: + * @Date 2023/3/3 + * @Version V1.0 + **/ +public class KqWorkflowRangeLimitServiceImpl extends Service implements KqWorkflowRangeLimitService { + + @Override + public Map rangeLimit(Map params) { + return commandExecutor.execute(new KqWorkflowRangeLimitCmd(params, user)); + } +} diff --git a/src/com/engine/leshanvc/service/impl/LeaverWorkflowServiceImpl.java b/src/com/engine/leshanvc/service/impl/LeaverWorkflowServiceImpl.java new file mode 100644 index 0000000..ab72b2c --- /dev/null +++ b/src/com/engine/leshanvc/service/impl/LeaverWorkflowServiceImpl.java @@ -0,0 +1,92 @@ +package com.engine.leshanvc.service.impl; + +import com.engine.core.impl.Service; +import com.engine.leshanvc.service.LeaverWorkflowService; +import com.engine.leshanvc.util.HsDateUtil; +import org.apache.commons.lang3.StringUtils; +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.general.Util; + +import java.util.HashMap; +import java.util.Map; + +/** + * @author:dxfeng + * @createTime: 2023/04/19 + * @version: 1.0 + */ +public class LeaverWorkflowServiceImpl extends Service implements LeaverWorkflowService { + private static final String DAY_SHIFT_ID = "2"; + + @Override + public Map getEndDate(Map params) { + Map returnMap = new HashMap<>(16); + String newLeaveType = Util.null2String(params.get("newLeaveType")); + String resourceId = Util.null2String(params.get("resourceId")); + String fromDate = Util.null2String(params.get("fromDate")); + String startTime = ""; + String endTime = ""; + String viewAttr = "1"; + + Boolean includeHoliday = null; + + if (StringUtils.isBlank(fromDate)) { + fromDate = DateUtil.getCurrentDate(); + } + + RecordSet rs = new RecordSet(); + String sql = "select times,onoffworktype,record from kq_shiftonoffworksections where serialid = ? order by record"; + rs.executeQuery(sql, DAY_SHIFT_ID); + while (rs.next()) { + if ("start".equalsIgnoreCase(rs.getString("onoffworktype")) && "0".equals(rs.getString("record"))) { + startTime = rs.getString("times"); + } else if ("end".equalsIgnoreCase(rs.getString("onoffworktype"))) { + endTime = rs.getString("times"); + } + } + + // 根据白名单,判断结束时间是否可以自行调整 + sql = "select * from uf_xjlx where qjlx = ? and qjr = ? and sfqy = 1 "; + rs.executeQuery(sql, newLeaveType, resourceId); + if (rs.next()) { + viewAttr = "3"; + } + + // 根据假期类型,判断是否包含节假日 + switch (newLeaveType) { + // 陪产假、婚假、丧假 + case "9": + case "32": + case "35": + includeHoliday = true; + break; + // 产假、产假(剖腹产顺延)、产假(多胞胎顺延) + case "8": + case "17": + case "18": + includeHoliday = false; + break; + default: + viewAttr = "3"; + break; + + } + + Integer holidayAmount = HsDateUtil.getHolidayAmount(resourceId, newLeaveType, fromDate); + String endDate; + if (null != includeHoliday && holidayAmount != 0) { + endDate = HsDateUtil.addDay(resourceId, holidayAmount, fromDate, includeHoliday); + } else { + endDate = ""; + viewAttr = "3"; + } + returnMap.put("endDate", endDate); + returnMap.put("endTime", endTime); + returnMap.put("startDate", fromDate); + returnMap.put("startTime", startTime); + returnMap.put("viewAttr", viewAttr); + + return returnMap; + } +} diff --git a/src/com/engine/leshanvc/service/impl/LzWorkflowManageServiceImpl.java b/src/com/engine/leshanvc/service/impl/LzWorkflowManageServiceImpl.java new file mode 100644 index 0000000..a018981 --- /dev/null +++ b/src/com/engine/leshanvc/service/impl/LzWorkflowManageServiceImpl.java @@ -0,0 +1,269 @@ +package com.engine.leshanvc.service.impl; + +import com.engine.core.impl.Service; +import com.engine.leshanvc.service.LzWorkflowManageService; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.Util; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class LzWorkflowManageServiceImpl extends Service implements LzWorkflowManageService { + BaseBean baseBean = new BaseBean(); + @Override + public Map getHrmInfoByLinSup(Map params) { + Map data = new HashMap<>(); + String lineSup = Util.null2String(params.get("userid")); + List hrmInfoList = new ArrayList<>(); + RecordSet rs = new RecordSet(); + rs.execute("select a.id,b.lastname,b.departmentid,field35,jobtitle,field102,xnfzmc,b.workcode,c.departmentname,d.jobtitlename from cus_fielddata a \n" + + "inner join hrmresource b on a.id=b.id " + + "left join hrmdepartment c ON b.DEPARTMENTID=c.id\n" + + "left join hrmjobtitles d on b.JOBTITLE=d.ID \n" + + "left join uf_xlfz e on a.field102 =e.xnfzbm \n" + + "where scope ='HrmCustomFieldByInfoType' and b.status < 4\n" + + "and scopeid ='-1' and field89='"+lineSup+"'"); + while (rs.next()) { + String userId = rs.getString("id"); + String bm = rs.getString("departmentid"); + String zjj = rs.getString("field35"); + String gw = rs.getString("jobtitle"); + String xnfz = rs.getString("field102"); + String xnfzmc = rs.getString("xnfzmc"); + String gh = rs.getString("workcode"); + String departmentname = rs.getString("departmentname"); + String jobtitlename = rs.getString("jobtitlename"); + + String dyyljjbxs = getJBTimes(userId); + String dyljjbcexs = getJbCHETimes(bm,zjj,gw); + String sfgpczg = getSfgpczg(bm,zjj,gw); + hrmInfoList.add(new HrmInfo(userId,rs.getString("lastname"),bm,dyyljjbxs,dyljjbcexs,gh,gw,sfgpczg,xnfz,xnfzmc,zjj,departmentname,jobtitlename)); + } + data.put("data",hrmInfoList); + + return data; + } + + /** + * 当月已累计加班时长 + */ + String getJBTimes(String userId){ + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery("select sum(cast(duration_min as decimal(18,4)))/60 jbtimes \n" + + "from kq_flow_overtime b\n" + + "where date_format(b.belongdate,'%Y-%m')=date_format(curdate(),'%Y-%m') and b.resourceid=? ",userId); + String jbTimes = ""; + if(recordSet.next()){ + jbTimes = Util.null2String(recordSet.getString("jbtimes")); + } + return jbTimes; + } + /** + * 当月累计加班超额(小时) + */ + String getJbCHETimes(String bm,String zjj,String gw){ + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery("select a.dyljjbcexs from uf_jbfjsp a where a.bm =? " + + "and a.zjj=? and gw=? " + + "union all select 500 ",bm,zjj,gw); + String dyljjbcexs = ""; + if (recordSet.next()) { + dyljjbcexs = Util.null2String(recordSet.getString("dyljjbcexs")); + } + return dyljjbcexs; + } + + + /** + * 是否过PC主管 + */ + public String getSfgpczg(String bm,String zjj,String gw){ + String sfgpczg = ""; + RecordSet rs = new RecordSet(); + rs.executeQuery(" select sfgpczg from uf_jbfjsp " + + " where bm=? and zjj=? and gw=? ",new Object[]{bm,zjj,gw}); + if (rs.next()) { + sfgpczg = Util.null2String(rs.getString("sfgpczg")); + } + return sfgpczg; + } + + + private static class HrmInfo { + /** + * 人员id + */ + private String id; + /** + * 人员姓名 + */ + private String lastName; + /** + * 部门id + */ + private String departmentId; + + /** + * 当月已累计加班小时 + */ + private String dyyljjbxs; + + /** + * 当月累计加班超额(小时) + */ + private String dyljjbcexs; + + /** + * 工号 + */ + private String gh; + + /** + * 岗位 + */ + private String gw; + + /** + * 是否过pc主管 + */ + private String sfgpczg; + + /** + * 线内分组 + */ + private String xnfz; + + /** + * 线内分组 + */ + private String xnfzmc; + + private String zjj; + private String deptName; + private String jobTitleName; + + + public HrmInfo(String id, String lastName, String departmentId, String dyyljjbxs, String dyljjbcexs, String gh, String gw,String sfgpczg, String xnfz,String xnfzmc, String zjj, String deptName, String jobTitleName) { + this.id = id; + this.lastName = lastName; + this.departmentId = departmentId; + this.dyyljjbxs = dyyljjbxs; + this.dyljjbcexs = dyljjbcexs; + this.gh = gh; + this.gw = gw; + this.sfgpczg = sfgpczg; + this.xnfz = xnfz; + this.xnfzmc = xnfzmc; + this.zjj = zjj; + this.deptName = deptName; + this.jobTitleName = jobTitleName; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getDepartmentId() { + return departmentId; + } + + public void setDepartmentId(String departmentId) { + this.departmentId = departmentId; + } + + public String getDyyljjbxs() { + return dyyljjbxs; + } + + public void setDyyljjbxs(String dyyljjbxs) { + this.dyyljjbxs = dyyljjbxs; + } + + public String getDyljjbcexs() { + return dyljjbcexs; + } + + public void setDyljjbcexs(String dyljjbcexs) { + this.dyljjbcexs = dyljjbcexs; + } + + public String getGh() { + return gh; + } + + public void setGh(String gh) { + this.gh = gh; + } + + public String getGw() { + return gw; + } + + public void setGw(String gw) { + this.gw = gw; + } + + public String getSfgpczg() { + return sfgpczg; + } + + public void setSfgpczg(String sfgpczg) { + this.sfgpczg = sfgpczg; + } + + public String getXnfz() { + return xnfz; + } + + public void setXnfz(String xnfz) { + this.xnfz = xnfz; + } + + public String getXnfzmc() { + return xnfzmc; + } + + public void setXnfzmc(String xnfzmc) { + this.xnfzmc = xnfzmc; + } + + public String getZjj() { + return zjj; + } + + public void setZjj(String zjj) { + this.zjj = zjj; + } + + public String getDeptName() { + return deptName; + } + + public void setDeptName(String deptName) { + this.deptName = deptName; + } + + public String getJobTitleName() { + return jobTitleName; + } + + public void setJobTitleName(String jobTitleName) { + this.jobTitleName = jobTitleName; + } + } +} diff --git a/src/com/engine/leshanvc/service/impl/ResourceCardServiceImpl.java b/src/com/engine/leshanvc/service/impl/ResourceCardServiceImpl.java new file mode 100644 index 0000000..6813ccd --- /dev/null +++ b/src/com/engine/leshanvc/service/impl/ResourceCardServiceImpl.java @@ -0,0 +1,105 @@ +package com.engine.leshanvc.service.impl; + +import com.engine.core.impl.Service; +import com.engine.leshanvc.service.ResourceCardService; +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.systeminfo.systemright.CheckUserRight; + +import java.util.Map; + +/** + * @author:dxfeng + * @createTime: 2023/04/20 + * @version: 1.0 + */ +public class ResourceCardServiceImpl extends Service implements ResourceCardService { + + @Override + public void editResourceCard(Map params) { + String field102 = ""; + Integer lineLeaderId = null; + String probationDate = ""; + String dimissionDate = ""; + RecordSet rs = new RecordSet(); + + String resourceId = Util.null2String(params.get("id")); + String roleName = Util.null2String(params.get("roleName")); + // 查询线内分组字段的值 + String sql = "select field102 from cus_fielddata cf where scope ='HrmCustomFieldByInfoType' and scopeid ='-1' and id = ?"; + rs.executeQuery(sql, resourceId); + if (rs.next()) { + field102 = rs.getString("field102"); + } + // 查询分组的 + sql = "select xc from uf_xlfz where xnfzbm = ?"; + rs.executeQuery(sql, field102); + if (rs.next()) { + lineLeaderId = rs.getInt("xc"); + } + // 补充线长字段,判断当前线长是否拥有线长角色 + sql = "update cus_fielddata set field89 = ? where scope ='HrmCustomFieldByInfoType' and scopeid ='-1' and id = ? "; + rs.executeUpdate(sql, lineLeaderId, resourceId); + sql = "select id from hrmroles where ROLESMARK = ? "; + rs.executeQuery(sql, roleName); + if (rs.next()) { + addResourceRoles(String.valueOf(lineLeaderId), rs.getString("id")); + } + + // 查询转正日期、离职日期 + sql = "select field18,field82 from cus_fielddata where scope ='HrmCustomFieldByInfoType' and scopeid ='3' and id = ?"; + rs.executeQuery(sql, resourceId); + if (rs.next()) { + probationDate = rs.getString("field18"); + dimissionDate = rs.getString("field82"); + } + // 修改当前人员为正式(转正日期小于等于当前日期) + if (probationDate.length() >0 ) { + if (probationDate.compareTo(DateUtil.getCurrentDate()) <= 0) { + sql = "update hrmresource set status = 1 where id = ?"; + rs.executeUpdate(sql, resourceId); + } + } + // 修改当前人员为离职(离职日期小于当前日期) + if (dimissionDate.length() > 0) { + if (dimissionDate.compareTo(DateUtil.getCurrentDate()) <0) { + sql = "update hrmresource set status = 5 where id = ?"; + rs.executeUpdate(sql,resourceId); + } + } + } + + + /** + * 给人员添加角色 + * + * @param resourceId + * @param roleId + */ + private void addResourceRoles(String resourceId, String roleId) { + RecordSet rs = new RecordSet(); + + // 角色级别:总部 + String roleLevel = "2"; + CheckUserRight checkUserRight = new CheckUserRight(); + if (!"".equals(roleId)) { + boolean isExist = false; + String sql = " select count(id) from HrmRoleMembers where roleid=" + roleId + " and resourceid = " + resourceId + " and resourcetype = 1 "; + rs.executeQuery(sql); + if (rs.next()) { + if (rs.getInt(1) > 0) { + isExist = true; + } + } + if (!isExist) { + sql = " INSERT INTO HrmRoleMembers ( roleid ,resourceid ,rolelevel ,resourcetype) " + + " VALUES ( " + roleId + ", " + resourceId + " , '" + roleLevel + "', '1')"; + } + rs.executeUpdate(sql); + + } + checkUserRight.removeMemberRoleCache(); + checkUserRight.removeRoleRightdetailCache(); + } +} diff --git a/src/com/engine/leshanvc/service/impl/SyncXcDataServiceImpl.java b/src/com/engine/leshanvc/service/impl/SyncXcDataServiceImpl.java new file mode 100644 index 0000000..4e3183e --- /dev/null +++ b/src/com/engine/leshanvc/service/impl/SyncXcDataServiceImpl.java @@ -0,0 +1,322 @@ +package com.engine.leshanvc.service.impl; + +import com.engine.core.impl.Service; +import com.engine.kq.biz.KQGroupMemberComInfo; +import com.engine.kq.biz.KQHolidaySetBiz; +import com.engine.leshanvc.service.SyncXcDataService; +import org.apache.commons.lang3.StringUtils; +import org.apache.tools.ant.util.DateUtils; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.PasswordUtil; +import weaver.general.Util; +import weaver.hrm.HrmUserVarify; +import weaver.interfaces.leshanvc.workflow.util.ResourceSyncUtil; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; +import java.util.*; + +public class SyncXcDataServiceImpl extends Service implements SyncXcDataService { + BaseBean baseBean = new BaseBean(); + static String dateFormat = "yyyy-MM-dd"; + static SimpleDateFormat format = new SimpleDateFormat(dateFormat); + + @Override + public Map syncXcData(Map params) { + Map data = new HashMap<>(16); + baseBean.writeLog("同步线长信息至花名册"); + RecordSet recordSet = new RecordSet(); + Boolean boo = false; + try { + boo = recordSet.execute("update cus_fielddata a, uf_xlfz b \n" + + "set a.field89=SUBSTRING_INDEX(b.xc,',',1) where a.SCOPEID='-1' and a.SCOPE='HrmCustomFieldByInfoType' and a.field102=b.xnfzbm "); + if (boo) { + data.put("status","success"); + data.put("msg","线长信息同步成功!"); + } + }catch (Exception e) { + data.put("status","error"); + data.put("msg","线长信息同步失败,请联系管理员!"); + baseBean.writeLog(e); + } + return data; + } + + @Override + public Map nonOfficeUpload(Map params) { + Map result = new HashMap(); + try { + String ids = Util.null2String(params.get("ids")); + boolean canEdit = HrmUserVarify.checkUserRight("HrmResourceEdit:Edit", user); + if (!canEdit) { + baseBean.writeLog("人员新增失败,当前用户不具备权限"); + result.put("msg", "人员新增失败,当前用户不具备权限"); + result.put("status", "error"); + return result; + } + String[] idStr = ids.split(","); + for (String s : idStr) { + //------请在下面编写业务逻辑代码------ + RecordSet rs = new RecordSet(); + rs.executeQuery("select sfzhm,xm,xb,mz,csrq,jtzz,ksyxq,jzyxq,sfrhmc from uf_sfzxxgl where id=?", s); + Map paraMap = new HashMap<>(); + String defId = null; + RecordSet recordSet = new RecordSet(); + if (rs.next()) { + String xm = Util.null2String("xm"); + paraMap.put("certificatenum", Util.null2String(rs.getString("sfzhm"))); + paraMap.put("lastname", Util.null2String(rs.getString("xm"))); + paraMap.put("sex", Util.null2String(rs.getString("xb"))); + paraMap.put("folk", Util.null2String(rs.getString("mz"))); + paraMap.put("birthday", Util.null2String(rs.getString("csrq"))); + paraMap.put("regresidentplace", Util.null2String(rs.getString("jtzz"))); + paraMap.put("status", "0"); + paraMap.put("ksyxq", Util.null2String(rs.getString("ksyxq"))); + paraMap.put("jzyxq", Util.null2String(rs.getString("jzyxq"))); + if (StringUtils.isNotBlank(rs.getString("sfrhmc"))) { + recordSet.executeQuery("select id from hrmresource where CERTIFICATENUM='"+Util.null2String(rs.getString("sfzhm"))+"' and status < 4"); + if (recordSet.next()) { + baseBean.writeLog("【"+xm+"】已存在花名册中,系统自动更新数据!!"); + String updateHrmSql = "update hrmresource set CERTIFICATENUM='"+paraMap.get("certificatenum")+"', " + + "LASTNAME='"+paraMap.get("lastname")+"',FOLK='"+paraMap.get("folk")+"',BIRTHDAY='"+paraMap.get("birthday")+"', " + + "REGRESIDENTPLACE='"+paraMap.get("regresidentplace")+"',SEX='"+paraMap.get("sex")+"' where id='"+Util.null2String(recordSet.getString("id"))+"'"; + String updateCusSql = "update cus_fielddata set field103='"+paraMap.get("ksyxq")+"',field104='"+paraMap.get("jzyxq")+"'" + + " where id='"+Util.null2String(recordSet.getString("id"))+"' and scopeid = 1"; + rs.execute(updateHrmSql); + rs.execute(updateCusSql); + result.put("msg", "【"+xm+"】已存在花名册中,系统自动更新数据!!"); + result.put("status", "warning"); + return result; + } + } + + Map retMap = ResourceSyncUtil.addResource(user, paraMap); + if (!"1".equals(retMap.get("status"))) { + baseBean.writeLog("人员新增失败,请联系管理员"); + result.put("msg", "人员新增失败,请联系管理员"); + result.put("status", "error"); + return result; + } else { + defId = retMap.get("id").toString(); + + BaseBean bb = new BaseBean(); + //新增人员自动排考勤组和班次 + //考勤组 + String kqz = "12"; + //平时班次 + String bcId = "2"; + //周末班次 + String zmbc = "15"; + bb.writeLog("新增人员id:"+defId+"kqz:"+kqz+"bcId:"+bcId+"zmbc:"+zmbc); + //当前日期 + String nowDate = DateUtils.format(new Date(), "yyyy-MM-dd"); + //本月最后一天 +// String toDate = TimeUtil.getMonthEndDay(nowDate); + String toDate = nowDate.substring(0,4)+"-12-31"; + Set all = new HashSet<>(); + all.add(nowDate); + List back = days(nowDate,toDate); + all.addAll(back); + all.add(toDate); + //插入考勤组 + insertGroupMember(defId,kqz); + bb.writeLog("考勤组插入完成"); + RecordSet rsn = new RecordSet(); + //默认排班 + String sql = "insert into kq_shiftschedule(kqdate,serialid,resourceid,groupid,isdelete)values(?,?,?,?,?)"; + for (String date : all) { + boolean holiday = KQHolidaySetBiz.isHoliday(defId, date, true); + bb.writeLog("date:"+date+"holiday:"+holiday); + if (holiday) { + //节假日休息班 + rsn.executeUpdate(sql, date, zmbc, defId, kqz, "0"); + } else { + rsn.executeUpdate(sql, date, bcId, defId, kqz, "0"); + } + } + bb.writeLog("默认排班插入完成"); + } + } + String queryHrmSql = "select workcode from hrmresource h where h.id = '" + defId + "'"; + rs.executeQuery(queryHrmSql); + + String encrptPassword = ""; + String salt = ""; + if (rs.next()) { + if (StringUtils.isNotBlank(rs.getString("workcode"))) { + String[] encrypts = PasswordUtil.encrypt(rs.getString("workcode")); + encrptPassword = encrypts[0]; + salt = encrypts[1]; + } + recordSet.execute("update hrmresource set loginid='" + rs.getString("workcode") + "',password='" + encrptPassword + "',salt='" + + salt + "',certificatenum='" + Util.null2String(paraMap.get("certificatenum")) + "',folk='"+paraMap.get("folk")+"'," + + "birthday='"+paraMap.get("birthday")+"',regresidentplace='"+paraMap.get("regresidentplace")+"' where id=" + defId); + } else { + baseBean.writeLog("未查到对应人员Id,请联系管理员"); + result.put("msg", "未查到对应人员Id,请联系管理员"); + result.put("status", "error"); + return result; + } + + // 自定义表cus_fielddata + String insertCusFieldData = "insert cus_fielddata(scope,scopeid,id,field81,field103,field104) " + + "values ('HrmCustomFieldByInfoType','1'," + defId + ",'0','" + paraMap.get("ksyxq") + "','" + paraMap.get("jzyxq") + "')"; + rs.execute(insertCusFieldData); + // 更新状态 + String updateStatus = "update uf_sfzxxgl set sfrhmc = '1' where id = ?"; + rs.executeUpdate(updateStatus, s); + } + } catch (Exception e) { + result.put("msg", "内部错误,请联系管理员"); + result.put("status", "error"); + } + result.put("status", "success"); + result.put("msg", "所选人员上岗成功!"); + return result; + } + + + @Override + public Map saveIDCard(Map params) { + baseBean.writeLog(params); + Map result = new HashMap(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd"); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss"); + + String cardNo = Util.null2String(params.get("cardno")); + String name = Util.null2String(params.get("name")); + String sex = Util.null2String(params.get("sex")).equals("男") ? "0" : "1"; + String nation = Util.null2String(params.get("nation")); + String born = null; + String userLifeB = null; + String userLifeE = null; + try { + Date date = df.parse(Util.null2String(params.get("born"))); + born = sdf.format(date); + date = df.parse(Util.null2String(params.get("userlifeb"))); + userLifeB = sdf.format(date); + date = df.parse(Util.null2String(params.get("userlifee"))); + userLifeE = sdf.format(date); + } catch (ParseException e) { + throw new RuntimeException(e); + } + String address = Util.null2String(params.get("address")); + String police = Util.null2String(params.get("police")); + String CardType = Util.null2String(params.get("CardType")); + String photobase64 = Util.null2String(params.get("photobase64")); + + + String modeUuid = UUID.randomUUID().toString(); + int modeDataCreate = user.getUID(); + + String modeDataCreateDate = sdf.format(new Date()); + String modeDataCreateTime = LocalTime.now().format(formatter); + + RecordSet rs = new RecordSet(); + + //身份证录入时,系统需检验 + //① 身份证号码相同 且 是否黑名单:否,身份信息可录入,并且提示:该入职员工属于二次入职。 + //② 身份证号码相同 且 是否黑名单:是,身份信息不可录入,提示:该入职员工属于黑名单,不允许入职。 + //③ 身份证号码不相同 且 是否和名单:否,身份信息可录入。 + + String msg = "身份证读取录入成功"; + boolean isBlack = false; + String checkSql = " select a.certificatenum ,b.field113 from hrmresource a " + + " left join cus_fielddata b on a.id=b.id and b.scopeid =3 where certificatenum=? "; + rs.executeQuery(checkSql,cardNo); + if(rs.next()){ + isBlack = Util.getIntValue(rs.getString("field113"))==0; + if(isBlack){ + msg = "该入职员工属于黑名单,不允许入职"; + }else{ + msg = "该入职员工属于二次入职"; + } + } + + if(!isBlack){ + String insertSql = "INSERT INTO uf_sfzxxgl (formmodeid, modedatacreater, modedatacreatertype, " + + "modedatacreatedate, modedatacreatetime, MODEUUID, sfzhm, xm, " + + "xb, mz, csrq, jtzz, ksyxq, jzyxq, sfrhmc, qfjg, zjlx, zjtx) VALUES (50, "+modeDataCreate+", 0, " + + "'"+modeDataCreateDate+"', '"+modeDataCreateTime+"', '"+modeUuid+"', '"+cardNo+"', '"+name+"'," + + sex+", '"+nation+"', '"+born+"', '"+address+"', '"+userLifeB+"', '"+userLifeE+"', 0, '"+police+"', '"+CardType+"', '"+photobase64+"')"; + boolean res = rs.execute(insertSql); + if(!res){ + msg = "身份证读取录入失败"; + } + + } + result.put("status","success"); + result.put("msg",msg); + + return result; + } + + /** + * 获取两个日期之间所有的日期 + * @param date1 + * @param date2 + * @return + */ + public static ArrayList days(String date1, String date2) { + ArrayList L = new ArrayList(); + if (date1.equals(date2)) { + System.out.println("两个日期相等!"); + return L; + } + + String tmp; + if (date1.compareTo(date2) > 0) { // 确保 date1的日期不晚于date2 + tmp = date1; + date1 = date2; + date2 = tmp; + } + + tmp = format.format(str2Date(date1).getTime() + 3600 * 24 * 1000); + + int num = 0; + while (tmp.compareTo(date2) < 0) { + L.add(tmp); + num++; + tmp = format.format(str2Date(tmp).getTime() + 3600 * 24 * 1000); + } + + if (num == 0) + System.out.println("两个日期相邻!"); + return L; + } + + private static Date str2Date(String str) { + if (str == null) + return null; + + try { + return format.parse(str); + } catch (ParseException e) { + e.printStackTrace(); + } + return null; + } + + /** + * 插入考勤组 + * @param rzry + * @param groupId + */ + private static void insertGroupMember(String rzry,String groupId){ + BaseBean bb = new BaseBean(); + RecordSet rsInsert = new RecordSet(); + String sql = "insert into kq_groupmember (type,typevalue,groupid) " + + " values(?,?,?) "; + rsInsert.executeUpdate(sql, 1,rzry,groupId); + bb.writeLog("insertSql:"+sql); + new KQGroupMemberComInfo().removeCache(); + } + + +} + + diff --git a/src/com/engine/leshanvc/service/impl/WorkflowCheckServiceImpl.java b/src/com/engine/leshanvc/service/impl/WorkflowCheckServiceImpl.java new file mode 100644 index 0000000..03bfd05 --- /dev/null +++ b/src/com/engine/leshanvc/service/impl/WorkflowCheckServiceImpl.java @@ -0,0 +1,21 @@ +package com.engine.leshanvc.service.impl; + +import com.engine.core.impl.Service; +import com.engine.leshanvc.cmd.WorkflowCheckCmd; +import com.engine.leshanvc.service.WorkflowCheckService; + +import java.util.Map; + +/** + * @Author weaver_cl + * @Description: + * @Date 2023/3/8 + * @Version V1.0 + **/ +public class WorkflowCheckServiceImpl extends Service implements WorkflowCheckService { + + @Override + public Map workflowController(Map params) { + return commandExecutor.execute(new WorkflowCheckCmd(params, user)); + } +} diff --git a/src/com/engine/leshanvc/util/ExceptionUtil.java b/src/com/engine/leshanvc/util/ExceptionUtil.java new file mode 100644 index 0000000..06f6c93 --- /dev/null +++ b/src/com/engine/leshanvc/util/ExceptionUtil.java @@ -0,0 +1,20 @@ +package com.engine.leshanvc.util; + +/** + * @Author weaver_cl + * @Description: + * @Date 2023/2/21 + * @Version V1.0 + **/ +public class ExceptionUtil { + public static String getRealMessage(Throwable e) { + while (e != null) { + Throwable cause = e.getCause(); + if (cause == null) { + return e.getMessage(); + } + e = cause; + } + return ""; + } +} diff --git a/src/com/engine/leshanvc/util/HsDateUtil.java b/src/com/engine/leshanvc/util/HsDateUtil.java new file mode 100644 index 0000000..030902e --- /dev/null +++ b/src/com/engine/leshanvc/util/HsDateUtil.java @@ -0,0 +1,93 @@ +package com.engine.leshanvc.util; + +import com.engine.kq.biz.KQBalanceOfLeaveBiz; +import com.engine.kq.biz.KQGroupMemberComInfo; +import com.engine.kq.biz.KQHolidaySetComInfo; +import weaver.common.DateUtil; +import weaver.general.Util; + +/** + * @author:dxfeng + * @createTime: 2023/04/19 + * @version: 1.0 + */ +public class HsDateUtil { + + + /** + * 根据开始日期,假期余额,自动计算结束日期 + * + * @param resourceId 人员ID + * @param addDays 假期余额 + * @param startDate 假期开始日期 + * @param includeHoliday 假期是否包含节假期 + * @return + */ + public static String addDay(String resourceId, Integer addDays, String startDate, boolean includeHoliday) { + int i = 0; + String tempDate = startDate; + boolean isCurrentDate = false; + while (i < addDays) { + if (isCurrentDate) { + tempDate = DateUtil.addDate(tempDate, 1); + } else { + isCurrentDate = true; + } + boolean holiday = isHoliday(resourceId, tempDate, false); + if (includeHoliday || !holiday) { + i++; + } + } + + return tempDate; + } + + /** + * 获取假期余额 + * + * @param resourceId 人员ID + * @param newLeaveType 假期类型 + * @param startDate 假期开始时间 + * @return + */ + public static Integer getHolidayAmount(String resourceId, String newLeaveType, String startDate) { + String restAmount = KQBalanceOfLeaveBiz.getRestAmount(resourceId, newLeaveType, startDate); + String substring = "0".equals(restAmount) ? restAmount : restAmount.substring(0, restAmount.lastIndexOf('.')); + return Integer.parseInt(substring); + } + + /** + * @param resourceId 人员ID + * @param date 判断日期 + * @param containWeekend 是否包含周末 + * @return + */ + public static boolean isHoliday(String resourceId, String date, boolean containWeekend) { + boolean flag = false; + + /*获取考勤组的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) { + flag = true; + } + return flag; + } + + /** + * @param groupId 考勤组的ID + * @param date 判断日期 + * @return + */ + public static int getChangeType(String groupId, String date) { + //默认没有设置过节假日(节假日设置的类型:1-公众假日、2-调配工作日、3-调配休息日) + KQHolidaySetComInfo kqHolidaySetComInfo = new KQHolidaySetComInfo(); + return Util.getIntValue(kqHolidaySetComInfo.getChangeType(groupId, date), -1); + } +} diff --git a/src/com/engine/leshanvc/util/ResponseResult.java b/src/com/engine/leshanvc/util/ResponseResult.java new file mode 100644 index 0000000..18f5003 --- /dev/null +++ b/src/com/engine/leshanvc/util/ResponseResult.java @@ -0,0 +1,171 @@ +package com.engine.leshanvc.util; + + + +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.engine.core.exception.ECException; +import com.engine.leshanvc.exception.CustomizeRunTimeException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.extern.slf4j.Slf4j; +import weaver.general.BaseBean; +import weaver.hrm.User; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Supplier; + +/** + * 请求执行器 + *

Copyright: Copyright (c) 2022

+ *

Company: 泛微软件

+ * + * @author qiantao + * @version 1.0 + **/ +@Slf4j +public class ResponseResult { + + private static final long serialVersionUID = 1L; + + private final User user; + + private final BaseBean baseBean = new BaseBean(); + + private final Boolean isLog = "true".equals(baseBean.getPropValue("hrmSalary", "log")); + + public ResponseResult(User user) { + this.user = user; + } + + + /** + * 统一返回方法 + */ + public String run(Function f, T t) { + try { + if (isLog) { + log.info("run api , param {}", t); + } + return Ok(f.apply(t)); + } catch (CustomizeRunTimeException e) { + log.error("api run fail", e); + return Error(e.getMessage()); + } catch (ECException e) { + log.error("api run fail", e); + Throwable cause = e.getCause(); + return Error(cause.getMessage()); + } catch (Exception e) { + log.error("api run fail", e); + return Error("系统异常!"); + } + } + + /** + * 统一返回方法(有参无返回) + */ + public String run(Consumer f, T t) { + try { + if (isLog) { + log.info("run api , param {}", t); + } + f.accept(t); + return Ok(); + } catch (CustomizeRunTimeException e) { + log.error("api run fail", e); + return Error(e.getMessage()); + } catch (ECException e) { + log.error("api run fail", e); + return Error(ExceptionUtil.getRealMessage(e)); + } catch (Exception e) { + log.error("api run fail", e); + return Error("系统异常!", e); + } + } + + + /** + * 统一返回方法(无参有返回) + */ + public String run(Supplier f) { + try { + if (isLog) { + log.info("run api"); + } + return Ok(f.get()); + } catch (CustomizeRunTimeException e) { + log.error("api run fail", e); + return Error(e.getMessage()); + } catch (ECException e) { + log.error("api run fail", e); + Throwable cause = e.getCause(); + return Error(cause.getMessage()); + } catch (Exception e) { + log.error("api run fail", e); + return Error("系统异常!", e); + } + } + + + private static String getJsonString(Object apidatas) { + ObjectMapper mapper = new ObjectMapper(); + try { + return mapper.writeValueAsString(apidatas); + } catch (JsonProcessingException e) { + e.printStackTrace(); + } + return ""; + } + + + /** + * 成功返回 + */ + private String Ok() { + Map apidatas = new HashMap<>(); + apidatas.put("status", true); + return JSONObject.toJSONString(apidatas, SerializerFeature.DisableCircularReferenceDetect); + } + + + /** + * 成功返回 + */ + private String Ok(R r) { + Map apidatas = new HashMap<>(); + apidatas.put("status", true); + apidatas.put("data", r); + String success = getJsonString(apidatas); + if (isLog) { + log.info("run salary api success return {}", success); + } + return success; + } + + + /** + * 失败返回 + */ + private static String Error(String message) { + Map apidatas = new HashMap<>(); + apidatas.put("status", false); + apidatas.put("errormsg", message); + return JSONObject.toJSONString(apidatas, SerializerFeature.DisableCircularReferenceDetect); + } + + + /** + * 系统异常失败返回 + */ + private static String Error(String message, Exception e) { + Map apidatas = new HashMap<>(); + apidatas.put("status", false); + apidatas.put("errormsg", message); + apidatas.put("error", e.getMessage()); + return JSONObject.toJSONString(apidatas, SerializerFeature.DisableCircularReferenceDetect); + } + +} diff --git a/src/com/engine/leshanvc/web/EntryCommitFormModeController.java b/src/com/engine/leshanvc/web/EntryCommitFormModeController.java new file mode 100644 index 0000000..0c6cca8 --- /dev/null +++ b/src/com/engine/leshanvc/web/EntryCommitFormModeController.java @@ -0,0 +1,42 @@ +package com.engine.leshanvc.web; + +import com.engine.common.util.ParamUtil; +import com.engine.common.util.ServiceUtil; +import com.engine.leshanvc.service.EntryCommitFormModeService; +import com.engine.leshanvc.service.EntryWorkflowSaveEventService; +import com.engine.leshanvc.service.impl.EntryCommitFormModeServiceImpl; +import com.engine.leshanvc.service.impl.EntryWorkflowSaveEventServiceImpl; +import com.engine.leshanvc.util.ResponseResult; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; + +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.Map; + +/** + * @Author ml + * @Date 2023/3/1 11:10 + * @Description This is description of class + * @Since version-1.0 + */ +public class EntryCommitFormModeController { + + public EntryCommitFormModeService getService(User user) { + return ServiceUtil.getService(EntryCommitFormModeServiceImpl.class, user); + } + + + @POST + @Path("/entryCommit") + @Produces(MediaType.APPLICATION_JSON) + public String entryCommit(@Context HttpServletRequest request, @Context HttpServletResponse response) { + User user = HrmUserVarify.getUser(request, response); + return new ResponseResult, Map>(user).run(getService(user)::entryCommit, ParamUtil.request2Map(request)); + } +} diff --git a/src/com/engine/leshanvc/web/EntryWorkflowSaveEventAction.java b/src/com/engine/leshanvc/web/EntryWorkflowSaveEventAction.java new file mode 100644 index 0000000..e285f2b --- /dev/null +++ b/src/com/engine/leshanvc/web/EntryWorkflowSaveEventAction.java @@ -0,0 +1,43 @@ +package com.engine.leshanvc.web; + +import com.engine.common.util.ParamUtil; +import com.engine.common.util.ServiceUtil; +import com.engine.leshanvc.service.EntryWorkflowSaveEventService; +import com.engine.leshanvc.service.impl.EntryWorkflowSaveEventServiceImpl; +import com.engine.leshanvc.util.ResponseResult; +import lombok.extern.slf4j.Slf4j; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; + +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.Map; + +/** + * @Author weaver_cl + * @Description: + * @Date 2023/2/21 + * @Version V1.0 + **/ +@Slf4j +public class EntryWorkflowSaveEventAction { + + public EntryWorkflowSaveEventService getService(User user) { + return ServiceUtil.getService(EntryWorkflowSaveEventServiceImpl.class, user); + } + + + @POST + @Path("/changeStatus") + @Produces(MediaType.APPLICATION_JSON) + public String changeStatus(@Context HttpServletRequest request, @Context HttpServletResponse response) { + User user = HrmUserVarify.getUser(request, response); + return new ResponseResult< Map, Map>(user).run(getService(user)::changeStatus, ParamUtil.request2Map(request)); + } + +} diff --git a/src/com/engine/leshanvc/web/KqWorkflowRangeLimitAction.java b/src/com/engine/leshanvc/web/KqWorkflowRangeLimitAction.java new file mode 100644 index 0000000..159890c --- /dev/null +++ b/src/com/engine/leshanvc/web/KqWorkflowRangeLimitAction.java @@ -0,0 +1,39 @@ +package com.engine.leshanvc.web; + +import com.engine.common.util.ParamUtil; +import com.engine.common.util.ServiceUtil; +import com.engine.leshanvc.service.KqWorkflowRangeLimitService; +import com.engine.leshanvc.service.impl.KqWorkflowRangeLimitServiceImpl; +import com.engine.leshanvc.util.ResponseResult; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import java.util.Map; + +/** + * @Author weaver_cl + * @Description: + * @Date 2023/3/3 + * @Version V1.0 + **/ +public class KqWorkflowRangeLimitAction { + + public KqWorkflowRangeLimitService getService(User user) { + return ServiceUtil.getService(KqWorkflowRangeLimitServiceImpl.class,user); + } + + @GET + @Path("/rangeLimit") + @Produces(MediaType.APPLICATION_JSON) + public String rangeLimit(@Context HttpServletRequest request, @Context HttpServletResponse response) { + User user = HrmUserVarify.getUser(request, response); + return new ResponseResult< Map, Map>(user).run(getService(user)::rangeLimit, ParamUtil.request2Map(request)); + } +} diff --git a/src/com/engine/leshanvc/web/LeaverWorkflowAction.java b/src/com/engine/leshanvc/web/LeaverWorkflowAction.java new file mode 100644 index 0000000..6fa03e7 --- /dev/null +++ b/src/com/engine/leshanvc/web/LeaverWorkflowAction.java @@ -0,0 +1,38 @@ +package com.engine.leshanvc.web; + +import com.engine.common.util.ParamUtil; +import com.engine.common.util.ServiceUtil; +import com.engine.leshanvc.service.LeaverWorkflowService; +import com.engine.leshanvc.service.impl.LeaverWorkflowServiceImpl; +import com.engine.leshanvc.util.ResponseResult; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; + +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.Map; + +/** + * @author:dxfeng + * @createTime: 2023/04/19 + * @version: 1.0 + */ +public class LeaverWorkflowAction { + + public LeaverWorkflowService getService(User user) { + return ServiceUtil.getService(LeaverWorkflowServiceImpl.class, user); + } + + @POST + @Path("/getEndDate") + @Produces(MediaType.APPLICATION_JSON) + public String rangeLimit(@Context HttpServletRequest request, @Context HttpServletResponse response) { + User user = HrmUserVarify.getUser(request, response); + return new ResponseResult, Map>(user).run(getService(user)::getEndDate, ParamUtil.request2Map(request)); + } +} diff --git a/src/com/engine/leshanvc/web/LzWorkflowManageAction.java b/src/com/engine/leshanvc/web/LzWorkflowManageAction.java new file mode 100644 index 0000000..a26ceb6 --- /dev/null +++ b/src/com/engine/leshanvc/web/LzWorkflowManageAction.java @@ -0,0 +1,38 @@ +package com.engine.leshanvc.web; + +import com.engine.common.util.ParamUtil; +import com.engine.common.util.ServiceUtil; +import com.engine.leshanvc.service.LzWorkflowManageService; +import com.engine.leshanvc.service.impl.LzWorkflowManageServiceImpl; +import com.engine.leshanvc.util.ResponseResult; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import java.util.Map; + +public class LzWorkflowManageAction { + public LzWorkflowManageService getService(User user){ + return ServiceUtil.getService(LzWorkflowManageServiceImpl.class,user); + } + + /** + * @Author ml + * @Date 2023/3/16 10:44 + * @Description 根据线长查询生产线人员 + * @Since version-1.0 + */ + @GET + @Path("/getHrmInfoByLinSup") + @Produces(MediaType.APPLICATION_JSON) + public String getHrmInfoByLinSup(@Context HttpServletRequest request, @Context HttpServletResponse response) { + User user = HrmUserVarify.getUser(request, response); + return new ResponseResult, Map>(user).run(getService(user)::getHrmInfoByLinSup, ParamUtil.request2Map(request)); + } +} diff --git a/src/com/engine/leshanvc/web/ResourceCardAction.java b/src/com/engine/leshanvc/web/ResourceCardAction.java new file mode 100644 index 0000000..07e518a --- /dev/null +++ b/src/com/engine/leshanvc/web/ResourceCardAction.java @@ -0,0 +1,39 @@ +package com.engine.leshanvc.web; + +import com.engine.common.util.ParamUtil; +import com.engine.common.util.ServiceUtil; +import com.engine.leshanvc.service.ResourceCardService; +import com.engine.leshanvc.service.impl.ResourceCardServiceImpl; +import com.engine.leshanvc.util.ResponseResult; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; + +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.Map; + +/** + * @author:dxfeng + * @createTime: 2023/04/20 + * @version: 1.0 + */ +public class ResourceCardAction { + + public ResourceCardService getService(User user) { + return ServiceUtil.getService(ResourceCardServiceImpl.class, user); + } + + + @POST + @Path("/editResourceCard") + @Produces(MediaType.APPLICATION_JSON) + public String rangeLimit(@Context HttpServletRequest request, @Context HttpServletResponse response) { + User user = HrmUserVarify.getUser(request, response); + return new ResponseResult, Map>(user).run(getService(user)::editResourceCard, ParamUtil.request2Map(request)); + } +} diff --git a/src/com/engine/leshanvc/web/SyncXcDataAction.java b/src/com/engine/leshanvc/web/SyncXcDataAction.java new file mode 100644 index 0000000..3189d99 --- /dev/null +++ b/src/com/engine/leshanvc/web/SyncXcDataAction.java @@ -0,0 +1,55 @@ +package com.engine.leshanvc.web; + +import com.engine.common.util.ParamUtil; +import com.engine.common.util.ServiceUtil; +import com.engine.leshanvc.service.SyncXcDataService; +import com.engine.leshanvc.service.WorkflowCheckService; +import com.engine.leshanvc.service.impl.SyncXcDataServiceImpl; +import com.engine.leshanvc.service.impl.WorkflowCheckServiceImpl; +import com.engine.leshanvc.util.ResponseResult; +import com.engine.organization.util.response.ReturnResult; +import io.swagger.v3.oas.annotations.parameters.RequestBody; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import java.util.Map; + +public class SyncXcDataAction { + public SyncXcDataService getService(User user) { + return ServiceUtil.getService(SyncXcDataServiceImpl.class,user); + } + @GET + @Path("/syncXcData") + @Produces(MediaType.APPLICATION_JSON) + public String workflowController(@Context HttpServletRequest request, @Context HttpServletResponse response) { + User user = HrmUserVarify.getUser(request, response); + return new ResponseResult, Map>(user).run(getService(user)::syncXcData, ParamUtil.request2Map(request)); + } + @GET + @Path("/nonOfficeUpload") + @Produces(MediaType.APPLICATION_JSON) + public String nonOfficeUpload(@Context HttpServletRequest request, @Context HttpServletResponse response) { + User user = HrmUserVarify.getUser(request, response); + return new ResponseResult, Map>(user).run(getService(user)::nonOfficeUpload, ParamUtil.request2Map(request)); + } + + @POST + @Path("/saveIDCard") + @Produces(MediaType.APPLICATION_JSON) + public ReturnResult saveBaseComp(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody Map params) { + try { + User user = HrmUserVarify.getUser(request, response); + return ReturnResult.successed(getService(user).saveIDCard(params)); + } catch (Exception e) { + return ReturnResult.exceptionHandle(e); + } + } +} diff --git a/src/com/engine/leshanvc/web/WorkflowCheckAction.java b/src/com/engine/leshanvc/web/WorkflowCheckAction.java new file mode 100644 index 0000000..926c95e --- /dev/null +++ b/src/com/engine/leshanvc/web/WorkflowCheckAction.java @@ -0,0 +1,39 @@ +package com.engine.leshanvc.web; + +import com.engine.common.util.ParamUtil; +import com.engine.common.util.ServiceUtil; +import com.engine.leshanvc.service.WorkflowCheckService; +import com.engine.leshanvc.service.impl.WorkflowCheckServiceImpl; +import com.engine.leshanvc.util.ResponseResult; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import java.util.Map; + +/** + * @Author weaver_cl + * @Description: + * @Date 2023/3/8 + * @Version V1.0 + **/ +public class WorkflowCheckAction { + + public WorkflowCheckService getService(User user) { + return ServiceUtil.getService(WorkflowCheckServiceImpl.class,user); + } + + @GET + @Path("/controller") + @Produces(MediaType.APPLICATION_JSON) + public String workflowController(@Context HttpServletRequest request, @Context HttpServletResponse response) { + User user = HrmUserVarify.getUser(request, response); + return new ResponseResult< Map, Map>(user).run(getService(user)::workflowController, ParamUtil.request2Map(request)); + } +} diff --git a/src/com/engine/workflow/biz/requestForm/Html2Pdf.java b/src/com/engine/workflow/biz/requestForm/Html2Pdf.java new file mode 100644 index 0000000..26c8b8a --- /dev/null +++ b/src/com/engine/workflow/biz/requestForm/Html2Pdf.java @@ -0,0 +1,220 @@ +package com.engine.workflow.biz.requestForm; + +import java.io.BufferedInputStream; +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Properties; + +import com.engine.workflow.util.FileUtils; +import org.apache.axis.client.Call; +import org.apache.axis.client.Service; + +import weaver.general.BaseBean; +import weaver.general.GCONST; +import weaver.general.Util; + +/** + * Description: html表单转pdf + * + * @author Mcr + * + */ +public class Html2Pdf extends BaseBean{ + + /** + * 将离线html表单转成pdf格式 + * + * @param htmlPath 离线表单路径 + * @param pdfPath 生成的pdf文件路径 + * @param filename 文件名 + * @param zipPath zip文件路径 + * @return + */ + public boolean getPdf(String htmlPath,String pdfPath,String filename,String zipPath){ + boolean result = true; + + boolean isWindows = isWindows(); + boolean useLocalServer = isUseLocalServer(isWindows); + + if(useLocalServer){//使用本地插件转pdf useLocalServer + String cmd = getToolPath(isWindows) + " --enable-local-file-access " + htmlPath + " " + pdfPath; + + long l1 = System.currentTimeMillis(); + writeLog("开始导出pdf"); + writeLog("执行脚本:" + cmd); + Process p = null; + BufferedInputStream err = null; + BufferedReader errBr = null; + try { + Runtime run = Runtime.getRuntime(); + p = run.exec(cmd);//启动另一个进程来执行命令 + err = new BufferedInputStream(p.getErrorStream()); + errBr = new BufferedReader(new InputStreamReader(err)); + String lineStr = ""; + while ((lineStr = errBr.readLine()) != null){ + writeLog(lineStr); + } + //检查命令是否执行失败。 + try { + if (p.waitFor()!=0) { + if(p.exitValue()==1)//p.exitValue()==0表示正常结束,1:非正常结束 + writeLog("执行过程中出现异常"); + } + }catch (InterruptedException e){ + e.printStackTrace(); + } + writeLog("执行成功"); + + } catch (Exception e) { + result = false; + e.printStackTrace(); + }finally { + try { + errBr.close(); + err.close(); + if (p != null) { + p.destroy(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + long l2 = System.currentTimeMillis(); + writeLog("开始导出结束,耗时:"+ (l2-l1)); + }else{//使用window中转服务转pdf + String windowsServer = getPropValue("form2pdf_e9", "windowsServer"); + if(!"".equals(windowsServer)){ + File zipFile = new File(zipPath); + try { + String fileString = FileUtils.file2String(zipFile); + String pdfString = callService(fileString, windowsServer, filename); + if(!"".equals(pdfString)){ + byte[] string2Byte = FileUtils.string2Byte(pdfString); + result = FileUtils.saveFile(pdfPath, string2Byte); + }else{ + result = false; + } + } catch (IOException e) { + e.printStackTrace(); + } + }else{ + result = false; + writeLog("form2pdf_e9.properties中的windowsServer参数未配置,请检查!"); + } + } + + return result; + } + + /** + * 是否使用本地插件 + * + * @param isWindows + * @return + */ + private boolean isUseLocalServer(boolean isWindows){ + boolean result = true; + if(!isWindows){//linux系统 + if(getConvertType() == 3) + result = false;//使用windows中转服务 + } + return result; + } + + /** + * 获取转换类型 + * @return + */ + private int getConvertType(){ + int convertType = Util.getIntValue(getPropValue("form2pdf_e9", "convertType"),1); + return convertType; + } + + /** + * 判断当前服务器是否为windows系统 + * + * @return + */ + public boolean isWindows(){ + boolean isWindows = true; + Properties properties = System.getProperties(); + String os = properties.getProperty("os.name").toLowerCase(); + + if(os.indexOf("windows") > -1){ + isWindows = true; + }else{ + isWindows = false; + } + + return isWindows; + } + + /** + * 获取wkhtmltopdf地址 + * @return + */ + private String getToolPath(boolean isWindows){ + String toolPath = GCONST.getRootPath() + "wkhtmltopdf"; + if(isWindows){//Windows系统 + toolPath = "cmd /c " + toolPath + File.separator + "windows" + File.separator + "bin" + File.separator + "wkhtmltopdf.exe"; + }else{//Linux系统 + int convertType = getConvertType(); + if(convertType == 1){//使用ecology自带插件 + toolPath += File.separator + "linux" + File.separator + "bin" + File.separator + "./wkhtmltopdf"; + }else if(convertType == 2){//使用自行安装插件 + toolPath = Util.null2String(getPropValue("form2pdf_e9", "wkhtml2xPath")) + File.separator + "bin" + File.separator + "./wkhtmltopdf"; + } + } + + return toolPath; + } + + public static void wKConvertLinux(String whktmlExe,String htmlUrl, String pdfFilePath) { + try { + //ProcessBuilder pb = new ProcessBuilder(whktmlExe,"--print-media-type", "--margin-left", "10mm", "--margin-right", "10mm", htmlUrl, pdfFilePath); + ProcessBuilder pb = new ProcessBuilder(whktmlExe, htmlUrl, pdfFilePath); + pb.redirectErrorStream(true); + Process process = pb.start(); + BufferedReader errstreamReader = new BufferedReader(new InputStreamReader(process.getInputStream())); + String line = errstreamReader.readLine(); + while (line != null) { + line = errstreamReader.readLine(); + } + } catch (IOException e) { + e.printStackTrace(); + } + + } + + /** + * 调用windows中转服务 + * @param fileString + * @param windowsServer + * @param filename + * @return + */ + private String callService(String fileString,String windowsServer,String filename){ + String result = ""; + try { + String endpoint = windowsServer + "/services/PdfService"; + Service service = new Service(); + Call call = (Call) service.createCall(); + call.setTargetEndpointAddress(endpoint); + call.setOperationName("convertPdf");//方法 + call.addParameter("fileString", org.apache.axis.encoding.XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.IN);//接口的参数 + call.addParameter("filename", org.apache.axis.encoding.XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.IN); + call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);//设置返回类型 + + + result = (String)call.invoke(new Object[]{fileString,filename}); + }catch (Exception e) { + writeLog("调用window中转服务【html->pdf】失败!"); + } + + return result; + } + +} + diff --git a/src/com/engine/workflow/cmd/monitor/DoArchivingCmd.java b/src/com/engine/workflow/cmd/monitor/DoArchivingCmd.java new file mode 100644 index 0000000..6f77312 --- /dev/null +++ b/src/com/engine/workflow/cmd/monitor/DoArchivingCmd.java @@ -0,0 +1,234 @@ +package com.engine.workflow.cmd.monitor; + +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import com.engine.common.biz.AbstractCommonCommand; +import com.engine.common.constant.BizLogOperateType; +import com.engine.common.constant.BizLogSmallType4Workflow; +import com.engine.common.constant.BizLogType; +import com.engine.common.constant.ParamConstant; +import com.engine.common.entity.BizLogContext; +import com.engine.common.util.ParamUtil; + +import com.engine.core.interceptor.Command; +import com.engine.workflow.biz.requestForm.RequestRemindBiz; +import com.engine.workflow.constant.RemindTypeEnum; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.Util; +import weaver.hrm.User; +import weaver.workflow.monitor.Monitor; +import weaver.workflow.workflow.WFManager; +import weaver.workflow.workflow.WfForceOver; +import weaver.workflow.workflow.WfFunctionManageUtil; + +import com.engine.core.interceptor.CommandContext; +import weaver.workflow.request.RequestCheckAddinRules; +import weaver.workflow.request.RequestManager; +import weaver.workflow.workflow.WorkflowComInfo; +/** + * 流程强制归档 + * @author luosy 2017/11/17 + * + */ +public class DoArchivingCmd extends AbstractCommonCommand> { + + private HttpServletRequest request; + private HttpServletResponse response; + private User user; + + public DoArchivingCmd(HttpServletRequest request,HttpServletResponse response,User user){ + this.request = request; + this.response = response; + this.user = user; + } + + public DoArchivingCmd(){ + //空参构造器 + } + + @Override + public Map execute(CommandContext commandContext) { + return this.doArchiving(request, response, user); + } + + + /** + * 流程强制归档 + * @param request + * @param response + * @param user + * @return + */ + public Map doArchiving(HttpServletRequest request,HttpServletResponse response,User user){ + Map apidatas = new HashMap(); + String multiRequestIds = Util.null2String(request.getParameter("multiRequestIds")); + if(multiRequestIds.endsWith(",")) multiRequestIds = multiRequestIds.substring(0,multiRequestIds.length() - 1); + + String[] requestids = Util.TokenizerString2(multiRequestIds, ","); + RecordSet rs = new RecordSet(); + WfFunctionManageUtil WfFunctionManageUtil = new WfFunctionManageUtil(); + Monitor Monitor = new Monitor(); + WfForceOver WfForceOver = new WfForceOver(); + int success = 0,fail = 0; + if (requestids != null) { + for (int i = 0; i < requestids.length; i++) { + ArrayList requestidsArr = new ArrayList(); + int requestid_tmp = Util.getIntValue(requestids[i]); + if(requestid_tmp == -1){ + fail++; + continue; + } + if(!WfFunctionManageUtil.haveOtherOperationRight(requestid_tmp)){ + continue; + } + boolean isForceOver=false; + rs.execute("select creater,workflowid from workflow_requestbase where requestid = " + requestid_tmp); + rs.next(); + String creater = rs.getString(1); + int workflowid_rs = rs.getInt(2); + + weaver.workflow.monitor.MonitorDTO dto = Monitor.getMonitorInfo(user.getUID()+"",creater,workflowid_rs+""); + isForceOver = dto.getIsforceover(); + + if (isForceOver && !WfForceOver.isOver(requestid_tmp)) { + requestidsArr.add(requestids[i]); + WfForceOver.doForceOver(requestidsArr, request, response); + DoRepossessedCmd dor = new DoRepossessedCmd(); + Map data = dor.getWorkflowInfo(requestids[i]); + if(data.size() > 0){ + dor.releaseNumber(Util.getIntValue(data.get("formid")), Util.getIntValue(data.get("workflowid"))); + } + success++; + this.doRemind(requestid_tmp,workflowid_rs); + + //no.2545225 强制归档需要触发节点附加操作,实现一键审批 + try { + RequestManager requestManager = new RequestManager(); + requestManager.setUser(user); + requestManager.setWorkflowid(workflowid_rs); + requestManager.setRequestid(requestid_tmp); + WorkflowComInfo wfComInfo = new WorkflowComInfo(); + int formid = Util.getIntValue(wfComInfo.getFormId(workflowid_rs+"")); + int isbill = Util.getIntValue(wfComInfo.getIsBill(workflowid_rs+"")); + String sql2 = "select nodeid from workflow_flownode where workflowid = ? and nodetype = 3"; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql2,workflowid_rs); + int nodeid = -1; + if(recordSet.next()) { + nodeid = recordSet.getInt("nodeid"); + } + RequestCheckAddinRules requestCheckAddinRules = new RequestCheckAddinRules(); + requestCheckAddinRules.resetParameter(); + requestCheckAddinRules.setWorkflowid(workflowid_rs); + requestCheckAddinRules.setRequestid(requestid_tmp); + requestCheckAddinRules.setNodeid(nodeid); + requestCheckAddinRules.setObjid(nodeid); + requestCheckAddinRules.setObjtype(1); + requestCheckAddinRules.setIsbill(isbill); + requestCheckAddinRules.setFormid(formid); + requestCheckAddinRules.setIspreadd("0"); + requestCheckAddinRules.setRequestManager(requestManager); + requestCheckAddinRules.checkAddinRules(); + } catch (Exception e) { + e.printStackTrace(); + apidatas.put("api_errormsg", "节点后附加操作执行失败!"); + } + }else{ + fail++; + } + } + apidatas.put("total", requestids.length); + apidatas.put("success", success); + apidatas.put("fail", fail); + }else{ + apidatas.put("api_errormsg", "The parameters passed in are not valid"); + } + return apidatas; + } + + /** + * 流程监控强制归档 + * @param requestId + * @param workflowId + */ + private void doRemind(int requestId,int workflowId){ + RequestRemindBiz remindBiz = new RequestRemindBiz(user); + + try{ + WFManager wfManager = new WFManager(); + wfManager.setWfid(workflowId); + wfManager.getWfInfo(); + RecordSet rs = new RecordSet(); + rs.executeQuery("select remindscope from workflow_base where id = ? ", workflowId); + rs.next(); + int remindscope = Util.getIntValue(rs.getString("remindscope"),0); + if (remindscope ==1) { + remindBiz.requestRemind(requestId,workflowId,"", RemindTypeEnum.EMAIL,0); + } else { + + String isArchiveNoRemind = wfManager.getIsArchiveNoRemind(); + if("1".equals(isArchiveNoRemind)) return; //强制归档不需要提醒 + + String isSms = wfManager.getIsDefaultSmsRemind(); + String isEmail = wfManager.getIsDefaultEmailRemind(); + if("1".equals(isEmail) ){ + remindBiz.requestRemind(requestId,workflowId,"", RemindTypeEnum.EMAIL,0); + } + if("1".equals(isSms)){ + remindBiz.requestRemind(requestId,workflowId, "",RemindTypeEnum.SMS,0); + } + + String archiveNoMsgAlert = wfManager.getArchiveNoMsgAlert(); + String archiveNoMailAlert = wfManager.getArchiveNoMailAlert(); + + String messageType = wfManager.getMessageType(); + String mailMessageType = wfManager.getMailMessageType(); + + if("1".equals(mailMessageType) && !"1".equals(archiveNoMailAlert)){ + remindBiz.requestRemind(requestId,workflowId,"", RemindTypeEnum.EMAIL,0); + } + if(!"1".equals(archiveNoMsgAlert)){ + if("2".equals(messageType)){ + remindBiz.requestRemind(requestId,workflowId, "",RemindTypeEnum.SMS,0); + } + if("1".equals(messageType)){ + remindBiz.requestRemind(requestId,workflowId,"", RemindTypeEnum.SMS,1); + } + } + } + }catch (Exception e){ + + } + } + + public HttpServletRequest getRequest() { + return request; + } + + public User getUser() { + return user; + } + @Override + public BizLogContext getLogContext() { + BizLogContext bizLogContext = new BizLogContext(); + BizLogOperateType bizLogOperateType = BizLogOperateType.APPROVE; + bizLogContext.setDateObject(new Date()); + bizLogContext.setUserid(user.getUID()); + bizLogContext.setUsertype(Util.getIntValue(user.getLogintype())); + bizLogContext.setTargetId("monitor_archiving"); + bizLogContext.setTargetName("流程强制归档"); + bizLogContext.setLogType(BizLogType.WORKFLOW); + bizLogContext.setLogSmallType(BizLogSmallType4Workflow.WORKFLOW_APPROVE); + bizLogContext.setOperateType(bizLogOperateType); + bizLogContext.setClientIp(Util.null2String(Util.getIpAddr(request))); + bizLogContext.setParams(ParamUtil.request2Map(request)); + bizLogContext.setDesc(String.format(user.getLastname() + "进行了流程强制归档操作")); + return bizLogContext; + } +} \ No newline at end of file diff --git a/src/com/engine/workflow/cmd/requestForm/FunctionManageCmd.java b/src/com/engine/workflow/cmd/requestForm/FunctionManageCmd.java new file mode 100644 index 0000000..535b7c9 --- /dev/null +++ b/src/com/engine/workflow/cmd/requestForm/FunctionManageCmd.java @@ -0,0 +1,375 @@ +package com.engine.workflow.cmd.requestForm; + +import com.api.workflow.util.ServiceUtil; +import com.cloudstore.dev.api.util.Util_TableMap; +import com.engine.common.biz.AbstractCommonCommand; +import com.engine.common.constant.BizLogOperateType; +import com.engine.common.constant.BizLogSmallType4Workflow; +import com.engine.common.constant.BizLogType; +import com.engine.common.entity.BizLogContext; +import com.engine.common.util.ParamUtil; +import com.engine.core.interceptor.CommandContext; +import com.engine.workflow.biz.WorkflowTestBiz; +import com.engine.workflow.biz.publicApi.RequestOperateBiz; +import com.engine.workflow.biz.requestForm.RequestRemindBiz; +import com.engine.workflow.biz.requestForm.SubmitErrorMsgBiz; +import com.engine.workflow.biz.requestForm.TestWorkflowCheckBiz; +import com.engine.workflow.biz.requestList.RequestAttentionBiz; +import com.engine.workflow.biz.workflowOvertime.OvertimeBiz; +import com.engine.workflow.constant.RemindTypeEnum; +import com.engine.workflow.constant.requestForm.RequestExecuteType; +import com.engine.workflow.entity.requestForm.RequestOperationResultBean; +import weaver.conn.RecordSet; +import weaver.file.FileUpload; +import weaver.general.BaseBean; +import weaver.general.Util; +import weaver.hrm.User; +import weaver.systeminfo.SystemEnv; +import weaver.workflow.agent.AgentManager; +import weaver.workflow.msg.MsgPushUtil; +import weaver.workflow.msg.entity.MsgEntity; +import weaver.workflow.request.*; +import weaver.workflow.workflow.*; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.util.*; + +/** + * 功能管理 + * @author liuzy 2018/5/4 + */ +public class FunctionManageCmd extends AbstractCommonCommand>{ + + private HttpServletRequest request; + private HttpServletResponse response; + + public FunctionManageCmd(HttpServletRequest request, HttpServletResponse response, User user){ + this.request = request; + this.response = response; + this.user = user; + } + + public Map execute(CommandContext commandContext){ + Map apidatas = new HashMap(); + + Map resultmap = new HashMap(); + int logintype = Util.getIntValue(user.getLogintype()); + int requestid = Util.getIntValue(request.getParameter("requestid"), 0); + String flag = Util.null2String(request.getParameter("flag")); + WfFunctionManageUtil wffmu = new WfFunctionManageUtil(); + ArrayList requestidlist = new ArrayList(); + + int formid = Util.getIntValue(request.getParameter("formid"), 0); + int requestLogId = Util.getIntValue(request.getParameter("workflowRequestLogId"), 0); + String signdocids = Util.null2String(request.getParameter("signdocids")); + String signworkflowids = Util.null2String(request.getParameter("signworkflowids")); + String remark = Util.null2String(request.getParameter("remark")); + int workflowid = Util.getIntValue(request.getParameter("workflowid"), 0); + int nodeid = -1; + + + String isnew = new BaseBean().getPropValue("WorkflowOvertimeIsNew" , "isNew"); + boolean isnewFlag = "1".equals(isnew); + // 流程暂停 + if ("stop".equals(flag)) { + wffmu.setStopOperation(requestid, user); +// this.pushOperationMsg(requestid,user,flag); + if(isnewFlag) + OvertimeBiz.getInstance().cancelOvertimeTask(requestid, nodeid);//取消超时任务 + } + + // 流程撤销 + if ("cancel".equals(flag)) { + wffmu.setCancelOperation(requestid, user); +// this.pushOperationMsg(requestid,user,flag); + if(isnewFlag) + OvertimeBiz.getInstance().cancelOvertimeTask(requestid, nodeid);//取消超时任务 + } + + // 流程启用 + if ("restart".equals(flag)) { + wffmu.setRestartOperation(requestid, user); +// this.pushOperationMsg(requestid,user,flag); + if(isnewFlag) + OvertimeBiz.getInstance().addOvertimeTaskThread(requestid, workflowid, nodeid);//添加超时任务 + } + + + // 强制归档 + if ("ov".equals(flag)) { + WfForceOver wfo = new WfForceOver(); + String annexdocids = ""; + String fromflow = Util.null2String(request.getParameter("fromflow")); + String remarkLocation = Util.null2String(request.getParameter("remarkLocation")); + + int agentType = Util.getIntValue(Util.null2String(request.getParameter("agentType"))); + int agentorByAgentId = Util.getIntValue(Util.null2String(request.getParameter("agentorByAgentId"))); + if (agentType == 1) {//流程代理出去,本人强制归档,需先收回代理 + AgentManager agentManager = new AgentManager(user); + agentManager.agentBackRequest(agentorByAgentId, user.getUID(), workflowid + "", requestid); + Date currentDate = new Date(); + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd"); + SimpleDateFormat timeForamt = new SimpleDateFormat("HH:mm:ss"); + new RecordSet().executeUpdate("update workflow_currentoperator set operatedate = ? , operatetime = ? where userid = ? and requestid = ? and (operatedate is null or operatedate < ' ' ) ", + dateFormat.format(currentDate), timeForamt.format(currentDate), user.getUID(), requestid); + } + + if (fromflow.equals("1")) { + FileUpload fu = new FileUpload(request); + remark = Util.null2String(fu.getParameter("remark")); + workflowid = Util.getIntValue(fu.getParameter("workflowid"), -1); + nodeid = Util.getIntValue(fu.getParameter("nodeid"), -1); + + // 获取签字意见相关文档,相关流程 + + signdocids = Util.null2String(fu.getParameter("signdocids")); + signworkflowids = Util.null2String(fu.getParameter("signworkflowids")); + String ismode = Util.null2String(request.getParameter("ismode")); + if (!ismode.equals("1")) { + RequestAnnexUpload rau = new RequestAnnexUpload(); + rau.setRequest(fu); + rau.setUser(user); + annexdocids = rau.AnnexUpload(); + } else { + String hasSign = "0";// 模板中是否设置了签字 + RecordSet rs = new RecordSet(); + rs.executeSql("select * from workflow_modeview where formid=" + formid + " and nodeid=" + nodeid + " and fieldid=-4"); + if (rs.next()) + hasSign = "1"; + if ("1".equals(hasSign)) {// 模板中设置了签字 + annexdocids = Util.null2String(fu.getParameter("qianzi")); + } else {// 模板中没有设置签字,按普通方式上传签字意见的附件 + RequestAnnexUpload rau = new RequestAnnexUpload(); + rau.setRequest(fu); + rau.setUser(user); + annexdocids = rau.AnnexUpload(); + } + } + + + WFManager wfManager = new WFManager(); + wfManager.setWfid(workflowid); + try { + wfManager.getWfInfo(); + } catch (Exception e) { + e.printStackTrace(); + } + String isShowChart = Util.null2s(wfManager.getIsShowChart().trim(),"0"); + apidatas.put("isShowChart", isShowChart); + } + + wfo.setRemark(remark); + wfo.setAnnexdocids(annexdocids); + wfo.setSigndocids(signdocids); + wfo.setSignworkflowids(signworkflowids); + wfo.setRequestLogId(requestLogId); + wfo.setRemarkLocation(remarkLocation); + + WFUrgerManager wfum = new WFUrgerManager(); + if (wffmu.haveOtherOperationRight(requestid) && !wfo.isOver(requestid) && (wfo.isNodeOperator(requestid, user.getUID()) || wfum.getMonitorViewRight(requestid, user.getUID()))) { + requestidlist.add("" + requestid); + wfo.doForceOver(requestidlist, request, response, user); + apidatas.put("success",1); + if(isnewFlag) + OvertimeBiz.getInstance().cancelOvertimeTask(requestid, nodeid);//取消超时任务 + + //no.2545225 强制归档需要触发节点附加操作,实现一键审批 + try { + RequestManager requestManager = new RequestManager(); + requestManager.setUser(user); + requestManager.setWorkflowid(workflowid); + requestManager.setRequestid(requestid); + WorkflowComInfo wfComInfo = new WorkflowComInfo(); + int tempformid = Util.getIntValue(wfComInfo.getFormId(workflowid+"")); + int tempisbill = Util.getIntValue(wfComInfo.getIsBill(workflowid+"")); + String sql2 = "select nodeid from workflow_flownode where workflowid = ? and nodetype = 3"; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql2,workflowid); + int tempnodeid = -1; + if(recordSet.next()) { + tempnodeid = recordSet.getInt("nodeid"); + } + RequestCheckAddinRules requestCheckAddinRules = new RequestCheckAddinRules(); + requestCheckAddinRules.resetParameter(); + requestCheckAddinRules.setWorkflowid(workflowid); + requestCheckAddinRules.setRequestid(requestid); + requestCheckAddinRules.setNodeid(tempnodeid); + requestCheckAddinRules.setObjid(tempnodeid); + requestCheckAddinRules.setObjtype(1); + requestCheckAddinRules.setIsbill(tempisbill); + requestCheckAddinRules.setFormid(tempformid); + requestCheckAddinRules.setIspreadd("0"); + requestCheckAddinRules.setRequestManager(requestManager); + requestCheckAddinRules.checkAddinRules(); + } catch (Exception e) { + e.printStackTrace(); + } + + }else{ + apidatas.put("success",0); + } + //判断是否属于流程测试 + TestWorkflowCheckBiz testBiz = new TestWorkflowCheckBiz(); + boolean belongTest = testBiz.judgeBelongTest(request, false); + if(belongTest) { + RecordSet rs = new RecordSet(); + rs.executeQuery("select nodeid from workflow_flownode where workflowid = ? and nodetype = 3",workflowid); + rs.next(); + WorkflowTestBiz.setWorkflowTestInfo(flag, requestid, nodeid, "", null,rs.getInt("nodeid")); + } + + this.doArchiveRemind(workflowid,requestid); + + new weaver.cpt.util.CptWfUtil().releaseFrozenCptnum(requestid+""); //清除资产冻结 + } + + // 强制收回 + if ("rb".equals(flag)) { + WfForceDrawBack wfdb = new WfForceDrawBack(); + RequestForceDrawBack requestForceDrawBack = new RequestForceDrawBack(); + RequestOperationResultBean resultBean = new RequestOperationResultBean(); + if (wffmu.haveOtherOperationRight(requestid) && wfdb.isHavePurview(requestid, user.getUID(), logintype, -1, -1)) { + requestidlist.add("" + requestid); + // WfForceDrawBack.doForceDrawBack(requestidsArr, request, + // response, -1, -1); + // 使用新的收回方式 + String sessionkey = workflowid + "_" + nodeid + "_" + user.getUID() + "_" + System.currentTimeMillis(); + int result = requestForceDrawBack.foreceDrawBack(user, requestid, false, -1, -1); + if (!requestForceDrawBack.isAddInOperateSuccess()) {//强制收回附加操作执行失败,返回错误信息 + String message = requestForceDrawBack.getMessage(); + String messagecontent = requestForceDrawBack.getMessageContent(); + if("".equals(message) || requestid <= 0) { + message = "1"; + } + resultBean.setMessageInfo(SubmitErrorMsgBiz.getMsgInfo(request,user,message,messagecontent)); + resultBean.setType(RequestExecuteType.FAILD); + Util_TableMap.setObjVal(Util.null2String(sessionkey), resultBean); + apidatas.put("success",false); + apidatas.put("msg",SystemEnv.getHtmlLabelNames("506175,83071",user.getLanguage())); + return apidatas; + } + if (result == RequestForceDrawBack.OLDDATA) { + wfdb.doForceDrawBack(requestidlist, request, response, -1, -1); + } + RequestOperateBiz.drawBackSpecialTreatment(formid, workflowid); + + /*E9打印登录超时报错(QC:527424)*/ + if(user == null) { + try { + response.sendRedirect(weaver.general.GCONST.getContextPath()+"/wui/index.html"); + return null; + } catch (IOException e) { + e.printStackTrace(); + } + } + //判断是否可以跳转到新的页面 + boolean reqRoute = ServiceUtil.isReqRoute(String.valueOf(requestid),user); + apidatas.put("reqRoute", reqRoute); + apidatas.put("success",result == RequestForceDrawBack.SUCCESS); + if(result == RequestForceDrawBack.SUCCESS){ + apidatas.put("msg",SystemEnv.getHtmlLabelName(83585,user.getLanguage())); + }else if(result == RequestForceDrawBack.FAIL){ + apidatas.put("msg",SystemEnv.getHtmlLabelName(389102,user.getLanguage())); + }else if(result == RequestForceDrawBack.NORIGHT){ + apidatas.put("msg",SystemEnv.getHtmlLabelName(18567,user.getLanguage())); + } + apidatas.put("sessionkey", sessionkey); + }else { + apidatas.put("success",false); + apidatas.put("msg",SystemEnv.getHtmlLabelName(18567,user.getLanguage())); + } + } + //自动取消 流程关注 + new RequestAttentionBiz().cancelAttention(requestid,flag); + return apidatas; + } + + @Override + public BizLogContext getLogContext() { + String targetName = ""; + String flag = Util.null2String(request.getParameter("flag")); + if ("stop".equals(flag)) { + targetName = "流程暂停"; + } else if ("cancel".equals(flag)) { + targetName = "流程撤销"; + } else if ("restart".equals(flag)) { + targetName = "流程启用"; + } else if ("ov".equals(flag)) { + targetName = "强制归档"; + } else if ("rb".equals(flag)) { + targetName = "强制收回"; + } + BizLogContext bizLogContext = new BizLogContext(); + BizLogOperateType bizLogOperateType = BizLogOperateType.APPROVE; + bizLogContext.setDateObject(new Date()); + bizLogContext.setUserid(user.getUID()); + bizLogContext.setUsertype(Util.getIntValue(user.getLogintype())); + bizLogContext.setTargetId("request_functionlink_" + flag); + bizLogContext.setTargetName(targetName); + bizLogContext.setLogType(BizLogType.WORKFLOW); + bizLogContext.setLogSmallType(BizLogSmallType4Workflow.WORKFLOW_APPROVE); + bizLogContext.setOperateType(bizLogOperateType); + bizLogContext.setClientIp(Util.null2String(Util.getIpAddr(request))); + bizLogContext.setParams(ParamUtil.request2Map(request)); + bizLogContext.setDesc(String.format(user.getLastname() + "进行了"+targetName+"操作")); + return bizLogContext; + } + + + /** + * 暂停、撤销、启用消息数据 + * @param requestId + * @param user + * @param flag + */ + private boolean pushOperationMsg(int requestId,User user,String flag){ + + RequestOperationMsgManager romm = new RequestOperationMsgManager(); + List requestMsgEntity = romm.getOperateMsgByReqId(String.valueOf(requestId),user,flag); + new MsgPushUtil().pushMsg(requestMsgEntity); + return true; + } + + + private void doArchiveRemind(int workflowid,int requestid){ + String src = Util.null2String(request.getParameter("src")); + String remindTypes = Util.null2String(request.getParameter("remindTypes")); //表单上提醒方式 + RequestRemindBiz requestRemindBiz = new RequestRemindBiz(user); + //默认提醒 + WFManager wfManager = new WFManager(); + try{ + wfManager.setWfid(workflowid); + wfManager.getWfInfo(); + }catch (Exception e){} + + if("-1".equals(remindTypes)){ //老数据 + int messageType = Util.getIntValue(Util.null2String(request.getParameter("messageType")),-1); // 老短信提醒 + int mailMessageType = Util.getIntValue(Util.null2String(request.getParameter("chatsType")),-1); // 老邮件提醒 + if(messageType >=1) requestRemindBiz.requestRemind(requestid,workflowid,src, RemindTypeEnum.SMS,messageType); + //历史数据可能只有短信提醒,但是其实也开启了邮件提醒 + int _mailMessageType = Util.getIntValue(wfManager.getMailMessageType(),-1); + if(mailMessageType == 1 || _mailMessageType == 1) requestRemindBiz.requestRemind(requestid,workflowid,src,RemindTypeEnum.EMAIL,0); + Set remindType = new HashSet<>(); + if(messageType >=1) { + requestRemindBiz.requestRemind(requestid,workflowid,src,RemindTypeEnum.SMS,messageType); + } + if(mailMessageType == 1 || _mailMessageType == 1) { + requestRemindBiz.requestRemind(requestid,workflowid,src,RemindTypeEnum.EMAIL,0); + } + }else{ + + String isSmsRemind = remindTypes.indexOf(RemindTypeEnum.SMS.getCode()) > -1 ? "1" : "0"; + String isEmailRemind = remindTypes.indexOf(RemindTypeEnum.EMAIL.getCode()) > -1 ? "1" : "0"; + if("1".equals(isSmsRemind)) requestRemindBiz.requestRemind(requestid,workflowid,src,RemindTypeEnum.SMS,0); + if("1".equals(isEmailRemind)) requestRemindBiz.requestRemind(requestid,workflowid,src,RemindTypeEnum.EMAIL,0); + } + requestRemindBiz.requestEmailApproveRemind(String.valueOf(workflowid),String.valueOf(requestid),src); + } + + public HttpServletRequest getRequest() { + return request; + } +} \ No newline at end of file diff --git a/src/weaver/formmode/excel/ImpExcelReader.java b/src/weaver/formmode/excel/ImpExcelReader.java new file mode 100644 index 0000000..6d0135d --- /dev/null +++ b/src/weaver/formmode/excel/ImpExcelReader.java @@ -0,0 +1,5832 @@ +/* + * ExpExcelWriter.java Created on 2017年1月5日 16:14:48 by cdy + * + * Copyright (c) 2001-2017 泛微软件, 版权所有. + */ +package weaver.formmode.excel; + +import com.api.cube.cache.CustomTreeComInfo; +import com.api.cube.util.CubeCipherUitl; +import com.api.cube.util.CubeUtil; +import com.api.formmode.cache.ModeFormFieldEncryptComInfo; +import com.engine.cube.biz.ShardingActionHelper; +import com.engine.cube.biz.VSqlUtil; +import com.engine.cube.util.AddSeclevelUtil; +import com.engine.cube.util.SaveConditionUtil; +import com.greenpineyu.fel.FelEngine; +import com.greenpineyu.fel.FelEngineImpl; +import com.greenpineyu.fel.context.FelContext; +import com.weaver.formmodel.util.DateHelper; +import com.weaver.formmodel.util.StringHelper; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.Sheet; +import weaver.conn.RecordSet; +import weaver.conn.RecordSetTrans; +import weaver.dateformat.DateTransformer; +import weaver.dateformat.TimeZoneVar; +import weaver.docs.docs.DocImageManager; +import weaver.file.ExcelParseForPOI; +import weaver.formmode.cache.StringCacheMap; +import weaver.formmode.dao.BaseDao; +import weaver.formmode.data.FieldInfo; +import weaver.formmode.data.ModeDataIDUpdateSingle; +import weaver.formmode.data.ModeDataIdUpdate; +import weaver.formmode.interfaces.ImportFieldTransAction; +import weaver.formmode.interfaces.ImportFieldTransActionPOI; +import weaver.formmode.interfaces.InterfacesUtil; +import weaver.formmode.log.FormmodeLog; +import weaver.formmode.service.FormInfoService; +import weaver.formmode.service.SelectItemPageService; +import weaver.formmode.setup.ModeSetUtil; +import weaver.formmode.tree.CustomTreeData; +import weaver.general.SplitPageParaBean; +import weaver.general.SplitPageUtil; +import weaver.general.Util; +import weaver.hrm.User; +import weaver.interfaces.workflow.browser.Browser; +import weaver.interfaces.workflow.browser.BrowserBean; +import weaver.systeminfo.SystemEnv; +import weaver.conn.ConnectionPool; +import weaver.conn.constant.DBConstant; +import java.math.BigDecimal; +import java.text.MessageFormat; +import java.text.NumberFormat; +import java.util.*; +import java.util.concurrent.CountDownLatch; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + + +/** + * Description: CreateExcelServer.java + * + * @author dongping + * @version 1.0 2005-4-21 + */ +public class ImpExcelReader extends FormmodeLog implements Runnable { + private String action; + private CountDownLatch doneSignal; + private int start; + private int end; + private String threadname; + private int currentIndex; + private String key; + private Sheet sheet; + Map params; + private User user; + private int formid; + private int modeid; + private Map> validateMap; + private Map IdMap; + private ArrayList errorRow; + private Map checkMap; + private String clientaddress; + private ArrayList errorTable; + //导入明细表时用 + private FieldInfo FieldInfo; + private String maintable; + private Map map; + private String Errmsg; + private int sheetIndex; + /** + * 默认共享是否与明细表字段有关,如果有关,则权限重构需等到明细表插入完成才重构,否则可以主表插入一条就重构一条 + */ + private boolean isdetailright = false; + private List billList; + private List rowNumList; + private HashMap creatoridMap; + private List addBillIdList; + private List detailList; + private List updateList; + private List errorRowList; + private Hashtable> errorDetailMap; + private Map customBrowserMap = new HashMap(); + private Map>> treeBaseMap = new HashMap>>(); + private ModeFormFieldEncryptComInfo modeFormFieldEncryptComInfo = new ModeFormFieldEncryptComInfo(); + private Map modeVFormMap = new HashMap(); + private Map modeLogMap;//记录主表id及对应的viewlogid + private int realRows; + private String timezone; + private ModeDataIDUpdateSingle modeDataIDUpdateSingle = ModeDataIDUpdateSingle.INSTANCE; + //明细日志信息处理 + private String columnNames_d; + private Map columnFieldids_d = new HashMap(); + + private List> impFieldIds;//记录excel中字段顺序 + private Object fieldTransObject; + private List fieldtranslist; + private jxl.Sheet sheetJXL; + private static final int pageSize = 1000;//1000条查询一次 + + public ImpExcelReader() { + super(); + } + + @SuppressWarnings("unchecked") + public ImpExcelReader(String action, CountDownLatch doneSignal, int start, int end, int currentIndex, + String key, Sheet sheet, Map params, User user, int formid + , int modeid, Map validateMap, Map IdMap, Map checkMap, ArrayList errorRow + , String clientaddress, String threadname + //子表需要的参数 + , FieldInfo FieldInfo, + HashMap map, String maintable, String Errmsg, int sheetIndex + , List billList, HashMap creatoridMap, List addBillIdList, List detailList, List operatelList, List errorRowList, Hashtable> errorDetailMap, int realRows, List rowNumList, Map modeLogMap, ArrayList errorTable + , String timezone, boolean isdetailright, List> impFieldIds + ) { + this.action = action; + this.doneSignal = doneSignal; + this.start = start; + this.end = end; + this.currentIndex = currentIndex; + this.key = key; + this.sheet = sheet; + this.params = params; + this.user = user; + this.formid = formid; + this.modeid = modeid; + this.validateMap = validateMap; + this.IdMap = IdMap; + this.checkMap = checkMap; + this.clientaddress = clientaddress; + this.threadname = threadname; + this.errorTable = errorTable; + this.FieldInfo = FieldInfo; + this.map = map; + this.errorRow = errorRow; + this.maintable = maintable; + this.Errmsg = Errmsg; + this.sheetIndex = sheetIndex; + this.billList = billList; + this.creatoridMap = creatoridMap; + this.addBillIdList = addBillIdList; + this.detailList = detailList; + this.updateList = operatelList; + this.errorRowList = errorRowList; + this.errorDetailMap = errorDetailMap; + this.realRows = realRows; + this.rowNumList = rowNumList; + this.modeLogMap = modeLogMap; + this.isdetailright = isdetailright; + this.timezone = timezone; + this.impFieldIds = impFieldIds; + this.fieldTransObject = this.params.get("fieldTransObject"); + if (fieldTransObject != null) { + fieldtranslist = (List) this.params.get("fieldtranslist"); + sheetJXL = (jxl.Sheet) this.params.get("sheetJXL"); + } + } + + public void run() { + this.initDepartAndSubpany(); + if (this.action.equals("importMainData")) { + importMainData(); + } else if (this.action.equals("importDetailData")) { + importDetailData(); + } + } + + private void importDetailData() { + ExpExcelUtil.refreshImpUserState(user.getUID(), key);//刷新导入状态 + try { + InterfacesUtil InterfacesUtil = new InterfacesUtil(); + RecordSet recordSet = new RecordSet(); + RecordSet rs = new RecordSet(); + String sql = ""; + ArrayList detailTableFields = FieldInfo.getDetailTableFields(); + if (detailTableFields.size() == 0) { + FieldInfo tempFieldInfo = new FieldInfo(); + tempFieldInfo.setUser(user); + int isHaveTemplate = 0; + String templateSql = "select 1 from mode_import_template a where modeid=" + modeid + " and formid=" + formid + " and (exists(select 1 from workflow_billfield b where b.billid=" + formid + " and b.id=a.fieldid) or a.fieldid in(-1000,-1001,-1002)) "; + rs.execute(templateSql); + if (rs.getCounts() > 0) { + isHaveTemplate = 1; + } + if (isHaveTemplate == 1) { + tempFieldInfo.GetDetailTableFieldToExcelTemplate(formid, 1, user.getLanguage(), modeid);//根据模块导入模板获得明细字段 + } else { + tempFieldInfo.GetDetailTableFieldToExcel(formid, 1, user.getLanguage());//获得明细字段 + } + this.FieldInfo = tempFieldInfo; + detailTableFields = FieldInfo.getDetailTableFields(); + } + ArrayList detailTableFieldIds = FieldInfo.getDetailTableFieldIds(); + ArrayList detailtablefieldnames = FieldInfo.getDetailDBFieldNames(); + ArrayList detailtablefielddbtypes = FieldInfo.getDetailFieldDBTypes(); + ArrayList detailtablenames = FieldInfo.getDetailTableNames(); + ArrayList detailtablekeys = FieldInfo.getDetailTableKeys(); + ArrayList detailtableqfws = FieldInfo.getDetailQfwses(); + ArrayList detailtablelabelname = FieldInfo.getDetailTableFieldNames(); + ImpExcelUtil impExcelUtil = new ImpExcelUtil(); + impExcelUtil.setModeVFormMap(modeVFormMap); + String detailtable = ""; + String detailtablekey = ""; + int sheetcount = this.sheetIndex; + ExpExcelUtil.refreshImpUserState(user.getUID(), key);//刷新导入状态 + int subIndex = currentIndex - 1; + detailtable = Util.null2String((String) detailtablenames.get(subIndex)); + detailtablekey = Util.null2String((String) detailtablekeys.get(subIndex)); + if (detailtablekey.equals("")) { + detailtablekey = "mainid"; + } + map.put(detailtable, detailtablekey); + + ArrayList dtlfieldIdsTemp = (ArrayList) detailTableFieldIds.get(subIndex); + ArrayList dtlfieldsTemp = (ArrayList) detailTableFields.get(subIndex); + ArrayList dtlfieldnamesTemp = (ArrayList) detailtablefieldnames.get(subIndex); + ArrayList dtlfielddbtypesTemp = (ArrayList) detailtablefielddbtypes.get(subIndex); + ArrayList dtlqwfsTemp = (ArrayList) detailtableqfws.get(subIndex); + ArrayList dtfieldlabelnameTemp = (ArrayList) detailtablelabelname.get(subIndex); + + //excel中的明细表信息 + ArrayList dtlfields = new ArrayList(); + ArrayList dtlFieldIds = new ArrayList(); + ArrayList dtlfieldnames = new ArrayList(); + ArrayList dtlfielddbtypes = new ArrayList(); + ArrayList dtlqwfs = new ArrayList(); + ArrayList dtfieldlabelname = new ArrayList(); + + List detailFieldIds = impFieldIds.get(subIndex + 1);//excel中的明细表字段id + int mainIdCol = detailFieldIds.indexOf("-2001"); + for (int i = 0, len = detailFieldIds.size(); i < len; i++) { + int fieldId = Util.getIntValue(detailFieldIds.get(i)); + if (fieldId <= 0) { + continue; + } + int index = dtlfieldIdsTemp.indexOf(detailFieldIds.get(i)); + dtlfields.add(dtlfieldsTemp.get(index)); + dtlfieldnames.add(dtlfieldnamesTemp.get(index)); + dtlfielddbtypes.add(dtlfielddbtypesTemp.get(index)); + dtlqwfs.add(dtlqwfsTemp.get(index)); + dtfieldlabelname.add(dtfieldlabelnameTemp.get(index)); + dtlFieldIds.add(fieldId); + } + if (dtlfields.size() > 0) { + FormInfoService formInfoService = new FormInfoService(); + List> needlogFieldList = formInfoService.getNeedlogField_detail(formid, detailtable); + if (needlogFieldList.size() > 0) { + for (int i = 0; i < needlogFieldList.size(); i++) { + Map needlogField = needlogFieldList.get(i); + String fieldname = Util.null2String(needlogField.get("fieldname")); + String fieldid = Util.null2String(needlogField.get("id")); + if (this.columnNames_d == null || this.columnNames_d.equals("")) { + this.columnNames_d = fieldname; + } else { + this.columnNames_d += "," + fieldname; + } + this.columnFieldids_d.put(fieldname, fieldid); + } + } + + boolean canImport = ImpExcelServer.getProgressCanImport(key); + int rows = start; + if (rows == 0) { + rows = 1; + } + if (end >= realRows + 1) { + end = realRows; + } + + NumberFormat nf = NumberFormat.getInstance(); + nf.setGroupingUsed(false); + nf.setMaximumFractionDigits(100); + List indexList = new ArrayList(); + while (canImport = ImpExcelServer.getProgressCanImport(key) && rows <= end && rows >= start) { + if (StringCacheMap.containsKey(key + "_cancel")) { + break; + } + rowNumList.add(1); + if (rowNumList.size() % 20 == 0) { + ExpExcelUtil.refreshImpUserState(user.getUID(), key);//刷新导入状态 + } + ImpExcelServer.writeProgressMsg(key, MessageFormat.format(SystemEnv.getHtmlLabelName(132242, user.getLanguage()), sheetIndex) + ":" + rowNumList.size() + "/" + (POIUtil.getLastRowNum(sheet) - 1), "0"); + + String detailid = Util.null2String(POIUtil.getValue(sheet, rows, mainIdCol)).trim(); + String mainids = Util.null2String(IdMap.get(detailid)); + String[] mainidarr = mainids.split(","); + for (String _mainid : mainidarr) { + String sql1 = ""; + String sql2 = ""; + boolean flag = false; + boolean isnull = true; + boolean iserrordata = false; + int mainid = Util.getIntValue(_mainid, 0); + String Countsql = Util.null2String(IdMap.get(detailid + "sql")); + + Map> oldData_detail = new HashMap>(); + if (needlogFieldList.size() > 0) { + oldData_detail = formInfoService.getTableData(detailtable, mainid, this.columnNames_d, "id", "mainid"); + } + boolean rowCanImport = true;//当前行进行验证,如,设置了导入字段必填,如果值为空则不允许导入当前行 + indexList.clear(); + // 生成插入sql + for (int k = 0; k < dtlFieldIds.size(); k++) { + boolean isDepSup = false; //全路径导入的>处理 + String f = StringHelper.null2String(dtlfields.get(k)); + String[] arr = f.split("_"); + String dhtmltype = ""; + if (arr.length == 4) { + dhtmltype = arr[3]; + //if(dhtmltype.equals("6")){ + // continue; + //} + } + String detailFieldId = Util.null2String(dtlFieldIds.get(k)); + int col = detailFieldIds.indexOf(detailFieldId); + ArrayList tempfields = Util.TokenizerString((String) dtlfields.get(k), "_"); + int type = Util.getIntValue((String) tempfields.get(2)); + int htmltype = Util.getIntValue((String) tempfields.get(3)); + // Cell cell = sheet.getCell(col, rows); + String tempvalue = ""; + if ((type == 5 || type == 4 || type == 3) && htmltype == 1) {//浮点数的话避免被四舍五入 + tempvalue = POIUtil.getValue(sheet, rows, col); + } else { + tempvalue = Util.null2String(POIUtil.getValue(sheet, rows, col)); + if (type == 1 && htmltype == 1) {//文本 + tempvalue = tempvalue.replaceAll("\\n", ""); + if ("1".equals(modeFormFieldEncryptComInfo.getIsencrypt(detailFieldId))) { + tempvalue = CubeCipherUitl.encrypt(tempvalue); + } + // if(cell.getType() == CellType.NUMBER) { + // int dindex = tempvalue.indexOf("."); + // if(dindex!=-1){//不包含小数点,直接导入 + // double tempDoubleVal=((NumberCell)cell).getValue(); + // tempvalue=nf.format(tempDoubleVal);//避免转换为值的时候变为科学计数法 + // } + // } + } + if (htmltype == 3 && (type == 161 || type == 162)) { + tempvalue = CubeCipherUitl.getBrowserEncryptValueImp(Util.null2String(dtlfielddbtypes.get(k)), tempvalue, type + ""); + } + } + + tempvalue = StringHelper.convertSpecialChar2Html(tempvalue); + String tempvalueForIdentify = tempvalue; + String detailfieldid = Util.null2String((String) tempfields.get(0)).replaceAll("field", ""); + + //根据条件来判断是否必填 + String tempCondition = ""; + String tempHead = ""; + String tempFieldName = ""; + boolean validateflag = false; + for (Map.Entry> et : validateMap.entrySet()) { + String key = et.getKey(); + if (detailfieldid.equals(key)) { + List value = et.getValue(); + if (value.size() == 0) { + tempHead = Util.null2String(POIUtil.getValue(sheet, 0, col)); + validateflag = true; + break; + } + for (String selectid : value) { + String[] values = selectid.split(":"); + int temp_index = -1; + for (int n = 0; n < dtlfields.size(); n++) { + String tempField = (String) dtlfields.get(n); + if (tempField.indexOf("field" + values[0]) > -1) { + temp_index = n; + break; + } + } + if (Util.null2String(POIUtil.getValue(sheet, rows, temp_index + 1)).equals(values[1])) { + tempCondition = Util.null2String(POIUtil.getValue(sheet, rows, temp_index + 1)); + tempHead = Util.null2String(POIUtil.getValue(sheet, 0, col)); + tempFieldName = Util.null2String(POIUtil.getValue(sheet, 0, temp_index + 1)); + validateflag = true; + break; + } + } + } + if (validateflag) { + break; + } + } + + + if (tempvalue.equals("") && validateflag) { + if (!tempCondition.equals("")) { + tempCondition = MessageFormat.format(SystemEnv.getHtmlLabelName(132243, user.getLanguage()), tempFieldName, tempCondition, tempHead); + } else { + tempCondition = MessageFormat.format(SystemEnv.getHtmlLabelName(132244, user.getLanguage()), tempHead); + } + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + "" + tempCondition); + if (mainid > 0) { + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + "" + tempCondition + "+" + dtfieldlabelname.get(k) + + "+" + dtlfieldnames.get(k) + "+" + dtlfielddbtypes.get(k) + "+" + detailtable + "+" + + SystemEnv.getHtmlLabelName(19325, user.getLanguage()) + dtfieldlabelname.get(k) + tempCondition); + } + indexList.add((String) errorRow.get(errorRow.size() - 1)); //获得当前错误提示的idnex + rowCanImport = false; + } + // excel值转换 + if (!tempvalue.equals("")) { + isnull = false; + String fieldid = Util.null2String(dtlFieldIds.get(k)); + if (fieldTransObject != null && fieldtranslist.contains(fieldid)) {//调用自定义转换接口 + this.params.put("fieldid", fieldid); + this.params.put("fieldname", "d" + currentIndex + "_" + dtlfieldnames.get(k)); + if (fieldTransObject instanceof ImportFieldTransAction) { + ImportFieldTransAction fieldTrans = (ImportFieldTransAction) fieldTransObject; + tempvalue = fieldTrans.getTransValue(this.params, user, sheetJXL, rows, col); + } else if (fieldTransObject instanceof ImportFieldTransActionPOI) { + ImportFieldTransActionPOI fieldTrans = (ImportFieldTransActionPOI) fieldTransObject; + ExcelParseForPOI excelParse = (ExcelParseForPOI) this.params.get("excelParse"); + tempvalue = fieldTrans.getTransValue(this.params, user, excelParse, (rows + 1), (col + 1)); + } + } else { + tempvalue = tempvalue.replace("'", "''"); + if (type == 2 && htmltype == 1) {//整数 + Pattern pattern = Pattern.compile("^(-)?\\d+$"); + Matcher isFlag = pattern.matcher(tempvalue); + if (!isFlag.matches()) { + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + tempvalue + "," + SystemEnv.getHtmlLabelName(382376, user.getLanguage())); + if (mainid > 0) { + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + tempvalue + "+" + SystemEnv.getHtmlLabelName(382376, user.getLanguage()) + + "+" + dtfieldlabelname.get(k) + "+" + dtlfieldnames.get(k) + "+" + dtlfielddbtypes.get(k) + "+" + detailtable + + "+" + tempvalue + ":" + SystemEnv.getHtmlLabelName(382376, user.getLanguage()) + "," + SystemEnv.getHtmlLabelName(391252, user.getLanguage()) + "!"); + } + iserrordata = true; + tempvalue = ""; + } + } else if ((type == 3 || type == 4 || type == 5) && htmltype == 1) {//浮点数 + String excelVal = tempvalue; + tempvalue = tempvalue.replace(",", ""); + Pattern pattern = Pattern.compile("^(-)?(0|([1-9]\\d*))(.\\d+)?$"); //浮点数 + Matcher isFlag = pattern.matcher(tempvalue); + if (!isFlag.matches()) { + String errMsg = ""; + if (type == 3) { + errMsg = SystemEnv.getHtmlLabelName(382377, user.getLanguage()); + } else if (type == 4) { + errMsg = SystemEnv.getHtmlLabelName(382378, user.getLanguage()); + } else if (type == 5) { + errMsg = SystemEnv.getHtmlLabelName(382379, user.getLanguage()); + } + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + ",“" + excelVal + "”," + errMsg); + if (mainid > 0) { + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+“" + excelVal + "”+" + errMsg + + "+" + dtfieldlabelname.get(k) + "+" + dtlfieldnames.get(k) + "+" + dtlfielddbtypes.get(k) + + "+" + detailtable + "+" + excelVal + ":" + errMsg); + } + iserrordata = true; + tempvalue = ""; + } + } else if (htmltype == 3) { + //判断是否ID串 + boolean isNumber = false; + String[] number = tempvalue.split(","); + if (number != null && number.length > 0) { + for (String num : number) { + Pattern pattern = Pattern.compile("^(-)?[1-9][0-9]*$"); //验证正数或负数 + Matcher isNum = pattern.matcher(num.trim()); + if (!isNum.matches()) {//非数字 进行ID获取 + isNumber = false; + break; + } else { + isNumber = true; + } + } + } + + + //虚拟表单修改主键后 主键不一定是数字类型 不能用数字类型作为判断 只能检查主键数据中是否存在改数据 zwbo + if (!isNumber) { + if (type == 161 || type == 162) { //自定义单选和多选 + //浏览框为虚拟表单 并且修改主键 + Browser browser = ModeCacheManager.getInstance().getBrowserSetMap((String) dtlfielddbtypes.get(k)); + String browser_id = browser.getCustomid(); + if (!StringHelper.isEmpty(browser_id)) { + boolean isVFrom = false; + if (customBrowserMap.containsKey(browser_id)) { + isVFrom = customBrowserMap.get(browser_id); + } else { + RecordSet virrs = new RecordSet(); + virrs.execute("select a.formid,b.vprimarykey from mode_custombrowser a,modeformextend b where a.id =" + browser_id + " AND a.formid=b.formid "); + if (virrs.next()) { + isVFrom = true; + } + customBrowserMap.put(browser_id, isVFrom); + } + if (isVFrom && number.length > 0) { + BrowserBean browserBean = browser.searchById(number[0].trim()); + if (browserBean.getId() == null) { + isNumber = false; + } else { + isNumber = true; + } + } + } + } + } + //------------------------提取start------------------------------ + if (type == 2 || type == 19 || type == 403) { // 日期 + Cell cell = POIUtil.getCell(sheet, rows, col); + tempvalue = ImpExcelUtil.getDateOrTime(cell, tempvalue, type); + + if (tempvalue.startsWith("#@ERROR@#")) { + tempvalue = tempvalue.replace("#@ERROR@#", ""); + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + tempvalue + "," + SystemEnv.getHtmlLabelName(24944, user.getLanguage())); + if (mainid > 0) { + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + tempvalue + "+" + SystemEnv.getHtmlLabelName(24944, user.getLanguage()) + + "+" + dtfieldlabelname.get(k) + "+" + dtlfieldnames.get(k) + "+" + dtlfielddbtypes.get(k) + "+" + detailtable + + "+" + tempvalue + ":" + SystemEnv.getHtmlLabelName(24944, user.getLanguage())); + } + iserrordata = true; + tempvalue = ""; + } + } else if (type == 290) {//日期时间 + Cell cell = POIUtil.getCell(sheet, rows, col); + tempvalue = ImpExcelUtil.getDateTime(cell, tempvalue, type); + TimeZoneVar.setTimeZone(timezone); + tempvalue = "".equals(Util.null2String(tempvalue)) ? "" : new DateTransformer().getServerDateTime(tempvalue); + if (tempvalue != null && tempvalue.indexOf(":") != tempvalue.lastIndexOf(":")) { + tempvalue = tempvalue.substring(0, tempvalue.lastIndexOf(":")); + } + if (tempvalue.startsWith("#@ERROR@#")) { + tempvalue = tempvalue.replace("#@ERROR@#", ""); + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + tempvalue + "," + SystemEnv.getHtmlLabelName(24944, user.getLanguage())); + if (mainid > 0) { + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + tempvalue + "+" + SystemEnv.getHtmlLabelName(24944, user.getLanguage()) + + "+" + dtfieldlabelname.get(k) + "+" + dtlfieldnames.get(k) + "+" + dtlfielddbtypes.get(k) + "+" + detailtable + + "+" + tempvalue + ":" + SystemEnv.getHtmlLabelName(24944, user.getLanguage())); + } + iserrordata = true; + tempvalue = ""; + } + } else if (type == 402) {//年、年是int型,判断值是否是整数 + Pattern pattern = Pattern.compile("^(-)?\\d+$"); + Matcher isFlag = pattern.matcher(tempvalue); + if (!isFlag.matches()) { + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + tempvalue + "," + SystemEnv.getHtmlLabelName(382376, user.getLanguage())); + if (mainid > 0) { + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + tempvalue + "+" + SystemEnv.getHtmlLabelName(382376, user.getLanguage()) + + "+" + dtfieldlabelname.get(k) + "+" + dtlfieldnames.get(k) + "+" + dtlfielddbtypes.get(k) + "+" + detailtable + + "+" + tempvalue + ":" + SystemEnv.getHtmlLabelName(382376, user.getLanguage()) + "," + SystemEnv.getHtmlLabelName(391252, user.getLanguage()) + "!"); + } + iserrordata = true; + tempvalue = ""; + } + } else if ((type == 4 || type == 57 || type == 168 || type == 167) && (tempvalue.indexOf(">") > -1 || tempvalue.indexOf(this.sepCharacter) > -1 && this.isDepartAndSubpany)) {//如果部门里面有> 代表逐级导入 + ArrayList tempvalues = Util.TokenizerString(tempvalue, ","); + String temps = ""; + for (int n = 0; n < tempvalues.size(); n++) { + String temp = Util.null2String(tempvalues.get(n)); + Map tempvalueMap = getIdByPathName(1, temp); + if (Util.null2String(tempvalueMap.get("flag")).equals("0")) { + temp = tempvalueMap.get("value"); + } else { + boolean isflag = isDepartAndSubpany; + if (!isflag) { + errorRow.add(sheetcount + "," + rows + "," + col + "," + ((String) tempvalueMap.get("orgname")).trim()); + if (mainid > 0) { + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + ((String) tempvalueMap.get("orgname")).trim() + + "+" + dtfieldlabelname.get(k) + "+" + dtlfieldnames.get(k) + "+" + dtlfielddbtypes.get(k) + + "+" + detailtable + "+" + temp + ":" + SystemEnv.getHtmlLabelName(391288, user.getLanguage()) + "select id from hrmdepartment where departmentname='" + temp + "'"); + } + } else { + isDepSup = true; + } + } + temps += "," + temp; + } + if (temps.length() > 0) { + temps = temps.substring(1); + } + if (!isDepSup) { + tempvalue = temps; + } + } else if ((type == 164 || type == 169 || type == 170 || type == 194) && (tempvalue.indexOf(">") > -1 || tempvalue.indexOf(this.sepCharacter) > -1 && this.isDepartAndSubpany)) {//如果分部里面有> 代表逐级导入 + ArrayList tempvalues = Util.TokenizerString(tempvalue, ","); + String temps = ""; + for (int n = 0; n < tempvalues.size(); n++) { + String temp = Util.null2String(tempvalues.get(n)); + Map tempvalueMap = getIdByPathName(0, temp); + if (Util.null2String(tempvalueMap.get("flag")).equals("0")) { + temp = tempvalueMap.get("value"); + } else { + boolean isflag = isDepartAndSubpany; + if (!isflag) { + errorRow.add(sheetcount + "," + rows + "," + col + "," + ((String) tempvalueMap.get("orgname")).trim()); + if (mainid > 0) { + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + ((String) tempvalueMap.get("orgname")).trim() + + "+" + dtfieldlabelname.get(k) + "+" + dtlfieldnames.get(k) + "+" + dtlfielddbtypes.get(k) + + "+" + detailtable + "+" + temp + ":" + SystemEnv.getHtmlLabelName(391267, user.getLanguage()) + ":select id from HrmSubCompany where subcompanyname='" + temp + "'"); + } + } else { + isDepSup = true; + } + } + temps += "," + temp; + } + if (temps.length() > 0) { + temps = temps.substring(1); + } + if (!isDepSup) { + tempvalue = temps; + } + } else if ((type == 1 || type == 17 || type == 165 || type == 166) && tempvalue.indexOf(">") > -1) {//如果人员里面有> 代表逐级导入 + ArrayList tempvalues = Util.TokenizerString(tempvalue, ","); + String temps = ""; + for (int n = 0; n < tempvalues.size(); n++) { + String temp = Util.null2String(tempvalues.get(n)); + Map tempvalueMap = getIdByPathName(2, temp); + if (Util.null2String(tempvalueMap.get("flag")).equals("0")) { + temp = tempvalueMap.get("value"); + } else { + errorRow.add(sheetcount + "," + rows + "," + col + "," + ((String) tempvalueMap.get("orgname")).trim()); + if (mainid > 0) { + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + ((String) tempvalueMap.get("orgname")).trim() + + "+" + dtfieldlabelname.get(k) + "+" + dtlfieldnames.get(k) + "+" + dtlfielddbtypes.get(k) + "+" + detailtable + + "+" + temp + ":" + SystemEnv.getHtmlLabelName(391270, user.getLanguage()) + "select id from hrmresource where lastname='" + temp + "' and departmentid=0"); + } + } + temps += "," + temp; + } + if (temps.length() > 0) { + temps = temps.substring(1); + } + tempvalue = temps; + } else if (type == 224 || type == 225 || type == 226 || type == 227) { + tempvalue = tempvalue; + } else if ((type == 4 || type == 57) || (type == 164 || type == 194)) { //虚拟部门 + String flagStr = ""; + String keyname = ""; + String tablename = ""; + String keynameall = "";//支持全称导入 + if ((type == 4 || type == 57)) { + if (tempvalue.toLowerCase().startsWith("virtual_")) { + flagStr = "virtual_"; + if (tempvalue.startsWith("VIRTUAL_")) { + flagStr = "VIRTUAL_"; + } + keyname = "departmentmark"; + keynameall = "departmentname"; + tablename = "HrmDepartmentVirtual"; + } else if (tempvalue.startsWith("-")) { + keyname = "id"; + tablename = "HrmDepartmentVirtual"; + } else if (tempvalue.startsWith("deptcode_")) { + tablename = "HrmDepartment"; + keyname = "departmentcode"; + if (tempvalue.indexOf("deptcode_") != -1) { + tempvalue = tempvalue.replace("deptcode_", ""); + } else { + tempvalue = tempvalue.substring(9); + } + } else { + keyname = "departmentmark"; + tablename = "HrmDepartment"; + if (isNumber) { + keyname = "id"; + } else { + keynameall = "departmentname"; + } + } + } else if ((type == 164 || type == 194)) { + if (tempvalue.toLowerCase().startsWith("virtual_")) { + flagStr = "virtual_"; + if (tempvalue.startsWith("VIRTUAL_")) { + flagStr = "VIRTUAL_"; + } + //分部要优先简称导入 + keyname = "subcompanydesc"; + keynameall = "subcompanyname"; + tablename = "hrmsubcompanyvirtual"; + } else if (tempvalue.startsWith("-")) { + keyname = "id"; + tablename = "hrmsubcompanyvirtual"; + } else { + keyname = "subcompanydesc"; + tablename = "hrmsubcompany"; + if (isNumber) { + keyname = "id"; + } else { + keynameall = "subcompanyname"; + } + } + } + //部门及分部封存,人员离职过滤 + String hrmFilterCondiction = ""; + if ("HrmDepartment".equalsIgnoreCase(tablename.toLowerCase()) || "hrmsubcompany".equalsIgnoreCase(tablename.toLowerCase()) + || "HrmDepartmentVirtual".equalsIgnoreCase(tablename.toLowerCase()) || + "hrmsubcompanyvirtual".equalsIgnoreCase(tablename.toLowerCase())) { + hrmFilterCondiction = " and (canceled!=1 or canceled is null)"; + } + + ArrayList tempvalues = Util.TokenizerString(tempvalue, ","); + + ArrayList tempvalueForIdentifys = Util.TokenizerString(tempvalueForIdentify, ","); + tempvalue = ""; + String values = ""; + for (int n = 0; n < tempvalues.size(); n++) { + if (!((String) tempvalues.get(n)).trim().toLowerCase().startsWith(flagStr)) + continue; + values += ",'" + ((String) tempvalues.get(n)).trim().replace(flagStr, "") + "'"; + } + if (!StringHelper.isEmpty(values)) { + values = values.substring(1); + for (int n = 0; n < tempvalues.size(); n++) { + rs = new RecordSet(); + String value = ((String) tempvalues.get(n)).trim().replace(flagStr, ""); + value = checkDepartAndSubpany(value); + //添加判断value 是不是id 或者编号 + + String valueForIdentify = ((String) tempvalueForIdentifys.get(n)).trim().replace(flagStr, ""); + if (isNumberOrCode(valueForIdentify)) { + hrmFilterCondiction = ""; + } + if (!"".equals(keynameall)) { + sql = "select id," + keynameall + " as showname from " + tablename + " where " + keynameall + " ='" + value + "' " + hrmFilterCondiction + " order by id desc"; + rs.executeSql(sql); + } + if (rs.getCounts() <= 0) { + sql = "select id," + keyname + " as showname from " + tablename + " where " + keyname + " ='" + value + "' " + hrmFilterCondiction + " order by id desc"; + rs.executeSql(sql); + } + if (!rs.next()) {//判断是否为多语言 + if (!"".equals(keynameall)) { + String tempSqlTemp = "select id," + keynameall + " as showname from " + tablename + + " where (" + keynameall + " like '%" + "`~`7 " + value + "`~`" + "%' or " + keynameall + " like '%" + "`~`8 " + value + "`~`" + "%' or " + keynameall + " like '%" + "`~`9 " + value + "`~`" + "%')" + + hrmFilterCondiction + " order by id desc"; + rs.execute(tempSqlTemp); + } + if (rs.getCounts() <= 0) { + String tempSqlTemp = "select id," + keyname + " as showname from " + tablename + + " where (" + keyname + " like '%" + "`~`7 " + value + "`~`" + "%' or " + keyname + " like '%" + "`~`8 " + value + "`~`" + "%' or " + keyname + " like '%" + "`~`9 " + value + "`~`" + "%')" + + hrmFilterCondiction + " order by id desc"; + rs.execute(tempSqlTemp); + } + } + rs.beforFirst(); + boolean isExists = false; + while (rs.next()) { + String showname = rs.getString("showname"); + showname = Util.formatMultiLang(showname, user.getLanguage() + ""); + String tempValue = (String) tempvalues.get(n); + tempValue = checkDepartAndSubpany(tempValue.trim()); + String shownameNew = (flagStr + showname).replace("'", "''"); + if (shownameNew.equals(tempValue)) { + tempvalue += "," + rs.getString(1); + isExists = true; + break; + } + } + if (!isExists) { + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + ((String) tempvalues.get(n)).trim()); + if (mainid > 0) { + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + ((String) tempvalues.get(n)).trim() + + "+" + dtfieldlabelname.get(k) + "+" + dtlfieldnames.get(k) + "+" + dtlfielddbtypes.get(k) + + "+" + detailtable + "+" + ((String) tempvalues.get(n)).trim() + ":" + SystemEnv.getHtmlLabelName(391271, user.getLanguage()) + "
" + SystemEnv.getHtmlLabelName(132258, user.getLanguage()) + ":
" + sql); + } + iserrordata = true; + } + } + if (tempvalue.startsWith(",")) { + tempvalue = tempvalue.substring(1); + } + } + } else if (type == 161 || type == 162) { + if (!isNumber) {//不是数字 + if (type == 161) { // 自定义单选 + Browser browser = ModeCacheManager.getInstance().getBrowserSetMap((String) dtlfielddbtypes.get(k)); + Map browserMap = ModeCacheManager.getInstance().getIdByNames((String) dtlfielddbtypes.get(k), tempvalue, user.getLanguage()); + if (browserMap.containsKey("ids")) { + tempvalue = browserMap.get("ids"); + } else { + //解决浏览框名称为整数,判断有误情况 + String realTempvalue = analyzeNameValue(tempvalue); + Map resultmap = analyzeIdValue(realTempvalue); + BrowserBean BrowserBean = null; + if (!("").equals(resultmap.get("id"))) { + BrowserBean = browser.searchById(resultmap.get("id").toString().replace("''", "'")); + } else { + BrowserBean = browser.searchForImport(resultmap.get("name").toString().replace("''", "'"), user); + } + if (null == BrowserBean) { + BrowserBean = browser.searchById(realTempvalue.replace("''", "'")); + } + if (BrowserBean != null) { + String val = BrowserBean.getId(); + String browserSql = browser.getSearchByName(); + if (val == null) { + tempvalue = CubeCipherUitl.decrypt(tempvalue); + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + tempvalue.replace(",", ",")); + if (mainid > 0) { + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + tempvalue.replace(",", ",") + + "+" + dtfieldlabelname.get(k) + "+" + dtlfieldnames.get(k) + "+" + dtlfielddbtypes.get(k) + "+" + detailtable + + "+" + SystemEnv.getHtmlLabelName(391272, user.getLanguage()) + "" + tempvalue.replace(",", ",") + "" + "
" + SystemEnv.getHtmlLabelName(132258, user.getLanguage()) + ":
" + browserSql); + } + iserrordata = true; + tempvalue = ""; + } else { + tempvalue = val; + } + } else { + if (mainid > 0) { + tempvalue = CubeCipherUitl.decrypt(tempvalue); + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + tempvalue.replace(",", ",")); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + tempvalue.replace(",", ",") + + "+" + dtfieldlabelname.get(k) + "+" + dtlfieldnames.get(k) + "+" + dtlfielddbtypes.get(k) + "+" + detailtable + + "+" + SystemEnv.getHtmlLabelName(391272, user.getLanguage())); + iserrordata = true; + // writeErrorRow(); + } + tempvalue = ""; + } + } + } else if (type == 162) { // 自定义多选 + Browser browser = ModeCacheManager.getInstance().getBrowserSetMap((String) dtlfielddbtypes.get(k)); + Map browserMap = ModeCacheManager.getInstance().getIdByNames((String) dtlfielddbtypes.get(k), tempvalue, user.getLanguage()); + if (browserMap.containsKey("ids")) { + tempvalue = browserMap.get("ids"); + } else { + //解决浏览框名称为整数,判断有误情况 + String realTempvalue = analyzeNameValue(tempvalue); + Map resultmap = analyzeIdValue(realTempvalue); + BrowserBean BrowserBean = null; + if (!("").equals(resultmap.get("id"))) { + BrowserBean = browser.searchById2(resultmap.get("id").toString().replace("''", "'")); + } else { + BrowserBean = browser.searchForImport2(resultmap.get("name").toString().replace("''", "'"), user); + } + if (null == BrowserBean) { + BrowserBean = browser.searchById(realTempvalue.replace("''", "'")); + } + if (BrowserBean != null) { + String tempvaluenew = BrowserBean.getId(); + if (tempvaluenew.indexOf("null") > -1) { + BrowserBean = browser.searchById2(tempvalue); + } + } + if (BrowserBean != null) { + String name = BrowserBean.getName(); + String browserSql = browser.getSearchByName(); + if (browserSql == null || browserSql.equals("")) { + browserSql = SystemEnv.getHtmlLabelName(500319, user.getLanguage()); + } + if (name.startsWith("#@ERROR@#")) { + String old_val = name.replace("#@ERROR@#", ""); + old_val = CubeCipherUitl.decrypt(old_val); + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + old_val); + if (mainid > 0) { + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + old_val + "+" + dtfieldlabelname.get(k) + + "+" + dtlfieldnames.get(k) + "+" + dtlfielddbtypes.get(k) + "+" + detailtable + + "+" + SystemEnv.getHtmlLabelName(391272, user.getLanguage()) + "" + old_val + "" + "
" + SystemEnv.getHtmlLabelName(132258, user.getLanguage()) + ":
" + browserSql); + } + iserrordata = true; + tempvalue = ""; + } else { + String old_val = tempvalue; + tempvalue = BrowserBean.getId(); + if (tempvalue.indexOf("null") > -1) { + tempvalue = CubeCipherUitl.decrypt(tempvalue); + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + old_val); + if (mainid > 0) { + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + old_val + "+" + dtfieldlabelname.get(k) + + "+" + dtlfieldnames.get(k) + "+" + dtlfielddbtypes.get(k) + "+" + detailtable + + "+" + SystemEnv.getHtmlLabelName(391274, user.getLanguage()) + "" + tempvalue + "
" + SystemEnv.getHtmlLabelName(132258, user.getLanguage()) + ":
" + browserSql); + } + iserrordata = true; + tempvalue = ""; + } + } + } else { + if (mainid > 0) { + tempvalue = CubeCipherUitl.decrypt(tempvalue); + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + tempvalue); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + tempvalue + + "+" + dtfieldlabelname.get(k) + "+" + dtlfieldnames.get(k) + "+" + dtlfielddbtypes.get(k) + "+" + detailtable + + "+" + tempvalue + ":" + SystemEnv.getHtmlLabelName(391272, user.getLanguage())); + iserrordata = true; + // writeErrorRow(); + } + tempvalue = ""; + } + } + } + } else { //是数字 + Browser browser = ModeCacheManager.getInstance().getBrowserSetMap((String) dtlfielddbtypes.get(k)); + int r = ModeCacheManager.getInstance().isContainBrowserIds((String) dtlfielddbtypes.get(k), tempvalue, user.getLanguage()); + if (r == -1) {//没有缓存 + if (number != null && number.length > 0) { + for (String num : number) { + BrowserBean browserBean = browser.searchById(num.trim()); + String browserSql = browser.getSearchByName(); + if (browserBean == null || browserBean.getId() == null) { + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + tempvalue); + if (mainid > 0) { + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + tempvalue + + "+" + dtfieldlabelname.get(k) + "+" + dtlfieldnames.get(k) + "+" + dtlfielddbtypes.get(k) + + "+" + detailtable + "+" + tempvalue + "
" + SystemEnv.getHtmlLabelName(132258, user.getLanguage()) + ":
" + browserSql); + } + iserrordata = true; + tempvalue = ""; + break; + } + } + } + } else if (r == 0) {//存在未找到 + String browserSql = ModeCacheManager.getInstance().getBrowserSql((String) dtlfielddbtypes.get(k), tempvalue, user.getLanguage()); + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + tempvalue); + if (mainid > 0) { + errorTable.add(sheetcount + "+" + (col + 1) + "+" + (col + 1) + "+" + tempvalue + + "+" + dtfieldlabelname.get(k) + "+" + dtlfieldnames.get(k) + "+" + dtlfielddbtypes.get(k) + + "+" + detailtable + "+" + SystemEnv.getHtmlLabelName(391272, user.getLanguage()) + "" + tempvalue + "
" + SystemEnv.getHtmlLabelName(132258, user.getLanguage()) + ":
" + browserSql); + } + iserrordata = true; + tempvalue = ""; + break; + } + + + } + } else if (type == 256 || type == 257) { + String tempIdStr = ""; + if (!tempvalue.isEmpty()) { + String fielddbtype = (String) dtlfielddbtypes.get(k); + CustomTreeComInfo comInfo = new CustomTreeComInfo(); + boolean showlevel = "1".equals(comInfo.get(CustomTreeComInfo.showlevel, fielddbtype)); + String levelsplitchar = comInfo.get(CustomTreeComInfo.levelsplitchar, fielddbtype); + List> list = new ArrayList>(); + List> listBak = new ArrayList>(); + if (treeBaseMap.containsKey(fielddbtype)) { + list = treeBaseMap.get(fielddbtype); + listBak = treeBaseMap.get("showfield"); + } else { + String treeSetSql = "select id,sourcefrom,sourceid,tablename,tablekey,showfield,supnode,datacondition,tablesup,supnodefield,nodefield from mode_customtreedetail where mainid=" + fielddbtype; + recordSet.execute(treeSetSql); + while (recordSet.next()) { + Map setMap = new HashMap(); + Map setMapBak = new HashMap(); + String nodeid = recordSet.getString("id");//节点id + String tablename = recordSet.getString("tablename");//表名 + String tablekey = recordSet.getString("tablekey");//主键字段 + String showfield = recordSet.getString("showfield");//显示名称字段 + String datacondition = recordSet.getString("datacondition").trim();//数据显示条件 + String sourcefrom = recordSet.getString("sourcefrom"); + String sourceid = recordSet.getString("sourceid"); + String supnode = recordSet.getString("supnode"); + String tablesup = recordSet.getString("tablesup"); + String supnodefield = recordSet.getString("supnodefield"); + String nodefield = recordSet.getString("nodefield"); + setMap.put("nodeid", nodeid); + setMap.put("tablename", tablename); + setMap.put("tablekey", tablekey); + setMap.put("showfield", showfield); + setMap.put("datacondition", datacondition); + setMap.put("sourcefrom", sourcefrom); + setMap.put("sourceid", sourceid); + setMap.put("supnode", supnode); + setMap.put("tablesup", tablesup); + setMap.put("supnodefield", supnodefield); + setMap.put("nodefield", nodefield); + setMapBak.put("showfield", showfield); + list.add(setMap); + listBak.add(setMapBak); + } + treeBaseMap.put(fielddbtype, list); + treeBaseMap.put("showfield", listBak); + } + + String[] nameArray = null; + if (type == 257) { + if (tempvalue.indexOf("DH{") != -1) {//批量导入自定义多选时,如果选项中有英文逗号,批量导入时用DH{}包裹 + String[] tempNumber = tempvalue.split(",");//数组格式:{"xxxx","DH{XXXX","XXXX"?(也许有),"xxx}"},其中DH{}中间包裹的值是自定义多选的一个选项 + List list1 = new ArrayList(); + int m = 0; + int j = 0; + while (m < tempNumber.length) { + if (tempNumber[m].indexOf("DH{") != -1) { + list1.add(tempNumber[m].substring(3, tempNumber[m].length()) + ","); + m++; + boolean flag1 = false; + while (!flag1) {//判断数组中是否含有 + if (tempNumber[m].indexOf("}") != -1) { + list1.add(list1.get(j) + tempNumber[m].substring(0, tempNumber[m].length() - 1)); + list1.remove(j); + m++; + j++; + flag1 = true; + } else { + list1.add(list1.get(j) + tempNumber[m] + ","); + list1.remove(j); + m++; + } + } + } else { + list1.add(tempNumber[m]); + m++; + j++; + } + } + nameArray = list1.toArray(new String[list1.size()]); + } else { + nameArray = tempvalue.split(","); + } + } else {//type=256 + nameArray = tempvalue.split("weaver_ecology"); + } + + for (int m = 0; m < nameArray.length; m++) { + String tempName = nameArray[m]; + String tempid = ""; + String tempSql = ""; + if (!tempName.isEmpty()) { + tempName = tempName.trim(); + //解决浏览框名称为整数,判断有误情况 + String realTempvalue = analyzeNameValue(tempName); + if (realTempvalue.startsWith("tree_")) { + String[] valuearr = realTempvalue.split("_"); + if (valuearr.length == 3) { + for (int n = 0; n < list.size(); n++) { + Map setMap = list.get(n); + if (setMap.get("nodeid").equals(valuearr[1])) { + setMap.put("showfield", "id"); + } else { + continue; + } + Map value = impExcelUtil.getTreeValue("", "", setMap, valuearr[2]); + tempSql = Util.null2String(value.get("sql")); + if (value.size()>0 && listBak.get(0).size()>0){ + setMap.put("showfield", listBak.get(0).get("showfield")); + } + + if (!"".equals(Util.null2String(value.get("id")))) { + if (!tempIdStr.equals("")) { + tempIdStr += ","; + } + tempid = Util.null2String(value.get("id")); + tempIdStr += Util.null2String(value.get("id")); + break; + } + } + } + } else if (showlevel && realTempvalue.indexOf(levelsplitchar) > 0) { + Map value = impExcelUtil.importTreeDataAllLevel(list, levelsplitchar, realTempvalue); + if (!tempIdStr.equals("")) { + tempIdStr += ","; + } + tempid = Util.null2String(value.get("id")); + tempIdStr += Util.null2String(value.get("id")); + tempSql = Util.null2String(value.get("sql")); + } else { + for (int n = 0; n < list.size(); n++) { + Map setMap = list.get(n); + Map value = impExcelUtil.getTreeValue("", "", setMap, realTempvalue); + tempSql = Util.null2String(value.get("sql")); + + if (!"".equals(Util.null2String(value.get("id")))) { + if (!tempIdStr.equals("")) { + tempIdStr += ","; + } + tempid = Util.null2String(value.get("id")); + tempIdStr += Util.null2String(value.get("id")); + break; + } + } + } + if (tempid.equals("")) { + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + tempName); + if (mainid > 0) { + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + tempName + + "+" + dtfieldlabelname.get(k) + "+" + dtlfieldnames.get(k) + "+" + dtlfielddbtypes.get(k) + + "+" + detailtable + "+" + tempName + SystemEnv.getHtmlLabelName(391276, user.getLanguage()) + "
" + SystemEnv.getHtmlLabelName(132258, user.getLanguage()) + ":
" + tempSql); + } + iserrordata = true; + tempIdStr = ""; + } + } + } + + } + tempvalue = tempIdStr.replace("'", "''"); + } else { + if (!isNumber) { + rs.executeSql("select tablename,columname,keycolumname from workflow_browserurl where id=" + type); + if (rs.next()) { + ArrayList tempvalues = null; + if (type == 1) {//如果是单人力不分割 + tempvalues = new ArrayList(); + tempvalues.add(tempvalue); + } else { + tempvalues = Util.TokenizerString(tempvalue, ","); + } + tempvalue = ""; + String keyname = Util.null2String(rs.getString("keycolumname")); + String tablename = Util.null2String(rs.getString("tablename")); + String columname = Util.null2String(rs.getString("columname")); + String columnameCopy = columname; + String[] realProjectName = CubeUtil.getRealProjectName(tablename, columname); + tablename = realProjectName[0]; + columname = realProjectName[1]; + columnameCopy = columname; + String columnameall = ""; + if (tablename.toLowerCase().equals("hrmdepartment") || tablename.toLowerCase().equals("hrmdepartmentallview")) { + columname = "departmentmark"; + columnameall = "departmentname"; + } else if (tablename.toLowerCase().equals("hrmsubcompanyallview")) { + columnameall = columname;//分部优先简称 + columname = "subcompanydesc"; + } + //部门及分部封存,人员离职过滤 + String hrmFilterCondiction = ""; + if ("HrmDepartment".equalsIgnoreCase(tablename.toLowerCase()) || "hrmsubcompanyallview".equalsIgnoreCase(tablename.toLowerCase())) { + hrmFilterCondiction = " and (canceled!=1 or canceled is null)"; + } else if ("HrmResource".equalsIgnoreCase(tablename.toLowerCase())) { + hrmFilterCondiction = " and (status in(0,1,2,3) or status is null)"; + } else if ("crm_customerinfo".equalsIgnoreCase(tablename)) { + hrmFilterCondiction = " and deleted=0"; + } + if ((!keyname.equals("") && !tablename.equals("") && !columname.equals("")) || isDepSup) { + for (int n = 0; n < tempvalues.size(); n++) { + columname = columnameCopy; + rs = new RecordSet(); + if (SystemEnv.getHtmlLabelName(16139, user.getLanguage()).equals(Util.null2String(tempvalues.get(n)).trim())) {//系统管理员 + if (tempvalue.equals("")) { + tempvalue = "1"; + } else { + tempvalue += "," + "1"; + } + continue; + } + String importValue = Util.null2String(tempvalues.get(n)).trim(); + String keyValue = importValue; + if ("hrmresource".equalsIgnoreCase(tablename.toLowerCase()) && importValue.toLowerCase().startsWith("workcode_")) { + keyValue = keyValue.substring(9); + columname = "workcode"; + } else if ("hrmdepartment".equalsIgnoreCase(tablename.toLowerCase()) && importValue.toLowerCase().startsWith("deptcode_")) { + keyValue = keyValue.substring(9); + columname = "departmentcode"; + } else if ("HrmResource".equalsIgnoreCase(tablename.toLowerCase())) { + if (importValue.startsWith("LZRY_")) { + keyValue = keyValue.substring(5); + hrmFilterCondiction = "";//包含LZRY_ 就可以导入所有类型的人员 + } else { + hrmFilterCondiction = " and (status in(0,1,2,3) or status is null)"; + } + } else { + //解决浏览框名称为整数,判断有误情况 + keyValue = analyzeNameValue(keyValue); + } + if (type == 164 || type == 169 || type == 170 || type == 194 || type == 167 || type == 168 || isDepSup) { + keyValue = checkDepartAndSubpany(keyValue); + } + //添加判断value 是不是id 或者编号 + if (isNumberOrCode(importValue)) { + hrmFilterCondiction = ""; + } + if (!"".equals(keyValue)) { + if (!"".equals(columnameall)) { + sql = "select " + keyname + " from " + tablename + + " where " + columnameall + " ='" + keyValue + + "' " + hrmFilterCondiction + " order by " + keyname + " desc"; + rs.executeSql(sql); + } + if (rs.getCounts() <= 0) { + sql = "select " + keyname + " from " + tablename + + " where " + columname + " ='" + keyValue + + "' " + hrmFilterCondiction + " order by " + keyname + " desc"; + rs.executeSql(sql); + } + if (rs.next()) { + if (tempvalue.equals("")) { + tempvalue = rs.getString(1); + } else { + tempvalue += "," + rs.getString(1); + } + } else { //先判断下是否是多语言结构 + if (!"".equals(columnameall)) { + sql = "select " + keyname + " from " + tablename + + " where (" + columnameall + " like '%" + "`~`7 " + keyValue + "`~`" + "%' or " + columnameall + " like '%" + "`~`8 " + keyValue + "`~`" + "%' or " + columnameall + " like '%" + "`~`9 " + keyValue + "`~`" + "%')" + + " order by " + keyname + " desc"; + rs.executeSql(sql); + } + if (rs.getCounts() <= 0) { + sql = "select " + keyname + " from " + tablename + + " where (" + columname + " like '%" + "`~`7 " + keyValue + "`~`" + "%' or " + columname + " like '%" + "`~`8 " + keyValue + "`~`" + "%' or " + columname + " like '%" + "`~`9 " + keyValue + "`~`" + "%')" + + " order by " + keyname + " desc"; + rs.executeSql(sql); + } + if (rs.next()) { + if (tempvalue.equals("")) { + tempvalue = rs.getString(1); + } else { + tempvalue += "," + rs.getString(1); + } + } else { + if (mainid > 0) { + sql = "select " + keyname + " from " + tablename + + " where (" + columname + " like '%" + "`~`7 " + keyValue + "`~`" + "%' or " + columname + " like '%" + "`~`8 " + keyValue + "`~`" + "%' or " + columname + " like '%" + "`~`9 " + keyValue + "`~`" + "%' or " + columname + "='" + keyValue + "')" + + " order by " + keyname + " desc"; + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + importValue); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + importValue + + "+" + dtfieldlabelname.get(k) + "+" + dtlfieldnames.get(k) + "+" + dtlfielddbtypes.get(k) + + "+" + detailtable + "+" + importValue + ":" + SystemEnv.getHtmlLabelName(391277, user.getLanguage()) + sql); + iserrordata = true; + } + } + } + } else { + if (mainid > 0) { + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + importValue); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + importValue + + "+" + dtfieldlabelname.get(k) + "+" + dtlfieldnames.get(k) + "+" + dtlfielddbtypes.get(k) + "+" + detailtable + + "+" + importValue + ":" + SystemEnv.getHtmlLabelName(391278, user.getLanguage()) + keyValue + "," + SystemEnv.getHtmlLabelName(382055, user.getLanguage())); + iserrordata = true; + } + } + } + } + } else { + tempvalue = ""; + } + } else {//浏览按钮ID导入验证 + rs.executeSql("select tablename,columname,keycolumname from workflow_browserurl where id=" + type); + if (rs.next()) { + ArrayList tempvalues = Util.TokenizerString(tempvalue, ","); + tempvalue = ""; + String keyname = Util.null2String(rs.getString("keycolumname")); + String tablename = Util.null2String(rs.getString("tablename")); + String columname = Util.null2String(rs.getString("columname")); + String[] realProjectName = CubeUtil.getRealProjectName(tablename, columname); + tablename = realProjectName[0]; + columname = realProjectName[1]; + if (tablename.toLowerCase().equals("hrmdepartment")) { + columname = "departmentname"; + } + //部门及分部封存,人员离职过滤 + String hrmFilterCondiction = ""; + if ("HrmDepartment".equalsIgnoreCase(tablename.toLowerCase()) || "hrmsubcompanyallview".equalsIgnoreCase(tablename.toLowerCase())) { + hrmFilterCondiction = " and (canceled!=1 or canceled is null)"; + } else if ("HrmResource".equalsIgnoreCase(tablename.toLowerCase())) { + hrmFilterCondiction = " and (status in(0,1,2,3) or status is null)"; + } else if ("crm_customerinfo".equalsIgnoreCase(tablename)) { + hrmFilterCondiction = " and deleted=0"; + } + if (!keyname.equals("") && !tablename.equals("") && !columname.equals("")) { + for (int n = 0; n < tempvalues.size(); n++) { + String importValue = Util.null2String(tempvalues.get(n)).trim(); + if ("1".equals(Util.null2String(tempvalues.get(n)).trim())) { + if (tempvalue.equals("")) { + tempvalue = "1"; + } else { + tempvalue += "," + "1"; + } + continue; + } + //添加判断value 是不是id 或者编号 + if (isNumberOrCode(((String) tempvalues.get(n)).trim())) { + hrmFilterCondiction = ""; + } + if ("HrmResource".equalsIgnoreCase(tablename.toLowerCase())) { + if (importValue.startsWith("LZRY_")) { + importValue = importValue.substring(5); + hrmFilterCondiction = "";//包含LZRY_ 就可以导入所有类型的人员 + } else { + hrmFilterCondiction = " and (status in(0,1,2,3) or status is null)"; + } + } + sql = "select " + keyname + " from " + tablename + + " where " + keyname + " ='" + importValue + + "' " + hrmFilterCondiction + " order by " + keyname + " desc"; + rs.executeSql(sql); + if (rs.next()) { + if (tempvalue.equals("")) { + tempvalue = rs.getString(1); + } else { + tempvalue += "," + rs.getString(1); + } + } else { + if (mainid > 0) { + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + ((String) tempvalues.get(n)).trim()); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + ((String) tempvalues.get(n)).trim() + + "+" + dtfieldlabelname.get(k) + "+" + dtlfieldnames.get(k) + "+" + dtlfielddbtypes.get(k) + "+" + detailtable + + "+" + ((String) tempvalues.get(n)).trim() + ":" + SystemEnv.getHtmlLabelName(391271, user.getLanguage()) + "
" + SystemEnv.getHtmlLabelName(132258, user.getLanguage()) + ":
" + sql); + iserrordata = true; + // writeErrorRow(); + } + } + } + } + } else { + tempvalue = ""; + } + } + } + if (isDepSup) { //虚拟部门 + String flagStr = ""; + String keyname = ""; + String tablename = ""; + if ((type == 4 || type == 57)) { + if (tempvalue.toLowerCase().startsWith("virtual_")) { + flagStr = "virtual_"; + if (tempvalue.startsWith("VIRTUAL_")) { + flagStr = "VIRTUAL_"; + } + keyname = "departmentname"; + tablename = "HrmDepartmentVirtual"; + } else if (tempvalue.startsWith("-")) { + keyname = "id"; + tablename = "HrmDepartmentVirtual"; + } else if (tempvalue.startsWith("deptcode_")) { + tablename = "HrmDepartment"; + keyname = "departmentcode"; + if (tempvalue.indexOf("deptcode_") != -1) { + tempvalue = tempvalue.replace("deptcode_", ""); + } else { + tempvalue = tempvalue.substring(9); + } + } else { + keyname = "departmentname"; + tablename = "HrmDepartment"; + if (isNumber) { + keyname = "id"; + } + } + } else if ((type == 164 || type == 194)) { + if (tempvalue.toLowerCase().startsWith("virtual_")) { + flagStr = "virtual_"; + if (tempvalue.startsWith("VIRTUAL_")) { + flagStr = "VIRTUAL_"; + } + keyname = "subcompanyname"; + tablename = "hrmsubcompanyvirtual"; + } else if (tempvalue.startsWith("-")) { + keyname = "id"; + tablename = "hrmsubcompanyvirtual"; + } else { + keyname = "subcompanyname"; + tablename = "hrmsubcompany"; + if (isNumber) { + keyname = "id"; + } + } + } + //部门及分部封存,人员离职过滤 + String hrmFilterCondiction = ""; + if ("HrmDepartment".equalsIgnoreCase(tablename.toLowerCase()) || "hrmsubcompany".equalsIgnoreCase(tablename.toLowerCase()) + || "HrmDepartmentVirtual".equalsIgnoreCase(tablename.toLowerCase()) || + "hrmsubcompanyvirtual".equalsIgnoreCase(tablename.toLowerCase())) { + hrmFilterCondiction = " and (canceled!=1 or canceled is null)"; + } + + ArrayList tempvalues = Util.TokenizerString(tempvalue, ","); + tempvalue = ""; + String values = ""; + for (int n = 0; n < tempvalues.size(); n++) { + if (!((String) tempvalues.get(n)).trim().toLowerCase().startsWith(flagStr)) + continue; + values += ",'" + ((String) tempvalues.get(n)).trim().replace(flagStr, "") + "'"; + } + if (!StringHelper.isEmpty(values)) { + values = values.substring(1); + for (int n = 0; n < tempvalues.size(); n++) { + String value = ((String) tempvalues.get(n)).trim().replace(flagStr, ""); + value = checkDepartAndSubpany(value); + //添加判断value 是不是id 或者编号 + if (isNumberOrCode(value)) { + hrmFilterCondiction = ""; + } + sql = "select id," + keyname + " as showname from " + tablename + " where " + keyname + " ='" + value + "' " + hrmFilterCondiction + " order by id desc"; + rs.executeSql(sql); + if (!rs.next()) {//判断是否为多语言 + String tempSqlTemp = "select id," + keyname + " as showname from " + tablename + + " where (" + keyname + " like '%" + "`~`7 " + value + "`~`" + "%' or " + keyname + " like '%" + "`~`8 " + value + "`~`" + "%' or " + keyname + " like '%" + "`~`9 " + value + "`~`" + "%')" + + hrmFilterCondiction + " order by id desc"; + rs.execute(tempSqlTemp); + } + rs.beforFirst(); + boolean isExists = false; + while (rs.next()) { + String showname = rs.getString("showname"); + showname = Util.formatMultiLang(showname, user.getLanguage() + ""); + String tempValue = (String) tempvalues.get(n); + tempValue = checkDepartAndSubpany(tempValue.trim()); + String shownameNew = (flagStr + showname).replace("'", "''"); + if (shownameNew.equals(tempValue)) { + tempvalue += "," + rs.getString(1); + isExists = true; + break; + } + } + if (!isExists) { + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + ((String) tempvalues.get(n)).trim()); + if (mainid > 0) { + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + ((String) tempvalues.get(n)).trim() + + "+" + dtfieldlabelname.get(k) + "+" + dtlfieldnames.get(k) + "+" + dtlfielddbtypes.get(k) + + "+" + detailtable + "+" + ((String) tempvalues.get(n)).trim() + ":" + SystemEnv.getHtmlLabelName(391271, user.getLanguage()) + "
" + SystemEnv.getHtmlLabelName(132258, user.getLanguage()) + ":
" + sql); + } + iserrordata = true; + } + } + if (tempvalue.startsWith(",")) { + tempvalue = tempvalue.substring(1); + } + } + } + //------------------------提取end------------------------------ + + } else if (htmltype == 4) { + if (tempvalue.equals("1") || tempvalue.toLowerCase().trim().equals(SystemEnv.getHtmlLabelName(163, user.getLanguage()).toLowerCase().trim())) { + tempvalue = "1"; + } else if (tempvalue.equals("0") || tempvalue.toLowerCase().trim().equals(SystemEnv.getHtmlLabelName(161, user.getLanguage()).toLowerCase().trim())) { + tempvalue = "0"; + } else { + if (mainid > 0) { + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + tempvalue); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + tempvalue + + "+" + dtfieldlabelname.get(k) + "+" + dtlfieldnames.get(k) + "+" + dtlfielddbtypes.get(k) + "+" + detailtable + + "+" + tempvalue + ":" + SystemEnv.getHtmlLabelName(391252, user.getLanguage())); + iserrordata = true; + // writeErrorRow(); + } + tempvalue = ""; + } + } else if (htmltype == 5) { + if (type == 2) { + ArrayList tempvalues = Util.TokenizerString(tempvalue, ","); + tempvalue = ""; + for (int i = 0; i < tempvalues.size(); i++) { + sql = "select selectvalue from workflow_selectitem where (selectname='" + ((String) tempvalues.get(i)).trim() + "' or selectname like '%`~`7 " + ((String) tempvalues.get(i)).trim() + "`~`%' or selectname like '%`~`8 " + ((String) tempvalues.get(i)).trim() + "`~`%' or selectname like '%`~`9 " + ((String) tempvalues.get(i)).trim() + "`~`%') and fieldid=" + ((String) tempfields.get(0)).substring(5) + " and (cancel is null or cancel = 0)"; + rs.executeSql(sql); + if (rs.next()) { + if (tempvalue.equals("")) { + tempvalue = rs.getString(1); + } else { + tempvalue += "," + rs.getString(1); + } + } else { + if (mainid > 0) { + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + tempvalues.get(i)); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + tempvalues.get(i) + + "+" + dtfieldlabelname.get(k) + "+" + dtlfieldnames.get(k) + "+" + dtlfielddbtypes.get(k) + + "+" + detailtable + "+" + tempvalues.get(i) + ":" + SystemEnv.getHtmlLabelName(391279, user.getLanguage()) + "
" + SystemEnv.getHtmlLabelName(132258, user.getLanguage()) + ":
" + sql); + iserrordata = true; + } + } + } + } else { + List selectvalueList = ModeCacheManager.getInstance().getSelectValByName(((String) tempfields.get(0)).substring(5), tempvalue, user.getLanguage()); + if (selectvalueList.size() == 1) { + tempvalue = selectvalueList.get(0); + } else { + sql = "select selectvalue from workflow_selectitem where (selectname='" + tempvalue + "' or selectname like '%`~`7 " + tempvalue + "`~`%' or selectname like '%`~`8 " + tempvalue + "`~`%' or selectname like '%`~`9 " + tempvalue + "`~`%') and fieldid=" + ((String) tempfields.get(0)).substring(5) + " and (cancel is null or cancel = 0)"; + rs.executeSql(sql); + if (rs.next()) { + tempvalue = rs.getString(1); + } else { + if (mainid > 0) { + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + tempvalue); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + tempvalue + + "+" + dtfieldlabelname.get(k) + "+" + dtlfieldnames.get(k) + "+" + dtlfielddbtypes.get(k) + + "+" + detailtable + "+" + tempvalue + ":" + SystemEnv.getHtmlLabelName(391279, user.getLanguage()) + "
" + SystemEnv.getHtmlLabelName(132258, user.getLanguage()) + ":
" + sql); + iserrordata = true; + } + tempvalue = ""; + } + } + } + } else if (htmltype == 6) { + StringBuffer value = new StringBuffer(); + String[] tempvalues = tempvalue.split(","); + for (String val : tempvalues) { + Map map = doImportForFileOrImg(val, type); + if (map.containsKey("errorStr") && !StringHelper.isEmpty(map.get("errorStr"))) { + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + val); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + val + + "+" + dtfieldlabelname.get(k) + "+" + dtlfieldnames.get(k) + "+" + dtlfielddbtypes.get(k) + + "+" + detailtable + "+" + val + ":" + map.get("errorStr") + "
"); + iserrordata = true; + } else if (!StringHelper.isEmpty(map.get("value"))) { + value.append(",").append(map.get("value")); + } + } + String valuetemp = value.toString(); + if (!StringHelper.isEmpty(valuetemp) && valuetemp.startsWith(",")) { + valuetemp = valuetemp.substring(1); + } + tempvalue = valuetemp; + } + if (type != 1 && htmltype != 1) {//文本 + tempvalue = Util.toHtmltextarea(tempvalue); + } + tempvalue = InterfacesUtil.getSubStringValue(((String) dtlfielddbtypes.get(k)).toLowerCase(), tempvalue); + if ("5".equals(type + "") && htmltype == 1) { + int qfws = Util.getIntValue(Util.null2String(dtlqwfs.get(k)), 0); + //QC:311928 ,如果输入自带分号,那么先去掉分号,转换为double + if (tempvalue != null && tempvalue.indexOf(",") != -1) { + tempvalue = tempvalue.replace(",", ""); + } + tempvalue = Util.toDecimalDigits(tempvalue, qfws); + tempvalue = Util.milfloatFormat(tempvalue); + } else if (type == 3 && htmltype == 1) { + String fielddbtype = Util.null2String(dtlfielddbtypes.get(k)); + int digitsIndex = fielddbtype.indexOf(","); + int decimaldigits_t = 0; + if (digitsIndex > -1) { + decimaldigits_t = Util.getIntValue(fielddbtype.substring(digitsIndex + 1, fielddbtype.length() - 1), 2); + } else { + decimaldigits_t = 2; + } + if (tempvalue.indexOf(",") != -1) { + tempvalue = tempvalue.replace(",", ""); + } + tempvalue = Util.toDecimalDigits(tempvalue + "", decimaldigits_t); + } + } + } + if (!tempvalue.equals("")) { + if (sql1.equals("")) { + sql1 = "insert into " + detailtable + "("; + sql2 = " values("; + sql1 += detailtablekey; + sql2 += mainid; + sql1 += "," + dtlfieldnames.get(k); + if (((String) dtlfielddbtypes.get(k)).toLowerCase().indexOf("int") != -1 + || ((String) dtlfielddbtypes.get(k)).toLowerCase().indexOf("number") != -1 + || ((String) dtlfielddbtypes.get(k)).toLowerCase().indexOf("decimal") != -1 + || ((String) dtlfielddbtypes.get(k)).toLowerCase().indexOf("browser.") != -1) { + sql2 += ",'" + tempvalue + "'"; + //valueList.add(tempvalue); + } else { + sql2 += ",'" + tempvalue + "'"; + //valueList.add(tempvalue); + } + } else { + sql1 += "," + dtlfieldnames.get(k); + if (((String) dtlfielddbtypes.get(k)).toLowerCase().indexOf("int") != -1 + || ((String) dtlfielddbtypes.get(k)).toLowerCase().indexOf("number") != -1 + || ((String) dtlfielddbtypes.get(k)).toLowerCase().indexOf("decimal") != -1 + || ((String) dtlfielddbtypes.get(k)).toLowerCase().indexOf("browser.") != -1) { + sql2 += ",'" + tempvalue + "'"; + //valueList.add(tempvalue); + } else { + sql2 += ",'" + tempvalue + "'"; + //valueList.add(tempvalue); + } + } + } + } + + if (!isnull) { + if (mainid <= 0) { + errorRow.add(sheetcount + "," + (rows + 1) + ",1,mainid " + detailid + " "); + if (Countsql.equals("")) { + Countsql = SystemEnv.getHtmlLabelName(500098, user.getLanguage()); + } + errorTable.add(sheetcount + "+" + (rows + 1) + "+1+mainid " + detailid + " " + "+" + detailtable + "+" + Countsql); + Vector d; + if (errorDetailMap.containsKey(sheetIndex + "")) { + d = errorDetailMap.get(sheetIndex + ""); + } else { + d = new Vector(); + } + d.add(rows); + errorDetailMap.put(sheetIndex + "", d); + iserrordata = true; + // writeErrorRow(); + } + } + + if (!sql1.equals("") && mainid > 0) { + sql1 += ")"; + sql2 += ")"; + try { + if (rowCanImport) { + flag = rs.executeSql(sql1 + sql2); + } + if (flag) { + detailList.add(mainid); + // 进行列的计算. + getColCalStr(formid, -1, maintable, map, mainid, 1, detailtable); + //记录明细日志 + if (needlogFieldList.size() > 0) { + Map> nowData_detail = formInfoService.getTableData(detailtable, mainid, this.columnNames_d, "id", "mainid"); + Set intersectionKey = new HashSet(); + String[] columnsArray = this.columnNames_d.split(","); + for (String detaildataid : nowData_detail.keySet()) { + if (oldData_detail.containsKey(detaildataid)) {//编辑的明细数据 + Map od = oldData_detail.get(detaildataid); + Map nd = nowData_detail.get(detaildataid); + for (String column : columnsArray) { + String fieldvalue = Util.null2String(nd.get(column)); + String prefieldvalue = Util.null2String(od.get(column)); + if (!prefieldvalue.equals(fieldvalue)) { + String detailtable1 = detailtable; + rs.executeUpdate("insert into ModeLogFieldDetail(viewlogid,fieldid,fieldvalue,prefieldvalue,modeid,detaildataid,operateType,detailtable) values(?,?,?,?,?,?,?,?)", this.modeLogMap.get(mainid + ""), + this.columnFieldids_d.get(column), fieldvalue, prefieldvalue, this.modeid, detaildataid, "EDIT", detailtable); + } + } + intersectionKey.add(detaildataid); + } else {//新增的明细数据 + Map nd = nowData_detail.get(detaildataid); + for (String column : columnsArray) { + String fieldvalue = Util.null2String(nd.get(column)); + + rs.executeUpdate("insert into ModeLogFieldDetail(viewlogid,fieldid,fieldvalue,modeid,detaildataid,operateType,detailtable) values(?,?,?,?,?,?,?)", this.modeLogMap.get(mainid + ""), + this.columnFieldids_d.get(column), fieldvalue, this.modeid, detaildataid, "ADD", detailtable); + } + } + } + for (String detaildataid : oldData_detail.keySet()) { + if (!intersectionKey.contains(detaildataid)) {//被删除的明细数据 + Map od = oldData_detail.get(detaildataid); + for (String column : columnsArray) { + String prefieldvalue = Util.null2String(od.get(column)); + rs.executeUpdate("insert into ModeLogFieldDetail(viewlogid,fieldid,prefieldvalue,modeid,detaildataid,operateType,detailtable) values(?,?,?,?,?,?,?)", this.modeLogMap.get(mainid + ""), + this.columnFieldids_d.get(column), prefieldvalue, this.modeid, detaildataid, "DEL", detailtable); + } + } + } + } + } else { + writeLog(sql1 + sql2); + } + } catch (Exception e) { + writeLog(e); + errorRow.add(sheetcount + "," + (rows + 1)); + // writeErrorRow(); + } + } + + if ((!isnull && (!flag)) || iserrordata) { + errorRow.add(sheetcount + "," + (rows + 1)); + // writeErrorRow(); + } + + if (isnull) { + canImport = false; + ImpExcelServer.setProgressCanImport(key, false, MessageFormat.format(SystemEnv.getHtmlLabelName(132245, user.getLanguage()), sheetIndex, rows)); + if (!rowCanImport) { + errorRow.removeAll(indexList); + errorTable.removeAll(indexList); + } + } + } + rows++; + } + sheetcount++; + } + } catch (Exception e) { + writeLog("导入明细异常 modeId=" + modeid + " formid=" + formid + " Exception : " + e); + writeLog(e); + Errmsg = SystemEnv.getHtmlLabelName(27593, user.getLanguage()) + e.getMessage() + "!\\n"; + } finally { + doneSignal.countDown(); + } + } + + private void importMainData() { + try { + ExpExcelUtil.refreshImpUserState(user.getUID(), key);//刷新导入状态 + RecordSet rs = new RecordSet(); + InterfacesUtil InterfacesUtil = new InterfacesUtil(); + String sql = ""; + int importtype = Util.getIntValue(Util.null2String(params.get("importtype")), 0);//1 追加,2覆盖,3更新 + int updateadddata = Util.getIntValue(Util.null2String(params.get("updateadddata")), 0);//importtype==3的时候 + String keyField = Util.null2String(Util.null2String(params.get("keyfield"))).toLowerCase();//重复验证字段 + String conditionfield = Util.null2String(Util.null2String(params.get("conditionfield"))).toLowerCase();//条件验证字段 + String conditionfielddbType = "";//条件验证字段 数据库类型 + boolean isImportedWithIgnoringError = Util.getIntValue(Util.null2String(params.get("isImportedWithIgnoringError"))) == 1 ? true : false; + // 添加数据ID 创建人 创建日期时间字段 导入 + boolean ismainKeyid = false; + if (importtype == 3 && "dataid".equals(conditionfield)) {//3更新 并且 条件字段是数据ID + ismainKeyid = true; + } + boolean isHaveModedatastatus = false; + if (new ModeSetUtil().isHaveModedatastatusByformid(formid)) { + isHaveModedatastatus = true; + } + ArrayList fieldIdListTemp = new ArrayList(); + ArrayList fieldTypeListTemp = new ArrayList(); + ArrayList fieldDbTypeListTemp = new ArrayList(); + ArrayList fieldHtmlTypeListTemp = new ArrayList(); + ArrayList fieldNameListTemp = new ArrayList(); + ArrayList fieldLabelListTemp = new ArrayList(); + ArrayList fieldLabelNameListTemp = new ArrayList(); + ArrayList qfwsListTemp = new ArrayList(); + ImpExcelUtil impExcelUtil = new ImpExcelUtil(); + impExcelUtil.setModeVFormMap(modeVFormMap); + int isHaveTemplate = 0; + String templateSql = "select 1 from mode_import_template a where modeid=" + modeid + " and formid=" + formid + " and (exists(select 1 from workflow_billfield b where b.billid=" + formid + " and b.id=a.fieldid) or a.fieldid in(-1000,-1001,-1002)) "; + rs.execute(templateSql); + if (rs.getCounts() > 0) { + isHaveTemplate = 1; + } + if (isHaveTemplate == 1) { + sql = "select b.id,fieldlabel,fieldhtmltype,type,fielddbtype,fieldname,qfws,childfieldid,m.dsporder,1 as needExcel from workflow_billfield b join mode_import_template m on b.id=m.fieldId and m.modeid=" + modeid + " and m.formId='" + formid + "' where fieldhtmltype<> 7 and billid=" + formid + " and viewtype=0 order by m.dsporder,b.id"; + } else { + sql = "select id,fieldlabel,fieldhtmltype,type,fielddbtype,fieldname,qfws,childfieldid,dsporder,needExcel from workflow_billfield b left join ModeFormFieldExtend m on b.id=m.fieldId and m.formId='" + formid + "' where fieldhtmltype<> 7 and billid=" + formid + " and viewtype=0 order by dsporder,id"; + } + rs.execute(sql); + ExpExcelUtil.refreshImpUserState(user.getUID(), key);//刷新导入状态 + while (rs.next()) { + String needExcel = Util.null2String(rs.getString("needExcel")); + if ("0".equals(needExcel)) { + continue; + } + + String fieldid = Util.null2String(rs.getString("id")); + String fieldtype = Util.null2String(rs.getString("type")); + String fielddbtype = Util.null2String(rs.getString("fielddbtype")); + String fieldhtmltype = Util.null2String(rs.getString("fieldhtmltype")); + String fieldname = Util.null2String(rs.getString("fieldname")); + String labelname = Util.null2String(SystemEnv.getHtmlLabelName(rs.getInt("fieldlabel"), user.getLanguage())); + String fieldlabelname = labelname; + String qfws = Util.null2String(rs.getString("qfws")); + + fieldIdListTemp.add(fieldid); + fieldTypeListTemp.add(fieldtype); + fieldDbTypeListTemp.add(fielddbtype); + fieldHtmlTypeListTemp.add(fieldhtmltype); + fieldNameListTemp.add(fieldname); + fieldLabelListTemp.add(labelname); + fieldLabelNameListTemp.add(fieldlabelname); + qfwsListTemp.add(qfws); + } + + ArrayList fieldIdList = new ArrayList(); + ArrayList fieldTypeList = new ArrayList(); + ArrayList fieldDbTypeList = new ArrayList(); + ArrayList fieldHtmlTypeList = new ArrayList(); + ArrayList fieldNameList = new ArrayList(); + ArrayList fieldLabelList = new ArrayList(); + ArrayList fieldLabelNameList = new ArrayList(); + ArrayList qfwsList = new ArrayList(); + List mainFieldIds = impFieldIds.get(0);//excel中的主表字段id + for (int i = 0, len = mainFieldIds.size(); i < len; i++) { + int fieldId = Util.getIntValue(mainFieldIds.get(i)); + if (fieldId <= 0) { + continue; + } + int index = fieldIdListTemp.indexOf(mainFieldIds.get(i)); + fieldIdList.add(fieldIdListTemp.get(index)); + fieldTypeList.add(fieldTypeListTemp.get(index)); + fieldDbTypeList.add(fieldDbTypeListTemp.get(index)); + fieldHtmlTypeList.add(fieldHtmlTypeListTemp.get(index)); + fieldNameList.add(fieldNameListTemp.get(index)); + fieldLabelList.add(fieldLabelListTemp.get(index)); + fieldLabelNameList.add(fieldLabelNameListTemp.get(index)); + qfwsList.add(qfwsListTemp.get(index)); + } + + String maintablename = ""; + sql = "select * from workflow_bill where id = " + formid; + rs.executeSql(sql); + while (rs.next()) { + maintablename = Util.null2String(rs.getString("tablename")); + } + new ModeDataIdUpdate().updateModifyInfo(maintablename); + //看数据库是否有重复数据 组合验证每个组合的字段名为一个key(如wb1,wb2),所有的数据库值存到改key对应的map中 + Map> keyMap = new HashMap>(); + Map> keyMapExcel = new HashMap>();//看excel中是否有重复数据 + Map conditionFieldMap = new HashMap();//条件字段在数据库中的值 + List keyFields = this.getKeyFields(keyField); + // 草稿字段不参与验证 + String sqlwherebytemp = " where formmodeid=" + modeid + " "; + if (new ModeSetUtil().isHaveModedatastatus(formid)) { + sqlwherebytemp += " and modedatastatus <> 1 "; + } + setDataBaseValue(keyField, maintablename, keyMap, sqlwherebytemp); + if (!"".equals(conditionfield)) { + int totalPage = 1; + SplitPageUtil spu = new SplitPageUtil(); + SplitPageParaBean spp = new SplitPageParaBean(); + String primarykey = "id"; + String vdatasource = ""; + String backfield = ""; + String sqlfrom = ""; + String sqlwhere = "1=1"; + //创建临时表 + Boolean iscreatetemptab=IsCreateTempTab(conditionfield,fieldNameList,fieldTypeList,fieldHtmlTypeList); + if(iscreatetemptab){ + //获取excel更新条件字段 datas进行批量插入 + int rowsy=0; + if(start!=0){ + rowsy =start; + }else{ + rowsy =start+1; + } + List datas = new ArrayList(); + while(rowsy < end && rowsy >= start){ + List data = new ArrayList<>(); + if(conditionfield.equals("dataid")){ + String tempvalue = POIUtil.getValue(sheet, rowsy, 1); + data.add(tempvalue); + }else{ + for (int k = 0; k < fieldNameList.size(); k++) { + String fieldid = Util.null2String((String) fieldIdList.get(k)); + String fieldname = Util.null2String((String) fieldNameList.get(k)); + String fieldtype = Util.null2String((String)fieldTypeList.get(k)); + String fieldhtmltype = Util.null2String((String)fieldHtmlTypeList.get(k)); + int col = mainFieldIds.indexOf(fieldid); + String tempvalue = POIUtil.getValue(sheet, rowsy, col); + if (conditionfield.equals(fieldname)&&!"".equals(tempvalue)&&"1".equals(fieldhtmltype)&&"1".equals(fieldtype)) { + data.add(tempvalue); + } + } + } + + rowsy++; + datas.add(data); + } + + RecordSet rsSet = new RecordSet(); + rsSet.executeBatchSql("insert into M_"+modeid+"_"+user.getUID()+"("+conditionfield+") values (?)",datas); + } + + + if (conditionfield.equals("dataid")) { + backfield = "b.id,a.dataid " ; + primarykey= "b.id"; + sqlfrom = "M_"+modeid+"_"+user.getUID()+" a, "+maintablename + " b "; + sqlwhere = "a.dataid = b.id"; + spp.setBackFields(backfield);// t1.id,t1.formmodeid + spp.setDistinct(false);//false + spp.setPrimaryKey(primarykey);//t1.id + spp.setSqlFrom(sqlfrom);// + spp.setSqlWhere(sqlwhere); + spp.setCountColumns(primarykey); //统计项 + spp.setPoolname(vdatasource);//"" + spp.setIsPrintExecuteSql(false); + spu.setSpp(spp); + String countSql = spu.getCountSql(); + rs.executeSql(countSql); + if (rs.next()) { + int total = Util.getIntValue(rs.getString(1), 0); + totalPage = (total - 1) / pageSize + 1; + } + for (int i = 1; i <= totalPage; i++) { + rs = spu.getCurrentPageRs(i, pageSize); + while (rs.next()) { + String id = Util.null2String(rs.getString("id")); + if (conditionFieldMap.containsKey(id)) { + conditionFieldMap.put(id, conditionFieldMap.get(id) + "," + id); + } else { + conditionFieldMap.put(id, id); + } + } + } + } else { + boolean issingletext =IsSingleText(conditionfield,fieldNameList,fieldTypeList,fieldHtmlTypeList); + if(issingletext){ + backfield = "b.id,a." + conditionfield; + primarykey ="b.id"; + sqlfrom = "M_"+modeid+"_"+user.getUID()+" a,"+maintablename+" b"; + sqlwhere = "a."+conditionfield+" = b."+conditionfield; + spp.setBackFields(backfield);// t1.id,t1.formmodeid + spp.setDistinct(false);//false + spp.setPrimaryKey(primarykey);//t1.id + spp.setSqlFrom(sqlfrom);// + spp.setSqlWhere(sqlwhere); + spp.setCountColumns(primarykey); //统计项 + spp.setPoolname(vdatasource);//"" + spp.setIsPrintExecuteSql(false); + spu.setSpp(spp); + }else{ + backfield = "id," + conditionfield; + sqlfrom = maintablename; + spp.setBackFields(backfield);// t1.id,t1.formmodeid + spp.setDistinct(false);//false + spp.setPrimaryKey(primarykey);//t1.id + spp.setSqlFrom(sqlfrom);// + spp.setSqlWhere(sqlwhere); + spp.setCountColumns(primarykey); //统计项 + spp.setPoolname(vdatasource);//"" + spp.setIsPrintExecuteSql(false); + spu.setSpp(spp); + } + + String countSql = spu.getCountSql(); + rs.executeSql(countSql); + if (rs.next()) { + int total = Util.getIntValue(rs.getString(1), 0); + totalPage = (total - 1) / pageSize + 1; + } + for (int i = 1; i <= totalPage; i++) { + rs = spu.getCurrentPageRs(i, pageSize); + String [] filename = rs.getColumnName(); + while (rs.next()) { + String id = Util.null2String(rs.getString("id")); + String valuestr = ""; + for(String str : filename){ + if(str.toLowerCase().equals("id")) continue; + String value = Util.null2String(rs.getString(str)); + value = value.replace("\'","''"); + if(!value.isEmpty()) { + int indexi = fieldNameList.indexOf(str.toLowerCase()); + if (indexi > -1) { + String fieldtype = Util.null2String((String) fieldTypeList.get(indexi)); + String fieldhtmltype = Util.null2String((String) fieldHtmlTypeList.get(indexi)); + String fielddbtype = Util.null2String((String) fieldDbTypeList.get(indexi)); + int qfws = Util.getIntValue((String) qfwsList.get(indexi), 0); + int type = Util.getIntValue(fieldtype); + int htmltype = Util.getIntValue(fieldhtmltype); + if(htmltype==1&&(type==3||type==4||type==5)){ + if(value.indexOf(",")!=-1){ + value = value.replace(",", ""); + } + if (type==3&&!"".equals(value)) { + BigDecimal bigDecimal = new BigDecimal(value); + value=bigDecimal.stripTrailingZeros().toPlainString(); + } + } + /*if ("5".equals(type + "") && htmltype == 1) { + //QC:311928 ,如果输入自带分号,那么先去掉分号,转换为double + if (value != null && value.indexOf(",") != -1) { + value = value.replace(",", ""); + } + value = Util.toDecimalDigits(value, qfws); + value = Util.milfloatFormat(value); + } else if (type == 3 && htmltype == 1) {//浮点数 + int digitsIndex = fielddbtype.indexOf(","); + int decimaldigits_t = 0; + if (digitsIndex > -1) { + decimaldigits_t = Util.getIntValue(fielddbtype.substring(digitsIndex + 1, fielddbtype.length() - 1), 2); + } else { + decimaldigits_t = 2; + } + if (value.indexOf(",") != -1) { + value = value.replace(",", ""); + } + value = Util.toDecimalDigits(value + "", decimaldigits_t); + }*/ + } + } + rs.writeLog("****************str:"+str+",value:"+value); + if(valuestr.isEmpty()){ + valuestr = value; + }else{ + valuestr += "#_#" + value; + } + } + /*for(String str : filename){ + if(str.toLowerCase().equals("id")) continue;; + String value = Util.null2String(rs.getString(str)); + value = value.replace("\'","''"); + if(valuestr.isEmpty()){ + valuestr = value; + }else{ + valuestr += "#_#" + value; + } + }*/ + if (conditionFieldMap.containsKey(valuestr)) { + conditionFieldMap.put(valuestr,conditionFieldMap.get(valuestr)+","+id ); + }else { + conditionFieldMap.put(valuestr, id); + } + } + } + } + //删除临时表 + dropMtable(Util.null2String(modeid)); + } + + rs.writeLog("****************conditionfield:"+conditionfield+",conditionFieldMap:"+conditionFieldMap); + + int sheetcount = 1;//sheet1 主表数据 + int rows = start; + + ExpExcelUtil.refreshImpUserState(user.getUID(), key);//刷新导入状态 + FormInfoService formInfoService = new FormInfoService(); + List> needlogFieldList = formInfoService.getNeedlogField(formid); + String columnNames = ""; + String tableName = ""; + if (needlogFieldList.size() > 0) { + for (int i = 0; i < needlogFieldList.size(); i++) { + Map needlogField = needlogFieldList.get(i); + String fieldname = Util.null2String(needlogField.get("fieldname")); + String detailtable = Util.null2String(needlogField.get("detailtable")); + if (!detailtable.equals("")) { + continue; + } + columnNames += fieldname; + if (i != (needlogFieldList.size() - 1)) { + columnNames += ","; + } + } + rs.executeSql("select tablename from workflow_bill where id = " + formid); + if (rs.next()) { + tableName = rs.getString("tablename"); + } + } + + //如果当某一行的所有数据都为空,则导入终止 + boolean canImport = ImpExcelServer.getProgressCanImport(key); + RecordSet recordSet = new RecordSet(); + List indexList = new ArrayList(); + if (rows == 0) { + rows = 1; + } + + int idCol = mainFieldIds.indexOf("-2000"); + + NumberFormat nf = NumberFormat.getInstance(); + nf.setGroupingUsed(false); + nf.setMaximumFractionDigits(100); + //表头下的具体内容 + while (canImport = ImpExcelServer.getProgressCanImport(key) && rows < end && rows >= start) { + if (StringCacheMap.containsKey(key + "_cancel")) { + break; + } + rowNumList.add(1); + if (rowNumList.size() % 20 == 0) { + ExpExcelUtil.refreshImpUserState(user.getUID(), key);//刷新导入状态 + } + ExpExcelUtil.refreshImpUserState(user.getUID(), key);//刷新导入状态 + ImpExcelServer.writeProgressMsg(key, SystemEnv.getHtmlLabelName(132246, user.getLanguage()) + ":" + rowNumList.size() + "/" + (POIUtil.getLastRowNum(sheet) - 1), "0"); + String updatesql = " update " + maintablename + " set "; + String tempdatesql = updatesql; + boolean flag = false; + String flagMsg = ""; + boolean isnull = true; + boolean iserrordata = false; + String conditionFieldValue = "";//条件字段的值 + + //id列 + String id = Util.null2String(POIUtil.getValue(sheet, rows, idCol)).trim(); + if (!"".equals(id)) { + isnull = false; + } + String mainKeyValue = ""; + boolean rowCanImport = true;//当前行进行验证,如,设置了导入字段必填,如果值为空则不允许导入当前行 + indexList.clear(); + // 生成插入sql + int k = 0; + Map> rowdatainfosMap = new HashMap>(); + boolean allisnull = false; + String tjzdval = "";//条件字段数据 + Map tjzdValMap = new HashMap<>(); + for (; k < fieldNameList.size(); k++) { + boolean isDepSup = false; //全路径导入的>处理 + String fieldid = Util.null2String((String) fieldIdList.get(k)); + String fieldtype = Util.null2String((String) fieldTypeList.get(k)); + String fielddbtype = Util.null2String((String) fieldDbTypeList.get(k)); + String fieldhtmltype = Util.null2String((String) fieldHtmlTypeList.get(k)); + String fieldname = Util.null2String((String) fieldNameList.get(k)); + String fieldlabel = Util.null2String((String) fieldLabelList.get(k)); + String fieldlabelname = Util.null2String((String) fieldLabelNameList.get(k)); + if (conditionfield.equals(fieldname)) { + conditionfielddbType = fielddbtype; + }//获得重复验证字段的 数据库属性 + int qfws = Util.getIntValue((String) qfwsList.get(k), 0); + int col = mainFieldIds.indexOf(fieldid); +// Cell cell = sheet.getCell(col, rows); + String tempvalue = POIUtil.getValue(sheet, rows, col); + tempvalue = tempvalue.trim();//去除两头的空格防止导入重复校验出错 + if (!Util.null2String(tempvalue).trim().equals("")) { + allisnull = true; + } + String tempvalueForIdentify = tempvalue; +// if((fieldtype.equals("5")||fieldtype.equals("4")||fieldtype.equals("3"))&&fieldhtmltype.equals("1")){//浮点数的话避免被四舍五入 +// try { +// if(cell instanceof NumberCell){ +// NumberCell numberCell = (NumberCell)cell; +// Double numberValue = numberCell.getValue(); +// tempvalue=nf.format(numberValue);//避免转换为值的时候变为科学计数法 +// }else{ +// tempvalue = Util.null2String(cell.getContents()).trim(); +// } +// } catch (Exception e) { +// tempvalue = Util.null2String(cell.getContents()).trim(); +// rs.writeLog(e); +// } +// }else if(fieldtype.equals("2")&&fieldhtmltype.equals("1")){//整数 +// try { +// tempvalue = Util.null2String(cell.getContents()).trim(); +// } catch (Exception e) { +// tempvalue = Util.null2String(cell.getContents()).trim(); +// rs.writeLog(e); +// } +// }else{ +// tempvalue = Util.null2String(cell.getContents()); + if ("1".equals(fieldtype) && "1".equals(fieldhtmltype)) {//文本 + tempvalue = tempvalue.replaceAll("\\n", ""); + if ("1".equals(modeFormFieldEncryptComInfo.getIsencrypt(fieldid))) { + tempvalue = CubeCipherUitl.encrypt(tempvalue); + } +// if(cell.getType() == CellType.NUMBER) { +// int dindex = tempvalue.indexOf("."); +// if(dindex!=-1){//不包含小数点,直接导入 +// double tempDoubleVal=((NumberCell)cell).getValue(); +// tempvalue=nf.format(tempDoubleVal);//避免转换为值的时候变为科学计数法 +// } +// } + } + if ("3".equals(fieldhtmltype) && ("161".equals(fieldtype) || "162".equals(fieldtype))) { + tempvalue = CubeCipherUitl.getBrowserEncryptValueImp(fielddbtype, tempvalue, fieldtype); + } + + String tempString = tempvalue; + if ("2".equals(fieldtype) && "2".equals(fieldhtmltype) && !StringHelper.isEmpty(tempvalue)) { + String[] tempFieldValue = tempvalue.split("

|

||
"); + for (int i = 0; i < tempFieldValue.length; i++) { + String temp = tempFieldValue[i].replaceAll("<", "<"); + temp = temp.replaceAll(">", ">"); + tempString = tempString.replace(tempFieldValue[i], temp); + } + if (!tempString.isEmpty()) { + tempString = "

" + tempString.replaceAll("\n", "

\n

") + "

"; + } + tempString = tempString.replaceAll("'", "'"); + tempString = tempString.replaceAll("
", ""); + //String reg="[\u0000-\u001f|\ufffd|囧|]"; + tempString = tempString.replaceAll(" ", " "); + tempvalue = tempString; + } +// } + //判断tempvalue中的值是不是"null" + Boolean isNullValue = false; + String oldtempvalue = tempvalue; + tempvalue = StringHelper.convertSpecialChar2Html(tempvalue); + if (importtype == 3) {//更新才做NULL值导入 + String[] tmpv = tempvalue.split(","); + tempvalue = ""; + for (int i = 0; i < tmpv.length; i++) { + tmpv[i] = CubeCipherUitl.decrypt(tmpv[i]); + if (i != tmpv.length - 1) { + tempvalue += tmpv[i] + ","; + } else { + tempvalue += tmpv[i]; + } + } + isNullValue = "null".equalsIgnoreCase(tempvalue) ? true : false; + oldtempvalue = "null".equalsIgnoreCase(tempvalue) ? null : tempvalue; + tempvalue = StringHelper.convertSpecialChar2Html(oldtempvalue); + } + int type = Util.getIntValue(fieldtype); + int htmltype = Util.getIntValue(fieldhtmltype); + String checkvalue = tempvalue; + boolean iserrortime = false; + boolean iserrordatatime = false; + if (htmltype == 3) { + if (type == 2 || type == 19) { // 日期 + Cell cell = POIUtil.getCell(sheet, rows, col); + checkvalue = ImpExcelUtil.getDateOrTime(cell, checkvalue, type); + if (checkvalue.startsWith("#@ERROR@#")) { + checkvalue = checkvalue.replace("#@ERROR@#", ""); + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + checkvalue + "," + SystemEnv.getHtmlLabelName(24944, user.getLanguage())); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + checkvalue + "+" + SystemEnv.getHtmlLabelName(24944, user.getLanguage()) + + "+" + fieldlabelname + "+" + fieldname + "+" + fielddbtype + "+" + maintablename + + "+" + checkvalue + ":" + SystemEnv.getHtmlLabelName(24944, user.getLanguage())); + IdMap.put(id + "sql", "" + checkvalue + ":" + SystemEnv.getHtmlLabelName(391280, user.getLanguage())); + iserrordata = true; + checkvalue = ""; + iserrortime = true; + } + } else if (type == 290) {//日期时间 + Cell cell = POIUtil.getCell(sheet, rows, col); + checkvalue = ImpExcelUtil.getDateTime(cell, checkvalue, type); + if (checkvalue.startsWith("#@ERROR@#")) { + checkvalue = checkvalue.replace("#@ERROR@#", ""); + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + checkvalue + "," + SystemEnv.getHtmlLabelName(24944, user.getLanguage())); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + checkvalue + "+" + SystemEnv.getHtmlLabelName(24944, user.getLanguage()) + + "+" + fieldlabelname + "+" + fieldname + "+" + fielddbtype + "+" + maintablename + + "+" + checkvalue + ":" + SystemEnv.getHtmlLabelName(24944, user.getLanguage())); + IdMap.put(id + "sql", "" + checkvalue + ":" + SystemEnv.getHtmlLabelName(391281, user.getLanguage())); + iserrordata = true; + checkvalue = ""; + iserrordatatime = true; + } + } + } + + if (!checkDataByExpression(fieldid, checkvalue)) { + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + SystemEnv.getHtmlLabelName(132247, user.getLanguage())); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + checkvalue + "+" + SystemEnv.getHtmlLabelName(132247, user.getLanguage()) + + "+" + fieldlabelname + "+" + fieldname + "+" + fielddbtype + "+" + maintablename + + "+" + checkvalue + ":" + SystemEnv.getHtmlLabelName(132247, user.getLanguage())); + IdMap.put(id + "sql", "" + checkvalue + ":" + SystemEnv.getHtmlLabelName(391282, user.getLanguage())); + indexList.add((String) errorRow.get(errorRow.size() - 1)); //获得当前错误提示的idnex + updatesql = tempdatesql; + rowCanImport = false; + } + + // excel值转换 + //根据条件来判断是否必填 + String tempCondition = ""; + String tempHead = ""; + String tempFieldName = ""; + boolean validateflag = false; + for (Map.Entry> et : validateMap.entrySet()) { + String key = et.getKey(); + if (fieldid.equals(key)) { + List value = et.getValue(); + if (value.size() == 0) { + tempHead = Util.null2String(POIUtil.getValue(sheet, 0, col)); + validateflag = true; + break; + } + for (String selectid : value) { + String[] values = selectid.split(":"); + int index = mainFieldIds.indexOf(values[0]); + tempCondition = Util.null2String(POIUtil.getValue(sheet, rows, index)); + if ((tempCondition).equals(values[1])) { + tempHead = Util.null2String(POIUtil.getValue(sheet, 0, col)); + tempFieldName = Util.null2String(POIUtil.getValue(sheet, 0, index)); + validateflag = true; + break; + } + } + } + if (validateflag) { + break; + } + } + + if ("".equals(tempvalue) && validateflag) { + if (!"".equals(tempCondition)) { + tempCondition = MessageFormat.format(SystemEnv.getHtmlLabelName(132243, user.getLanguage()), tempFieldName, tempCondition, tempHead); + } else { + tempCondition = MessageFormat.format(SystemEnv.getHtmlLabelName(132244, user.getLanguage()), tempHead); + } + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + "" + tempCondition); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + "" + tempCondition + "+" + fieldlabelname + + "+" + fieldname + "+" + fielddbtype + "+" + maintablename + "+" + SystemEnv.getHtmlLabelName(21778, user.getLanguage()) + fieldlabelname + SystemEnv.getHtmlLabelName(391283, user.getLanguage())); + IdMap.put(id + "sql", SystemEnv.getHtmlLabelName(21778, user.getLanguage()) + fieldlabelname + SystemEnv.getHtmlLabelName(391284, user.getLanguage())); + indexList.add((String) errorRow.get(errorRow.size() - 1)); //获得当前错误提示的idnex + updatesql = tempdatesql; + rowCanImport = false; + } + + + if (!tempvalue.equals("") || isNullValue) { + isnull = false; + if (fieldTransObject != null && fieldtranslist.contains(fieldid)) {//调用自定义转换接口 + this.params.put("fieldid", fieldid); + this.params.put("fieldname", fieldname); + if (fieldTransObject instanceof ImportFieldTransAction) { + ImportFieldTransAction fieldTrans = (ImportFieldTransAction) fieldTransObject; + tempvalue = fieldTrans.getTransValue(this.params, user, sheetJXL, rows, col); + } else if (fieldTransObject instanceof ImportFieldTransActionPOI) { + ImportFieldTransActionPOI fieldTrans = (ImportFieldTransActionPOI) fieldTransObject; + ExcelParseForPOI excelParse = (ExcelParseForPOI) this.params.get("excelParse"); + tempvalue = fieldTrans.getTransValue(this.params, user, excelParse, (rows + 1), (col + 1)); + } + } else { + tempvalue = tempvalue.replace("'", "''"); + if (type == 2 && htmltype == 1) {//整数 + Pattern pattern = Pattern.compile("^(-)?\\d+$"); + Matcher isFlag = pattern.matcher(tempvalue); + if (!isFlag.matches() && !isNullValue) { + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + tempvalue + "," + SystemEnv.getHtmlLabelName(382376, user.getLanguage())); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + tempvalue + "+" + SystemEnv.getHtmlLabelName(382376, user.getLanguage()) + + "+" + fieldlabelname + "+" + fieldname + "+" + fielddbtype + "+" + maintablename + + "+" + tempvalue + ":" + SystemEnv.getHtmlLabelName(382376, user.getLanguage()) + "," + SystemEnv.getHtmlLabelName(391252, user.getLanguage()) + "!"); + IdMap.put(id + "sql", SystemEnv.getHtmlLabelName(21778, user.getLanguage()) + ":" + fieldlabelname + "-" + tempvalue + ":" + SystemEnv.getHtmlLabelName(391285, user.getLanguage())); + iserrordata = true; + tempvalue = ""; + } + } else if (htmltype == 2 && type == 2 && importtype == 3 && tempvalue.equalsIgnoreCase("

null

")) { + tempvalue = ""; + isNullValue = true; + } else if ((type == 3 || type == 4 || type == 5) && htmltype == 1) {//浮点数 + String excelVal = tempvalue; + tempvalue = tempvalue.replace(",", ""); + Pattern pattern = Pattern.compile("^(-)?(0|([1-9]\\d*))(.\\d+)?$"); //浮点数 + Matcher isFlag = pattern.matcher(tempvalue); + if (!isFlag.matches() && !isNullValue) { + String errMsg = ""; + if (type == 3) { + errMsg = SystemEnv.getHtmlLabelName(382377, user.getLanguage()); + } else if (type == 4) { + errMsg = SystemEnv.getHtmlLabelName(382378, user.getLanguage()); + } else if (type == 5) { + errMsg = SystemEnv.getHtmlLabelName(382379, user.getLanguage()); + } + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + ",“" + excelVal + "”," + errMsg); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+“" + excelVal + "”+" + errMsg + "+" + fieldlabelname + + "+" + fieldname + "+" + fielddbtype + "+" + maintablename + "+" + excelVal + ":" + errMsg); + IdMap.put(id + "sql", SystemEnv.getHtmlLabelName(21778, user.getLanguage()) + fieldlabelname + "," + errMsg + "!" + SystemEnv.getHtmlLabelName(391286, user.getLanguage())); + iserrordata = true; + tempvalue = ""; + } + } else if (htmltype == 3) { + //浏览按钮多支持 主键导入 + //判断是否ID串 + boolean isNumber = false; + String[] number = null; + if (type == 161) { + number = tempvalue.split("weaver_ecology"); + } else { + if (type != 1) { + if (tempvalue.indexOf("DH{") != -1) {//批量导入自定义多选时,如果选项中有英文逗号,批量导入时用DH{}包裹 + String[] tempNumber = tempvalue.split(",");//数组格式:{"xxxx","DH{XXXX","XXXX"?(也许有),"xxx}"},其中DH{}中间包裹的值是自定义多选的一个选项 + List list = new ArrayList(); + int i = 0; + int j = 0; + while (i < tempNumber.length) { + if (tempNumber[i].indexOf("DH{") != -1) { + list.add(tempNumber[i].substring(3, tempNumber[i].length()) + ","); + i++; + boolean flag1 = false; + while (!flag1) {//判断数组中是否含有 + if (tempNumber[i].indexOf("}") != -1) { + list.add(list.get(j) + tempNumber[i].substring(0, tempNumber[i].length() - 1)); + list.remove(j); + i++; + j++; + flag1 = true; + } else { + list.add(list.get(j) + tempNumber[i] + ","); + list.remove(j); + i++; + } + } + } else { + list.add(tempNumber[i]); + i++; + j++; + } + } + number = list.toArray(new String[list.size()]); + } else { + number = tempvalue.split(","); + } + } else { + number = new String[]{tempvalue}; + } + } + if (number != null && number.length > 0) { + for (String num : number) { + Pattern pattern = Pattern.compile("^(-)?[1-9][0-9]*$"); //验证正数或负数 + Matcher isNum = pattern.matcher(num.trim()); + if (!isNum.matches()) {//非数字 进行ID获取 + isNumber = false; + break; + } else { + isNumber = true; + } + } + } + + //虚拟表单修改主键后 主键不一定是数字类型 不能用数字类型作为判断 只能检查主键数据中是否存在改数据 zwbo + if (!isNumber) { + if (type == 161 || type == 162) { //自定义单选和多选 + //浏览框为虚拟表单 并且修改主键 + String pkname = ""; + Browser browser = ModeCacheManager.getInstance().getBrowserSetMap(fielddbtype); + String browser_id = browser.getCustomid(); + if (!StringHelper.isEmpty(browser_id)) { + boolean isVFrom = false; + if (customBrowserMap.containsKey(browser_id)) { + isVFrom = customBrowserMap.get(browser_id); + } else { + RecordSet virrs = new RecordSet(); + virrs.execute("select a.formid,b.vprimarykey from mode_custombrowser a,modeformextend b where a.id =" + browser_id + " AND a.formid=b.formid "); + if (virrs.next()) { + isVFrom = true; + } + customBrowserMap.put(browser_id, isVFrom); + } + if (isVFrom && number.length > 0) { + BrowserBean browserBean = browser.searchById(number[0].trim()); + if (browserBean.getId() == null) { + isNumber = false; + } else { + isNumber = true; + } + } + } + } + } + //---------------------------提取start----------------------------- + if (type == 2 || type == 19 || type == 403) { // 时间 + if (!iserrortime) { +// tempvalue = Util.null2String(cell.getContents()); + Cell cell = POIUtil.getCell(sheet, rows, col); + tempvalue = ImpExcelUtil.getDateOrTime(cell, tempvalue, type); + if (tempvalue.startsWith("#@ERROR@#")) { + tempvalue = tempvalue.replace("#@ERROR@#", ""); + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + tempvalue + "," + SystemEnv.getHtmlLabelName(24944, user.getLanguage())); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + tempvalue + "+" + SystemEnv.getHtmlLabelName(24944, user.getLanguage()) + + "+" + fieldlabelname + "+" + fieldname + "+" + fielddbtype + "+" + maintablename + + "+" + tempvalue + ":" + SystemEnv.getHtmlLabelName(24944, user.getLanguage())); + IdMap.put(id + "sql", SystemEnv.getHtmlLabelName(21778, user.getLanguage()) + ":" + fieldlabelname + "-" + tempvalue + ":" + SystemEnv.getHtmlLabelName(391280, user.getLanguage())); + iserrordata = true; + tempvalue = ""; + } + } + oldtempvalue = tempvalue; + } else if (type == 290) {//日期时间 + if (!iserrordatatime) { +// tempvalue = Util.null2String(cell.getContents()); + Cell cell = POIUtil.getCell(sheet, rows, col); + tempvalue = ImpExcelUtil.getDateTime(cell, tempvalue, type); + TimeZoneVar.setTimeZone(timezone); + tempvalue = "".equals(Util.null2String(tempvalue)) ? "" : new DateTransformer().getServerDateTime(tempvalue); + if (tempvalue != null && tempvalue.indexOf(":") != tempvalue.lastIndexOf(":")) { + tempvalue = tempvalue.substring(0, tempvalue.lastIndexOf(":")); + } + if (tempvalue.startsWith("#@ERROR@#")) { + tempvalue = tempvalue.replace("#@ERROR@#", ""); + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + tempvalue + "," + SystemEnv.getHtmlLabelName(24944, user.getLanguage())); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + tempvalue + "+" + SystemEnv.getHtmlLabelName(24944, user.getLanguage()) + + "+" + fieldlabelname + "+" + fieldname + "+" + fielddbtype + "+" + maintablename + + "+" + tempvalue + ":" + SystemEnv.getHtmlLabelName(24944, user.getLanguage())); + IdMap.put(id + "sql", SystemEnv.getHtmlLabelName(21778, user.getLanguage()) + ":" + fieldlabelname + "-" + tempvalue + ":" + SystemEnv.getHtmlLabelName(391281, user.getLanguage())); + iserrordata = true; + tempvalue = ""; + } + } + oldtempvalue = tempvalue; + } else if (type == 402) {//年、年是int型,判断值是否是整数 + Pattern pattern = Pattern.compile("^(-)?\\d+$"); + Matcher isFlag = pattern.matcher(tempvalue); + if (!isFlag.matches() && !isNullValue) { + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + tempvalue + "," + SystemEnv.getHtmlLabelName(382376, user.getLanguage())); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + tempvalue + "+" + SystemEnv.getHtmlLabelName(382376, user.getLanguage()) + + "+" + fieldlabelname + "+" + fieldname + "+" + fielddbtype + "+" + maintablename + + "+" + tempvalue + ":" + SystemEnv.getHtmlLabelName(382376, user.getLanguage()) + "," + SystemEnv.getHtmlLabelName(391252, user.getLanguage()) + "!"); + IdMap.put(id + "sql", SystemEnv.getHtmlLabelName(21778, user.getLanguage()) + ":" + fieldlabelname + "-" + tempvalue + ":" + SystemEnv.getHtmlLabelName(391285, user.getLanguage())); + iserrordata = true; + tempvalue = ""; + } + } else if ((type == 4 || type == 57 || type == 168 || type == 167) && (tempvalue.indexOf(">") > -1 || tempvalue.indexOf(this.sepCharacter) > -1 && this.isDepartAndSubpany)) {//如果部门里面有> 代表逐级导入 + ArrayList tempvalues = Util.TokenizerString(tempvalue, ","); + String temps = ""; + for (int n = 0; n < tempvalues.size(); n++) { + String temp = Util.null2String(tempvalues.get(n)); + Map tempvalueMap = getIdByPathName(1, temp); + if (Util.null2String(tempvalueMap.get("flag")).equals("0")) { + temp = tempvalueMap.get("value"); + } else { + boolean isflag = isDepartAndSubpany; + if (!isflag) { + errorRow.add(sheetcount + "," + rows + "," + col + "," + ((String) tempvalueMap.get("orgname")).trim()); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + ((String) tempvalueMap.get("orgname")).trim() + + "+" + fieldlabelname + "+" + fieldname + "+" + fielddbtype + "+" + maintablename + + "+" + temp + ":" + SystemEnv.getHtmlLabelName(391288, user.getLanguage()) + "select id from hrmdepartment where departmentname='" + temp + "'"); + IdMap.put(id + "sql", SystemEnv.getHtmlLabelName(21778, user.getLanguage()) + ":" + fieldlabelname + "-" + ((String) tempvalueMap.get("orgname")).trim() + ":" + SystemEnv.getHtmlLabelName(391287, user.getLanguage())); + } else { + isDepSup = true; + } + + } + temps += "," + temp; + } + if (temps.length() > 0) { + temps = temps.substring(1); + } + if (!isDepSup) { + tempvalue = temps; + } + } else if ((type == 164 || type == 169 || type == 170 || type == 194) && tempvalue.indexOf(">") > -1) { //如果分部里面有> 代表逐级导入 + ArrayList tempvalues = Util.TokenizerString(tempvalue, ","); + String temps = ""; + for (int n = 0; n < tempvalues.size(); n++) { + String temp = Util.null2String(tempvalues.get(n)); + Map tempvalueMap = getIdByPathName(0, temp); + if (Util.null2String(tempvalueMap.get("flag")).equals("0")) { + temp = tempvalueMap.get("value"); + } else { + boolean isflag = isDepartAndSubpany; + if (isflag) { + isDepSup = true; + } else { + errorRow.add(sheetcount + "," + rows + "," + col + "," + ((String) tempvalueMap.get("orgname")).trim()); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + ((String) tempvalueMap.get("orgname")).trim() + + "+" + fieldlabelname + "+" + fieldname + "+" + fielddbtype + "+" + maintablename + + "+" + temp + ":" + SystemEnv.getHtmlLabelName(391267, user.getLanguage()) + "select id from HrmSubCompany where subcompanyname='" + temp + "'"); + IdMap.put(id + "sql", SystemEnv.getHtmlLabelName(21778, user.getLanguage()) + ":" + fieldlabelname + "- " + ((String) tempvalueMap.get("orgname")).trim() + ":" + SystemEnv.getHtmlLabelName(391289, user.getLanguage())); + } + } + temps += "," + temp; + } + if (temps.length() > 0) { + temps = temps.substring(1); + } + if (!isDepSup) { + tempvalue = temps; + } + } else if ((type == 1 || type == 17 || type == 165 || type == 166) && (tempvalue.indexOf(">") > -1 || tempvalue.indexOf(this.sepCharacter) > -1 && this.isDepartAndSubpany)) { //如果人员里面有> 代表逐级导入 + ArrayList tempvalues = Util.TokenizerString(tempvalue, ","); + String temps = ""; + for (int n = 0; n < tempvalues.size(); n++) { + String temp = Util.null2String(tempvalues.get(n)); + Map tempvalueMap = getIdByPathName(2, temp); + if (Util.null2String(tempvalueMap.get("flag")).equals("0")) { + temp = tempvalueMap.get("value"); + } else { + errorRow.add(sheetcount + "," + rows + "," + col + "," + ((String) tempvalueMap.get("orgname")).trim()); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + ((String) tempvalueMap.get("orgname")).trim() + + "+" + fieldlabelname + "+" + fieldname + "+" + fielddbtype + "+" + maintablename + + "+" + temp + ":" + SystemEnv.getHtmlLabelName(391270, user.getLanguage()) + "select id from hrmresource where lastname='" + temp + "' and departmentid=0"); + IdMap.put(id + "sql", SystemEnv.getHtmlLabelName(21778, user.getLanguage()) + ":" + fieldlabelname + "-" + ((String) tempvalueMap.get("orgname")).trim() + ":" + SystemEnv.getHtmlLabelName(391290, user.getLanguage())); + } + temps += "," + temp; + } + if (temps.length() > 0) { + temps = temps.substring(1); + } + tempvalue = temps; + } else if (type == 224 || type == 225 || type == 226 || type == 227) { + oldtempvalue = tempvalue; + } else if ((type == 4 || type == 57) || (type == 164 || type == 194)) { //虚拟部门 虚拟分部 + String flagStr = ""; + String keyname = ""; + String tablename = ""; + String keynameall = "";//支持全称导入 + if ((type == 4 || type == 57)) { + if (tempvalue.toLowerCase().startsWith("virtual_")) { + flagStr = "virtual_"; + if (tempvalue.startsWith("VIRTUAL_")) { + flagStr = "VIRTUAL_"; + } + keyname = "departmentmark"; + keynameall = "departmentname"; + tablename = "HrmDepartmentVirtual"; + } else if (tempvalue.startsWith("-")) { + keyname = "id"; + tablename = "HrmDepartmentVirtual"; + } else if (tempvalue.startsWith("deptcode_")) { + tablename = "HrmDepartment"; + keyname = "departmentcode"; + if (tempvalue.indexOf("deptcode_") != -1) { + tempvalue = tempvalue.replace("deptcode_", ""); + } else { + tempvalue = tempvalue.substring(9); + } + } else { + tablename = "HrmDepartment"; + keyname = "departmentmark"; + if (isNumber) { + keyname = "id"; + } else { + keynameall = "departmentname"; + } + } + } else if ((type == 164 || type == 194)) { + if (tempvalue.toLowerCase().startsWith("virtual_")) { + flagStr = "virtual_"; + if (tempvalue.startsWith("VIRTUAL_")) { + flagStr = "VIRTUAL_"; + } + keyname = "subcompanydesc"; + keynameall = "subcompanyname"; + tablename = "hrmsubcompanyvirtual"; + } else if (tempvalue.startsWith("-")) { + keyname = "id"; + tablename = "hrmsubcompanyvirtual"; + } else { + tablename = "hrmsubcompany"; + keyname = "subcompanydesc"; + if (isNumber) { + keyname = "id"; + } else { + keynameall = "subcompanyname"; + } + } + } + //部门及分部封存,人员离职过滤 + String hrmFilterCondiction = ""; + if ("HrmDepartment".equalsIgnoreCase(tablename.toLowerCase()) || "hrmsubcompany".equalsIgnoreCase(tablename.toLowerCase()) + || "HrmDepartmentVirtual".equalsIgnoreCase(tablename.toLowerCase()) || + "hrmsubcompanyvirtual".equalsIgnoreCase(tablename.toLowerCase())) { + hrmFilterCondiction = " and (canceled!=1 or canceled is null)"; + } + + ArrayList tempvalues = Util.TokenizerString(tempvalue, ","); + + ArrayList tempvalueForIdentifys = Util.TokenizerString(tempvalueForIdentify, ","); + tempvalue = ""; + String values = ""; + for (int n = 0; n < tempvalues.size(); n++) { + if (!((String) tempvalues.get(n)).trim().toLowerCase().startsWith(flagStr)) + continue; + values += ",'" + ((String) tempvalues.get(n)).trim().replace(flagStr, "") + "'"; + } + if (!StringHelper.isEmpty(values)) { + values = values.substring(1); + + for (int n = 0; n < tempvalues.size(); n++) { + rs = new RecordSet(); + String value = ((String) tempvalues.get(n)).trim().replace(flagStr, ""); + value = checkDepartAndSubpany(value); + //添加判断value 是不是id 或者编号 + String identifyValue = ((String) tempvalueForIdentifys.get(n)).trim().replace(flagStr, ""); + if (isNumberOrCode(identifyValue)) { + hrmFilterCondiction = ""; + } + if (!"".equals(keynameall)) { + sql = "select id," + keynameall + " as showname from " + tablename + " where " + keynameall + " = '" + value + "' " + hrmFilterCondiction + " order by id desc"; + rs.executeSql(sql); + } + if (rs.getCounts() <= 0) { + sql = "select id," + keyname + " as showname from " + tablename + " where " + keyname + " = '" + value + "' " + hrmFilterCondiction + " order by id desc"; + rs.executeSql(sql); + } + if (!rs.next()) {//判断是否为多语言 + if (!"".equals(keynameall)) { + String tempSqlTemp = "select id," + keynameall + " as showname from " + tablename + + " where (" + keynameall + " like '%" + "`~`7 " + value + "`~`" + "%' or " + keynameall + " like '%" + "`~`8 " + value + "`~`" + "%' or " + keynameall + " like '%" + "`~`9 " + value + "`~`" + "%')" + + hrmFilterCondiction + " order by id desc"; + rs.execute(tempSqlTemp); + } + if (rs.getCounts() <= 0) { + String tempSqlTemp = "select id," + keyname + " as showname from " + tablename + + " where (" + keyname + " like '%" + "`~`7 " + value + "`~`" + "%' or " + keyname + " like '%" + "`~`8 " + value + "`~`" + "%' or " + keyname + " like '%" + "`~`9 " + value + "`~`" + "%')" + + hrmFilterCondiction + " order by id desc"; + rs.execute(tempSqlTemp); + } + } + rs.beforFirst(); + boolean isExists = false; + while (rs.next()) { + String showname = rs.getString("showname"); + showname = Util.formatMultiLang(showname, user.getLanguage() + ""); + String tempValue = (String) tempvalues.get(n); + tempValue = checkDepartAndSubpany(tempValue.trim()); + String shownameNew = (flagStr + showname).replace("'", "''"); + if (shownameNew.equals(tempValue)) { + tempvalue += "," + rs.getString(1); + isExists = true; + break; + } + } + if (!isExists) { + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + ((String) tempvalues.get(n)).trim()); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + ((String) tempvalues.get(n)).trim() + + "+" + fieldlabelname + "+" + fieldname + "+" + fielddbtype + "+" + maintablename + + "+" + ((String) tempvalues.get(n)).trim() + ":" + SystemEnv.getHtmlLabelName(391271, user.getLanguage()) + "
" + SystemEnv.getHtmlLabelName(132258, user.getLanguage()) + ":
" + sql); + IdMap.put(id + "sql", SystemEnv.getHtmlLabelName(21778, user.getLanguage()) + ":" + fieldlabelname + "-" + ((String) tempvalues.get(n)).trim() + ":" + SystemEnv.getHtmlLabelName(127576, user.getLanguage()) + "
" + SystemEnv.getHtmlLabelName(132258, user.getLanguage()) + ":
" + sql + "
" + SystemEnv.getHtmlLabelName(391286, user.getLanguage())); + iserrordata = true; + } + } + if (tempvalue.startsWith(",")) { + tempvalue = tempvalue.substring(1); + } + } + } else if (!isNullValue && (type == 161 || type == 162)) { + if (!isNumber) { + if (type == 161) { // 自定义单选 + Browser browser = ModeCacheManager.getInstance().getBrowserSetMap(fielddbtype); + Map browserMap = ModeCacheManager.getInstance().getIdByNames(fielddbtype, tempvalue, user.getLanguage()); + if (browserMap.containsKey("ids")) { + tempvalue = browserMap.get("ids"); + } else { + //解决浏览框名称为整数,判断有误情况 + String realTempvalue = analyzeNameValue(tempvalue); + Map resultmap = analyzeIdValue(realTempvalue); + BrowserBean BrowserBean = null; + if (!("").equals(resultmap.get("id"))) { + BrowserBean = browser.searchById(resultmap.get("id").toString().replace("''", "'")); + } else { + BrowserBean = browser.searchForImport(resultmap.get("name").toString().replace("''", "'"), user); + } + if (null == BrowserBean) { + BrowserBean = browser.searchById(realTempvalue.replace("''", "'")); + } + if (BrowserBean != null) { + String val = BrowserBean.getId(); + String browserSql = browser.getSearchByName(); + if (val == null) { + tempvalue = CubeCipherUitl.decrypt(tempvalue); + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + tempvalue.replace(",", ",")); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + tempvalue.replace(",", ",") + + "+" + fieldlabelname + "+" + fieldname + "+" + fielddbtype + "+" + maintablename + + "+" + SystemEnv.getHtmlLabelName(391272, user.getLanguage()) + "" + tempvalue.replace(",", ",") + "
" + SystemEnv.getHtmlLabelName(132258, user.getLanguage()) + ":
" + browserSql); + IdMap.put(id + "sql", SystemEnv.getHtmlLabelName(21778, user.getLanguage()) + ":" + fieldlabelname + "-" + tempvalue.replace(",", ",") + "" + SystemEnv.getHtmlLabelName(391291, user.getLanguage()) + ":
" + browserSql); + iserrordata = true; + tempvalue = ""; + } else { + tempvalue = val; + } + } else { + tempvalue = CubeCipherUitl.decrypt(tempvalue); + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + tempvalue.replace(",", ",")); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + tempvalue.replace(",", ",") + + "+" + fieldlabelname + "+" + fieldname + "+" + fielddbtype + "+" + maintablename + "+" + SystemEnv.getHtmlLabelName(391272, user.getLanguage())); + IdMap.put(id + "sql", SystemEnv.getHtmlLabelName(21778, user.getLanguage()) + ":" + fieldlabelname + "-" + tempvalue.replace(",", ",") + ":" + SystemEnv.getHtmlLabelName(391293, user.getLanguage())); + iserrordata = true; + tempvalue = ""; + } + } + } else if (type == 162) { // 自定义多选 + Browser browser = ModeCacheManager.getInstance().getBrowserSetMap(fielddbtype); + Map browserMap = ModeCacheManager.getInstance().getIdByNames(fielddbtype, tempvalue, user.getLanguage()); + if (browserMap.containsKey("ids")) { + tempvalue = browserMap.get("ids"); + } else { + //解决浏览框名称为整数,判断有误情况 + String realTempvalue = analyzeNameValue(tempvalue); + Map resultmap = analyzeIdValue(realTempvalue); + BrowserBean BrowserBean = null; + if (!("").equals(resultmap.get("id"))) { + BrowserBean = browser.searchById2(resultmap.get("id").toString().replace("''", "'")); + } else { + BrowserBean = browser.searchForImport2(resultmap.get("name").toString().replace("''", "'"), user); + } + if (BrowserBean != null) { + String tempvaluenew = BrowserBean.getId(); + if (tempvaluenew.indexOf("null") > -1 || StringHelper.isEmpty(tempvalue)) { + BrowserBean = browser.searchById2(tempvalue); + } + } + if (BrowserBean != null) { + String browserSql = browser.getSearchByName(); + if (browserSql == null || browserSql.equals("")) { + browserSql = SystemEnv.getHtmlLabelName(500319, user.getLanguage()); + } + String[] tempvalues = tempvalue.split(","); + String old_val = ""; + for (String string : tempvalues) { + old_val += "," + CubeCipherUitl.decrypt(string); + } + if (old_val.startsWith(",")) { + old_val = old_val.substring(1, old_val.length()); + } + tempvalue = BrowserBean.getId(); + if (tempvalue.indexOf("null") > -1 || StringHelper.isEmpty(tempvalue)) { + tempvalue = CubeCipherUitl.decrypt(tempvalue); + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + old_val); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + old_val + + "+" + fieldlabelname + "+" + fieldname + "+" + fielddbtype + "+" + maintablename + + "+" + SystemEnv.getHtmlLabelName(391272, user.getLanguage()) + "" + old_val + "
" + SystemEnv.getHtmlLabelName(132258, user.getLanguage()) + ":
" + browserSql); + IdMap.put(id + "sql", SystemEnv.getHtmlLabelName(21778, user.getLanguage()) + ":" + fieldlabelname + "-" + old_val + "" + SystemEnv.getHtmlLabelName(391291, user.getLanguage()) + ":" + SystemEnv.getHtmlLabelName(132258, user.getLanguage()) + ":
" + browserSql); + iserrordata = true; + tempvalue = ""; + } + } else { + tempvalue = CubeCipherUitl.decrypt(tempvalue); + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + tempvalue); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + tempvalue + + "+" + fieldlabelname + "+" + fieldname + "+" + fielddbtype + "+" + maintablename + "+" + SystemEnv.getHtmlLabelName(391272, user.getLanguage())); + IdMap.put(id + "sql", SystemEnv.getHtmlLabelName(21778, user.getLanguage()) + ":" + fieldlabelname + "-" + tempvalue + ":" + SystemEnv.getHtmlLabelName(391293, user.getLanguage())); + iserrordata = true; + tempvalue = ""; + } + } + } + } else { + Browser browser = ModeCacheManager.getInstance().getBrowserSetMap(fielddbtype); + if (number != null && number.length > 0) { + int r = ModeCacheManager.getInstance().isContainBrowserIds(fielddbtype, tempvalue, user.getLanguage()); + if (r == -1) { //没有缓存 + for (String num : number) { + BrowserBean browserBean = browser.searchById(num.trim()); + String browserSql = browser.getSearchByName(); + if (browserBean == null || browserBean.getId() == null) { + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + tempvalue); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + tempvalue + + "+" + fieldlabelname + "+" + fieldname + "+" + fielddbtype + "+" + maintablename + + "+" + tempvalue + "
" + SystemEnv.getHtmlLabelName(132258, user.getLanguage()) + ":
" + browserSql); + IdMap.put(id + "sql", SystemEnv.getHtmlLabelName(21778, user.getLanguage()) + ":" + fieldlabelname + "-" + tempvalue + "
" + SystemEnv.getHtmlLabelName(132258, user.getLanguage()) + ":
" + browserSql); + iserrordata = true; + tempvalue = ""; + break; + } + } + } else if (r == 0) {//存在未找到 + String browserSql = ModeCacheManager.getInstance().getBrowserSql(fielddbtype, tempvalue, user.getLanguage()); + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + tempvalue); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + tempvalue + + "+" + fieldlabelname + "+" + fieldname + "+" + fielddbtype + "+" + maintablename + "+" + SystemEnv.getHtmlLabelName(391272, user.getLanguage()) + "!" + tempvalue + "
" + SystemEnv.getHtmlLabelName(132258, user.getLanguage()) + ":
" + browserSql); + IdMap.put(id + "sql", SystemEnv.getHtmlLabelName(21778, user.getLanguage()) + ":" + fieldlabelname + ":" + SystemEnv.getHtmlLabelName(391272, user.getLanguage()) + "!" + SystemEnv.getHtmlLabelName(391286, user.getLanguage()) + ":
" + SystemEnv.getHtmlLabelName(132258, user.getLanguage()) + ":
" + browserSql); + iserrordata = true; + tempvalue = ""; + break; + } + } + } + } else if (!isNullValue && (type == 256 || type == 257)) { + String tempIdStr = ""; + if (!tempvalue.isEmpty()) { + CustomTreeComInfo comInfo = new CustomTreeComInfo(); + boolean showlevel = "1".equals(comInfo.get(CustomTreeComInfo.showlevel, fielddbtype)); + String levelsplitchar = comInfo.get(CustomTreeComInfo.levelsplitchar, fielddbtype); + List> list = new ArrayList>(); + List> listBak = new ArrayList>(); + if (treeBaseMap.containsKey(fielddbtype)) { + list = treeBaseMap.get(fielddbtype); + listBak = treeBaseMap.get("showfield"); + } else { + String treeSetSql = "select id,sourcefrom,sourceid,tablename,tablekey,showfield,supnode,datacondition,tablesup,supnodefield,nodefield from mode_customtreedetail where mainid=" + fielddbtype; + recordSet.execute(treeSetSql); + while (recordSet.next()) { + Map setMap = new HashMap(); + Map setMapBak = new HashMap(); + String nodeid = recordSet.getString("id");//节点id + String tablename = recordSet.getString("tablename");//表名 + String tablekey = recordSet.getString("tablekey");//主键字段 + String showfield = recordSet.getString("showfield");//显示名称字段 + String datacondition = recordSet.getString("datacondition").trim();//数据显示条件 + //解析树形浏览框 显示条件 的动态参数 + CustomTreeData customTreeData = new CustomTreeData(); + customTreeData.setUser(user); + datacondition = customTreeData.replaceParam(datacondition); + datacondition = "1=1"; + String sourcefrom = recordSet.getString("sourcefrom"); + String sourceid = recordSet.getString("sourceid"); + String supnode = recordSet.getString("supnode"); + String tablesup = recordSet.getString("tablesup"); + String supnodefield = recordSet.getString("supnodefield"); + String nodefield = recordSet.getString("nodefield"); + setMap.put("nodeid", nodeid); + setMap.put("tablename", tablename); + setMap.put("tablekey", tablekey); + setMap.put("showfield", showfield); + setMap.put("datacondition", datacondition); + setMap.put("sourcefrom", sourcefrom); + setMap.put("sourceid", sourceid); + setMap.put("supnode", supnode); + setMap.put("tablesup", tablesup); + setMap.put("supnodefield", supnodefield); + setMap.put("nodefield", nodefield); + setMapBak.put("showfield", showfield); + list.add(setMap); + listBak.add(setMapBak); + } + treeBaseMap.put(fielddbtype, list); + treeBaseMap.put("showfield", listBak); + } + String[] nameArray = null; + if (type == 257) { + //nameArray = tempvalue.split(","); + if (tempvalue.indexOf("DH{") != -1) {//批量导入自定义多选或树多选时,如果选项中有英文逗号,批量导入时用DH{}包裹 + String[] tempNumber = tempvalue.split(",");//数组格式:{"xxxx","DH{XXXX","XXXX"?(也许有),"xxx}"},其中DH{}中间包裹的值是自定义多选的一个选项 + List list1 = new ArrayList(); + int i = 0; + int j = 0; + while (i < tempNumber.length) { + if (tempNumber[i].indexOf("DH{") != -1) { + list1.add(tempNumber[i].substring(3, tempNumber[i].length()) + ","); + i++; + boolean flag1 = false; + while (!flag1) {//判断数组中是否含有 + if (tempNumber[i].indexOf("}") != -1) { + list1.add(list1.get(j) + tempNumber[i].substring(0, tempNumber[i].length() - 1)); + list1.remove(j); + i++; + j++; + flag1 = true; + } else { + list1.add(list1.get(j) + tempNumber[i] + ","); + list1.remove(j); + i++; + } + } + } else { + list1.add(tempNumber[i]); + i++; + j++; + } + } + nameArray = list1.toArray(new String[list1.size()]); + } else { + nameArray = tempvalue.split(","); + } + + } else if (type == 256) { + nameArray = tempvalue.split("weaver_ecology"); + } + for (int m = 0; m < nameArray.length; m++) { + String tempName = nameArray[m]; + String treeSql = ""; + if (!tempName.isEmpty()) { + tempName = tempName.trim(); + //解决浏览框名称为整数,判断有误情况 + String realTempvalue = analyzeNameValue(tempName); + String tempid = ""; + if (realTempvalue.startsWith("tree_")) { + String[] valuearr = realTempvalue.split("_"); + if (valuearr.length == 3) { + for (int n = 0; n < list.size(); n++) { + Map setMap = list.get(n); + if (setMap.get("nodeid").equals(valuearr[1])) { + setMap.put("showfield", "id"); + } else { + continue; + } + Map value = impExcelUtil.getTreeValue("", "", setMap, valuearr[2]); + treeSql = Util.null2String(value.get("sql")); + if (value.size()>0 && listBak.get(0).size()>0){ + setMap.put("showfield", listBak.get(0).get("showfield")); + } + if (!"".equals(Util.null2String(value.get("id")))) { + if (!tempIdStr.equals("")) { + tempIdStr += ","; + } + tempid = Util.null2String(value.get("id")); + tempIdStr += Util.null2String(value.get("id")); + break; + } + } + } + } else if (showlevel && realTempvalue.indexOf(levelsplitchar) > 0) { + Map value = impExcelUtil.importTreeDataAllLevel(list, levelsplitchar, realTempvalue); + if (!tempIdStr.equals("")) { + tempIdStr += ","; + } + tempid = Util.null2String(value.get("id")); + tempIdStr += Util.null2String(value.get("id")); + treeSql = Util.null2String(value.get("sql")); + } else { + for (int n = 0; n < list.size(); n++) { + Map setMap = list.get(n); + Map value = impExcelUtil.getTreeValue("", "", setMap, realTempvalue); + treeSql = Util.null2String(value.get("sql")); + if (!"".equals(Util.null2String(value.get("id")))) { + if (!tempIdStr.equals("")) { + tempIdStr += ","; + } + tempid = Util.null2String(value.get("id")); + tempIdStr += Util.null2String(value.get("id")); + break; + } + } + } + if (tempid.equals("")) { + // 防止数据的英文加号拆分出错 + tempName = tempName.replace("+", "+"); + treeSql = treeSql.replace("+", "+"); + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + tempName); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + tempName + + "+" + fieldlabelname + "+" + fieldname + "+" + fielddbtype + "+" + maintablename + "+" + tempName + ":" + + SystemEnv.getHtmlLabelName(391276, user.getLanguage()) + "
" + SystemEnv.getHtmlLabelName(132258, user.getLanguage()) + ":
" + treeSql); + IdMap.put(id + "sql", SystemEnv.getHtmlLabelName(21778, user.getLanguage()) + ":" + fieldlabelname + "-" + tempName + ":" + "
" + SystemEnv.getHtmlLabelName(132258, user.getLanguage()) + ":
" + treeSql + "
" + SystemEnv.getHtmlLabelName(391299, user.getLanguage())); + iserrordata = true; + tempIdStr = ""; + } + } + } + + } + tempvalue = tempIdStr.replace("'", "''"); + } else { + if (!isNumber && !isNullValue) {//非主键值 + rs.executeSql("select tablename,columname,keycolumname from workflow_browserurl where id=" + type); + if (rs.next()) { + ArrayList tempvalues = null; + if (type == 1) {//如果是单人力不分割 + tempvalues = new ArrayList(); + tempvalues.add(tempvalue); + } else { + tempvalues = Util.TokenizerString(tempvalue, ","); + } + tempvalue = ""; + String keyname = Util.null2String(rs.getString("keycolumname")); + String tablename = Util.null2String(rs.getString("tablename")); + String columname = Util.null2String(rs.getString("columname")); + String columnameCopy = columname; + String[] realProjectName = CubeUtil.getRealProjectName(tablename, columname); + tablename = realProjectName[0]; + columname = realProjectName[1]; + columnameCopy = columname; + String columnameall = ""; + if (tablename.toLowerCase().equals("hrmdepartment") || tablename.toLowerCase().equals("hrmdepartmentallview")) { + columname = "departmentmark"; + columnameall = "departmentname"; + } else if (tablename.toLowerCase().equals("hrmsubcompanyallview")) { + columnameall = columname; + columname = "subcompanydesc"; + } + + //部门及分部封存,人员离职过滤 + String hrmFilterCondiction = ""; + if ("HrmDepartment".equalsIgnoreCase(tablename.toLowerCase()) || "hrmsubcompanyallview".equalsIgnoreCase(tablename.toLowerCase())) { + hrmFilterCondiction = " and (canceled!=1 or canceled is null)"; + } else if ("HrmResource".equalsIgnoreCase(tablename.toLowerCase())) { + hrmFilterCondiction = " and (status in(0,1,2,3) or status is null)"; + } else if ("crm_customerinfo".equalsIgnoreCase(tablename)) { + hrmFilterCondiction = " and deleted=0"; + } + if ((!keyname.equals("") && !tablename.equals("") && !columname.equals("")) || isDepSup) { + for (int n = 0; n < tempvalues.size(); n++) { + columname = columnameCopy; + rs = new RecordSet(); + if (SystemEnv.getHtmlLabelName(16139, user.getLanguage()).equals(Util.null2String(tempvalues.get(n)).trim())) {//系统管理员 + if (tempvalue.equals("")) { + tempvalue = "1"; + } else { + tempvalue += "," + "1"; + } + continue; + } + String importValue = Util.null2String(tempvalues.get(n)).trim(); + + //添加判断value 是不是id 或者编号 + if (isNumberOrCode(importValue)) { + hrmFilterCondiction = ""; + } + String keyValue = importValue; + if ("hrmresource".equalsIgnoreCase(tablename.toLowerCase()) && importValue.toLowerCase().startsWith("workcode_")) { + keyValue = keyValue.substring(9); + columname = "workcode"; + } else if ("hrmdepartment".equalsIgnoreCase(tablename.toLowerCase()) && importValue.toLowerCase().startsWith("deptcode_")) { + keyValue = keyValue.substring(9); + keyValue = checkDepartAndSubpany(keyValue); + columname = "departmentcode"; + } else if ("HrmResource".equalsIgnoreCase(tablename.toLowerCase())) { + if (importValue.startsWith("LZRY_")) { + keyValue = keyValue.substring(5); + hrmFilterCondiction = "";//包含LZRY_ 就可以导入所有类型的人员 + } else { + hrmFilterCondiction = " and (status in(0,1,2,3) or status is null)"; + } + } else { + //解决浏览框名称为整数,判断有误情况 + keyValue = analyzeNameValue(keyValue); + } + if (type == 164 || type == 169 || type == 170 || type == 194 || type == 168 || type == 167 || isDepSup) { + keyValue = checkDepartAndSubpany(keyValue); + } + if (!"".equals(keyValue)) { + if(type==179){ + if (!"".equals(columnameall)) { + sql = "select " + keyname + " from " + tablename + + " where " + columnameall + " ='" + keyValue + + "' and isdata=1 order by " + keyname + " desc"; + rs.executeSql(sql); + } + if (rs.getCounts()<=0) { + sql = "select " + keyname + " from " + tablename + + " where " + columname + " ='" + keyValue + + "' and isdata=1 order by " + keyname + " desc"; + rs.executeSql(sql); + } + if (rs.next()) { + if (tempvalue.equals("")) { + tempvalue = rs.getString(1); + } else { + tempvalue += "," + rs.getString(1); + } + } else { //先判断下是否是多语言结构 + if (!"".equals(columnameall)) { + sql = "select " + keyname + " from " + tablename + + " where (" + columnameall + " like '%"+"`~`7 "+keyValue+"`~`"+"%' or " + columnameall + " like '%"+"`~`8 "+keyValue+"`~`"+"%' or " + columnameall + " like '%"+"`~`9 "+keyValue+"`~`"+"%')" + + " and isdata=1 order by " + keyname + " desc"; + rs.executeSql(sql); + } + if (rs.getCounts()<=0) { + sql = "select " + keyname + " from " + tablename + + " where (" + columname + " like '%"+"`~`7 "+keyValue+"`~`"+"%' or " + columname + " like '%"+"`~`8 "+keyValue+"`~`"+"%' or " + columname + " like '%"+"`~`9 "+keyValue+"`~`"+"%')" + + " and isdata=1 order by " + keyname + " desc"; + rs.executeSql(sql); + } + if (rs.next()) { + if (tempvalue.equals("")) { + tempvalue = rs.getString(1); + } else { + tempvalue += "," + rs.getString(1); + } + } else { + sql = "select " + keyname + " from " + tablename + + " where (" + columname + " like '%"+"`~`7 "+keyValue+"`~`"+"%' or " + columname + " like '%"+"`~`8 "+keyValue+"`~`"+"%' or " + columname + " like '%"+"`~`9 "+keyValue+"`~`"+"%' or "+columname+"='"+keyValue+"')" + + " and isdata=1 order by " + keyname + " desc"; + errorRow.add(sheetcount + "," + (rows+1) + "," + (col+1) +","+importValue); + errorTable.add(sheetcount + "+" + (rows+1) + "+" + (col+1) +"+"+importValue+ + "+"+fieldlabelname+"+"+fieldname+"+"+fielddbtype+"+"+maintablename+ + "+"+importValue+":"+SystemEnv.getHtmlLabelName(391271, user.getLanguage())+"
"+SystemEnv.getHtmlLabelName(132258, user.getLanguage())+":
"+sql); + IdMap.put(id+"sql",SystemEnv.getHtmlLabelName(21778, user.getLanguage())+":"+fieldlabelname+"-"+importValue+":"+"
"+SystemEnv.getHtmlLabelName(132258, user.getLanguage())+":
"+sql+"
"+SystemEnv.getHtmlLabelName(391303, user.getLanguage())); + + iserrordata = true; + } + } + }else if(type==23){ + if (!"".equals(columnameall)) { + sql = "select " + keyname + " from " + tablename + + " where " + columnameall + " ='" + keyValue + + "' and isdata=2 order by " + keyname + " desc"; + // + "' "+hrmFilterCondiction+" order by " + keyname + " desc"; + rs.executeSql(sql); + } + if (rs.getCounts()<=0) { + sql = "select " + keyname + " from " + tablename + + " where " + columname + " ='" + keyValue + + "' and isdata=2 order by " + keyname + " desc"; + // + "' "+hrmFilterCondiction+" order by " + keyname + " desc"; + rs.executeSql(sql); + } + if (rs.next()) { + if (tempvalue.equals("")) { + tempvalue = rs.getString(1); + } else { + tempvalue += "," + rs.getString(1); + } + } else { //先判断下是否是多语言结构 + if (!"".equals(columnameall)) { + sql = "select " + keyname + " from " + tablename + + " where (" + columnameall + " like '%"+"`~`7 "+keyValue+"`~`"+"%' or " + columnameall + " like '%"+"`~`8 "+keyValue+"`~`"+"%' or " + columnameall + " like '%"+"`~`9 "+keyValue+"`~`"+"%')" + + "' and isdata=2 order by " + keyname + " desc"; + + rs.executeSql(sql); + } + if (rs.getCounts()<=0) { + sql = "select " + keyname + " from " + tablename + + " where (" + columname + " like '%"+"`~`7 "+keyValue+"`~`"+"%' or " + columname + " like '%"+"`~`8 "+keyValue+"`~`"+"%' or " + columname + " like '%"+"`~`9 "+keyValue+"`~`"+"%')" + + "' and isdata=2 order by " + keyname + " desc"; + rs.executeSql(sql); + } + if (rs.next()) { + if (tempvalue.equals("")) { + tempvalue = rs.getString(1); + } else { + tempvalue += "," + rs.getString(1); + } + } else { + sql = "select " + keyname + " from " + tablename + + " where ( " + columname + " like '%"+"`~`7 "+keyValue+"`~`"+"%' or " + columname + " like '%"+"`~`8 "+keyValue+"`~`"+"%' or " + columname + " like '%"+"`~`9 "+keyValue+"`~`"+"%' or "+columname+"='"+keyValue+"')" + + "' and isdata=2 order by " + keyname + " desc"; + errorRow.add(sheetcount + "," + (rows+1) + "," + (col+1) +","+importValue); + errorTable.add(sheetcount + "+" + (rows+1) + "+" + (col+1) +"+"+importValue+ + "+"+fieldlabelname+"+"+fieldname+"+"+fielddbtype+"+"+maintablename+ + "+"+importValue+":"+SystemEnv.getHtmlLabelName(391271, user.getLanguage())+"
"+SystemEnv.getHtmlLabelName(132258, user.getLanguage())+":
"+sql); + IdMap.put(id+"sql",SystemEnv.getHtmlLabelName(21778, user.getLanguage())+":"+fieldlabelname+"-"+importValue+":"+"
"+SystemEnv.getHtmlLabelName(132258, user.getLanguage())+":
"+sql+"
"+SystemEnv.getHtmlLabelName(391303, user.getLanguage())); + + iserrordata = true; + } + } + }else{ + if (!"".equals(columnameall)) { + sql = "select " + keyname + " from " + tablename + + " where " + columnameall + " ='" + keyValue + + "' " + hrmFilterCondiction + " order by " + keyname + " desc"; + rs.executeSql(sql); + } + if (rs.getCounts() <= 0) { + sql = "select " + keyname + " from " + tablename + + " where " + columname + " ='" + keyValue + + "' " + hrmFilterCondiction + " order by " + keyname + " desc"; + rs.executeSql(sql); + } + if (rs.next()) { + if (tempvalue.equals("")) { + tempvalue = rs.getString(1); + } else { + tempvalue += "," + rs.getString(1); + } + } else { //先判断下是否是多语言结构 + if (!"".equals(columnameall)) { + sql = "select " + keyname + " from " + tablename + + " where ( " + columnameall + " like '%" + "`~`7 " + keyValue + "`~`" + "%' or " + columnameall + " like '%" + "`~`8 " + keyValue + "`~`" + "%' or " + columnameall + " like '%" + "`~`9 " + keyValue + "`~`" + "%' )" + + " " + hrmFilterCondiction + " order by " + keyname + " desc"; + rs.executeSql(sql); + } + if (rs.getCounts() <= 0) { + sql = "select " + keyname + " from " + tablename + + " where (" + columname + " like '%" + "`~`7 " + keyValue + "`~`" + "%' or " + columname + " like '%" + "`~`8 " + keyValue + "`~`" + "%' or " + columname + " like '%" + "`~`9 " + keyValue + "`~`" + "%')" + + " " + hrmFilterCondiction + " order by " + keyname + " desc"; + rs.executeSql(sql); + } + if (rs.next()) { + if (tempvalue.equals("")) { + tempvalue = rs.getString(1); + } else { + tempvalue += "," + rs.getString(1); + } + } else { + sql = "select " + keyname + " from " + tablename + + " where (" + columname + " like '%" + "`~`7 " + keyValue + "`~`" + "%' or " + columname + " like '%" + "`~`8 " + keyValue + "`~`" + "%' or " + columname + " like '%" + "`~`9 " + keyValue + "`~`" + "%' or " + columname + "='" + keyValue + "')" + + " " + hrmFilterCondiction + " order by " + keyname + " desc"; + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + importValue); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + importValue + + "+" + fieldlabelname + "+" + fieldname + "+" + fielddbtype + "+" + maintablename + + "+" + importValue + ":" + SystemEnv.getHtmlLabelName(391271, user.getLanguage()) + "
" + SystemEnv.getHtmlLabelName(132258, user.getLanguage()) + ":
" + sql); + IdMap.put(id + "sql", SystemEnv.getHtmlLabelName(21778, user.getLanguage()) + ":" + fieldlabelname + "-" + importValue + ":" + "
" + SystemEnv.getHtmlLabelName(132258, user.getLanguage()) + ":
" + sql + "
" + SystemEnv.getHtmlLabelName(391303, user.getLanguage())); + + iserrordata = true; + } + } + } + } else { + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + importValue); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + importValue + + "+" + fieldlabelname + "+" + fieldname + "+" + fielddbtype + "+" + maintablename + + "+" + importValue + ":" + SystemEnv.getHtmlLabelName(391278, user.getLanguage()) + keyValue + SystemEnv.getHtmlLabelName(382055, user.getLanguage())); + IdMap.put(id + "sql", SystemEnv.getHtmlLabelName(21778, user.getLanguage()) + ":" + fieldlabelname + "-" + importValue + ":" + SystemEnv.getHtmlLabelName(10000150, user.getLanguage()) + "!" + SystemEnv.getHtmlLabelName(391286, user.getLanguage())); + iserrordata = true; + } + } + } + } else { + tempvalue = ""; + } + } else {//浏览按钮ID导入验证 + rs.executeSql("select tablename,columname,keycolumname from workflow_browserurl where id=" + type); + if (rs.next()) { + ArrayList tempvalues = Util.TokenizerString(tempvalue, ","); + tempvalue = ""; + String keyname = Util.null2String(rs.getString("keycolumname")); + String tablename = Util.null2String(rs.getString("tablename")); + String columname = Util.null2String(rs.getString("columname")); + String[] realProjectName = CubeUtil.getRealProjectName(tablename, columname); + tablename = realProjectName[0]; + columname = realProjectName[1]; + if (tablename.toLowerCase().equals("hrmdepartment")) { + columname = "departmentname"; + } + //部门及分部封存,人员离职过滤 + String hrmFilterCondiction = ""; + if ("HrmDepartment".equalsIgnoreCase(tablename.toLowerCase()) || "hrmsubcompanyallview".equalsIgnoreCase(tablename.toLowerCase())) { + hrmFilterCondiction = " and (canceled!=1 or canceled is null)"; + } else if ("HrmResource".equalsIgnoreCase(tablename.toLowerCase())) { + hrmFilterCondiction = " and (status in(0,1,2,3) or status is null)"; + } else if ("crm_customerinfo".equalsIgnoreCase(tablename)) { + hrmFilterCondiction = " and deleted=0"; + } + if (!keyname.equals("") && !tablename.equals("") && !columname.equals("")) { + for (int n = 0; n < tempvalues.size(); n++) { + String importValue = Util.null2String(tempvalues.get(n)).trim(); + if ("1".equals(Util.null2String(tempvalues.get(n)).trim())) { + if (tempvalue.equals("")) { + tempvalue = "1"; + } else { + tempvalue += "," + "1"; + } + continue; + } + //添加判断value 是不是id 或者编号 + if (isNumberOrCode(((String) tempvalues.get(n)).trim())) { + hrmFilterCondiction = ""; + } + if ("HrmResource".equalsIgnoreCase(tablename.toLowerCase())) { + if (importValue.startsWith("LZRY_")) { + importValue = importValue.substring(5); + hrmFilterCondiction = "";//包含LZRY_ 就可以导入所有类型的人员 + } else { + hrmFilterCondiction = " and (status in(0,1,2,3) or status is null)"; + } + } + sql = "select " + keyname + " from " + tablename + + " where " + keyname + " ='" + importValue + + "' " + hrmFilterCondiction + " order by " + keyname + " desc"; + rs.executeSql(sql); + if (rs.next()) { + if (tempvalue.equals("")) { + tempvalue = rs.getString(1); + } else { + tempvalue += "," + rs.getString(1); + } + } else { + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + ((String) tempvalues.get(n)).trim()); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + ((String) tempvalues.get(n)).trim() + + "+" + fieldlabelname + "+" + fieldname + "+" + fielddbtype + "+" + maintablename + + "+" + ((String) tempvalues.get(n)).trim() + ":" + SystemEnv.getHtmlLabelName(391271, user.getLanguage()) + "
" + SystemEnv.getHtmlLabelName(132258, user.getLanguage()) + ":
" + sql); + IdMap.put(id + "sql", SystemEnv.getHtmlLabelName(21778, user.getLanguage()) + ":" + fieldlabelname + "-" + ((String) tempvalues.get(n)).trim() + ":" + "
" + SystemEnv.getHtmlLabelName(132258, user.getLanguage()) + ":
" + sql + "
" + SystemEnv.getHtmlLabelName(391303, user.getLanguage())); + iserrordata = true; + // writeErrorRow(); + } + } + } + } else { + tempvalue = ""; + } + } + } + if (isDepSup) { //当>在上面导入出问题时,这里可以继续导入 + String flagStr = ""; + String keyname = ""; + String tablename = ""; + if ((type == 4 || type == 57) || (type == 167 || type == 168)) { + if (tempvalue.toLowerCase().startsWith("virtual_")) { + flagStr = "virtual_"; + if (tempvalue.startsWith("VIRTUAL_")) { + flagStr = "VIRTUAL_"; + } + keyname = "departmentname"; + tablename = "HrmDepartmentVirtual"; + } else if (tempvalue.startsWith("-")) { + keyname = "id"; + tablename = "HrmDepartmentVirtual"; + } else if (tempvalue.startsWith("deptcode_")) { + tablename = "HrmDepartment"; + keyname = "departmentcode"; + if (tempvalue.indexOf("deptcode_") != -1) { + tempvalue = tempvalue.replace("deptcode_", ""); + } else { + tempvalue = tempvalue.substring(9); + } + } else { + tablename = "HrmDepartment"; + keyname = "departmentname"; + if (isNumber) { + keyname = "id"; + } + } + } else if ((type == 164 || type == 194) || (type == 170 || type == 169)) { + if (tempvalue.toLowerCase().startsWith("virtual_")) { + flagStr = "virtual_"; + if (tempvalue.startsWith("VIRTUAL_")) { + flagStr = "VIRTUAL_"; + } + keyname = "subcompanyname"; + tablename = "hrmsubcompanyvirtual"; + } else if (tempvalue.startsWith("-")) { + keyname = "id"; + tablename = "hrmsubcompanyvirtual"; + } else { + tablename = "hrmsubcompany"; + keyname = "subcompanyname"; + if (isNumber) { + keyname = "id"; + } + } + } + //部门及分部封存,人员离职过滤 + String hrmFilterCondiction = ""; + if ("HrmDepartment".equalsIgnoreCase(tablename.toLowerCase()) || "hrmsubcompany".equalsIgnoreCase(tablename.toLowerCase()) + || "HrmDepartmentVirtual".equalsIgnoreCase(tablename.toLowerCase()) || + "hrmsubcompanyvirtual".equalsIgnoreCase(tablename.toLowerCase())) { + hrmFilterCondiction = " and (canceled!=1 or canceled is null)"; + } + + ArrayList tempvalues = Util.TokenizerString(tempvalue, ","); + tempvalue = ""; + String values = ""; + for (int n = 0; n < tempvalues.size(); n++) { + if (!((String) tempvalues.get(n)).trim().toLowerCase().startsWith(flagStr)) + continue; + values += ",'" + ((String) tempvalues.get(n)).trim().replace(flagStr, "") + "'"; + } + if (!StringHelper.isEmpty(values)) { + values = values.substring(1); + for (int n = 0; n < tempvalues.size(); n++) { + String value = ((String) tempvalues.get(n)).trim().replace(flagStr, ""); + value = checkDepartAndSubpany(value); + if (isNumberOrCode(value)) { + hrmFilterCondiction = ""; + } + sql = "select id," + keyname + " as showname from " + tablename + " where " + keyname + " = '" + value + "' " + hrmFilterCondiction + " order by id desc"; + rs.executeSql(sql); + if (!rs.next()) {//判断是否为多语言 + String tempSqlTemp = "select id," + keyname + " as showname from " + tablename + + " where (" + keyname + " like '%" + "`~`7 " + value + "`~`" + "%' or " + keyname + " like '%" + "`~`8 " + value + "`~`" + "%' or " + keyname + " like '%" + "`~`9 " + value + "`~`" + "%')" + + hrmFilterCondiction + " order by id desc"; + rs.execute(tempSqlTemp); + } + rs.beforFirst(); + boolean isExists = false; + while (rs.next()) { + String showname = rs.getString("showname"); + showname = Util.formatMultiLang(showname, user.getLanguage() + ""); + String tempValue = (String) tempvalues.get(n); + tempValue = checkDepartAndSubpany(tempValue.trim()); + String shownameNew = (flagStr + showname).replace("'", "''"); + if (shownameNew.equals(tempValue)) { + tempvalue += "," + rs.getString(1); + isExists = true; + break; + } + } + if (!isExists) { + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + ((String) tempvalues.get(n)).trim()); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + ((String) tempvalues.get(n)).trim() + + "+" + fieldlabelname + "+" + fieldname + "+" + fielddbtype + "+" + maintablename + + "+" + ((String) tempvalues.get(n)).trim() + ":" + SystemEnv.getHtmlLabelName(391271, user.getLanguage()) + "
" + SystemEnv.getHtmlLabelName(132258, user.getLanguage()) + ":
" + sql); + IdMap.put(id + "sql", SystemEnv.getHtmlLabelName(21778, user.getLanguage()) + ":" + fieldlabelname + "-" + ((String) tempvalues.get(n)).trim() + ":" + SystemEnv.getHtmlLabelName(127576, user.getLanguage()) + "
" + SystemEnv.getHtmlLabelName(132258, user.getLanguage()) + ":
" + sql + "
" + SystemEnv.getHtmlLabelName(391286, user.getLanguage())); + iserrordata = true; + } + } + if (tempvalue.startsWith(",")) { + tempvalue = tempvalue.substring(1); + } + } + } + //---------------------------提取end----------------------------- + + } else if (htmltype == 4) { + if (!isNullValue) { + if (tempvalue.equals("1") || tempvalue.toLowerCase().trim().equals(SystemEnv.getHtmlLabelName(163, user.getLanguage()).toLowerCase().trim())) { + tempvalue = "1"; + } else if (tempvalue.equals("0") || tempvalue.toLowerCase().trim().equals(SystemEnv.getHtmlLabelName(161, user.getLanguage()).toLowerCase().trim())) { + tempvalue = "0"; + } else { + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + tempvalue); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + tempvalue + + "+" + fieldlabelname + "+" + fieldname + "+" + fielddbtype + "+" + maintablename + + "+" + tempvalue + ":" + SystemEnv.getHtmlLabelName(391252, user.getLanguage())); + IdMap.put(id + "sql", SystemEnv.getHtmlLabelName(21778, user.getLanguage()) + ":" + fieldlabelname + "-" + tempvalue + ":" + SystemEnv.getHtmlLabelName(391303, user.getLanguage())); + iserrordata = true; +// writeErrorRow(); + tempvalue = ""; + } + } + } else if (htmltype == 5) { + if (!isNullValue) { + if (type == 2) { + ArrayList tempvalues = Util.TokenizerString(tempvalue, ","); + tempvalue = ""; + for (int i = 0; i < tempvalues.size(); i++) { + sql = "select selectvalue from workflow_selectitem where (selectname='" + ((String) tempvalues.get(i)).trim() + "' or selectname like '%`~`7 " + ((String) tempvalues.get(i)).trim() + "`~`%' or selectname like '%`~`8 " + ((String) tempvalues.get(i)).trim() + "`~`%' or selectname like '%`~`9 " + ((String) tempvalues.get(i)).trim() + "`~`%') and fieldid=" + fieldid + " and (cancel is null or cancel = 0)"; + rs.executeSql(sql); + if (rs.next()) { + if (tempvalue.equals("")) { + tempvalue = rs.getString(1); + } else { + tempvalue += "," + rs.getString(1); + } + } else { + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + tempvalues.get(i)); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + tempvalues.get(i) + + "+" + fieldlabelname + "+" + fieldname + "+" + fielddbtype + "+" + maintablename + + "+" + tempvalues.get(i) + ":" + SystemEnv.getHtmlLabelName(391279, user.getLanguage()) + "
" + SystemEnv.getHtmlLabelName(132258, user.getLanguage()) + ":
" + sql); + IdMap.put(id + "sql", SystemEnv.getHtmlLabelName(21778, user.getLanguage()) + ":" + fieldlabelname + "-" + tempvalues.get(i) + "
" + SystemEnv.getHtmlLabelName(132258, user.getLanguage()) + ":
" + sql + "!" + SystemEnv.getHtmlLabelName(391286, user.getLanguage())); + iserrordata = true; + } + } + } else { + if ("seclevel".equals(fieldname)) {//密级字段默认值等于公开 公开默认值为 4(由人力资源定义) + tempvalue = "4"; + } else { + List selectvalueList = ModeCacheManager.getInstance().getSelectValByName(fieldid, tempvalue, user.getLanguage()); + if (selectvalueList.size() == 1) { + tempvalue = selectvalueList.get(0); + } else { + sql = "select selectvalue from workflow_selectitem where (selectname='" + tempvalue + "' or selectname like '%`~`7 " + tempvalue + "`~`%' or selectname like '%`~`8 " + tempvalue + "`~`%' or selectname like '%`~`9 " + tempvalue + "`~`%') and fieldid=" + fieldid + " and (cancel is null or cancel = 0)"; + rs.executeSql(sql); + if (rs.next()) { + tempvalue = rs.getString(1); + } else { + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + tempvalue); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + tempvalue + + "+" + fieldlabelname + "+" + fieldname + "+" + fielddbtype + "+" + maintablename + + "+" + tempvalue + ":" + SystemEnv.getHtmlLabelName(391279, user.getLanguage()) + "
" + SystemEnv.getHtmlLabelName(132258, user.getLanguage()) + ":
" + sql); + IdMap.put(id + "sql", SystemEnv.getHtmlLabelName(21778, user.getLanguage()) + ":" + fieldlabelname + "-" + tempvalue + "" + "
" + SystemEnv.getHtmlLabelName(132258, user.getLanguage()) + ":
" + sql + "!
" + SystemEnv.getHtmlLabelName(391286, user.getLanguage())); + iserrordata = true; + tempvalue = ""; + } + } + } + + } + } + } else if (htmltype == 6 && !isNullValue) { + StringBuffer value = new StringBuffer(); + String[] tempvalues = tempvalue.split(","); + for (String val : tempvalues) { + Map map = doImportForFileOrImg(val, type); + if (map.containsKey("errorStr") && !StringHelper.isEmpty(map.get("errorStr"))) { + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + val); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + val + + "+" + fieldlabelname + "+" + fieldname + "+" + fielddbtype + "+" + maintablename + + "+" + val + ":" + map.get("errorStr") + "
"); + iserrordata = true; + } else if (!StringHelper.isEmpty(map.get("value"))) { + value.append(",").append(map.get("value")); + } + } + String valuetemp = value.toString(); + if (!StringHelper.isEmpty(valuetemp) && valuetemp.startsWith(",")) { + valuetemp = valuetemp.substring(1); + } + tempvalue = valuetemp; + } else if (htmltype == 8 && !isNullValue) { + SelectItemPageService selectItemPageService = new SelectItemPageService(); + Map map = selectItemPageService.getTopSelectItemIdByField(Util.getIntValue(fieldid), 1); + + int selectitemid = map.get("selectitemid"); + int level = map.get("level"); + sql = "select id from mode_selectitempagedetail where mainid=" + selectitemid + " and statelev=" + level + " and name='" + tempvalue + "'"; + rs.executeSql(sql); + if (rs.next()) { + tempvalue = rs.getString("id"); + } else { + errorRow.add(sheetcount + "," + (rows + 1) + "," + (col + 1) + "," + tempvalue); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (col + 1) + "+" + tempvalue + + "+" + fieldlabelname + "+" + fieldname + "+" + fielddbtype + "+" + maintablename + + "+" + tempvalue + ":" + SystemEnv.getHtmlLabelName(391279, user.getLanguage()) + sql); + IdMap.put(id + "sql", SystemEnv.getHtmlLabelName(21778, user.getLanguage()) + ":" + fieldlabelname + "-" + tempvalue + ":" + sql + "!" + SystemEnv.getHtmlLabelName(391286, user.getLanguage())); + iserrordata = true; + tempvalue = ""; + } + } + + if (!tempvalue.equals("") || isNullValue) { + if ("5".equals(type + "") && htmltype == 1) { + //QC:311928 ,如果输入自带分号,那么先去掉分号,转换为double + if (tempvalue != null && tempvalue.indexOf(",") != -1) { + tempvalue = tempvalue.replace(",", ""); + } + tempvalue = Util.toDecimalDigits(tempvalue, qfws); + tempvalue = Util.milfloatFormat(tempvalue); + } else if (type == 3 && htmltype == 1) {//浮点数 + int digitsIndex = fielddbtype.indexOf(","); + int decimaldigits_t = 0; + if (digitsIndex > -1) { + decimaldigits_t = Util.getIntValue(fielddbtype.substring(digitsIndex + 1, fielddbtype.length() - 1), 2); + } else { + decimaldigits_t = 2; + } + if (tempvalue.indexOf(",") != -1) { + tempvalue = tempvalue.replace(",", ""); + } + tempvalue = Util.toDecimalDigits(tempvalue + "", decimaldigits_t); + } + //tempvalue = Util.toHtmltextarea(tempvalue); + } + } + rs.writeLog("**3511**************fieldname:"+fieldname+",tempvalue:"+tempvalue); + if (!"".equals(conditionfield) && importtype == 3 && fieldname.equalsIgnoreCase(conditionfield)) {//更新 + conditionFieldValue = tempvalue; + mainKeyValue = tempvalue; + } + if (!"".equals(tempvalue) || isNullValue) { + updatesql += " " + fieldname + " = "; + //valueList.add(tempvalue); + fielddbtype = fielddbtype.toLowerCase(); + tempvalue = isNullValue ? null : InterfacesUtil.getSubStringValue(fielddbtype, tempvalue); + if (isNullValue) { + updatesql += tempvalue + ","; + } else { + updatesql += "'" + tempvalue + "',"; + } + /*if (fielddbtype.indexOf("int") != -1 || fielddbtype.indexOf("number") != -1 || fielddbtype.indexOf("decimal") != -1 || fielddbtype.indexOf("browser.") != -1) { + updatesql += "'" + tempvalue + "',"; + } else { + updatesql += "'" + tempvalue + "',"; + }*/ + } + } + rs.writeLog("**3533**************fieldname:"+fieldname+",tempvalue:"+tempvalue); + //导入时判断字段唯一性 + //由于重复性验证改造为组合验证,非单个字段,这里先记录本行的数据信息,等字段循环完毕再判断是否重复 + if ((!"".equals(keyField) && keyFields.contains(fieldname.toLowerCase())) + || (!"".equals(conditionfield) && (","+conditionfield.toLowerCase()+",").indexOf(","+fieldname.toLowerCase()+",")>-1)) { + if (htmltype == 1 && (type == 3 || type == 4 || type == 5)) { + if (tempvalue.indexOf(",") != -1) { + tempvalue = tempvalue.replace(",", ""); + } + rs.writeLog("**3542**************fieldname:"+fieldname+",tempvalue:"+tempvalue); + if (type == 3 && !"".equals(tempvalue)) { + BigDecimal bigDecimal = new BigDecimal(tempvalue); + tempvalue = bigDecimal.stripTrailingZeros().toPlainString(); + } + } + rs.writeLog("**3548**************fieldname:"+fieldname+",tempvalue:"+tempvalue); + Map rowdataMap = new HashMap(); + rowdataMap.put("htmltype", htmltype + ""); + rowdataMap.put("type", type + ""); + rowdataMap.put("tempvalue", tempvalue); + rowdataMap.put("col", (col + 1) + ""); + rowdataMap.put("oldtempvalue", CubeCipherUitl.decrypt(oldtempvalue));//提示信息需要解密 + rowdataMap.put("fieldlabelname", fieldlabelname); + rowdataMap.put("fieldname", fieldname); + rowdataMap.put("fielddbtype", fielddbtype); + rowdataMap.put("maintablename", maintablename); + rowdatainfosMap.put(fieldname.toLowerCase(), rowdataMap); + } + rs.writeLog("**3559**************fieldname:"+fieldname+",tempvalue:"+tempvalue); + if((","+conditionfield.toLowerCase()+",").indexOf(","+fieldname.toLowerCase()+",")>-1){ + tjzdValMap.put(fieldname.toLowerCase(),tempvalue); + } + } + for(String str : conditionfield.split(",")){ + String val = Util.null2String(tjzdValMap.get(str)); + if(tjzdval.isEmpty()){ + tjzdval = val; + }else{ + tjzdval += "#_#"+val; + } + } + rs.writeLog("****************conditionfield:"+conditionfield+",tjzdval:"+tjzdval+",tjzdValMap:"+tjzdValMap); + if (!allisnull) { +// isnull = true; + } + if (importtype == 3) {//更新 + //先判断数据在数据库是否存在 + Map rowdatainfo = rowdatainfosMap.get(conditionfield.split(",")[0]); + if (rowdatainfo != null) { + String tempvalue = rowdatainfo.get("tempvalue");//当前要更新的条件字段值 + String col = rowdatainfo.get("col");//当前要更新的条件字段值 + String oldtempvalue = rowdatainfo.get("oldtempvalue");//原始值 + String fieldlabelname = rowdatainfo.get("fieldlabelname");//字段名称 + String fieldname = rowdatainfo.get("fieldname");//字段名 + String fielddbtype = rowdatainfo.get("fielddbtype");//字段类型 + if (!conditionFieldMap.containsKey(tjzdval)) {//如果数据库不存在该值 + if (updateadddata == 1) { //如果选择了追加 + //判断追加是否重复 + Map result = this.judgeExistsOrNot(keyMap, keyField, rowdatainfosMap); + boolean databaseflag = "true".equals(result.get("isrepeat"));//与数据是否重复 + List> repeats = (List>) result.get("repeats");//组合验证如果有多个组合,并且都不符合,则要提示多条 + boolean excelflag = false; + if (!databaseflag) {//与数据没重复,判断与excel中数据有没有重复 + result = this.judgeExistsOrNot(keyMapExcel, keyField, rowdatainfosMap); + excelflag = "true".equals(result.get("isrepeat"));//与数据是否重复 + repeats = (List>) result.get("repeats"); + } + if (databaseflag) { + String message = this.putError(sheetcount, rows, maintablename, id, true, repeats); + iserrordata = true; + if (!isImportedWithIgnoringError) { + ImpExcelServer.setProgressCanImport(key, false, message); + canImport = false; + } + } else if (excelflag) { + String message = this.putError(sheetcount, rows, maintablename, id, false, repeats); + iserrordata = true; + if (!isImportedWithIgnoringError) { + ImpExcelServer.setProgressCanImport(key, false, message); + canImport = false; + } + } else { + addData2Excel(keyMapExcel, keyField, rowdatainfosMap, rows); + } + } else {//提示错误 + if(conditionfield.indexOf(",") > -1){ + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + "+" + tjzdval.replaceAll("#_#","_") + SystemEnv.getHtmlLabelName(132251, user.getLanguage()) + + "+" + "+" + "+" + "+" + maintablename + + "+" + tjzdval.replaceAll("#_#","_") + ":" + SystemEnv.getHtmlLabelName(132251, user.getLanguage())); + }else { + errorRow.add(sheetcount + "," + (rows + 1) + "," + col + "," + oldtempvalue + SystemEnv.getHtmlLabelName(132251, user.getLanguage())); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + col + "+" + oldtempvalue + SystemEnv.getHtmlLabelName(132251, user.getLanguage()) + + "+" + fieldlabelname + "+" + fieldname + "+" + fielddbtype + "+" + maintablename + + "+" + oldtempvalue + ":" + SystemEnv.getHtmlLabelName(132251, user.getLanguage())); + IdMap.put(id + "sql", SystemEnv.getHtmlLabelName(21778, user.getLanguage()) + ":" + fieldlabelname + SystemEnv.getHtmlLabelName(132251, user.getLanguage()) + "!" + SystemEnv.getHtmlLabelName(391286, user.getLanguage())); + } + iserrordata = true; + } + } + } else { + if (ismainKeyid && updateadddata == 1) {//如果是根据id更新,并且勾选了不满足就追加 + //判断追加是否重复 + Map result = this.judgeExistsOrNot(keyMap, keyField, rowdatainfosMap); + boolean databaseflag = "true".equals(result.get("isrepeat"));//与数据是否重复 + List> repeats = (List>) result.get("repeats");//组合验证如果有多个组合,并且都不符合,则要提示多条 + boolean excelflag = false; + if (!databaseflag) {//与数据没重复,判断与excel中数据有没有重复 + result = this.judgeExistsOrNot(keyMapExcel, keyField, rowdatainfosMap); + excelflag = "true".equals(result.get("isrepeat"));//与数据是否重复 + repeats = (List>) result.get("repeats"); + } + if (databaseflag) { + String message = this.putError(sheetcount, rows, maintablename, id, true, repeats); + iserrordata = true; + if (!isImportedWithIgnoringError) { + ImpExcelServer.setProgressCanImport(key, false, message); + canImport = false; + } + } else if (excelflag) { + String message = this.putError(sheetcount, rows, maintablename, id, false, repeats); + iserrordata = true; + if (!isImportedWithIgnoringError) { + ImpExcelServer.setProgressCanImport(key, false, message); + canImport = false; + } + } + } + } + } + //字段循环完毕进行重复验证 + if (importtype != 3 && !"".equals(keyField)) { + //判断数据库是否重复 + Map result = this.judgeExistsOrNot(keyMap, keyField, rowdatainfosMap); + boolean databaseflag = "true".equals(result.get("isrepeat"));//与数据是否重复 + List> repeats = (List>) result.get("repeats");//组合验证如果有多个组合,并且都不符合,则要提示多条 + boolean excelflag = false; + if (!databaseflag) {//与数据没重复,判断与excel中数据有没有重复 + result = this.judgeExistsOrNot(keyMapExcel, keyField, rowdatainfosMap); + excelflag = "true".equals(result.get("isrepeat"));//与数据是否重复 + repeats = (List>) result.get("repeats"); + } + if (importtype == 1 || importtype == 2) {//追加z + if (databaseflag) { + String message = this.putError(sheetcount, rows, maintablename, id, true, repeats); + iserrordata = true; + if (!isImportedWithIgnoringError) { + ImpExcelServer.setProgressCanImport(key, false, message); + canImport = false; + } + } else if (excelflag) { + String message = this.putError(sheetcount, rows, maintablename, id, false, repeats); + iserrordata = true; + if (!isImportedWithIgnoringError) { + ImpExcelServer.setProgressCanImport(key, false, message); + canImport = false; + } + } else { + addData2Excel(keyMapExcel, keyField, rowdatainfosMap, rows); + } + } +// else if(importtype==2){ //覆盖 +// if(excelflag){ +// this.putError(sheetcount, rows, maintablename, id, importtype, false, repeats); +// iserrordata = true; +// if(!isImportedWithIgnoringError) { +// ImpExcelServer.setProgressCanImport(key,false,MessageFormat.format(SystemEnv.getHtmlLabelName(132250, user.getLanguage()),sheetIndex,rows,"","","")); +// canImport=false; +// } +// }else{ +// keyMapExcel.put(oldtempvalue, rows+1); +// } +// } + } + + //数据ID列 + String mainKeydata = ""; + if ((mainFieldIds.contains("-1000") || ismainKeyid)) { + int dataIdCol = mainFieldIds.indexOf("-1000"); + String colName = Util.null2String(POIUtil.getValue(sheet, 0, dataIdCol)).trim(); + if (!SystemEnv.getHtmlLabelName(81287, user.getLanguage()).equals(colName) &&!"Data ID".equals(colName)) {//数据ID + errorRow.add(sheetcount + "," + (rows + 1) + ",2," + SystemEnv.getHtmlLabelName(132252, user.getLanguage())); + errorTable.add(sheetcount + "+" + (rows + 1) + "+2+" + SystemEnv.getHtmlLabelName(132252, user.getLanguage()) + + "+" + SystemEnv.getHtmlLabelName(81287, user.getLanguage()) + "+id+int+" + maintablename + "+" + colName + ":" + SystemEnv.getHtmlLabelName(503401, user.getLanguage()));//数据ID,不是数据ID字段! + IdMap.put(id + "sql", SystemEnv.getHtmlLabelName(132252, user.getLanguage()) + "!" + SystemEnv.getHtmlLabelName(391286, user.getLanguage())); + iserrordata = true; + if (!isImportedWithIgnoringError) { + ImpExcelServer.setProgressCanImport(key, false, MessageFormat.format(SystemEnv.getHtmlLabelName(132253, user.getLanguage()), sheetIndex, rows)); + canImport = false; + } + } else { + mainKeydata = Util.null2String(POIUtil.getValue(sheet, rows, dataIdCol)).trim(); + if (!"".equals(mainKeydata) && importtype == 3 && ismainKeyid) { + isnull = false; + Pattern pattern = Pattern.compile("^(-)?[1-9][0-9]*$"); //验证正数或负数 + Matcher isNum = pattern.matcher(mainKeydata.trim()); + if (!isNum.matches()) {//非数字 + errorRow.add(sheetcount + "," + (rows + 1) + "," + dataIdCol + "," + SystemEnv.getHtmlLabelName(132254, user.getLanguage()) + "!"); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + dataIdCol + "+" + SystemEnv.getHtmlLabelName(132254, user.getLanguage()) + "!" + + "+" + SystemEnv.getHtmlLabelName(81287, user.getLanguage()) + "+id+int+" + maintablename + "+" + dataIdCol + ":" + SystemEnv.getHtmlLabelName(503402, user.getLanguage()));//数据ID,非整数,校验主键有误 + IdMap.put(id + "sql", SystemEnv.getHtmlLabelName(132254, user.getLanguage()) + "!" + SystemEnv.getHtmlLabelName(391286, user.getLanguage())); + iserrordata = true; + } + if (!conditionFieldMap.containsKey(mainKeydata) && updateadddata != 1) {//当根据数据id更新的时候,表中没有该id且没有勾选追加 + errorRow.add(sheetcount + "," + (rows + 1) + "," + dataIdCol + "," + mainKeydata + SystemEnv.getHtmlLabelName(132251, user.getLanguage())); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + dataIdCol + "+" + mainKeydata + SystemEnv.getHtmlLabelName(132251, user.getLanguage()) + + "+" + SystemEnv.getHtmlLabelName(81287, user.getLanguage()) + "+" + "id" + "+" + "int" + "+" + maintablename + + "+" + mainKeydata + ":" + SystemEnv.getHtmlLabelName(132251, user.getLanguage())); + IdMap.put(id + "sql", SystemEnv.getHtmlLabelName(21778, user.getLanguage()) + ":" + "dataid" + SystemEnv.getHtmlLabelName(132251, user.getLanguage()) + "!" + SystemEnv.getHtmlLabelName(391286, user.getLanguage())); + iserrordata = true; + } + } else if ("".equals(mainKeydata) && importtype == 3 && ismainKeyid) { + if (!isnull) { + errorRow.add(sheetcount + "," + (rows + 1) + "," + dataIdCol + "," + SystemEnv.getHtmlLabelName(132255, user.getLanguage()) + "!"); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + dataIdCol + "+" + SystemEnv.getHtmlLabelName(132255, user.getLanguage()) + "!" + + "+" + SystemEnv.getHtmlLabelName(81287, user.getLanguage()) + "+id+int+" + maintablename + "+" + dataIdCol + ":" + SystemEnv.getHtmlLabelName(503403, user.getLanguage()));//数据ID,校验主键有误,数据ID为空 + IdMap.put(id + "sql", SystemEnv.getHtmlLabelName(132255, user.getLanguage()) + "!" + SystemEnv.getHtmlLabelName(391286, user.getLanguage())); + iserrordata = true; + } + } + } + } + //创建人列 + String modedatacreater = ""; + if (mainFieldIds.contains("-1001")) { + int creatorCol = mainFieldIds.indexOf("-1001"); + modedatacreater = Util.null2String(POIUtil.getValue(sheet, rows, creatorCol)).trim(); + //判断是否为空 + if (!"".equals(modedatacreater)) { + isnull = false; + Pattern pattern = Pattern.compile("^(-)?[1-9][0-9]*$"); //验证正数或负数 + Matcher isNum = pattern.matcher(modedatacreater.trim()); + if (!isNum.matches()) {//非数字 进行ID获取 + if (modedatacreater.indexOf(">") > -1) {//如果人员里面有> 代表逐级导入 + ArrayList tempvalues = Util.TokenizerString(modedatacreater, ","); + String temps = ""; + for (int n = 0; n < tempvalues.size(); n++) { + String temp = Util.null2String(tempvalues.get(n)); + Map tempvalueMap = getIdByPathName(2, temp); + if (Util.null2String(tempvalueMap.get("flag")).equals("0")) { + temp = tempvalueMap.get("value"); + } else { + errorRow.add(sheetcount + "," + (rows + 1) + "," + creatorCol + "," + modedatacreater + SystemEnv.getHtmlLabelName(132256, user.getLanguage())); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (creatorCol + 1) + "+" + modedatacreater + SystemEnv.getHtmlLabelName(132256, user.getLanguage()) + + "+" + SystemEnv.getHtmlLabelName(125357, user.getLanguage()) + "+modedatacreater+int" + "+" + maintablename + "+" + modedatacreater + ":" + SystemEnv.getHtmlLabelName(503404, user.getLanguage()) + "
" + SystemEnv.getHtmlLabelName(132258, user.getLanguage()) + ":
" + "select id from hrmresource where lastname='" + temp + "' and departmentid=0");//创建人,在人力资源未找到值 + IdMap.put(id + "sql", "" + modedatacreater + ":" + SystemEnv.getHtmlLabelName(132256, user.getLanguage()) + "!"); + iserrordata = true; + } + temps += "," + temp; + } + if (temps.length() > 0) { + temps = temps.substring(1); + } + modedatacreater = temps; + } else { + String hrmSql = "select id from HrmResource where "; + if (modedatacreater.toLowerCase().startsWith("workcode_")) { + modedatacreater = modedatacreater.substring(9); + hrmSql = "select id from HrmResource where workcode='" + modedatacreater + "' order by id desc"; + } else { + hrmSql = "select id from HrmResource where lastname='" + modedatacreater + "'"; + } + recordSet.execute(hrmSql); + if (recordSet.next()) { + modedatacreater = Util.null2String(recordSet.getString("id")); + } else { + errorRow.add(sheetcount + "," + (rows + 1) + "," + creatorCol + "," + modedatacreater + SystemEnv.getHtmlLabelName(132256, user.getLanguage())); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (creatorCol + 1) + "+" + modedatacreater + SystemEnv.getHtmlLabelName(132256, user.getLanguage()) + + "+" + SystemEnv.getHtmlLabelName(125357, user.getLanguage()) + "+modedatacreater+int" + "+" + maintablename + "+" + modedatacreater + ":" + SystemEnv.getHtmlLabelName(503404, user.getLanguage()) + "
" + SystemEnv.getHtmlLabelName(132258, user.getLanguage()) + ":
" + hrmSql);//创建人,在人力资源未找到值 + IdMap.put(id + "sql", "" + modedatacreater + ":" + SystemEnv.getHtmlLabelName(132256, user.getLanguage()) + "!"); + iserrordata = true; + } + } + } + updatesql += " modedatacreater = '" + modedatacreater + "',"; + //valueList.add(modedatacreater); + } else { + if (!isnull && importtype != 3) { + modedatacreater = user.getUID() + ""; + updatesql += " modedatacreater = '" + modedatacreater + "',"; + //valueList.add(modedatacreater); + } + } + } + //创建日期时间列 + if (mainFieldIds.contains("-1002")) { + int creatDateCol = mainFieldIds.indexOf("-1002"); + //判断是否为空 + Cell cell = POIUtil.getCell(sheet, rows, creatDateCol); + String checkvalue = Util.null2String(POIUtil.getValue(sheet, rows, creatDateCol)).trim(); + checkvalue = ImpExcelUtil.getDateOrTime(cell, checkvalue, 2); + if (checkvalue.startsWith("#@ERROR@#")) { + checkvalue = checkvalue.replace("#@ERROR@#", ""); + errorRow.add(sheetcount + "," + (rows + 1) + "," + (creatDateCol) + "," + checkvalue + "," + SystemEnv.getHtmlLabelName(24944, user.getLanguage())); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + (creatDateCol + 1) + "+" + checkvalue + "+" + SystemEnv.getHtmlLabelName(24944, user.getLanguage()) + + "+" + SystemEnv.getHtmlLabelName(722, user.getLanguage()) + "+modedatacreatedate+varchar(2000)+" + maintablename + "+" + checkvalue + ":" + SystemEnv.getHtmlLabelName(24944, user.getLanguage()));//创建日期 + IdMap.put(id + "sql", "" + checkvalue + ":" + SystemEnv.getHtmlLabelName(24944, user.getLanguage()) + "!" + SystemEnv.getHtmlLabelName(391286, user.getLanguage())); + iserrordata = true; + checkvalue = ""; + } else if (!StringHelper.isEmpty(checkvalue)) { + isnull = false; + updatesql += " modedatacreatedate = '" + checkvalue + "',"; + //valueList.add(checkvalue); + } + } + + if (isHaveModedatastatus) { + updatesql += " modedatastatus = '0',"; + } + + Map oldData = new HashMap(); + if (!isnull && !iserrordata && rowCanImport) { + if (importtype == 1 || importtype == 2) {//追加或覆盖 + int billid = getMainId(maintablename, modeid, user.getUID(), user.getType()); + //插入formbizid + String formBizId = ShardingActionHelper.constructBizId(billid, formid); + rs.executeUpdate(String.format("update %s set form_biz_id = '%s' where id = %d", maintablename, formBizId, billid)); + if (needlogFieldList.size() > 0) { + oldData = formInfoService.getTableData(tableName, billid, columnNames); + } + if (updatesql.trim().endsWith(" set") || !allisnull) { + flagMsg = SystemEnv.getHtmlLabelName(514873, user.getLanguage()); + flag = false; + } else { + updatesql = updatesql.substring(0, updatesql.length() - 1); + updatesql += " where id = " + billid; + //valueList.add(billid); + flag = rs.executeSql(updatesql); + if (!flag) { + writeLog(updatesql); + flagMsg = SystemEnv.getHtmlLabelName(132258, user.getLanguage()); + } + } + //添加置顶计算逻辑 formid billid + + String formId = formid + ""; + int classprotect =0; + try{ + String sqlp = "select classprotect from modeinfo where id =?"; + rs.executeQuery(sqlp,modeid); + if(rs.next()){ + classprotect=rs.getInt("classprotect"); + } + }catch (Exception e){ + e.printStackTrace(); + } + if (flag && classprotect==1) { + + SaveConditionUtil.buildTopDataForExcelImport(billid, maintablename, formId, modeid); + + // 添加 密级逻辑 + Map params = new HashMap<>(); + params.put("billid", billid + ""); + params.put("billtablename", maintablename); + params.put("formId", formId); + params.put("formmodeid", modeid); + params.put("userId", user.getUID()); + AddSeclevelUtil addSeclevelUtil = new AddSeclevelUtil(); + addSeclevelUtil.updateSeclevelForImport(params); + + } + + if (billid <= 0) { + flag = false; + flagMsg = SystemEnv.getHtmlLabelName(132259, user.getLanguage()); + } + + if (flag) {//更新成功,则记录当前数据 + //-----记录增加删除------ + billList.add(String.valueOf(billid)); + creatoridMap.put(String.valueOf(billid), modedatacreater); + addBillIdList.add(billid + ""); + IdMap.put(id, String.valueOf(billid)); + //CodeBuild codeBuild = new CodeBuild(modeid); + //String codeStr = codeBuild.getModeCodeStr(formid,billid);//生成编号 + + //权限统一放在主表以及子表数据全部添加完毕后生成---子表字段也支持权限 + //ModeRightInfo ModeRightInfo = new ModeRightInfo(); + //ModeRightInfo.editModeDataShare(user.getUID(),modeid,billid);//新建的时候添加共享 + if (!isdetailright) {//如果权限与明细表无关,则现在生成权限 + int creatorid = Util.getIntValue(modedatacreater); + if (creatorid == -1) { + creatorid = user.getUID(); + } + ExpExcelUtil.getInstance().getAsynimpPool().submit(new ImpAsynTask(ImpAsynTask.TASK_RIGHT, billid, modeid, creatorid)); + } + //------------记录新建日志---------------- + String operatedesc = SystemEnv.getHtmlLabelName(125682, user.getLanguage());//新建(导入追加) + int htmllabelindex = 125682; + + String operatetype = "1";//操作的类型: 1:新建 2:修改 3:删除 4:查看 + if (importtype == 2) { + operatedesc = SystemEnv.getHtmlLabelName(125683, user.getLanguage());//新建(导入覆盖) + htmllabelindex = 125683; + } + + Map nowData = new HashMap(); + if (needlogFieldList.size() > 0) { + nowData = formInfoService.getTableData(tableName, billid, columnNames); + } + writeBeatchLog(modeid, operatedesc, operatetype, billid, needlogFieldList, oldData, nowData, htmllabelindex); + //------------记录新建日志---------------- + } else {//更新失败,删除当前数据 + IdMap.put(id + "sql", updatesql); + sql = "delete from " + maintablename + " where id = " + billid; + rs.executeSql(sql); + } + } else if (importtype == 3) {//更新 + List billids = new ArrayList(); + boolean isInsert = false; + if (!ismainKeyid) { + String billidstr = getMapValue(conditionFieldMap, conditionFieldValue); + if(conditionfield.indexOf(",") > -1){ + billidstr=getMapValue(conditionFieldMap,tjzdval); + } + if (billidstr != null && !"".equals(billidstr)) { + for (String billid : billidstr.split(",")) { + if (!"".equals(billid)) { + billids.add(billid); + } + } + } + } else { + if (updateadddata == 1) { //如果选择了追加 + String billidstr = getMapValue(conditionFieldMap, mainKeydata); + if (billidstr != null && !"".equals(billidstr)) { + for (String billid : billidstr.split(",")) { + if (!"".equals(billid)) { + billids.add(billid); + } + } + } + } else { + billids.add(mainKeydata); + //billids.add( "'"+mainKeydata+"'"); + } + } + if (updateadddata == 1 && billids.size() <= 0) { + isInsert = true; + } + + if (isInsert) { + int newBillid = getMainId(maintablename, modeid, user.getUID(), user.getType()); + //插入formbizid + String formBizId = ShardingActionHelper.constructBizId(newBillid, formid); + rs.executeUpdate(String.format("update %s set form_biz_id = '%s' where id = %d", maintablename , formBizId, newBillid)); + if (needlogFieldList.size() > 0) { + oldData = formInfoService.getTableData(tableName, newBillid, columnNames); + } + updatesql = updatesql.substring(0, updatesql.length() - 1); + updatesql += " where id = " + newBillid; + //valueList.add(newBillid); + if (rowCanImport) { + flag = rs.executeSql(updatesql); + if (!flag) { + writeLog(updatesql); + flagMsg = SystemEnv.getHtmlLabelName(132258, user.getLanguage()); + } + } + if (newBillid <= 0) { + flag = false; + flagMsg = SystemEnv.getHtmlLabelName(132260, user.getLanguage()); + } + if (flag) { //更新成功,则记录当前数据 + if(conditionfield.indexOf(",") > -1){ + conditionFieldMap.put(tjzdval, newBillid + ""); + }else{ + conditionFieldMap.put(conditionFieldValue, newBillid + ""); + } + //-----记录增加删除------ + addBillIdList.add(String.valueOf(newBillid)); + billList.add(String.valueOf(newBillid)); + creatoridMap.put(String.valueOf(newBillid), modedatacreater); + IdMap.put(id, newBillid); + Map nowData = new HashMap(); + if (needlogFieldList.size() > 0) { + nowData = formInfoService.getTableData(tableName, newBillid, columnNames); + } + if (!isdetailright) {//如果权限与明细表无关,则现在生成权限 + int creatorid = Util.getIntValue(modedatacreater); + if (creatorid == -1) { + creatorid = user.getUID(); + } + ExpExcelUtil.getInstance().getAsynimpPool().submit(new ImpAsynTask(ImpAsynTask.TASK_RIGHT, newBillid, modeid, creatorid)); + } + //------------记录新建日志---------------- + String operatedesc = SystemEnv.getHtmlLabelName(125684, user.getLanguage());//新建(导入更新追加) + int htmllabelindex = 125684; + String operatetype = "1";//操作的类型: 1:新建 2:修改 3:删除 4:查看 + writeBeatchLog(modeid, operatedesc, operatetype, newBillid, needlogFieldList, oldData, nowData, htmllabelindex); + //------------记录新建日志---------------- + } else { + IdMap.put(id + "sql", updatesql); + } + } else { + Map> oldDatas = new HashMap>(); + if (needlogFieldList.size() > 0) { + if (columnNames == null || columnNames.trim().equals("")) { + columnNames = "*"; + } + if (columnNames.lastIndexOf(",") == columnNames.length() - 1) { + columnNames = columnNames.substring(0, columnNames.lastIndexOf(",")); + } + String ids = billids.stream().collect(Collectors.joining(",")).replaceAll("'", ""); + sql = "select id," + columnNames + " from " + tableName + " where id in (" + ids + ")"; + oldDatas = new BaseDao().getResultMapByMap(sql, "id"); + } + updatesql = updatesql.substring(0, updatesql.length() - 1); + String sqlwhere = ""; + if (!"".equals(conditionfield) && !"dataid".equals(conditionfield) && conditionfield.indexOf(",") == -1) { + //数据库字段类型若为text 则转为 varchar(max)进行判断 + if ("text".equals(conditionfielddbType)) { + sqlwhere = " where cast( " + conditionfield + " as varchar(max)) = " + " '" + mainKeyValue + "'"; + //valueList.add(mainKeyValue); + //数据库字段类型若为clob 则转为 varchar进行判断 + } else if ("clob".equals(conditionfielddbType)) { + sqlwhere = " where to_char( " + conditionfield + " ) = " + " '" + mainKeyValue + "'"; + //valueList.add(mainKeyValue); + } else { + sqlwhere = " where " + conditionfield + " = " + " '" + mainKeyValue + "'"; + //valueList.add(mainKeyValue); + } + } else { + //这种情况,billids应该只有一个 + sqlwhere = " where id = " + billids.get(0); + //valueList.add(billids.get(0)); + } + updatesql += sqlwhere; + if (rowCanImport) { + flag = rs.executeSql(updatesql); + if (!flag) { + writeLog(updatesql); +// errorTable.add(updatesql); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + "" + "+" + "" + //导入更新时,如果存在行只有id时的处理 + "+" + "" + "+" + "" + "+" + "" + "+" + maintablename + + "+" + "" + "" + SystemEnv.getHtmlLabelName(514873, user.getLanguage()) + "
" + SystemEnv.getHtmlLabelName(132258, user.getLanguage()) + ":
" + updatesql); + IdMap.put(id + "sql", updatesql); + flagMsg = SystemEnv.getHtmlLabelName(132258, user.getLanguage()); + } else { + setDataBaseValue(keyField, maintablename, keyMap, sqlwhere); + } + } + if (flag) { + for (String billid : billids) { + oldData = oldDatas.get(billid.replaceAll("'", "")); + //-----记录增加删除------ + updateList.add(String.valueOf(billid)); + //添加置顶计算逻辑 + String formId = formid + ""; + int billidInt = Util.getIntValue(billid); + SaveConditionUtil.buildTopDataForExcelUpdate(billidInt, maintablename, formId, modeid); + + /** + * qc1769430。解决批量导入更新,创建人为空时,会用当前登陆人覆盖之前的创建人的权限。 + * */ + RecordSet rscr = new RecordSet(); + String sqlStr2 = "select modedatacreater from " + maintablename + " where id = " + billid; + rscr.execute(sqlStr2); + String modedatacreaterNew = ""; + if(rscr.next()){ + modedatacreaterNew = rscr.getString("modedatacreater"); + } + if (modedatacreater == null || modedatacreater == ""){ + modedatacreater =modedatacreaterNew; + } + + billList.add(String.valueOf(billid).replaceAll("'", "")); + if (!isdetailright) {//如果权限与明细表无关,则现在生成权限 + int creatorid = Util.getIntValue(modedatacreater); + if (creatorid == -1) { + creatorid = user.getUID(); + } + ExpExcelUtil.getInstance().getAsynimpPool().submit(new ImpAsynTask(ImpAsynTask.TASK_RIGHT, Util.getIntValue(billid.replaceAll("'", "")), modeid, creatorid)); + } + creatoridMap.put(String.valueOf(billid).replaceAll("'", ""), modedatacreater); + if (IdMap.containsKey(id)) { + IdMap.put(id, IdMap.get(id) + "," + String.valueOf(billid).replaceAll("'", "")); + } else { + IdMap.put(id, String.valueOf(billid).replaceAll("'", "")); + } + } + Map> nowDatas = new HashMap>(); + if (needlogFieldList.size() > 0) { + if (columnNames == null || columnNames.trim().equals("")) { + columnNames = "*"; + } + if (columnNames.lastIndexOf(",") == columnNames.length() - 1) { + columnNames = columnNames.substring(0, columnNames.lastIndexOf(",")); + } + String ids = billids.stream().collect(Collectors.joining(",")).replaceAll("'", ""); + sql = "select id," + columnNames + " from " + tableName + " where id in (" + ids + ")"; + nowDatas = new BaseDao().getResultMapByMap(sql, "id"); + } + //------------记录日志---------------- + String operatedesc = SystemEnv.getHtmlLabelName(125699, user.getLanguage());// 修改(导入更新) + String operatetype = "2";//操作的类型: 1:新建 2:修改 3:删除 4:查看 + int htmllabelindex = 125699; + // writeBeatchLog(modeid,operatedesc, operatetype, billids,needlogFieldList,oldDatas,nowDatas); + writeBeatchLog(modeid, operatedesc, operatetype, billids, needlogFieldList, oldDatas, nowDatas, htmllabelindex); + } + } + } + } + + //插入数据 + if ((!isnull && (!flag)) || iserrordata) { + if (!"".equals(flagMsg)) { + flagMsg = "~~weaverSplit~~" + flagMsg; + } + errorRow.add(sheetcount + "," + (rows + 1) + flagMsg); + errorRowList.add(rows); + } + + if (isnull) { + ImpExcelServer.setProgressCanImport(key, false, MessageFormat.format(SystemEnv.getHtmlLabelName(132261, user.getLanguage()), sheetIndex, rows)); + canImport = false; + if (!rowCanImport) { + errorRow.removeAll(indexList); + errorTable.removeAll(indexList); + } + } + + rows++; + } + IdMap.put("billList", billList); + IdMap.put("creatoridMap", creatoridMap); + IdMap.put("addBillIdList", addBillIdList); + } catch (Exception e) { + writeLog("导入主表异常 modeId=" + modeid + " formid=" + formid + " Exception : " + e); + writeLog(e); + Errmsg = SystemEnv.getHtmlLabelName(27593, user.getLanguage()) + e.getMessage() + "!\\n"; + } finally { + doneSignal.countDown(); + } + + } + + /** + * 设置数据库数据,用于判断与数据库数据是否重复 + * + * @param keyField + * @param maintablename + * @param keyMap + * @param sqlwhere 全部就传null + */ + private void setDataBaseValue(String keyField, String maintablename, + Map> keyMap, String sqlwhere) { + RecordSet rs = new RecordSet(); + String sql; + if (!"".equals(keyField) && !"dataid".equals(keyField)) { + String[] arr1 = keyField.split("\\|"); + for (String arr : arr1) { + sql = "select id," + arr + " from " + maintablename; + if (sqlwhere != null && !"".equals(sqlwhere)) { + sql += sqlwhere; + } + rs.execute(sql); + String[] arr2 = arr.split(","); + Map groupMap = new HashMap(); + if (keyMap.containsKey(arr)) { + groupMap = keyMap.get(arr); + } + while (rs.next()) { + String endvalue = ""; + for (String field : arr2) { + String value = Util.null2String(rs.getString(field)); + value = value.trim();//去除两头的空格防止导入重复校验出错 + endvalue += value + Util.getSeparator(); + } + endvalue = endvalue.replaceAll(Util.getSeparator() + "$", ""); + groupMap.put(endvalue, rs.getString("id")); + } + keyMap.put(arr, groupMap); + } + } + } + + + /** + * 将组合的重复验证字段转换为list集合 like wb1,wb2|fds,wb3 + * + * @param keyfield + * @return + */ + private List getKeyFields(String keyfield) { + List list = new ArrayList(); + if (!"".equals(keyfield)) { + String[] arr1 = keyfield.split("\\|"); + for (String arr : arr1) { + String[] arr2 = arr.split(","); + for (String field : arr2) { + field = field.toLowerCase(); + if (!"".equals(field) && !list.contains(field)) { + list.add(field); + } + } + } + } + return list; + } + + + /** + * 正则表达式字段校验 + * + * @param fieldid + * @param value + * @return + */ + public boolean checkDataByExpression(String fieldid, String value) { + if (Util.null2String(value).equals("")) { + return true; + } else if (checkMap.containsKey(fieldid)) { + String expression = checkMap.get(fieldid); + Pattern pattern = Pattern.compile(expression); + Matcher matcher = pattern.matcher(value); + boolean bool = matcher.find(); + return bool; + } + return true; + } + + /** + * 解析浏览框名称的值:如果为name_整数,则去掉name_前缀 + * + * @param nameValue + * @return + */ + public String analyzeNameValue(String nameValue) { + if (nameValue == null || "".equals(nameValue)) return ""; + String realNameValue = ""; + String[] nameValues = nameValue.split(","); + Pattern pattern = Pattern.compile("^(-)?[1-9][0-9]*$"); //验证正数或负数 + if (nameValues.length > 0) { + for (String value : nameValues) { + //value = value.trim(); + if (value.toLowerCase().startsWith("name_")) { + String realValue = value.substring("name_".length()); + Matcher isNum = pattern.matcher(realValue); + if (isNum.matches()) { + realNameValue += realValue + ","; + } else { + realNameValue += value + ","; + } + } else { + realNameValue += value + ","; + } + } + } + if (realNameValue.length() > 0) { + if (nameValue.endsWith(",")) { + realNameValue = realNameValue.substring(0, realNameValue.length()); + } else { + realNameValue = realNameValue.substring(0, realNameValue.length() - 1); + } + + } + return realNameValue; + } + + /** + * 解析浏览框id的值:如果为key_非整数,则去掉key_前缀 + * + * @param id + * @return + */ + public Map analyzeIdValue(String id) { + HashMap resultMap = new HashMap(); + if (id == null || "".equals(id)) return resultMap; + String realNameValue = ""; + String realIdValue = ""; + String[] idValues = id.split(","); + if (idValues.length > 0) { + for (String value : idValues) { + //value = value.trim(); + if (value.toLowerCase().startsWith("key_")) { + String realValue = value.substring("key_".length()); + realIdValue += realValue + ","; + } else { + realNameValue += value + ","; + } + } + } + + if (realNameValue.length() > 0) { + if (id.endsWith(",")) { + realNameValue = realNameValue.substring(0, realNameValue.length()); + } else { + realNameValue = realNameValue.substring(0, realNameValue.length() - 1); + } + + } + + if (realIdValue.length() > 0) { + if (id.endsWith(",")) { + realIdValue = realIdValue.substring(0, realIdValue.length()); + } else { + realIdValue = realIdValue.substring(0, realIdValue.length() - 1); + } + } + resultMap.put("id", realIdValue); + resultMap.put("name", realNameValue); + return resultMap; + } + + /** + * 错误信息加入 + * + * @param sheetcount 表格索引 + * @param rows 行号 + * @param maintablename 主表名 + * @param id + * @param isdatabase 是否是与数据库数据重复(否则是excel重复) + * @param repeats + */ + private String putError(int sheetcount, int rows, String maintablename, String id, Boolean isdatabase, + List> repeats) { + String message = ""; + for (Map result : repeats) { + String col = result.get("col"); + String oldtempvalue = result.get("oldtempvalue"); + String fieldlabelname = result.get("fieldlabelname"); + String fieldname = result.get("fieldname"); + String fielddbtype = result.get("fielddbtype"); + String msg = result.get("msg"); + String msgdetail = result.get("msgdetail"); + String tablefield = result.get("tablefield"); + String hisrows = result.get("rows"); + if (isdatabase) {//数据库重复 + errorRow.add(sheetcount + "," + (rows + 1) + "," + col + "," + msg + "," + SystemEnv.getHtmlLabelName(24943, user.getLanguage())); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + col + "+" + msg + "+" + SystemEnv.getHtmlLabelName(24943, user.getLanguage()) + + "+" + Util.getSeparator() + "+" + Util.getSeparator() + "+" + tablefield + "+" + maintablename + + "+" + msgdetail + SystemEnv.getHtmlLabelName(24943, user.getLanguage())); + IdMap.put(id + "sql", SystemEnv.getHtmlLabelName(21778, user.getLanguage()) + ":" + fieldlabelname + "-" + oldtempvalue + ":" + SystemEnv.getHtmlLabelName(391309, user.getLanguage())); + message += MessageFormat.format(SystemEnv.getHtmlLabelName(132248, user.getLanguage()), sheetIndex, rows, col, msg) + "
"; + } else {//excel重复 + errorRow.add(sheetcount + "," + (rows + 1) + "," + col + "," + msg + "," + MessageFormat.format(SystemEnv.getHtmlLabelName(132249, user.getLanguage()), hisrows)); + errorTable.add(sheetcount + "+" + (rows + 1) + "+" + col + "+" + msg + "+" + MessageFormat.format(SystemEnv.getHtmlLabelName(132249, user.getLanguage()), hisrows) + + "+" + Util.getSeparator() + "+" + Util.getSeparator() + "+" + tablefield + "+" + maintablename + + "+" + msgdetail + MessageFormat.format(SystemEnv.getHtmlLabelName(132249, user.getLanguage()), hisrows)); + IdMap.put(id + "sql", SystemEnv.getHtmlLabelName(21778, user.getLanguage()) + ":" + fieldlabelname + "-" + oldtempvalue + ":" + SystemEnv.getHtmlLabelName(391309, user.getLanguage())); + message += MessageFormat.format(SystemEnv.getHtmlLabelName(132250, user.getLanguage()), sheetIndex, rows, col, msg, hisrows) + "
"; + } + } + message = message.replaceAll("
$", ""); + return message; + } + + /** + * 记录导入的excel数据,用于判断下面的数据是否和excel中的数据重复 + * + * @param keyMapExcel 记录已导入的excell数据 + * @param keyfield 组合验证 + * @param rowdatainfosMap 要加入的行信息 + */ + private void addData2Excel(Map> keyMapExcel, String keyfield, Map> rowdatainfosMap, int rows) { + if (keyfield == null || "".equals(keyfield)) { + return; + } + String[] arr1 = keyfield.split("\\|"); + for (String arr : arr1) { + Map groupMap = new HashMap(); + if (keyMapExcel.containsKey(arr)) { + groupMap = keyMapExcel.get(arr); + } + String[] arr2 = arr.split(","); + String endvalue = ""; + for (String field : arr2) { + field = field.toLowerCase(); + Map data = rowdatainfosMap.get(field); + String value = Util.null2String(data.get("tempvalue")); + endvalue += value + Util.getSeparator(); + } + endvalue = delEndChar(endvalue); + groupMap.put(endvalue, (rows + 1) + ""); + keyMapExcel.put(arr, groupMap); + } + } + + + /** + * 判断重复性验证字段是否重复 + * + * @param keyMap 数据库字段值 + * @param keyfield 重复性验证字段 类似 wb1,wb2|wb3,wb4 (用|分隔,每个|代表一个分组) + * @param rowdatainfosMap 当前导入行信息 + * @param exist 判断在数据库存在还是不存在 + * @return [isrepeat]是否重复 + * [repeats]重复信息 Map
+ * repeats中key值如下:[col] 列数(已加1)
+ * [oldtempvalue] excel输入值
+ * [fieldlabelname] 字段名称
+ * [fieldname] 字段名
+ * [fielddbtype] 字段类型
+ * [msg] 提示
+ * [msgdetail] 提示明细
+ */ + public Map judgeExistsOrNot(Map> keyMap, String keyfield, Map> rowdatainfosMap) { + String[] group = keyfield.split("\\|"); + boolean flag = false; + List issingles = new ArrayList();//是否是单个字段 + List listRepeats = new ArrayList();//重复的验证字段 + String rows = ""; + for (String arr : group) { + Map currKeyMap = keyMap.get(arr); + String[] arr2 = arr.split(","); + String value = "";//要验证是否重复的值 + for (String field : arr2) { + field = field.toLowerCase(); + Map rowdatainfo = rowdatainfosMap.get(field); + if (rowdatainfo != null) { + String tempvalue = rowdatainfo.get("tempvalue"); + value += tempvalue + Util.getSeparator(); + } + } + value = delEndChar(value); + if (currKeyMap != null && currKeyMap.containsKey(value) && !value.equals("")) { + flag = true; + rows = currKeyMap.get(value); + listRepeats.add(arr); + issingles.add(arr2.length > 1 ? false : true); + } + } + Map result = new HashMap(); + result.put("isrepeat", Util.null2String(flag)); + List> list = new ArrayList>(); + if (flag) {//如果重复 + for (int i = 0; i < listRepeats.size(); i++) { + String[] infos = {"", "", "", "", "", "", "", "", ""}; + String[] repeats = listRepeats.get(i).split(","); + Boolean issingle = issingles.get(i); + for (String field : repeats) { + Map rowdatainfo = rowdatainfosMap.get(field); + if (rowdatainfo != null) { + infos[0] += rowdatainfo.get("col") + ",";//列数 + infos[1] += rowdatainfo.get("oldtempvalue") + Util.getSeparator();//原始值 + infos[2] += rowdatainfo.get("fieldlabelname") + ",";//字段名称 + infos[3] += rowdatainfo.get("fieldname") + ",";//字段名 + infos[4] += rowdatainfo.get("fielddbtype") + Util.getSeparator();//字段类型 + infos[5] += "【" + rowdatainfo.get("fieldlabelname") + ":\"" + rowdatainfo.get("oldtempvalue") + "\"】" + ",";//提示 + infos[6] += "【" + rowdatainfo.get("fieldlabelname") + ":\"" + rowdatainfo.get("oldtempvalue") + "\"】" + ",";//提示明细 + infos[7] += rowdatainfo.get("fieldlabelname") + "(" + rowdatainfo.get("fieldname") + "," + rowdatainfo.get("fielddbtype") + ")" + "
"; + } + } + for (int j = 0; j < infos.length; j++) { + infos[j] = delEndChar(infos[j]);//去掉末尾分隔符 + if ((j == 5 || j == 6) && !issingle) {//提示//如果是组合验证,添加前缀 + infos[j] = SystemEnv.getHtmlLabelName(388904, user.getLanguage()) + infos[j]; + } + } + Map single = new HashMap(); + single.put("col", infos[0]); + single.put("oldtempvalue", infos[1]); + single.put("fieldlabelname", infos[2]); + single.put("fieldname", infos[3]); + single.put("fielddbtype", infos[4]); + single.put("msg", infos[5]); + single.put("msgdetail", infos[6]); + single.put("tablefield", infos[7]); + single.put("rows", rows); + list.add(single); + } + result.put("repeats", list); + } + return result; + } + + /** + * 去除末尾的逗号或分隔符 + * + * @return + */ + private String delEndChar(String str) { + str = str.replaceAll(Util.getSeparator() + "$", "").replaceAll(",$", ""); + return str; + } + + + /** + * 判断某个值在map中是否存在,兼容浮点数判断 + * + * @param keyMap + * @param key + * @param htmltype + * @param type + * @return + */ + public boolean judgeExists(Map keyMap, String key, int htmltype, int type) { + boolean flag = false; + key = checkDepartAndSubpany(key); + if (htmltype == 1 && (type == 3 || type == 4)) { + double keyValue; + try { + keyValue = Double.parseDouble(key); + } catch (Exception e) { + return flag; + } + Set keys = keyMap.keySet(); + if (keys != null) { + Iterator iterator = keys.iterator(); + while (iterator.hasNext()) { + Object keyObject = iterator.next(); + try { + double tmpKeyValue = Double.parseDouble(keyObject.toString()); + if (Double.compare(tmpKeyValue, keyValue) == 0) flag = true; + } catch (Exception e) { + continue; + } + } + } + } else { + flag = keyMap.containsKey(key.trim()); + } + return flag; + } + + public int getMainId(String billtablename, int formmodeid, int userid, int usertype) { + int billid = -1; + + String currentdate = DateHelper.getCurrentDate(); + + String currenttime = DateHelper.getCurrentTime(); + //取数据库服务器的当前时间 + RecordSet rs = new RecordSet(); + rs.executeProc("GetDBDateAndTime", ""); + if (rs.next()) { + currentdate = rs.getString("dbdate"); + currenttime = rs.getString("dbtime"); + } + billid = modeDataIDUpdateSingle.getModeDataNewIdByUUID(billtablename, formmodeid, userid, usertype, currentdate, currenttime); + return billid; + } + + /** + * 批量插入日志,以及更新最后修改人和修改时间 + * + * @param modeid + * @param operatedesc + * @param operatetype + * @param billids 主键id集合 + * @param needlogFieldList 需要记录日志的表单字段 + * @param oldDatas 更新前的旧数据集合 + * @param nowDatas 更新后的数据集合 + */ + private void writeBeatchLog(int modeid, String operatedesc, String operatetype, List billids + , List> needlogFieldList, Map> oldDatas, Map> nowDatas, int htmllabelindex) { + updateModifierAndTime(operatetype, billids, formid); + batchInsertLog(modeid, billids, operatetype, operatedesc, user, needlogFieldList, oldDatas, nowDatas, htmllabelindex); + } + + /** + * 批量插入日志,以及更新最后修改人和修改时间 + * + * @param modeid + * @param operatedesc + * @param operatetype + * @param billids 主键id集合 + * @param needlogFieldList 需要记录日志的表单字段 + * @param oldDatas 更新前的旧数据集合 + * @param nowDatas 更新后的数据集合 + */ +// private void writeBeatchLog(int modeid, String operatedesc, String operatetype, List billids +// ,List> needlogFieldList,Map>oldDatas,Map> nowDatas){ +// updateModifierAndTime(operatetype, billids, formid); +// batchInsertLog(modeid, billids, operatetype, operatedesc, user, needlogFieldList, oldDatas, nowDatas); +// } +// +// private void batchInsertLog(int modeid,List billids,String operatetype,String operatedesc,User user,List> needlogFieldList +// ,Map>oldDatas,Map> nowDatas){ +// if (billids.size()<=0) { +// return; +// } +// int count=billids.size(); +// String tablename = "ModeViewLog_"+modeid; +// String relatedname=SystemEnv.getHtmlLabelName(128713,user.getLanguage()); +// int operateuserid=user.getUID(); +// String operatedate=DateHelper.getCurrentDate(); +// String operatetime=DateHelper.getCurrentTime(); +// List> params = new ArrayList>(); +// for (String billid : billids) { +// List param = new ArrayList(); +// param.add(billid); +// param.add(relatedname); +// param.add(operatetype); +// param.add(operatedesc); +// param.add(user.getUID()); +// param.add(operatedate); +// param.add(operatetime); +// param.add(clientaddress); +// params.add(param); +// } +// String batchsql = "insert into "+tablename+"(relatedid,relatedname,operatetype,operatedesc,operateuserid,operatedate,operatetime,clientaddress)values(?,?,?,?,?,?,?,?)"; +// RecordSetTrans trans = new RecordSetTrans(); +// trans.setAutoCommit(false); +// try { +// trans.executeBatchSql(batchsql, params); +// trans.commit(); +// RecordSet rs = new RecordSet(); +// String idsql=""; +// if(rs.getDBType().contains("sqlserver")){ +// idsql="select id,relatedid from (select top "+count+" id,relatedid from "+tablename+" order by id desc) t order by id asc"; +// }else if(rs.getDBType().contains("mysql")){ +// idsql="select id,relatedid from (select id,relatedid from "+tablename+" order by id desc limit "+count+") t order by id asc"; +// }else if(rs.getDBType().contains("oracle")){ +// idsql="select id,relatedid from ( select id,relatedid from "+tablename+" order by id desc) t where rownum<="+count+" order by id asc"; +// } +// rs.executeQuery(idsql); +// Map idsMap = new HashMap(); +// while (rs.next()) { +// String viewlogid = rs.getString("id"); +// String billid = rs.getString("relatedid"); +// idsMap.put(billid, viewlogid); +// this.modeLogMap.put(billid, viewlogid); +// } +// if(needlogFieldList!=null&&needlogFieldList.size() > 0){//明细日志插入 +// params = new ArrayList>(); +// batchsql = "insert into ModeLogFieldDetail(viewlogid,fieldid,modeid,fieldvalue,prefieldvalue) values(?,?,?,?,?)"; +// for (String billid : billids) { +// Map oldData = oldDatas.get(billid); +// Map nowData = nowDatas.get(billid); +// for(int i = 0; i < needlogFieldList.size(); i++){ +// List param = new ArrayList(); +// Map needlogField = needlogFieldList.get(i); +// String fieldid = Util.null2String(needlogField.get("id")); +// String fieldname = Util.null2String(needlogField.get("fieldname")); +// String oldFieldValue = Util.null2String(oldData.get(fieldname)); +// String nowFieldValue = Util.null2String(nowData.get(fieldname)); +// if(!oldFieldValue.equals(nowFieldValue)){ +// String viewlogid=idsMap.get(billid); +// param.add(viewlogid); +// param.add(fieldid); +// param.add(modeid); +// param.add(nowFieldValue); +// param.add(oldFieldValue); +// params.add(param); +// } +// } +// } +// if (params.size()>0) { +// trans = new RecordSetTrans(); +// trans.setAutoCommit(false); +// trans.executeBatchSql(batchsql, params); +// trans.commit(); +// } +// } +// } catch (Exception e) { +// trans.rollback(); +// trans.writeLog(e); +// } +// } + private void batchInsertLog(int modeid, List billids, String operatetype, String operatedesc, User user, List> needlogFieldList + , Map> oldDatas, Map> nowDatas, int htmllabelindex) { + if (billids.size() <= 0) { + return; + } + int count = billids.size(); + String tablename = "ModeViewLog_" + modeid; + String relatedname = SystemEnv.getHtmlLabelName(128713, user.getLanguage()); + int operateuserid = user.getUID(); + String operatedate = DateHelper.getCurrentDate(); + String operatetime = DateHelper.getCurrentTime(); + List> params = new ArrayList>(); + //校验是否存在 htmllabelindex + RecordSet rsGetHtmlLableIndex = new RecordSet(); + String sqlGetHtmllabelindex = " select htmllabelindex from " + tablename +" where 1=2"; + boolean htmlLabelIndexFlag = true; + rsGetHtmlLableIndex.execute(sqlGetHtmllabelindex); + if (!"".equals(rsGetHtmlLableIndex.getExceptionMsg())) { + String addHtmlLableIndex = " alter table " + tablename + " add htmllabelindex int "; + htmlLabelIndexFlag = rsGetHtmlLableIndex.execute(addHtmlLableIndex); + } + for (String billid : billids) { + List param = new ArrayList(); + param.add(billid); + param.add(relatedname); + param.add(operatetype); + param.add(operatedesc); + param.add(user.getUID()); + param.add(operatedate); + param.add(operatetime); + param.add(clientaddress); + if (htmlLabelIndexFlag) { + param.add(htmllabelindex); + } + params.add(param); + } + + String batchsql = "insert into " + tablename + "(relatedid,relatedname,operatetype,operatedesc,operateuserid,operatedate,operatetime,clientaddress)values(?,?,?,?,?,?,?,?)"; + if (htmlLabelIndexFlag) { + batchsql = "insert into " + tablename + "(relatedid,relatedname,operatetype,operatedesc,operateuserid,operatedate,operatetime,clientaddress,htmllabelindex)values(?,?,?,?,?,?,?,?,?)"; + } + RecordSetTrans trans = new RecordSetTrans(); + trans.setAutoCommit(false); + try { + trans.executeBatchSql(batchsql, params); + trans.commit(); + RecordSet rs = new RecordSet(); + String idsql = ""; + if (rs.getDBType().contains("sqlserver")) { + idsql = "select id,relatedid from (select top " + count + " id,relatedid from " + tablename + " order by id desc) t order by id asc"; + } else if (rs.getDBType().contains("mysql")) { + idsql = "select id,relatedid from (select id,relatedid from " + tablename + " order by id desc limit " + count + ") t order by id asc"; + } else if (rs.getDBType().contains("oracle")) { + idsql = "select id,relatedid from ( select id,relatedid from " + tablename + " order by id desc) t where rownum<=" + count + " order by id asc"; + } else if (rs.getDBType().contains("postgresql")) { + idsql = "select id,relatedid from (select id,relatedid from " + tablename + " order by id desc limit " + count + ") t order by id asc"; + } + rs.executeQuery(idsql); + Map idsMap = new HashMap(); + while (rs.next()) { + String viewlogid = rs.getString("id"); + String billid = rs.getString("relatedid"); + idsMap.put(billid, viewlogid); + this.modeLogMap.put(billid, viewlogid); + } + if (needlogFieldList != null && needlogFieldList.size() > 0) {//明细日志插入 + params = new ArrayList>(); + batchsql = "insert into ModeLogFieldDetail(viewlogid,fieldid,modeid,fieldvalue,prefieldvalue,detailtable) values(?,?,?,?,?,?)"; + for (String billid : billids) { + Map oldData = oldDatas.get(billid); + Map nowData = nowDatas.get(billid); + for (int i = 0; i < needlogFieldList.size(); i++) { + List param = new ArrayList(); + Map needlogField = needlogFieldList.get(i); + String fieldid = Util.null2String(needlogField.get("id")); + String fieldname = Util.null2String(needlogField.get("fieldname")); + String detailtable = Util.null2String(needlogField.get("detailtable")); + String oldFieldValue = Util.null2String(oldData.get(fieldname)); + String nowFieldValue = Util.null2String(nowData.get(fieldname)); + if (!oldFieldValue.equals(nowFieldValue)) { + String viewlogid = idsMap.get(billid); + param.add(viewlogid); + param.add(fieldid); + param.add(modeid); + param.add(nowFieldValue); + param.add(oldFieldValue); + param.add(detailtable); + params.add(param); + } + } + } + if (params.size() > 0) { + trans = new RecordSetTrans(); + trans.setAutoCommit(false); + + trans.executeBatchSql(batchsql, params); + trans.commit(); + } + } + } catch (Exception e) { + trans.rollback(); + trans.writeLog(e); + } + } + + /** + * 批量更新最后修改人和修改时间 + * + * @param operatetype + * @param billids + * @param formid + */ + private void updateModifierAndTime(String operatetype, List billids, int formid) { + if (!"2".equals(operatetype)) { + return; + } + if (billids.size() <= 0) { + return; + } + String tablename = new FormInfoService().getTablenameByFormid(Util.getIntValue(formid)); + if ("".equals(tablename)) { + return; + } + RecordSetTrans trans = new RecordSetTrans(); + trans.setAutoCommit(false); + String batchsql = "update " + tablename + " set modedatamodifier=?,modedatamodifydatetime=? where id=?"; + String modifydatatime = DateHelper.getCurDateTime(); + int uid = user.getUID(); + List> params = new ArrayList>(); + for (String billid : billids) { + List param = new ArrayList(); + param.add(uid); + param.add(modifydatatime); + param.add(billid); + params.add(param); + } + try { + trans.executeBatchSql(batchsql, params); + trans.commit(); + } catch (Exception e) { + trans.rollback(); + trans.writeLog(e); + } + + } + + public void writeBeatchLog(int modeid, String operatedesc, String operatetype, int relatedid + , List> needlogFieldList, Map oldData, Map nowData, int htmllabelindex) { + List billids = new ArrayList(1); + billids.add(relatedid + ""); + Map> oldDatas = new HashMap>(); + oldDatas.put(relatedid + "", oldData); + Map> nowDatas = new HashMap>(); + nowDatas.put(relatedid + "", nowData); + writeBeatchLog(modeid, operatedesc, operatetype, billids, + needlogFieldList, oldDatas, nowDatas, htmllabelindex); + } + + /** + * 根据key获取value值,兼容浮点数 + * + * @param keyMap + * @param key + * @return + */ + public String getMapValue(Map keyMap, String key) { + String result = ""; + if (keyMap.containsKey(key.trim())) { + result = Util.null2String(keyMap.get(key.trim())); + } else if (Util.null2String(key).length() > 15) { + //qc407268 + } else { + double keyValue; + try { + keyValue = Double.parseDouble(key); + } catch (Exception e) { + return result; + } + Set keys = keyMap.keySet(); + if (keys != null) { + Iterator iterator = keys.iterator(); + while (iterator.hasNext()) { + Object keyObject = iterator.next(); + try { + double tmpKeyValue = Double.parseDouble(keyObject.toString()); + if (Double.compare(tmpKeyValue, keyValue) == 0) + result = Util.null2String(keyMap.get(keyObject)); + } catch (Exception e) { + continue; + } + } + } + } + return result; + } + + // 计算列转换的值. + public void getColCalStr(int formid, int billid, String mainTableName, + Map map, int mainid, int isbill, String dtname) { + RecordSet rs = new RecordSet(); + RecordSet rs2 = new RecordSet(); + String colcalstr = ""; + String maincalstr = ""; + String rowcalstr = ""; + String sql = "select * from workflow_formdetailinfo where formid =" + formid; + if (formid != 0) + rs.executeSql(sql); + if (rs.next()) { + colcalstr = rs.getString("colcalstr"); + maincalstr = rs.getString("maincalstr"); + rowcalstr = rs.getString("rowcalstr"); + } + // 计算多个明细表的行列规则 + if (rowcalstr != null && !"".equals(rowcalstr.trim())) { + String[] rowcalstrs = rowcalstr.split(";"); + for (int ii = 0; ii < rowcalstrs.length; ii++) { + colCal(rowcalstrs[ii], isbill, formid, map, mainid, billid); + } + } + + // 下面计算总和 + if (maincalstr != null && !"".equals(maincalstr.trim())) { + String[] m = maincalstr.split(";"); + for (int i = 0; i < m.length; i++) { + String detailTableName = ""; + String dfname = ""; + String mfname = ""; + String[] temp = m[i].split("="); + String mf = temp[0].replace("mainfield_", ""); + String qfws = ""; + String df = temp[1].replace("detailfield_", ""); + if (isbill > 0) { + sql = "select fieldname,qfws from workflow_billfield where id = " + + mf; + } else { + sql = "select fieldname from workflow_formdict where id = " + + mf; + + } + rs2.executeSql(sql); + if (rs2.next()) { + mfname = rs2.getString("fieldname"); + qfws = rs2.getString("qfws"); + } + + // 得到等于号左边的对应的fdname. + dfname = getFdName(df, isbill, formid); + // 得到明细表名 + detailTableName = getDtName(df, isbill, formid); + + String mainKey = (String) map.get(detailTableName); + if (mainKey == null || "".equals(mainKey.trim())) { + mainKey = "mainid"; + } + double d = 0; +// sql = "select sum(" + dfname + ") dd from " + detailTableName +// + " where " + mainKey + " = " + mainid; +// rs2.executeSql(sql); +// if (rs2.next()) { +// d = Util.getDoubleValue(rs2.getString("dd"), 0); +// } + + sql = "select " + dfname + " dd from " + detailTableName + + " where " + mainKey + " = " + mainid; + rs2.executeSql(sql); + double ddvaluesum = 0; + while (rs2.next()) { + String ddvalue = Util.null2String(rs2.getString("dd")); + ddvaluesum += Util.getDoubleValue(ddvalue.replace(",", ""), 0); + } + String dstr = ""; + String sql2 = "select fieldhtmltype,type,fielddbtype,qfws from workflow_billfield where id=" + df; + rs2.executeSql(sql2); + if (rs2.next()) { + String fieldhtmltype = rs2.getString("fieldhtmltype"); + String type = rs2.getString("type"); + String fielddbtype = Util.null2String(rs2.getString("fielddbtype")); + + if (fieldhtmltype.equals("1") && type.equals("2")) { + BigDecimal b = new BigDecimal(ddvaluesum); + int f1 = b.setScale(0, BigDecimal.ROUND_HALF_UP).intValue(); + dstr = Util.toDecimalDigits(f1 + "", 0); + } else if (fieldhtmltype.equals("1") && type.equals("4")) { + BigDecimal b = new BigDecimal(ddvaluesum + ""); + double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); + dstr = Util.toDecimalDigits(f1 + "", 2); + } else if (fieldhtmltype.equals("1") && type.equals("5")) { + BigDecimal b = new BigDecimal(ddvaluesum + ""); + double f1 = b.setScale(Util.getIntValue(qfws, 2), BigDecimal.ROUND_HALF_UP).doubleValue(); + dstr = Util.toDecimalDigits(f1 + "", Util.getIntValue(qfws, 2)); + dstr = Util.milfloatFormat(dstr + ""); + } else if (type.equals("" + 3) && fieldhtmltype.equals("1")) { + int digitsIndex = fielddbtype.indexOf(","); + int decimaldigits_t = 0; + if (digitsIndex > -1) { + decimaldigits_t = Util.getIntValue(fielddbtype.substring(digitsIndex + 1, fielddbtype.length() - 1), 2); + } else { + decimaldigits_t = 2; + } + BigDecimal b = new BigDecimal(ddvaluesum + ""); + double f1 = b.setScale(decimaldigits_t, BigDecimal.ROUND_HALF_UP).doubleValue(); + dstr = Util.toDecimalDigits(f1 + "", decimaldigits_t); + } else { + dstr = ddvaluesum + ""; + } + } + + // 更新新表单 + if (isbill > 0 && formid < 0) + sql = " update " + mainTableName + " set " + mfname + " = '" + dstr + "' where id = " + mainid; + rs.executeSql(sql); + } + } + } + + + // 得到明细表字段的属性描述 + private String getFdName(String fid, int isbill, int formid) { + RecordSet rs = new RecordSet(); + String sql; + if (isbill > 0) { + sql = "select fieldname from workflow_billfield where id = " + fid; + } else { + sql = "SELECT a.fieldname FROM workflow_formfield wf , ( SELECT DISTINCT id , fielddbtype , fieldname ,description FROM workflow_formdictdetail ) a WHERE wf.formid = " + + formid + + " AND wf.isdetail = '1' " + + "AND wf.fieldid = a.id AND a.id = " + fid; + } + rs.executeSql(sql); + if (rs.next()) { + return rs.getString("fieldname"); + } + + return null; + } + + private String getDtName(String id, int isbill, int formid) { + RecordSet rs = new RecordSet(); + String sql; + if (isbill > 0) { + sql = "select detailtable from workflow_billfield where id = " + id; + // 查询明细表列名 + rs.executeSql(sql); + if (rs.next()) { + return rs.getString("detailtable"); + } + } else + return "workflow_formdetail"; + return null; + } + + // 计算一个明细表的行列表达式. + private void colCal(String rowcalstr, int isbill, int formid, Map map, + int mainid, int billid) { + String sql = ""; + Set fdName = new HashSet(); + RecordSet rs2 = new RecordSet(); + RecordSet rs = new RecordSet(); + String firstFid = ""; + String firstFname = ""; + Pattern pattern = Pattern.compile("detailfield[_](\\d+)"); + Matcher matcher = null; + matcher = pattern.matcher(rowcalstr); + while (matcher.find()) { + if ("".equals(firstFid)) { + firstFid = matcher.group(1); + } else { + fdName.add(matcher.group(1)); + } + } + // 得到等于号左边的对应的fdname. + firstFname = getFdName(firstFid, isbill, formid); + // 得到明细表名 + String detailTableName = getDtName(firstFid, isbill, formid); + + List l = new ArrayList(); + l.addAll(fdName); + Iterator it = l.iterator(); + String allV = ""; + Map mmm = new HashMap(); + int count = 0; + while (it.hasNext()) { + String fidid = (String) it.next(); + String fdname = getFdName(fidid + "", isbill, formid); + allV += fdname + ","; + mmm.put(fdname, fidid); + count++; + } + if (allV.length() > 0) { + allV = allV.substring(0, allV.length() - 1); + String mainKey = (String) map.get(detailTableName); + if (isbill > 0) + sql = "select " + allV + ",id from " + detailTableName + " where " + mainKey + " = " + mainid; + rs.executeSql(sql); + while (rs.next()) { + FelEngine fel = new FelEngineImpl(); + FelContext ctx = fel.getContext(); + Iterator iterator = mmm.keySet().iterator(); + while (iterator.hasNext()) { + String eee = (String) iterator.next(); + int index = 1 + l.indexOf(mmm.get(eee)); + String string = rs.getString(index); + // 如果没有这个明细值,就设置为0 + if (string == null || "".equals(string)) { + ctx.set("detailfield_" + mmm.get(eee), new Double(0.0)); + } else { + if (string.indexOf(",") != -1) { + string = string.replace(",", ""); + } + double d = Util.getDoubleValue(string, 0); + ctx.set("detailfield_" + mmm.get(eee), d); + } + } + String idString = rs.getString(l.size() + 1); + Object result = fel.eval(rowcalstr.substring(rowcalstr + .indexOf("=") + 1, rowcalstr.length())); + + if (result != null && !result.toString().equals("") && !"NaN".equals(result.toString()) && !"Infinity".equals(result.toString())) { + String sql2 = "select fieldhtmltype,type,fielddbtype,qfws from workflow_billfield where id=" + firstFid; + rs2.executeSql(sql2); + if (rs2.next()) { + String fieldhtmltype = rs2.getString("fieldhtmltype"); + String type = rs2.getString("type"); + String qfws = rs2.getString("qfws"); + String fielddbtype = Util.null2String(rs2.getString("fielddbtype")); + if (fieldhtmltype.equals("1") && type.equals("2")) { + BigDecimal b = new BigDecimal(result + ""); + int f1 = b.setScale(0, BigDecimal.ROUND_HALF_UP).intValue(); + result = Util.toDecimalDigits(f1 + "", 0); + } else if (fieldhtmltype.equals("1") && type.equals("4")) { + BigDecimal b = new BigDecimal(result + ""); + double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); + result = Util.toDecimalDigits(f1 + "", 2); + } else if (fieldhtmltype.equals("1") && type.equals("5")) { + BigDecimal b = new BigDecimal(result + ""); + double f1 = b.setScale(Util.getIntValue(qfws, 2), BigDecimal.ROUND_HALF_UP).doubleValue(); + result = Util.toDecimalDigits(f1 + "", Util.getIntValue(qfws, 2)); + result = Util.milfloatFormat(result + ""); + } else if (type.equals("3") && fieldhtmltype.equals("1")) { + int digitsIndex = fielddbtype.indexOf(","); + int decimaldigits_t = 0; + if (digitsIndex > -1) { + decimaldigits_t = Util.getIntValue(fielddbtype.substring(digitsIndex + 1, fielddbtype.length() - 1), 2); + } else { + decimaldigits_t = 2; + } + BigDecimal b = new BigDecimal(result + ""); + double f1 = b.setScale(decimaldigits_t, BigDecimal.ROUND_HALF_UP).doubleValue(); + result = Util.toDecimalDigits(f1 + "", decimaldigits_t); + } + } + } + if (!"NaN".equals(result.toString()) && !"Infinity".equals(result.toString())) { + sql = "update " + detailTableName + " set " + firstFname + + " = '" + result + "' where id = " + idString; + rs2.execute(sql); + } + } + } + } + + /** + * @param type 0 分部 1 部门 2 人 + * @param path 全路径 + * @return + */ + public Map getIdByPathName(int type, String path) { + Map map = new HashMap(); + map.put("flag", "0");//默认成功 + String id = ""; + ArrayList tempvalues = new ArrayList(); + if (path.indexOf(">") > -1) { + tempvalues = Util.TokenizerString(path, ">"); + } else if (this.isDepartAndSubpany) { + tempvalues = Util.TokenizerString(path, this.sepCharacter); + } + int count = tempvalues.size(); + if (type == 0) { + int pid = 0; + for (int i = 0; i < count; i++) { + String orgname = Util.null2String(tempvalues.get(i)).trim(); + map.put("orgname", orgname); + int orgid = getSubcompanyByName(orgname, pid); + map.put("value", orgid + ""); + pid = orgid; + if (orgid == -1) {//找分部 + map.put("flag", "1");//失败 + map.put("message", SystemEnv.getHtmlLabelName(503406, user.getLanguage()));//失败,分部没有找到 + return map; + } + } + } else if (type == 1) { + int pid = 0; + int suptype = 0; + for (int i = 0; i < count; i++) { + String orgname = Util.null2String(tempvalues.get(i)).trim(); + map.put("orgname", orgname); + int orgid = 0; + //第一级必须是分部 + if (i != 0 || !"2".equals(deptShowLevel)) { + orgid = getDeptByName(orgname, pid, suptype); + map.put("value", orgid + ""); + if (orgid != -1) { + pid = orgid; + } + } else { + orgid = -1; + } + if (orgid == -1) { + //部门找不到再找分部 + orgid = getSubcompanyByName(orgname, pid); + pid = orgid; + if (orgid == -1) { + map.put("flag", "1");//失败 + map.put("message", SystemEnv.getHtmlLabelName(503407, user.getLanguage()));//失败,组织架构没有找到 + return map; + } else { + suptype = 0;//分部找到了 + } + } else { + suptype = 1;//部门找到了 + } + } + } else if (type == 2) { + int pid = 0; + int suptype = 0; + for (int i = 0; i < count; i++) { + String orgname = Util.null2String(tempvalues.get(i)).trim(); + map.put("orgname", orgname); + int orgid = 0; + if (i == count - 1) {//最后一级直接找人 + int userid = getUserByName(orgname, pid); + map.put("value", userid + ""); + if (userid == -1) { + map.put("flag", "1");//失败 + map.put("message", SystemEnv.getHtmlLabelName(503408, user.getLanguage()));//失败,人员没有找到 + return map; + } else { + return map; + } + + } + //第一级必须是分部 + if (i != 0) { + orgid = getDeptByName(orgname, pid, suptype); + if (orgid != -1) { + pid = orgid; + } + } else { + orgid = -1; + } + if (orgid == -1) { + //部门找不到再找分部 + orgid = getSubcompanyByName(orgname, pid); + pid = orgid; + if (orgid == -1) { + map.put("flag", "1");//失败 + map.put("message", SystemEnv.getHtmlLabelName(503407, user.getLanguage()));//失败,组织架构没有找到 + return map; + } else { + suptype = 0;//分部找到了 + } + } else { + suptype = 1;//部门找到了 + } + } + } + return map; + /* + Map map= new HashMap(); + String id=""; + ArrayList tempvalues = Util.TokenizerString(path,">"); + int count=tempvalues.size(); + int selecttype=0; + + map.put("flag", 0+""); + int pid=0; + for (int i = 0; i < count; i++) { + int orgid=0; + String orgname = Util.null2String(tempvalues.get(i)).trim(); + map.put("orgname", orgname); + if(selecttype==0){//按分部找 + orgid=getSubcompanyByName(orgname, pid); + map.put("value", orgid+""); + if(orgid==-1&&type==0){//找分部 + map.put("flag", "1");//失败 + map.put("message", "分部没有找到");//失败 + return map; + }else if(orgid==-1&&(type==1||type==2)){//找部门 分部下找部门 + orgid = getDeptByName(orgname, pid, 0); + map.put("value", orgid+""); + if(orgid==-1){ + map.put("flag", "1");//失败 + map.put("message", "部门没有找到");//失败 + return map; + }else{ + selecttype=1; + } + } + pid=orgid; + }else{//按部门找 + orgid = getDeptByName(orgname, pid, 1);//部门下找部门 + map.put("value", orgid+""); + if(orgid==-1&&type==1){ + map.put("flag", "1");//失败 + map.put("message", "部门没有找到");//失败 + return map; + }else if(orgid==-1&&type==2){ + orgid = getUserByName(orgname, pid); + map.put("value", orgid+""); + if(orgid==-1){ + map.put("flag", "1");//失败 + map.put("message", "人员没有找到");//失败 + } + } + pid=orgid; + } + } + + return map; + */ + } + + /** + * 根据名称获取部门 + * + * @param name 部门 + * @param pid pid + * @return + */ + public int getSubcompanyByName(String name, int pid) { + int companyid = -1; + RecordSet rs = new RecordSet(); + String sql = ""; + if (pid == 0) { + sql = "select id from HrmSubCompany where (subcompanyname='" + name + "' or subcompanyname like '%`~`7 " + name + "`~`%' or subcompanyname like '%`~`8 " + name + "`~`%' or subcompanyname like '%`~`9 " + name + "`~`%') and (canceled <> 1 or canceled is null or canceled='') "; + } else { + sql = "select id from HrmSubCompany where (subcompanyname='" + name + "' or subcompanyname like '%`~`7 " + name + "`~`%' or subcompanyname like '%`~`8 " + name + "`~`%' or subcompanyname like '%`~`9 " + name + "`~`%') and (canceled <> 1 or canceled is null or canceled='') and supsubcomid=" + pid; + } + rs.executeSql(sql); + if (rs.getCounts() <= 0) { + if (pid == 0) { + sql = "select id from HrmSubCompany where (subcompanydesc='" + name + "' or subcompanydesc like '%`~`7 " + name + "`~`%' or subcompanydesc like '%`~`8 " + name + "`~`%' or subcompanydesc like '%`~`9 " + name + "`~`%') and (canceled <> 1 or canceled is null or canceled='')"; + } else { + sql = "select id from HrmSubCompany where (subcompanydesc='" + name + "' or subcompanydesc like '%`~`7 " + name + "`~`%' or subcompanydesc like '%`~`8 " + name + "`~`%' or subcompanydesc like '%`~`9 " + name + "`~`%') and (canceled <> 1 or canceled is null or canceled='') and supsubcomid=" + pid; + } + rs.executeSql(sql); + } + if (rs.next()) { + companyid = Util.getIntValue(rs.getString("id"), -1); + } + return companyid; + } + + /** + * @param name 名称 + * @param pid 上级id + * @param type 0 分部 1部门 + * @return + */ + public int getDeptByName(String name, int pid, int suptype) { + int deptid = -1; + String sql = ""; + if (suptype == 0) {//找分部下的部门 + sql = "select id from hrmdepartment where supdepid =0 and (departmentname='" + name + "' or departmentname like '%`~`7 " + name + "`~`%' or departmentname like '%`~`8 " + name + "`~`%' or departmentname like '%`~`9 " + name + "`~`%') and (canceled <> 1 or canceled is null or canceled='') "; + if (pid > 0) { + sql += " and subcompanyid1='" + pid + "' "; + } + } else {//找部门下的部门 + sql = "select id from hrmdepartment where (departmentname='" + name + "' or departmentname like '%`~`7 " + name + "`~`%' or departmentname like '%`~`8 " + name + "`~`%' or departmentname like '%`~`9 " + name + "`~`%') and (canceled <> 1 or canceled is null or canceled='') "; + if (pid > 0) { + sql += " and supdepid='" + pid + "' "; + } + } + RecordSet rs = new RecordSet(); + rs.executeSql(sql); + if (rs.getCounts() <= 0) { + if (suptype == 0) {//找分部下的部门 + sql = "select id from hrmdepartment where supdepid =0 and (departmentmark='" + name + "' or departmentmark like '%`~`7 " + name + "`~`%' or departmentmark like '%`~`8 " + name + "`~`%' or departmentmark like '%`~`9 " + name + "`~`%') and (canceled <> 1 or canceled is null or canceled='') "; + if (pid > 0) { + sql += " and subcompanyid1='" + pid + "' "; + } + } else {//找部门下的部门 + sql = "select id from hrmdepartment where (departmentmark='" + name + "' or departmentmark like '%`~`7 " + name + "`~`%' or departmentmark like '%`~`8 " + name + "`~`%' or departmentmark like '%`~`9 " + name + "`~`%') and (canceled <> 1 or canceled is null or canceled='') "; + if (pid > 0) { + sql += " and supdepid='" + pid + "' "; + } + } + rs.executeSql(sql); + } + if (rs.next()) { + deptid = Util.getIntValue(rs.getString("id"), -1); + } + return deptid; + } + + /** + * @param name 用户名称 + * @param pid 部门id + * @return + */ + public int getUserByName(String name, int pid) { + int userid = -1; + String sql = ""; + sql = "select id from hrmresource where (lastname='" + name + "' or lastname like '%`~`7 " + name + "`~`%' or lastname like '%`~`8 " + name + "`~`%' or lastname like '%`~`9 " + name + "`~`%') and departmentid='" + pid + "' "; + RecordSet rs = new RecordSet(); + rs.executeSql(sql); + if (rs.next()) { + userid = Util.getIntValue(rs.getString("id"), -1); + } + return userid; + } + + + private String sepCharacter = ""; + private String applyToModel = ""; + private String deptShowLevel = ""; //1:部门全路径 2:组织全路径 0:本部门 + private boolean isDepartAndSubpany = false;//用于处理部门,判断是分部导入时配置自定义的全路径 + + public void initDepartAndSubpany() { + RecordSet rs = new RecordSet(); + rs.executeQuery("select * from HrmOrganizationShowSet"); + while (rs.next()) { + sepCharacter = Util.null2String(rs.getString("sepCharacter")); + sepCharacter = getEscapingsSepCharacter(sepCharacter); + applyToModel = Util.null2String(rs.getString("applyToModel")); + deptShowLevel = Util.null2String(rs.getString("deptShowLevel")); + } + if ("1".equals(applyToModel)) { + this.isDepartAndSubpany = true; + } + this.sepCharacter = sepCharacter; + this.applyToModel = applyToModel; + } + + + /** + * 用于处理部门,分部导入时配置自定义的全路径 + */ + public String checkDepartAndSubpany(String value) { + boolean isContainsSep=false;//值中是否含有全路径的分割符 + String oriValue=value; + if ("1".equals(applyToModel)) { + // value = getEscapingsSepCharacter(value); + value = value.replace("\\", "\\\\"); + boolean flag = value.indexOf(",") > -1; + if (value.indexOf(sepCharacter) > -1 && !flag) { + isContainsSep=true; + String[] changeValue = value.split(sepCharacter); + value = changeValue[changeValue.length - 1]; + } else if (value.indexOf(sepCharacter) > -1 && flag) { + isContainsSep=true; + String[] values = value.split(","); + String plValue = ""; + for (String v : values) { + v = getEscapingsSepCharacter(v); + if (v.indexOf(sepCharacter) > -1) { + String[] changValue = v.split(sepCharacter); + v = changValue[changValue.length - 1]; + plValue = v + ","; + } else { + plValue = v + ","; + } + } + value = plValue.substring(0, plValue.length() - 1); + } + } + return isContainsSep?value:oriValue; + } + + /** + * 将层级间分隔符进行转义,否则会报错 + * + * @param sepCharacter + * @return + */ + private String getEscapingsSepCharacter(String sepCharacter) { + String escapingsSepCharacter = ""; + escapingsSepCharacter = sepCharacter.replace("\\", "\\\\").replace("*", "\\*") + .replace("+", "\\+").replace("|", "\\|") + .replace("{", "\\{").replace("}", "\\}") + .replace("(", "\\(").replace(")", "\\)") + .replace("^", "\\^").replace("$", "\\$") + .replace("[", "\\[").replace("]", "\\]") + .replace("?", "\\?").replace(",", "\\,") + .replace(".", "\\.").replace("&", "\\&"); + return escapingsSepCharacter; + } + + /** + * 加密字段值处理方法 + * + * @param realTempvalue 原始字段值 + * @param tablename 表名 + * @param showfield 字段名 + * @param flag 是否明细,1是明细,0是主表 + * @return + */ + public String getFieldEncryptValue(String realTempvalue, String tablename, String showfield, String flag) { + RecordSet rs = new RecordSet(); + String sql = "select t2.fieldname, t1.isencrypt from ModeFormFieldEncrypt t1, workflow_billfield t2, workflow_bill t3" + + " where t1.fieldid=t2.id and t3.id=t1.formid and t3.tablename ='" + tablename + "'"; + if ("1".equals(flag)) { + sql = "select t2.fieldname, t1.isencrypt from ModeFormFieldEncrypt t1, workflow_billfield t2, workflow_bill t3, workflow_billdetailtable t4" + + " where t1.fieldid=t2.id and t3.id=t1.formid and t3.id=t4.billid and t4.tablename ='" + tablename + "'"; + } + rs.executeQuery(sql); + while (rs.next()) { + if (showfield.equalsIgnoreCase(Util.null2String(rs.getString("fieldname"))) && 1 == Util.getIntValue(Util.null2String(rs.getString("isencrypt")))) { + realTempvalue = CubeCipherUitl.encrypt(realTempvalue); + } + } + //对于虚拟表单,实际表字段加密了,但是虚拟表没有设置字段加密,上面的逻辑检测不到,单独处理 + if (realTempvalue.startsWith("cube~cipher~start")) { + realTempvalue = CubeCipherUitl.decrypt(realTempvalue); + } + return realTempvalue; + } + + /** + * 判断是否是加密字段 + * + * @param tablename 表名 + * @param showfield 字段名 + * @param flag 是否明细,1是明细,0是主表 + * @return + */ + private boolean isEntryField(String tablename, String showfield, String flag) { + boolean result = false; + RecordSet rs = new RecordSet(); + String sql = "select t2.fieldname, t1.isencrypt from ModeFormFieldEncrypt t1, workflow_billfield t2, workflow_bill t3" + + " where t1.fieldid=t2.id and t3.id=t1.formid and upper(t3.tablename) =upper('" + tablename + "') and t1.isencrypt=1"; + if ("1".equals(flag)) { + sql = "select t2.fieldname, t1.isencrypt from ModeFormFieldEncrypt t1, workflow_billfield t2, workflow_bill t3, workflow_billdetailtable t4" + + " where t1.fieldid=t2.id and t3.id=t1.formid and t3.id=t4.billid and upper(t4.tablename) =upper('" + tablename + "') and t1.isencrypt=1"; + } + rs.executeQuery(sql); + while (rs.next()) { + if (showfield.equalsIgnoreCase(Util.null2String(rs.getString("fieldname")))) { + result = true; + } + } + return result; + } + + /** + * 验证字符串是code 或者 数字(id) + * + * @param tempValue + * @return + */ + public Boolean isNumberOrCode(String tempValue) { + Boolean result = false; + Pattern pattern = Pattern.compile("^(-)?[1-9][0-9]*$"); //验证正数或负数 + if (StringHelper.isNotEmpty(tempValue)) { + Matcher isNum = pattern.matcher(tempValue.trim()); + if (isNum.matches() || tempValue.startsWith("workcode_") || tempValue.startsWith("deptcode_") || tempValue.startsWith("virtual_")) { + result = true; + } + } + return result; + } + + public Map getRealFileOrImg(RecordSet rs, String parentid, String value, int index, String[] docpaths, int type) { + Map map = new HashMap(); + if (index == docpaths.length - 1) { + rs.executeQuery("select id from docdetail where docsubject = ? and seccategory = ? order by id", docpaths[index], parentid); + while (rs.next()) { + value = Util.null2String(rs.getString("id")); + if (!StringHelper.isEmpty(value) && type == 2) {//图片需要判断后缀名 + try { + DocImageManager DocImageManager = new DocImageManager(); + DocImageManager.resetParameter(); + DocImageManager.setDocid(Integer.parseInt(value)); + DocImageManager.selectDocImageInfo(); + + String filename = ""; + String fileExtendName = ""; + if (DocImageManager.next()) { + filename = DocImageManager.getImagefilename(); + fileExtendName = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase(); + } + + if (StringHelper.isEmpty(filename)) { + value = ""; + } else if (!",jpg,jpeg,png,gif,bmp,".contains("," + fileExtendName + ",")) { + value = ""; + } + } catch (Exception e) { + value = ""; + writeLog(e); + } + } + if (!StringHelper.isEmpty(value)) { + map.put("value", value); + map.put("errorStr", ""); + break; + } + } + if (!map.containsKey("value")) { + map.put("value", ""); + map.put("errorStr", docpaths[index] + value + SystemEnv.getHtmlLabelName(132306, user.getLanguage())); + } + return map; + } else { + rs.executeQuery("select id from docseccategory where categoryname = ? and parentid = ? order by id", docpaths[index], parentid); + while (rs.next()) { + String categoryid = Util.null2String(rs.getString("id")); + if (!StringHelper.isEmpty(categoryid)) { + map = getRealFileOrImg(rs, categoryid, value, index + 1, docpaths, type); + } + if (map.containsKey("value") && !StringHelper.isEmpty(map.get("value"))) { + break; + } + } + if (!map.containsKey("value")) { + map.put("value", ""); + map.put("errorStr", docpaths[index] + value + SystemEnv.getHtmlLabelName(132306, user.getLanguage())); + } + return map; + } + } + + /** + * 附件图片导入 + * 支持id,name_,目录路径 + * + * @param val 文件名称 + * @return + */ + public Map doImportForFileOrImg(String val, int type) { + val = val.trim(); + RecordSet rs = new RecordSet(); + Map map = new HashMap(); + if (val.contains(">")) { + String[] docpaths = val.split(">"); + val = ""; + if (!StringHelper.isEmpty(docpaths[0])) { + rs.executeQuery("select id from docseccategory where categoryname = ? order by id", docpaths[0]); + while (rs.next()) { + String categoryid = Util.null2String(rs.getString("id")); + if (!StringHelper.isEmpty(categoryid)) { + map = getRealFileOrImg(rs, categoryid, "", 1, docpaths, type); + } + //只要第一个满足的文档id + if (map.containsKey("value") && !StringHelper.isEmpty(map.get("value"))) { + break; + } + } + } + if (!map.containsKey("value")) { + map.put("value", ""); + map.put("errorStr", docpaths[docpaths.length - 1] + SystemEnv.getHtmlLabelName(132306, user.getLanguage())); + } + } else { + Pattern pattern = Pattern.compile("^(-)?[1-9][0-9]*$"); //验证正数或负数 + Matcher isNum = pattern.matcher(val); + if (!isNum.matches()) {//名称 + boolean isname = false; + if (val.startsWith("name_")) { + val = val.substring("name_".length()); + isname = true; + } + rs.executeQuery("select id from docdetail where docsubject = ? order by id", val); + + while (rs.next()) { + + val = Util.null2String(rs.getString("id")); + if (!StringHelper.isEmpty(val) && type == 2) {//图片需要判断后缀名 + try { + DocImageManager DocImageManager = new DocImageManager(); + DocImageManager.resetParameter(); + DocImageManager.setDocid(Integer.parseInt(val)); + DocImageManager.selectDocImageInfo(); + + String filename = ""; + String fileExtendName = ""; + if (DocImageManager.next()) { + filename = DocImageManager.getImagefilename(); + fileExtendName = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase(); + } + + if (StringHelper.isEmpty(filename)) { + val = ""; + } else if (!",jpg,jpeg,png,gif,bmp,".contains("," + fileExtendName + ",")) { + val = ""; + } + } catch (Exception e) { + val = ""; + writeLog(e); + } + } + if (!StringHelper.isEmpty(val)) { + map.put("value", val); + map.put("errorStr", ""); + break; + } + } + if (!map.containsKey("value")) { + map.put("value", ""); + map.put("errorStr", (isname ? "name_" + val : val) + SystemEnv.getHtmlLabelName(132306, user.getLanguage())); + } + } else { + if (!StringHelper.isEmpty(val)) { + map.put("value", val); + map.put("errorStr", ""); + } + } + } + return map; + } + + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + private void createTable(String modeid_userid,String conditionField){ + String id = "id int IDENTITY(1,1) NOT NULL,"; + RecordSet rs = new RecordSet(); + String dbType = rs.getDBType(); + String checkSql =""; + String tablename = "M_"+modeid_userid; + boolean isMysql = DBConstant.DB_TYPE_MYSQL.equals(dbType); + long time = System.currentTimeMillis();// 校验sql不sql缓存 + if (DBConstant.DB_TYPE_ORACLE.equals(dbType)) { + id = " id integer NOT NULL,"; + checkSql ="select COUNT(1) from user_tables where upper(table_name)=? and "+time+"="+time; + }else if (isMysql) { + id = " id int auto_increment not null primary key,";// mysql中自增的必须为主键或唯一键等。 + checkSql ="select COUNT(1) from information_schema.tables where upper(table_name)=? and table_schema = database() and "+time+"="+time; + }else if(DBConstant.DB_TYPE_SQLSERVER.equals(dbType)){ + checkSql ="SELECT COUNT(1) FROM sysobjects WHERE upper(name)=? and "+time+"="+time; + }else if (DBConstant.DB_TYPE_POSTGRESQL.equals(dbType)) { + id = " id SERIAL not null primary key,";// mysql中自增的必须为主键或唯一键等。 + checkSql ="select COUNT(1) from information_schema.tables where upper(table_name)=upper(?) and table_schema = 'PUBLIC' and "+time+"="+time; + } + rs.executeQuery(checkSql,tablename); + rs.next(); + int counts = Util.getIntValue(rs.getString(1)); + if (counts == 0) { + StringBuffer sb = new StringBuffer(); + sb.append("create table "+tablename); + sb.append("( " +id); + sb.append(conditionField+" varchar(2000))"); + rs.execute(sb.toString()); + if (DBConstant.DB_TYPE_ORACLE.equals(dbType)) { + createSequenceAndTrigger(tablename); + } + } + + } + + public void createSequenceAndTrigger(String tablename) { + RecordSet rs = new RecordSet(); + try { + StringBuffer restr = new StringBuffer(); + restr.append("create sequence ").append(tablename).append("_id"); + restr.append(" start with 1"); + restr.append(" increment by 1"); + + String appendSql = ""; + if ("jc".equalsIgnoreCase(ConnectionPool.getInstance().getOrgindbtype())){ + appendSql = " MAXVALUE 9223372036854775807 "; + }else { + appendSql = " nomaxvalue "; + } + restr.append(appendSql); + + restr.append(" nocycle "); + rs.execute(restr.toString()); + + restr = new StringBuffer(""); + restr.append("create or replace trigger ").append(tablename).append("_Trigger"); + restr.append(" before insert on ").append(tablename); + restr.append(" for each row "); + restr.append(" begin "); + restr.append(" select ").append(tablename).append("_id.nextval into :new.id from dual; "); + restr.append("end; "); + rs.setChecksql(false); + rs.execute(restr.toString()); + } catch (Exception e) { + e.printStackTrace(); + } + } + + + public Boolean IsCreateTempTab(String conditionfield,ArrayList fieldNameList,ArrayList fieldTypeList,ArrayList fieldHtmlTypeList){ + RecordSet rs = new RecordSet(); + if(conditionfield.equals("dataid")){ + //更新字段为数据id,创建字段为dataid的临时表 + createTable(modeid+"_"+user.getUID(),conditionfield); + return true; + }else{ + //处理更新字段为单行文本-文本,创建临时表 + Boolean IsSingleText=IsSingleText(conditionfield,fieldNameList,fieldTypeList,fieldHtmlTypeList); + if(IsSingleText){ + createTable(modeid+"_"+user.getUID(),conditionfield); + return true; + }else{ + return false; + } + + } + + } + + //判断更新字段是否是单行文本或者数据id + public Boolean IsSingleText(String conditionfield,ArrayList fieldNameList,ArrayList fieldTypeList,ArrayList fieldHtmlTypeList){ + if(conditionfield.equals("dataid")){ + return true; + }else{ + for (int k = 0; k < fieldNameList.size(); k++) { + String fieldname = Util.null2String((String) fieldNameList.get(k)); + String fieldtype = Util.null2String((String)fieldTypeList.get(k)); + String fieldhtmltype = Util.null2String((String)fieldHtmlTypeList.get(k)); + if (conditionfield.equals(fieldname)&&"1".equals(fieldhtmltype)&&"1".equals(fieldtype)) { + return true; + } + } + return false; + } + } + public void dropMtable(String modeid){ + try{ + RecordSet rs = new RecordSet(); + String dbType = rs.getDBType(); + if(DBConstant.DB_TYPE_ORACLE.equals(dbType)){ + rs.execute("DROP SEQUENCE M_"+modeid+"_"+user.getUID()+"_id"); + rs.execute("DROP TRIGGER M_"+modeid+"_"+user.getUID()+"_Trigger"); + } + rs.execute("drop table M_"+modeid+"_"+user.getUID()); + } catch (Exception e) { + e.printStackTrace(); + } + } + +} \ No newline at end of file diff --git a/src/weaver/formmode/excel/ImpExcelServer.java b/src/weaver/formmode/excel/ImpExcelServer.java new file mode 100644 index 0000000..35ac160 --- /dev/null +++ b/src/weaver/formmode/excel/ImpExcelServer.java @@ -0,0 +1,2497 @@ +/** + * 批量导入数据 + */ +package weaver.formmode.excel; + + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.math.BigDecimal; +import java.text.MessageFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Hashtable; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.Vector; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.ss.usermodel.WorkbookFactory; +import org.apache.poi.xssf.streaming.SXSSFWorkbook; + +import com.engine.cube.biz.CodeBuilder; +import com.greenpineyu.fel.FelEngine; +import com.greenpineyu.fel.FelEngineImpl; +import com.greenpineyu.fel.context.FelContext; +import com.weaver.formmodel.util.DateHelper; +import com.weaver.formmodel.util.StringHelper; + +import jxl.WorkbookSettings; +import jxl.read.biff.BiffException; +import weaver.common.StringUtil; +import weaver.conn.RecordSet; +import weaver.dateformat.TimeZoneVar; +import weaver.file.ExcelParse; +import weaver.file.ExcelParseForJXL; +import weaver.file.ExcelParseForPOI; +import weaver.file.FileUploadToPath; +import weaver.formmode.FormModeConfig; +import weaver.formmode.cache.StringCacheMap; +import weaver.formmode.data.FieldInfo; +import weaver.formmode.data.ModeDataManager; +import weaver.formmode.exttools.impexp.common.FileUtils; +import weaver.formmode.exttools.impexp.common.StringUtils; +import weaver.formmode.interfaces.ImportFieldTransAction; +import weaver.formmode.interfaces.ImportFieldTransActionPOI; +import weaver.formmode.interfaces.ImportPreInterfaceAction; +import weaver.formmode.interfaces.ImportPreInterfaceForJXLAction; +import weaver.formmode.interfaces.ImportPreInterfaceForPOIAction; +import weaver.formmode.log.FormmodeLog; +import weaver.formmode.search.batchoperate.DeleteData; +import weaver.formmode.service.CommonConstant; +import weaver.general.Util; +import weaver.hrm.User; +import weaver.systeminfo.SystemEnv; + +/** + * -2000:id;-2001:mainid;-1000:dataid;-1001:modedatacreater;-1002:modedatacreatedate + */ +public class ImpExcelServer extends FormmodeLog { + + private String clientaddress = "";//clint IP + private String key = ""; + private boolean isprintlog = false; + /** + * 默认共享是否与明细表字段有关,如果有关,则权限重构需等到明细表插入完成才重构,否则可以主表插入一条就重构一条 + */ + private boolean isdetailright = false; + private User user ;//操作用户 + + private ArrayList errorRow = new ArrayList();//错误的数据行 + private ArrayList errorTable = new ArrayList();//错误的表名称 + + private ImportPreInterfaceAction object; + private Map checkMap = new HashMap(); + + public static Map progressMap = new HashMap(); + + private static final String CANIMPORT = "canImport";//是否可以继续导入 + private static final String CANIMPORTMSG = "canImportmsg";// + private static final String STATUS = "status";//状态 + private static final String STEP = "step";//进度步骤,一共6步 + private static final String STARTTIME = "starttime";//开始时间 + private static final String ERRMSG = "errmsg";//错误消息 + private static final String TIME = "time";//耗时 + private static final String ENDTIME = "endtime";//结束时间 + private static final String MSG = "msg";//进度消息 + private static final String IMPADDR = "impaddr";//导入服务器的地址 + + private static final String MODEIMP = "modeimp";//大KEY + private static final String SEARCHID = "searchid";//返回的页面搜索的id + private static final String ERRORFLAG = "errorflag";//是否展示页面 + private String backupremark="";//日志备注 + private static final String suffix="_bak";//覆盖删除备份表的后缀 + private int backindex=0; + public ArrayList getErrorRow() { + return errorRow; + } + + public void setErrorRow(ArrayList errorRow) { + this.errorRow = errorRow; + } + + + /** + * 获得是否允许创建节点导入明细 + * @param workflowid + * @param nodeid + * @param isremark + * @return + */ + public boolean getAllowesImport(int requestid, int workflowid, int nodeid, + int isremark, User user) { + boolean isimport = false; + if (isremark == 0) { + RecordSet rs = new RecordSet(); + // 看到当前节点是否是创建节点 + rs.execute("select id from workflow_nodebase where isstart='1' and id="+ nodeid); + if (rs.next()) { + // 看是否设置 这个流程可以导入明细表 + rs.execute("select formid,isbill from workflow_base where isImportDetail='1' and id="+ workflowid); + if (rs.next()) { + int formid = rs.getInt("formid"); + int isbill = rs.getInt("isbill"); + String ismode = ""; + int showdes = 0; + int modeid = 0; + // ismode “1”:模板模式 “0”:普通模式 + // showdes “1”:没有显示模板 “0”:有显示模板 + // printdes “1”:没有打印模板 “0”:有打印模板 + // toexcel “1”:导出excel + rs.execute("select ismode,showdes,printdes,toexcel from workflow_flownode where workflowid="+ workflowid + " and nodeid=" + nodeid); + if (rs.next()) { + ismode = Util.null2String(rs.getString("ismode")); + showdes = Util.getIntValue(Util.null2String(rs.getString("showdes")), 0); + } + // 是模板模式,并且有显示模板 + if (ismode.equals("1") && showdes != 1) { + // 得到可以打印的该节点的id??mode是什么?? + rs.execute("select id from workflow_nodemode where isprint='0' and workflowid="+ workflowid + " and nodeid=" + nodeid); + if (rs.next()) { + modeid = rs.getInt("id"); + } else { + rs.execute("select id from workflow_formmode where isprint='0' and formid=" + formid+ " and isbill='" + isbill + "'"); + if (rs.next()) { + modeid = rs.getInt("id"); + } + } + } + String tablename = "workflow_nodeform"; + if (ismode.equals("1") && modeid > 0) { + tablename = "workflow_modeview"; + } + // isbill:1 单据 0:表单! + if (isbill == 1) { + rs.execute("select b.fieldid from workflow_billfield a,"+ tablename+ " b where a.id=b.fieldid and a.viewtype=1 and b.isedit='1'"); + } else { + rs.execute("select b.fieldid from workflow_formdictdetail a,"+ tablename + " b where a.id=b.fieldid and b.isedit='1'"); + } + if (rs.next()) { + isimport = true; + } + } + } + } + return isimport; + } + + /** + * 获得是否有导入明细权限 + * + * @param requestid + * @param nodeid + * @param userid + * @return + */ + public boolean getImportRight(int requestid, int nodeid, int userid) { + boolean hasright = false; + RecordSet rs = new RecordSet(); + rs.execute("select requestid from workflow_currentoperator where isremark='0' and requestid="+ requestid + + " and userid="+ userid + " and nodeid="+ nodeid + + " and exists(select 1 from workflow_nodebase where isstart='1' and id="+ nodeid + ")"); + if (rs.next()) { + hasright = true; + } + return hasright; + } + + // 得到明细表字段的属性描述 + private String getFdName(String fid, int isbill, int formid) { + RecordSet rs = new RecordSet(); + String sql; + if (isbill > 0) { + sql = "select fieldname from workflow_billfield where id = " + fid; + } else { + sql = "SELECT a.fieldname FROM workflow_formfield wf , ( SELECT DISTINCT id , fielddbtype , fieldname ,description FROM workflow_formdictdetail ) a WHERE wf.formid = " + + formid + " AND wf.isdetail = '1' " + "AND wf.fieldid = a.id AND a.id = " + fid; + } + rs.execute(sql); + if (rs.next()) { + return rs.getString("fieldname"); + } + return null; + } + + private String getDtName(String id, int isbill, int formid) { + RecordSet rs = new RecordSet(); + String sql; + if (isbill > 0) { + sql = "select detailtable from workflow_billfield where id = " + id; + // 查询明细表列名 + rs.execute(sql); + if (rs.next()) { + return rs.getString("detailtable"); + } + } else + return "workflow_formdetail"; + return null; + } + + private String getDtValue(String dtName, String dtFieldId, String id) { + RecordSet rs = new RecordSet(); + String sql = "select dtFieldId from mainKey where id = " + id; + // 查询明细表列名 + rs.execute(sql); + if (rs.next()) { + return rs.getString("detailtable"); + } + return null; + } + + // 计算一个明细表的行列表达式. + private void colCal(String rowcalstr, int isbill, int formid, Map map, + int mainid, int billid) { + String sql = ""; + Set fdName = new HashSet(); + RecordSet rs2 = new RecordSet(); + RecordSet rs = new RecordSet(); + String firstFid = ""; + String firstFname = ""; + Pattern pattern = Pattern.compile("detailfield[_](\\d+)"); + Matcher matcher = null; + matcher = pattern.matcher(rowcalstr); + while (matcher.find()) { + if ("".equals(firstFid)) { + firstFid = matcher.group(1); + } else { + fdName.add(matcher.group(1)); + } + } + // 得到等于号左边的对应的fdname. + firstFname = getFdName(firstFid, isbill, formid); + // 得到明细表名 + String detailTableName = getDtName(firstFid, isbill, formid); + + List l = new ArrayList(); + l.addAll(fdName); + Iterator it = l.iterator(); + String allV = ""; + Map mmm = new HashMap(); + int count = 0; + while (it.hasNext()) { + String fidid = (String) it.next(); + String fdname = getFdName(fidid + "", isbill, formid); + allV += fdname + ","; + mmm.put(fdname, fidid); + count++; + } + if (allV.length() > 0) { + allV = allV.substring(0, allV.length() - 1); + String mainKey = (String) map.get(detailTableName); + if (isbill > 0) + sql = "select " + allV + ",id from " + detailTableName + " where " + mainKey + " = " + mainid; + rs.execute(sql); + while (rs.next()) { + FelEngine fel = new FelEngineImpl(); + FelContext ctx = fel.getContext(); + Iterator iterator = mmm.keySet().iterator(); + while (iterator.hasNext()) { + String eee = (String) iterator.next(); + int index = 1 + l.indexOf(mmm.get(eee)); + String string = rs.getString(index); + // 如果没有这个明细值,就设置为0 + if (string == null || "".equals(string)) { + ctx.set("detailfield_" + mmm.get(eee), new Double(0.0)); + } else { + if(string.indexOf(",")!=-1){ + string = string.replace(",", ""); + } + double d = Util.getDoubleValue(string,0); + ctx.set("detailfield_" + mmm.get(eee), d); + } + } + String idString = rs.getString(l.size() + 1); + Object result = fel.eval(rowcalstr.substring(rowcalstr + .indexOf("=") + 1, rowcalstr.length())); + + if(!result.equals("")){ + String sql2 = "select fieldhtmltype,type,fielddbtype,qfws from workflow_billfield where id="+firstFid; + rs2.execute(sql2); + if(rs2.next()){ + String fieldhtmltype = rs2.getString("fieldhtmltype"); + String type = rs2.getString("type"); + String qfws = rs2.getString("qfws"); + String fielddbtype = Util.null2String(rs2.getString("fielddbtype")); + if(fieldhtmltype.equals("1")&&type.equals("2")){ + BigDecimal b = new BigDecimal(result+""); + int f1 = b.setScale(0,BigDecimal.ROUND_HALF_UP).intValue(); + result = Util.toDecimalDigits(f1+"",0); + }else if(fieldhtmltype.equals("1")&&type.equals("4")){ + BigDecimal b = new BigDecimal(result+""); + double f1 = b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue(); + result = Util.toDecimalDigits(f1+"",2); + }else if(fieldhtmltype.equals("1")&&type.equals("5")){ + BigDecimal b = new BigDecimal(result+""); + double f1 = b.setScale(Util.getIntValue(qfws,2),BigDecimal.ROUND_HALF_UP).doubleValue(); + result = Util.toDecimalDigits(f1+"",Util.getIntValue(qfws,2)); + result = Util.milfloatFormat(result+""); + }else if(type.equals("3")&&fieldhtmltype.equals("1")){ + int digitsIndex = fielddbtype.indexOf(","); + int decimaldigits_t=0; + if(digitsIndex > -1){ + decimaldigits_t = Util.getIntValue(fielddbtype.substring(digitsIndex+1, fielddbtype.length()-1), 2); + }else{ + decimaldigits_t = 2; + } + BigDecimal b = new BigDecimal(result+""); + double f1 = b.setScale(decimaldigits_t,BigDecimal.ROUND_HALF_UP).doubleValue(); + result = Util.toDecimalDigits(f1+"",decimaldigits_t); + } + } + } + + sql = "update " + detailTableName + " set " + firstFname + " = '" + result + "' where id = " + idString; + rs2.execute(sql); + } + } + } + + // 计算列转换的值. + public void getColCalStr(int formid, int billid, String mainTableName, + Map map, int mainid, int isbill, String dtname) { + RecordSet rs = new RecordSet(); + RecordSet rs2 = new RecordSet(); + String colcalstr = ""; + String maincalstr = ""; + String rowcalstr = ""; + String sql = "select * from workflow_formdetailinfo where formid =" + formid; + if (formid != 0) + rs.execute(sql); + if (rs.next()) { + colcalstr = rs.getString("colcalstr"); + maincalstr = rs.getString("maincalstr"); + rowcalstr = rs.getString("rowcalstr"); + } + // 计算多个明细表的行列规则 + if (rowcalstr != null && !"".equals(rowcalstr.trim())) { + String[] rowcalstrs = rowcalstr.split(";"); + for (int ii = 0; ii < rowcalstrs.length; ii++) { + colCal(rowcalstrs[ii], isbill, formid, map, mainid, billid); + } + } + + // 下面计算总和 + if (maincalstr != null && !"".equals(maincalstr.trim())) { + String[] m = maincalstr.split(";"); + for (int i = 0; i < m.length; i++) { + String detailTableName = ""; + String dfname = ""; + String mfname = ""; + String[] temp = m[i].split("="); + String mf = temp[0].replace("mainfield_", ""); + String qfws = ""; + String df = temp[1].replace("detailfield_", ""); + if (isbill > 0) { + sql = "select fieldname,qfws from workflow_billfield where id = " + mf; + } else { + sql = "select fieldname from workflow_formdict where id = " + mf; + } + rs2.execute(sql); + if (rs2.next()) { + mfname = rs2.getString("fieldname"); + qfws = rs2.getString("qfws"); + } + + // 得到等于号左边的对应的fdname. + dfname = getFdName(df, isbill, formid); + // 得到明细表名 + detailTableName = getDtName(df, isbill, formid); + + String mainKey = (String) map.get(detailTableName); + if (mainKey == null || "".equals(mainKey.trim())) { + mainKey = "requestid"; + } + sql = "select " + dfname + " dd from " + detailTableName + " where " + mainKey + " = " + mainid; + rs2.execute(sql); + double ddvaluesum=0; + while (rs2.next()) { + String ddvalue = Util.null2String(rs2.getString("dd")); + ddvaluesum += Util.getDoubleValue(ddvalue.replace(",", ""),0); + } + String dstr=""; + String sql2 = "select fieldhtmltype,type,fielddbtype,qfws from workflow_billfield where id="+df; + rs2.execute(sql2); + if(rs2.next()){ + String fieldhtmltype = rs2.getString("fieldhtmltype"); + String type = rs2.getString("type"); + String fielddbtype = Util.null2String(rs2.getString("fielddbtype")); + if(fieldhtmltype.equals("1")&&type.equals("2")){ + BigDecimal b = new BigDecimal(ddvaluesum); + int f1 = b.setScale(0,BigDecimal.ROUND_HALF_UP).intValue(); + dstr = Util.toDecimalDigits(f1+"",0); + }else if(fieldhtmltype.equals("1")&&type.equals("4")){ + BigDecimal b = new BigDecimal(ddvaluesum+""); + double f1 = b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue(); + dstr = Util.toDecimalDigits(f1+"",2); + }else if(fieldhtmltype.equals("1")&&type.equals("5")){ + BigDecimal b = new BigDecimal(ddvaluesum+""); + double f1 = b.setScale(Util.getIntValue(qfws,2),BigDecimal.ROUND_HALF_UP).doubleValue(); + dstr = Util.toDecimalDigits(f1+"", Util.getIntValue(qfws,2)); + dstr = Util.milfloatFormat(dstr+""); + }else if(type.equals(""+3)&&fieldhtmltype.equals("1")){ + int digitsIndex = fielddbtype.indexOf(","); + int decimaldigits_t=0; + if(digitsIndex > -1){ + decimaldigits_t = Util.getIntValue(fielddbtype.substring(digitsIndex+1, fielddbtype.length()-1), 2); + }else{ + decimaldigits_t = 2; + } + BigDecimal b = new BigDecimal(ddvaluesum+""); + double f1 = b.setScale(decimaldigits_t,BigDecimal.ROUND_HALF_UP).doubleValue(); + dstr = Util.toDecimalDigits(f1+"",decimaldigits_t); + }else{ + dstr = ddvaluesum+""; + } + } + // 更新新表单 + if (isbill > 0 && formid < 0) + sql = " update " + mainTableName + " set " + mfname + " = '" + dstr + "' where id = " + mainid; + rs.execute(sql); + } + } + } + + + + + @Override + public void writeLog(Object obj) { + if(this.isprintlog) { + super.writeLog(obj); + } + } + + @Override + public void writeLog(String classname, Object obj) { + if(this.isprintlog) { + super.writeLog(classname, obj); + } + } + + /** + * 批量导入,E9已经不走此接口,废弃 + * @param fu + * @return + */ + @Deprecated + public String ImportData(FileUploadToPath fu, User user,HttpServletRequest req) { + Map params = new HashMap(); + + int modeid = Util.getIntValue(fu.getParameter("modeid"),0); + int importtype = Util.getIntValue(fu.getParameter("importtype"),0);//1 追加,2覆盖,3更新 + int updateadddata = Util.getIntValue(fu.getParameter("updateadddata"),0); //importtype==3的时候 + String keyfield=Util.null2String(fu.getParameter("keyField")).toLowerCase();//重复验证字段 + + int sourcetype = Util.getIntValue(fu.getParameter("sourcetype"));//为1的时候,表示是后台设置界面 + + int importorder = Util.getIntValue(fu.getParameter("importorder"));//为后台设置界面时,无需保存,导入顺序即可生效 + String tempkey = Util.null2String(fu.getParameter("tempkey")); + int formid = Util.getIntValue(fu.getParameter("formid")); + int pageexpandid = Util.getIntValue(fu.getParameter("pageexpandid")); + int isprintlog = Util.getIntValue(fu.getParameter("isprintlog")); + String isImportedWithIgnoringError = Util.null2String(fu.getParameter("isImportedWithIgnoringError")); + + String tempkeyStr = Util.null2String(params.get("tempkey")); + String key = user.getUID()+"_"+modeid+"_"+tempkeyStr; + this.key = key; + ExpExcelUtil.refreshImpUserState(user.getUID(),key);//刷新导入状态 + + params.put("modeid", modeid); + params.put("importtype", importtype); + params.put("updateadddata", updateadddata); + params.put("keyfield", keyfield); + params.put("sourcetype", sourcetype); + + params.put("importorder", importorder); + params.put("tempkey", tempkey); + + params.put("isprintlog", isprintlog); + params.put("isImportedWithIgnoringError", isImportedWithIgnoringError); + + //-----------------单独处理------------------ + RecordSet rs = new RecordSet(); + if(pageexpandid<1){ + String sql = "SELECT id FROM mode_pageexpand WHERE modeid="+modeid+" AND issystemflag=103 "; + rs.execute(sql); + if(rs.next()){ + pageexpandid = rs.getInt("id"); + } + } + if(formid<0){ + String sql = "SELECT formid FROM modeinfo WHERE id="+modeid; + rs.execute(sql); + if(rs.next()){ + formid = rs.getInt("formid"); + } + } + params.put("formid", formid); + params.put("pageexpandid", pageexpandid); + String filename = fu.uploadFiles("excelfile"); + HttpSession session = req.getSession(true); + params.put("session", session); + params.put("fu", fu); + params.put("filename", filename); + return this.ImportDataNew(params, user); + } + + /** + * 批量导入 + * @param params + * @param user + * @return + */ + public String ImportDataNew(Map params, User user) { + String filename = Util.null2String(params.get("filename")); + String startStr = DateHelper.getCurDateTime(); + //导入前先加载下缓存 + int modeid = Util.getIntValue(Util.null2String(params.get("modeid"))); + this.isdetailright=getIsDetailRight(modeid); + String tempkeyStr = Util.null2String(params.get("tempkey")); + String key = user.getUID()+"_"+modeid+"_"+tempkeyStr; + this.key = key; + //校验文件大小 + File file = new File(filename); + FormModeConfig config=new FormModeConfig(); + int batchimportSize = config.getBatchimportSize(); + if (file.exists()&&file.length()>(batchimportSize*1024*1024)) { + String msg=MessageFormat.format(SystemEnv.getHtmlLabelName(523743, user.getLanguage()), batchimportSize); + writeProgressMsg(key,msg, "-1"); + ExpExcelUtil.removeImpUserState(user.getUID(),modeid+""); + return msg; + } + //30s内禁止同一个用户的多次请求 + String stateStr=Util.null2String(ExpExcelUtil.getObject("modeImp30s_"+user.getUID())); + if(stateStr!=null&&!"".equals(stateStr)){ + String currentTime = DateHelper.getCurDateTime(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String lastTime = Util.splitString(stateStr,"##")[0]; + try { + Date dt1 = sdf.parse(lastTime);//上次的时间 + Date dt2 = sdf.parse(currentTime); + double t = (dt2.getTime() - dt1.getTime()) / (1000.0);//当前时间-上次的时间的秒数 + if(t<10){ + writeProgressMsg(key,MessageFormat.format(SystemEnv.getHtmlLabelName(512688, user.getLanguage()), "10"), "-1"); + writeLog("imp:10s内禁止同一个用户的多次请求",lastTime+"_"+currentTime); + ExpExcelUtil.removeImpUserState(user.getUID(),modeid+""); + return SystemEnv.getHtmlLabelName(508071, user.getLanguage()); + } + } catch (ParseException e) { + e.printStackTrace(); + writeLog("imp:10s内禁止同一个用户的多次请求:日期转换异常",lastTime+"_"+currentTime); + } + } + ExpExcelUtil.putObject("modeImp30s_"+user.getUID(), startStr, true); + //30s内禁止同一个用户的多次请求 + + + + + ExpExcelUtil.refreshImpUserState(user.getUID(),key);//刷新导入状态 + + Date starttime = new Date(); + String Errmsg = ""; + + + ExpExcelUtil.refreshImpUserState(user.getUID(),key);//刷新导入状态 + + ModeCacheManager.getInstance().loadCacheNow(modeid+"", "", ""); + ExpExcelUtil.refreshImpUserState(user.getUID(),key);//刷新导入状态 + int sourcetype = Util.getIntValue(Util.null2String(params.get("sourcetype")));//为1的时候,表示是后台设置界面 + int importorderReq = Util.getIntValue(Util.null2String(params.get("importorder")));//为后台设置界面时,无需保存,导入顺序即可生效 + int importtype = Util.getIntValue(Util.null2String(params.get("importtype")));//1 追加,2覆盖,3更新 + int formid = Util.getIntValue(Util.null2String(params.get("formid"))); + this.isprintlog = (1 == Util.getIntValue(Util.null2String(params.get("isprintlog")))); + String importhref = StringUtil.getURLDecode(Util.null2String(params.get("href"))); //导入地址 + String impAddr = ExcelCacheUtil.getHostaddr(); + setProgressCanImport(key, true); + putMessage(STARTTIME,key, starttime.getTime()+""); + putMessage(IMPADDR,key, impAddr); + writeProgressMsg(key,SystemEnv.getHtmlLabelName(132262, user.getLanguage()), "0"); + List rowNumList = new Vector();//仅记录当前进度,不管是否成功 + List billList = new Vector();//记录成功导入的id + List rightList = new Vector(); + List detailList = new Vector(); + List addBillIdList = new Vector();//增加 + List updateList = new Vector();//更新 + List errorRowList = new Vector();//出错行 + Hashtable> errorDetailMap = new Hashtable>(); + int mainrows = 0; + int mainrowsALL = 0; + int delmainRow = 0; + int deldetailRow = 0; + String ErrmsgRow = ""; + boolean hasDetail=false; + Sheet[] allSheets = null; + String sheetEmptyRowMsg = ""; + boolean isExcel2007=true; + try { + String sql = ""; + RecordSet rs = new RecordSet(); + RecordSet rs2 = new RecordSet(); + + String interfacePath = ""; + String fieldtranspath = ""; + String isuse = ""; //1启用 + int billid = -1; + int modetype = -1; + + sql = "select modename,modedesc,formid,modetype from modeinfo where id = " + modeid; + rs.execute(sql); + while(rs.next()){ + formid = Util.getIntValue(rs.getString("formid")); + modetype = Util.getIntValue(rs.getString("modetype")); + } + boolean hetong = false;//如果是合同数据 + String modetypeids = getPropValue("modedatabatchimport", "modetype"); + modetypeids = ","+modetypeids+","; + if(modetypeids.indexOf(","+modetype+",")>-1){//如果是合同数据 + String needrightmodeids =","+ getPropValue("modedatabatchimport", "modeneedrightids")+","; + if (needrightmodeids.indexOf(","+modeid+",")<0) { + hetong = true; + } + } + + sql = "select * from mode_DataBatchImport where modeid="+modeid; + rs.execute(sql); + if (rs.next()) { + interfacePath = rs.getString("interfacepath"); + fieldtranspath=Util.null2String(rs.getString("fieldtranspath")); + isuse = rs.getString("isuse"); + } + Object fieldTransObject=null; + List fieldtranslist = new ArrayList(); + if (!"".equals(fieldtranspath)) { + sql = "select fieldid from mode_import_fieldtrans where modeid=? and formid=?"; + rs.executeQuery(sql, modeid,formid); + while (rs.next()) { + String fieldid = Util.null2String(rs.getString("fieldid")); + fieldtranslist.add(fieldid); + } + try { + fieldtranspath=fieldtranspath.replaceAll(".java$", "").replaceAll(".class$", ""); + fieldTransObject = Class.forName(fieldtranspath).newInstance(); + } catch (Exception e) { + writeLog(e); + } + } + params.put("fieldTransObject", fieldTransObject); + params.put("fieldtranslist", fieldtranslist); + writeProgressMsgAndStep(key,SystemEnv.getHtmlLabelName(132263, user.getLanguage()), "0",1); + //init excel object +// String filename = fu.uploadFiles("excelfile"); + writeProgressMsg(key,SystemEnv.getHtmlLabelName(132264, user.getLanguage()), "0"); + ExpExcelUtil.refreshImpUserState(user.getUID(),key);//刷新导入状态 + //创建输入流 + InputStream stream = new FileInputStream(filename); + //获取Excel文件对象 + Workbook rwb = WorkbookFactory.create(stream); + if (rwb instanceof HSSFWorkbook) { + isExcel2007=false; + } + writeProgressMsgAndStep(key,SystemEnv.getHtmlLabelName(132265, user.getLanguage()), "0",1); + ExpExcelUtil.refreshImpUserState(user.getUID(),key);//刷新导入状态 + //---------------验证表头-------------------------- + writeProgressMsgAndStep(key,SystemEnv.getHtmlLabelName(132266, user.getLanguage()), "0",2); + int totalsheet=rwb.getNumberOfSheets(); + allSheets=new Sheet[totalsheet]; + for (int i = 0; i < totalsheet; i++) { + allSheets[i]=rwb.getSheetAt(i); + } + //#不需要添加共享数据模块类型,不是模块id,该类型下面的所有数据都不进行权限处理,也不能导入明细数据,只能导入主数据, + //modetype=17 + if(hetong&&allSheets.length>1){ + Sheet mainSheet = allSheets[0]; + allSheets = new Sheet[]{mainSheet}; + } + Sheet sheet = rwb.getSheetAt(0); + int realRows = getSheetRealRows(sheet); + try{ + if(importtype==2&&realRows<=1){//是覆盖操作 + if(realRows==POIUtil.getLastRowNum(sheet)){ + Errmsg = SystemEnv.getHtmlLabelName(519671, user.getLanguage());//"删除全部数据后导入本次数据操作,不允许导入空的excel" + throw new Exception(Errmsg); + }else if(realRows0){ + isHaveTemplate = 1; + } + FieldInfo FieldInfo = new FieldInfo(); + FieldInfo.setUser(user); + writeProgressMsg(key,SystemEnv.getHtmlLabelName(132271, user.getLanguage()), "0"); + ExpExcelUtil.refreshImpUserState(user.getUID(),key);//刷新导入状态 + List> impFieldIds = new ArrayList<>();//记录excel中字段顺序 + try{ + String keyfield = Util.null2String(params.get("keyfield")); + String conditionfield = Util.null2String(params.get("conditionfield")); + if(conditionfield.indexOf(",") > -1){ + conditionfield = conditionfield.split(",")[0]; + } + ExpExcelUtil.refreshImpUserState(user.getUID(),key);//刷新导入状态 + //验证主表表头 + if(isHaveTemplate==1){ + FieldInfo.GetManTableFieldToExcelTemplate(formid, 1, user.getLanguage(),modeid);//根据模块导入模板获得主字段 + }else{ + FieldInfo.GetManTableFieldToExcel(formid, 1, user.getLanguage());//获得主字段 + } + verifyExcelMainHeader(key, sheet,keyfield,conditionfield,modeid,user,FieldInfo,impFieldIds); + + //验证明细表表头 + writeProgressMsg(key,SystemEnv.getHtmlLabelName(132271, user.getLanguage()), "0"); + ExpExcelUtil.refreshImpUserState(user.getUID(),key);//刷新导入状态 + if(isHaveTemplate==1){ + FieldInfo.GetDetailTableFieldToExcelTemplate(formid, 1, user.getLanguage(),modeid);//根据模块导入模板获得明细字段 + }else{ + FieldInfo.GetDetailTableFieldToExcel(formid, 1, user.getLanguage());//获得明细字段 + } + verifyExcelDetailHeader(key,allSheets,modeid,user,FieldInfo,impFieldIds); + }catch (Exception e){ + Errmsg = e.getMessage(); + throw new Exception(Errmsg); + } + ExpExcelUtil.refreshImpUserState(user.getUID(),key);//刷新导入状态 + //---------------验证表头end-------------------------- + + try { + if (!StringHelper.isEmpty(interfacePath) && "1".equals(isuse)) { + writeProgressMsg(key,SystemEnv.getHtmlLabelName(132276, user.getLanguage()), "0"); + Object interfaceObject = Class.forName(interfacePath).newInstance(); + + if(interfaceObject instanceof ImportPreInterfaceAction) { //老的POI 方式 + ExcelParse ExcelParse = new ExcelParse(); + ExcelParse.init(filename); + ExpExcelUtil.refreshImpUserState(user.getUID(),key);//刷新导入状态 + if (ExcelParse.getWb()==null) { + Errmsg=MessageFormat.format(SystemEnv.getHtmlLabelName(513664, user.getLanguage()), SystemEnv.getHtmlLabelName(388652, user.getLanguage())); + throw new Exception(); + } + //---------------------验证待处理-------------------------------- + FileUploadToPath fu = (FileUploadToPath) params.get("fu"); + Errmsg = ((ImportPreInterfaceAction)interfaceObject).checkImportData(fu, user, formid, ExcelParse, modeid); + }else if(interfaceObject instanceof ImportPreInterfaceForJXLAction) { // JXL 方式 + //获取Excel文件对象 + WorkbookSettings settings=new WorkbookSettings(); + settings.setEncoding("iso-8859-1"); + jxl.Workbook workbook=null; + try { + stream = new FileInputStream(filename); + workbook = jxl.Workbook.getWorkbook(stream,settings); + } catch (BiffException e) { + Errmsg=MessageFormat.format(SystemEnv.getHtmlLabelName(513664, user.getLanguage()), SystemEnv.getHtmlLabelName(388652, user.getLanguage())); + throw new Exception(); + } + ExcelParseForJXL excelParseForJXL = new ExcelParseForJXL(workbook ); + ExpExcelUtil.refreshImpUserState(user.getUID(),key);//刷新导入状态 + //---------------------验证待处理-------------------------------- + Map paramsForJXL = new HashMap(); + paramsForJXL.put("modeid",params.get("modeid")); + paramsForJXL.put("formid",params.get("formid")); + Errmsg = ((ImportPreInterfaceForJXLAction)interfaceObject).checkImportData(paramsForJXL, user, excelParseForJXL ); + }else if(interfaceObject instanceof ImportPreInterfaceForPOIAction) { //新版poi方式,支持excel2007导入 + //获取Excel文件对象 + ExcelParseForPOI excelParse = new ExcelParseForPOI(); + excelParse.init(filename); + ExpExcelUtil.refreshImpUserState(user.getUID(),key);//刷新导入状态 + //---------------------验证待处理-------------------------------- + Map paramsForPOI = new HashMap(); + paramsForPOI.put("modeid",params.get("modeid")); + paramsForPOI.put("formid",params.get("formid")); + Errmsg = ((ImportPreInterfaceForPOIAction)interfaceObject).checkImportData(paramsForPOI, user, excelParse ); + } + + if (!StringHelper.isEmpty(Errmsg)) { + writeLog("Errmsg:"+Errmsg); + throw new Exception(Errmsg); + } + } + } catch(Exception e) { + if ("".equals(Errmsg)) { + Errmsg = SystemEnv.getHtmlLabelName(132277, user.getLanguage())+":"+e.getMessage(); + } + throw e; + } + writeProgressMsg(key,SystemEnv.getHtmlLabelName(132278, user.getLanguage()), "0"); + this.closeStream(stream); + writeProgressMsg(key,SystemEnv.getHtmlLabelName(132279, user.getLanguage()), "0"); + //获得后台配置的待验证的字段的id以及验证的条件 + Map> validateMap = new HashMap>(); + sql = "select b.* from mode_DataBatchImport a,mode_excelFieldDetail b where b.mainid=a.validateid and a.modeid="+modeid; + rs.execute(sql); + while(rs.next()){ + String fieldids = Util.null2String(rs.getString("fieldid")); + String selectid = Util.null2String(rs.getString("selectids")); + String selectvalue = Util.null2String(rs.getString("selectvalue")); + String selectname = Util.null2String(rs.getString("selectname")); + if(!selectid.equals("") && !selectvalue.equals("")){ + sql = "select * from workflow_SelectItem where fieldid="+selectid+" and selectvalue='"+selectvalue+"'"; + rs2.execute(sql); + if(rs2.next()){ + selectname =Util.formatMultiLang( rs2.getString("selectname"), user.getLanguage()+""); + } + } + if(!fieldids.equals("")){ + String[] ids = fieldids.split(","); + for(int i=0;i temp = validateMap.get(ids[i]); + if(selectid.equals("")){ + temp.clear(); + }else{ + if(temp.size() == 0){ + temp.clear(); + }else{ + temp.add(selectid+":"+selectname); + } + } + validateMap.put(ids[i], temp); + }else{ + List list = new ArrayList(); + if(!selectid.equals("") && !selectvalue.equals("")){ + list.add(selectid+":"+selectname); + } + validateMap.put(ids[i], list); + } + } + } + + } + ExpExcelUtil.refreshImpUserState(user.getUID(),key);//刷新导入状态 + writeProgressMsg(key,SystemEnv.getHtmlLabelName(132280, user.getLanguage()), "0"); + // + rs.execute("select fieldid,checkexpression from ModeFormFieldExtend where formId='"+formid+"' and (checkexpression is not null or checkexpression!='')"); + while(rs.next()){ + checkMap.put(rs.getString("fieldid"), rs.getString("checkexpression")); + } + writeProgressMsgAndStep(key,SystemEnv.getHtmlLabelName(132281, user.getLanguage()), "0",2); + //import maintable + writeProgressMsgAndStep(key,SystemEnv.getHtmlLabelName(132246, user.getLanguage()), "0",3); + int cpuNum = 2; + boolean useSingleThread = true;//默认为顺序导入 + if(sourcetype==1){//为后台设置界面时,按照后台设置界面导入顺序的选择,无需保存即可生效 + if(importorderReq==0){ + useSingleThread = false; + } + }else{ + //顺序导入仍然使用单线程导入 + sql = "select importorder from mode_DataBatchImport where modeid="+modeid; + rs.execute(sql); + if(rs.next()){ + int importorder = rs.getInt("importorder"); + if(importorder==0){ + useSingleThread = false; + } + } + } + ExpExcelUtil.refreshImpUserState(user.getUID(),key);//刷新导入状态 + if(importtype==2){//是否需要删除历史数据 + writeProgressMsg(key,SystemEnv.getHtmlLabelName(132282, user.getLanguage()), "0"); + RecordSet rs1 = new RecordSet(); + String tablename = ""; + String detailkeyfield = ""; + sql = "select tablename,detailkeyfield from workflow_bill where id = " + formid;//删除数据 + rs.execute(sql); + if(rs.next()){ + tablename = rs.getString("tablename"); + detailkeyfield = rs.getString("detailkeyfield"); + } + //-------------删除数据前记录覆盖删除日志------------- + sql ="select id from " + tablename + " where formmodeid = "+modeid ; + rs.execute(sql); + delmainRow = rs.getCounts(); + writeProgressMsg(key,MessageFormat.format(SystemEnv.getHtmlLabelName(132284,user.getLanguage()),tablename), "0"); + String operatedesc = SystemEnv.getHtmlLabelName(125685, user.getLanguage());//删除(导入被覆盖) + String operatetype = "3";//操作的类型: 1:新建 2:修改 3:删除 4:查看 + + ExpExcelUtil.refreshImpUserState(user.getUID(),key);//刷新导入状态 +// ImpExcelReader impExcelReader = new ImpExcelReader(); +// impExcelReader.setUser(user); + DeleteData delData = new DeleteData(); + delData.setUser(user); + delData.setClientaddress(clientaddress); + delData.setExcel(true); + int index = 0; + while(rs.next()){ + index++; + writeProgressMsg(key,MessageFormat.format(SystemEnv.getHtmlLabelName(132284,user.getLanguage()),tablename)+index+"/"+rs.getCounts(), "0"); + int relatedid = rs.getInt("id"); + delData.insertDeleteData(tablename, relatedid+"", modeid+"", formid+""); +// impExcelReader.writeBeatchLog(modeid,operatedesc, operatetype, relatedid,null,null,null); + } + //-------------删除数据前记录覆盖删除日志------------- + sql = "select tablename from Workflow_billdetailtable where billid = " + formid; + rs.execute(sql);//查询单据明细表的信息 + int backindex = this.getAndUpdateBackIndex(modeid); + this.backindex=backindex; + String detailremark=""; + while(rs.next()){ + String deltablename = rs.getString("tablename"); + sql = "select 1 from "+deltablename+" where "+detailkeyfield+" in (select id from "+tablename+" where formmodeid = "+modeid+" )"; + rs1.execute(sql);//删除明细 + deldetailRow += rs1.getCounts(); + writeProgressMsg(key,MessageFormat.format(SystemEnv.getHtmlLabelName(132283,user.getLanguage()),deltablename,rs1.getCounts()), "0"); + //修正逻辑,批量导入覆盖删除数据时不删除文档 +// if (isdelfile) { +// sql="select id from "+tablename+" where formmodeid = "+modeid; +// rs.executeQuery(sql); +// while (rs.next()) { +// String mainid=Util.null2String(rs.getString("id")); +// del.deleteDocFile(tablename, mainid, formid, false, null, null);//删除主表的附件 +// del.deleteDocFile(deltablename, mainid, formid, true, null, detailkeyfield);//再删除明细表的附件 +// } +// } + //备份明细表数据 + String sqlwhere=" where "+detailkeyfield+" in (select id from "+tablename+" where formmodeid = "+modeid+" )"; + this.BackUpTable(deltablename, modeid, false, backindex, sqlwhere); + if (rs1.getCounts()>0) {//明细表有数据则备份 + detailremark+=","+MessageFormat.format(SystemEnv.getHtmlLabelName(514955, user.getLanguage()), rs1.getCounts(),deltablename+this.suffix+backindex); + } + //{0}条明细数据已备份至{1} + sql = "delete from "+deltablename+sqlwhere; + rs1.execute(sql);//删除明细 + } + writeProgressMsg(key,MessageFormat.format(SystemEnv.getHtmlLabelName(132285,user.getLanguage()),tablename,rs.getCounts()), "0"); + String sqlwhere=" where formmodeid = "+modeid + " and id not in ("+billid+") "; + if (delmainRow>0) { + this.BackUpTable(tablename, modeid, true, backindex, sqlwhere); + this.backupremark+=MessageFormat.format(SystemEnv.getHtmlLabelName(514954, user.getLanguage()),tablename+this.suffix+backindex); + } + if (!"".equals(detailremark)) { + this.backupremark+=detailremark; + } + sql = "delete from " + tablename + sqlwhere; + rs.execute(sql); + } + + Map IdMap = new HashMap(); + ExecutorService executorService = ExpExcelUtil.getInstance().getImppool();//固定线程池 + ExecutorService asynService = ExpExcelUtil.getInstance().getAsynimpPool();//异步任务线程池 + Map modeLogMap = new ConcurrentHashMap();//记录主表id及对应的viewlogid + int currentIndex = 0; + CountDownLatch doneSignal = null; + HashMap creatoridMap = new HashMap(); + ExpExcelUtil.refreshImpUserState(user.getUID(),key);//刷新导入状态 + rowNumList.clear();//清除计数器 + params.put("sheetindex", 1); + jxl.Sheet[] allSheetsJXL = null; + if (fieldTransObject!=null) {//设置了导入转换接口,初始化所需参数 + this.closeStream(stream); + stream = new FileInputStream(filename); + if (fieldTransObject instanceof ImportFieldTransAction) {//JXL + WorkbookSettings settings=new WorkbookSettings(); + settings.setEncoding("iso-8859-1"); + try { + jxl.Workbook workbook = jxl.Workbook.getWorkbook(stream,settings); + allSheetsJXL = workbook.getSheets(); + params.put("sheetJXL", allSheetsJXL[0]); + } catch (BiffException e) { + Errmsg=MessageFormat.format(SystemEnv.getHtmlLabelName(513664, user.getLanguage()), SystemEnv.getHtmlLabelName(504236, user.getLanguage())); + throw new Exception(); + } + }else if (fieldTransObject instanceof ImportFieldTransActionPOI) {//poi + ExcelParseForPOI excelParse = new ExcelParseForPOI(); + excelParse.init(stream); + params.put("excelParse", excelParse); + } + } + if((rowNum-1)<100||useSingleThread){ + doneSignal = new CountDownLatch(1);//使用计数栅栏 + executorService.submit(new ImpExcelReader("importMainData",doneSignal, 0, rowNum,currentIndex + ,key,sheet,params,user,formid + ,modeid,validateMap,IdMap,checkMap,errorRow,clientaddress,SystemEnv.getHtmlLabelName(524507,user.getLanguage())//导入ALL线程 + ,FieldInfo,new HashMap(),"",Errmsg,1,billList + ,creatoridMap,addBillIdList,detailList,updateList,errorRowList,errorDetailMap,mainrows,rowNumList,modeLogMap, + errorTable,TimeZoneVar.getTimeZone(),isdetailright,impFieldIds)); + }else{ + doneSignal = new CountDownLatch(cpuNum);//使用计数栅栏 + int d = (rowNum-rowNum%cpuNum)/cpuNum; + for(int i=0;i0){ + ModeDataManager modeDataManager = new ModeDataManager(); + modeDataManager.setFormid(formidf); + modeDataManager.setFormmodeid(modeidf); + modeDataManager.setUser(userTemp); + modeDataManager.setParams(params); + for (int j = 0; j < addBillIdListTemp.size(); j++) { + int addBillId = Util.getIntValue(StringHelper.null2String(addBillIdListTemp.get(j)).replaceAll("'","")); + modeDataManager.setBillid(addBillId); + modeDataManager.setImporttype(importtype); + modeDataManager.setImporthref(importhref); + modeDataManager.doInterface(expandid); + } + + for (int j = 0; j < updateListTemp.size(); j++) { + int addBillId = Util.getIntValue(StringHelper.null2String(updateListTemp.get(j)).replaceAll("'","")); + modeDataManager.setBillid(addBillId); + modeDataManager.setImporttype(importtype); + modeDataManager.setImporthref(importhref); + modeDataManager.doInterface(expandid); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + + } + }); + thread.start(); + ExpExcelUtil.refreshImpUserState(user.getUID(),key);//刷新导入状态 + //如果权限和明细表字段有关,则在明细表数据全部插入完毕后再在这里统一进行权限重构,否则插入一条主表记录就使用多线程重构一条权限 + if (isdetailright) { + try { + for (int i = 0; i < billList.size(); i++) { + int souceid = Util.getIntValue(StringHelper.null2String(billList.get(i)),-1); + int creatorid = Util.getIntValue(StringHelper.null2String(creatoridMap.get(StringHelper.null2String(billList.get(i)))),-1); + if(creatorid == -1 ){ + creatorid = user.getUID(); + } + asynService.submit(new ImpAsynTask(ImpAsynTask.TASK_RIGHT, souceid, modeid,creatorid)); + } +// int currentIndex1 = 0; +// CountDownLatch doneSignal2 = null; +// rowNumList.clear();//清除计数器 +// if((rowNum2)<100){ +// doneSignal2 = new CountDownLatch(1);//使用计数栅栏 +// executorService.submit(new ImpExcelReader("insertRight",doneSignal2, 0, rowNum2,currentIndex1 +// ,key,null,params,user,formid +// ,modeid,validateMap,IdMap,checkMap,errorRow,clientaddress,"权限导入ALL线程" +// ,FieldInfo,map,maintable,Errmsg,1,billList,creatoridMap,addBillIdList,rightList,updateList,errorRowList,errorDetailMap,mainrows,rowNumList,modeLogMap,errorTable +// ,TimeZoneVar.getTimeZone(),isdetailright)); +// }else{ +// doneSignal2 = new CountDownLatch(cpuNum);//使用计数栅栏 +// int d = (rowNum2-rowNum2%cpuNum)/cpuNum; +// for(int i=0;i 0) { + StringBuffer buf = new StringBuffer(); + Iterator it = errorRow.iterator(); + int xx = 0; + while (it.hasNext()) { + xx++; + String v = (String) it.next(); + String[] strs = v.split(","); + writeLog(xx + " "+v+" "+strs.length); + if(strs.length==2){ //行出错 + String flagMsg = ""; + int index = strs[1].indexOf("~~weaverSplit~~"); + if(index!=-1){ + flagMsg = strs[1].substring(index+"~~weaverSplit~~".length()); + if(!"".equals(flagMsg)){ + flagMsg = ","+flagMsg; + } + strs[1] = strs[1].substring(0,index); + } + buf.append(fengeString + + SystemEnv.getHtmlLabelName(15323, user.getLanguage())//第 + + fengeString + + strs[0] + + fengeString + + SystemEnv.getHtmlLabelName(27591, user.getLanguage())//个 + + fengeString + + "sheet" + + fengeString + + SystemEnv.getHtmlLabelName(15323, user.getLanguage())//第 + + fengeString + + strs[1] + + fengeString + + SystemEnv.getHtmlLabelName(27592, user.getLanguage())//行 + + fengeString); + buf.append(fengeString + + SystemEnv.getHtmlLabelName(27593, user.getLanguage())//导入出错 + +flagMsg + + "!\\n"); + writeLog(buf.toString()); + }else if(strs.length>2){ //数据不合法 + buf.append(fengeString + + SystemEnv.getHtmlLabelName(15323, user.getLanguage())//第 + + fengeString + + strs[0] + + fengeString + + SystemEnv.getHtmlLabelName(27591, user.getLanguage())//个 + + fengeString + + "sheet" + + fengeString + + SystemEnv.getHtmlLabelName(15323, user.getLanguage())//第 + + fengeString + + strs[1] + + fengeString + + SystemEnv.getHtmlLabelName(27592, user.getLanguage())//行 + + fengeString); + buf.append(fengeString + + SystemEnv.getHtmlLabelName(15323, user.getLanguage())//第 + + fengeString + + strs[2] + + fengeString + + SystemEnv.getHtmlLabelName(18621, user.getLanguage())//列 + + fengeString); + buf.append(fengeString + + SystemEnv.getHtmlLabelName(27593, user.getLanguage()));//导入出错 + buf.append(","); + for(int k=3;k-1){ //132251 不存在无法更新 + buf.append("!"); + }else{ + if(user.getLanguage()==8)buf.append(" "); + buf.append(SystemEnv.getHtmlLabelName(132306, user.getLanguage())+"!"); //132306 不存在 + } + } + } + buf.append("\\n"); + } + } + Errmsg += buf.toString(); + }else{ + if(IdMap.size()==0){ + if(mainrows<1){ + Errmsg = SystemEnv.getHtmlLabelName(30790, user.getLanguage()) + "\\n"; + }else{ + Errmsg = SystemEnv.getHtmlLabelName(524514, user.getLanguage())+ "\\n";//没有成功导入或发生异常,请查看日志信息 + } + } + } + ExpExcelUtil.refreshImpUserState(user.getUID(),key);//刷新导入状态 + if(StringHelper.isEmpty(Errmsg) || !StringHelper.isEmpty(sheetEmptyRowMsg)){ + writeProgressMsgAndStep(key,SystemEnv.getHtmlLabelName(129463, user.getLanguage()), "0",5); + }else{ + writeProgressMsgAndStep(key,SystemEnv.getHtmlLabelName(27593, user.getLanguage()), "0",5); + } + + } catch (Exception e) { + if(StringHelper.isEmpty(Errmsg)){ + Errmsg = SystemEnv.getHtmlLabelName(132296, user.getLanguage())+":"+e.getMessage(); + } + writeLog(e); + }finally{ + try { + ExpExcelUtil.refreshImpUserState(user.getUID(),key);//刷新导入状态 + String msg = ""; + if(addBillIdList.size()>0){ + msg += ","+MessageFormat.format(SystemEnv.getHtmlLabelName(132297,user.getLanguage()),addBillIdList.size()); + } + if(updateList.size()>0){ + msg += ","+MessageFormat.format(SystemEnv.getHtmlLabelName(132298,user.getLanguage()),updateList.size()); + } + if(delmainRow>0){ + msg += ","+MessageFormat.format(SystemEnv.getHtmlLabelName(132299,user.getLanguage()),delmainRow); + } + if(!"".equals(msg)){ + msg = msg.substring(1); + msg = ","+MessageFormat.format(SystemEnv.getHtmlLabelName(132300,user.getLanguage()),mainrowsALL)+msg+""; + } + int ddtailErrorRow = 0; + Set set = errorDetailMap.keySet(); + Iterator it = set.iterator(); + while(it.hasNext()){ + String tempkey = it.next(); + Vector d = errorDetailMap.get(tempkey); + ddtailErrorRow += d.size(); + } + String allErrorMmsg = createErrorFile(user, modeid, formid, errorRowList, errorDetailMap, + allSheets, ddtailErrorRow,isExcel2007); + if("".equals(msg)){ + msg = ","+MessageFormat.format(SystemEnv.getHtmlLabelName(132304,user.getLanguage()),mainrowsALL); + } + if(hasDetail){ + msg += ","+MessageFormat.format(SystemEnv.getHtmlLabelName(132303,user.getLanguage()),detailList.size()); + } + String importtypename = ""; + if(importtype==1){ + importtypename = SystemEnv.getHtmlLabelName(31259,user.getLanguage()); + }else if(importtype==2){ + importtypename = SystemEnv.getHtmlLabelName(517042,user.getLanguage()); + }else if(importtype==3){ + importtypename = SystemEnv.getHtmlLabelName(17744,user.getLanguage()); + } + if(!StringHelper.isEmpty(importtypename)){ + importtypename = "["+importtypename+"]"; + } + if(StringHelper.isEmpty(Errmsg)&&progressMap.containsKey(CANIMPORTMSG+"_"+key)){ + Errmsg = progressMap.get(CANIMPORTMSG+"_"+key); + } + if(!StringHelper.isEmpty(sheetEmptyRowMsg)){ + putMessage(MSG,key, importtypename+SystemEnv.getHtmlLabelName(27593, user.getLanguage())+msg+allErrorMmsg); + if(!StringHelper.isEmpty(ErrmsgRow)){ + ErrmsgRow = ErrmsgRow.substring(0,ErrmsgRow.length()-1); + ErrmsgRow = ErrmsgRow + SystemEnv.getHtmlLabelName(132305, user.getLanguage()); + } + Errmsg += ErrmsgRow; + }else if(StringHelper.isEmpty(Errmsg)){ + putMessage(MSG,key, importtypename+SystemEnv.getHtmlLabelName(129463, user.getLanguage())+msg+allErrorMmsg); + }else{ + putMessage(MSG,key, importtypename+SystemEnv.getHtmlLabelName(27593, user.getLanguage())+msg+allErrorMmsg); + } + ExpExcelUtil.refreshImpUserState(user.getUID(),key);//刷新导入状态 + String flag = Util.null2String(errorTable.size()); + int failrow = 0; + String failurerow = ""; + if(errorTable.size()>0){ + failrow = errorTable.size(); + failurerow = failrow+"_imp123456"+UUID.randomUUID(); + } + int addrow = addBillIdList.size(); + int updaterow = updateList.size(); + int adddetailrow = detailList.size(); + String insertSql = "insert into mode_batchimp_log(modeid,operatetype,ipaddress,operator,optdatetime,addrow,updaterow,delrow,adddetailrow,deldetailrow,failurerow,backupremark,backindex,filepath)" + + " values("+modeid+","+importtype+",'"+clientaddress+"',"+user.getUID()+",'"+startStr+"',"+addrow+","+updaterow+","+delmainRow+","+adddetailrow+","+deldetailRow+",'"+failurerow+"','"+this.backupremark+"',"+this.backindex+",?)"; + RecordSet rs = new RecordSet(); + rs.executeUpdate(insertSql,filename); + saveFailureLog(errorTable,modeid,failurerow); + putMessage(ERRORFLAG,key, flag); + putMessage(STATUS,key, "-1"); + putMessage(ERRMSG,key, Errmsg); + putMessage(SEARCHID,key, failurerow); + } catch (Exception e) { + writeLog(e); + }finally{ + Date endtime = new Date(); + long t = endtime.getTime() - starttime.getTime(); + String timestr = secondsToStr(t); + putMessage(TIME,key, timestr); + putMessage(ENDTIME,key, endtime.getTime()+""); + ExpExcelUtil.removeImpUserState(user.getUID(),modeid+"");//导入完毕移除导入状态 + } + } + return Errmsg; + + } + + private String createErrorFile(User user, int modeid, int formid, List errorRowList, + Hashtable> errorDetailMap, Sheet[] allSheets, int ddtailErrorRow,boolean isExcel2007) { + String allErrorMmsg = ""; + if(errorRowList.size()>0||ddtailErrorRow>0){ + if(errorRowList.size()>0){ + allErrorMmsg += ","+MessageFormat.format(SystemEnv.getHtmlLabelName(132301,user.getLanguage()),errorRowList.size()); + } + if(ddtailErrorRow>0){ + allErrorMmsg += ","+MessageFormat.format(SystemEnv.getHtmlLabelName(132302,user.getLanguage()),ddtailErrorRow); + } + allErrorMmsg = allErrorMmsg.substring(1); + RecordSet rs = new RecordSet(); + String sql = "select * from modeinfo where Id="+modeid; + rs.execute(sql); + if(rs.next()&&allSheets!=null&&allSheets.length>0){ + Workbook wb=null; + if (isExcel2007) { + wb=new SXSSFWorkbook(); + }else { + wb=new HSSFWorkbook(); + } + Sheet sheet = wb.createSheet(SystemEnv.getHtmlLabelName(21778, user.getLanguage())); + sheet.setColumnWidth(0, 6000); + Row row = sheet.createRow(0); + Cell cell = row.createCell(0); + cell.setCellValue("ID"); +// String validateids = ""; +// sql = "select b.fieldid from mode_excelField a,mode_excelFieldDetail b where a.formid ="+formid+" and a.modeid="+modeid+" and b.mainid=a.id"; +// rs.execute(sql); +// while(rs.next()){ +// validateids += rs.getString("fieldid")+","; +// } + ExpExcelUtil.refreshImpUserState(user.getUID(),key);//刷新导入状态 + Sheet mainSheet = allSheets[0]; + int mainSheetcol = POIUtil.getLastCellNum(mainSheet); + for(int i=1;i d = errorDetailMap.get((i+1)+""); + Collections.sort(d); + Sheet detailSheet = allSheets[i]; + for(int k=0;k"+allErrorMmsg+"【"+SystemEnv.getHtmlLabelName(125264, user.getLanguage())+"】"; + } + } + return allErrorMmsg; + } + + private String createFile(Workbook wb){ + String uuid=StringUtils.getUnquieID(); + String excelPath = FileUtils.getExpCreateDir()+uuid; + if(!new File(excelPath).exists()){ + new File(excelPath).mkdirs(); + } + String path = excelPath+File.separator+uuid; + File file = new File(path); + OutputStream os = null; + try { + if(!file.exists()){ + file.createNewFile(); + } + os = new FileOutputStream(file); + wb.write(os); + os.flush(); + wb.close(); + } catch (Exception e) { + writeLog(e); + }finally { + try { + if(os!=null){ + os.close(); + } + if(wb!=null){ + wb.close(); + } + } catch (IOException e) { + writeLog(e); + } + } + return uuid; + } + + /** + * 验证Excel主表表头 + * @param key + * @param sheet + * @param keyfield 重复验证字段 + * @param modeId 模块id + * @param user 当前操作者 + * @throws Exception + */ + private void verifyExcelMainHeader(String key,Sheet sheet,String keyfield,String conditionfield,int modeId,User user,FieldInfo FieldInfo,List> impFieldIds) throws Exception { + ExpExcelUtil.refreshImpUserState(user.getUID(),key);//刷新导入状态 + ArrayList ManTableFieldlabel = FieldInfo.getManTableFieldlabel(); + ArrayList ManTableFieldHtmltypes = FieldInfo.getManTableFieldHtmltypes(); + ArrayList ManTableFieldIds = FieldInfo.getManTableFieldIds(); + ArrayList mainTableFieldNames = FieldInfo.getManTableFieldFieldNames(); + List excelFieldIds = new ArrayList<>();//记录excel中的主表字段顺序 + + //导入设置了必填,验证选择框框列和必填字段列是否存在 + Set condFieldIds = new HashSet<>();//必填条件列 + Set mustFieldIds = new HashSet<>();//必填字段列 + RecordSet rs = new RecordSet(); + String sql = "SELECT mefd.selectids,mefd.fieldid FROM mode_excelField mef,mode_excelfielddetail mefd,workflow_billfield wbf WHERE mef.id=mefd.mainid and mefd.selectids=wbf.id and "+CommonConstant.DB_ISNULL_FUN+"(wbf.viewtype,0)=0 and mef.modeid=?"; + rs.executeQuery(sql,modeId); + while(rs.next()){ + String selectIds = Util.null2String(rs.getString("selectids")); + String fieldId = Util.null2String(rs.getString("fieldid")); + if(!"".equals(selectIds)){ + condFieldIds.add(selectIds); + } + mustFieldIds.addAll(Arrays.asList(fieldId.split(","))); + } + //重复验证字段 + Map keyfieldmap = new HashMap(); + if (!"".equals(keyfield)) { + String[] arr1 = keyfield.split("\\|"); + for (String arr : arr1) { + String[] arr2 = arr.split(","); + for (String field : arr2) { + if (!"".equals(field)) { + keyfieldmap.put(field.toLowerCase(), null); + } + } + } + } + //模板中的名称 + Map mainFieldInfo = new HashMap<>(); + String conditionfieldtemp = ""; + Map> fieldsInfo = new HashMap<>(); + ExpExcelUtil.refreshImpUserState(user.getUID(),key);//刷新导入状态 + for(int i=0;i set; + if(fieldsInfo.containsKey(label)){ + set = fieldsInfo.get(label); + }else{ + set = new HashSet<>(); + } + set.add(fieldId); + fieldsInfo.put(label,set); + + if(fieldsInfo.containsKey(label_fieldname)){ + set = fieldsInfo.get(label_fieldname); + }else{ + set = new HashSet<>(); + } + set.add(fieldId); + fieldsInfo.put(label_fieldname,set); + } + + ExpExcelUtil.refreshImpUserState(user.getUID(),key);//刷新导入状态 + Map excelLabel = new HashMap<>();//key:字段id,value:excel中的显示名 + int cols = POIUtil.getLastCellNum(sheet); + Map excelFieldCol = new HashMap<>(); + boolean conditionFlag = false;//条件字段验证标识 + int idColCount = 0;//id列数量 + for(int i=0;i1){ + setProgressCanImport(key,false); + //第{sheetIndex}个sheet中找到{colCount}个[{colName}]列,请删除多余的{colName}列后重新导入。 + String tip = SystemEnv.getHtmlLabelName(504172, user.getLanguage()); + tip = tip.replace("{sheetIndex}","1") + .replace("{colCount}",String.valueOf(idColCount)) + .replace("{colName}","ID"); + writeProgressMsg(key,tip, "0"); + throw new Exception(tip); + } + excelFieldIds.add("-2000"); + continue; + } + + if(!fieldsInfo.containsKey(content)){ + setProgressCanImport(key,false); + //第{sheetIndex}个sheet中表头第{colIndex}列:{content},不是模板中字段,请检查是否有误。 + String tip = SystemEnv.getHtmlLabelName(504173, user.getLanguage()); + tip = tip.replace("{sheetIndex}","1") + .replace("{colIndex}",String.valueOf(i+1)) + .replace("{content}",content); + writeProgressMsg(key,tip, "0"); + throw new Exception(tip); + } + + Set fieldIds = fieldsInfo.get(content); + if(fieldIds.size()>1){ + setProgressCanImport(key,false); + //504174 第{sheetIndex}个sheet中表头第{colIndex}列:{content},在标准模板中找到{fieldCount}个对应字段,请按照以下格式修改列名后重新导入:显示名_数据库名称。 + //506661 第{sheetIndex}个sheet中表头第{colIndex}列:{content},存在{fieldCount}个列名重复的对应字段,请按照以下格式修改列名后重新导入:显示名_数据库名称。 + String tip = SystemEnv.getHtmlLabelName(506661, user.getLanguage()); + tip = tip.replace("{sheetIndex}","1") + .replace("{colIndex}",String.valueOf(i+1)) + .replace("{content}",content) + .replace("{fieldCount}",String.valueOf(fieldIds.size())); + writeProgressMsg(key,tip, "0"); + throw new Exception(tip); + } + + String fieldId = fieldIds.iterator().next(); + if(!excelLabel.containsKey(fieldId)){ + excelLabel.put(fieldId,content); + } + //excel中是否有重复列名 + if(excelFieldCol.containsKey(fieldId)){ + int col = excelFieldCol.get(fieldId); + setProgressCanImport(key,false); + //第{sheetIndex}个sheet中表头第{colIndex1}列:{colName1},第{colIndex1}列:{colName2},列名重复,请按照以下格式修改列名后重新导入:显示名_数据库名称。 + String tip = SystemEnv.getHtmlLabelName(504175, user.getLanguage()); + tip = tip.replace("{sheetIndex}","1") + .replace("{colIndex1}",String.valueOf(col)) + .replace("{colName1}",excelLabel.get(fieldId)) + .replace("{colIndex2}",String.valueOf(i+1)) + .replace("{colName2}",content); + writeProgressMsg(key,tip, "0"); + throw new Exception(tip); + }else{ + int col = i+1; + excelFieldCol.put(fieldId,col); + } + + //导入设置了重复验证字段,excel中是否有重复验证字段列 + if (!"".equals(keyfield)&&keyfieldmap.containsKey(fieldId)) { + keyfieldmap.put(fieldId, "exist"); + } + //导入设置了条件字段,excel中是否有条件字段列 + if(conditionfieldtemp.equals(fieldId)){ + conditionFlag = true; + } + + //导入设置了必填,验证选择框框列和必填字段列是否存在 + //第1个sheet中未找到导入必填条件列[状态】,请添加导入必填条件列后重新导入。 + if(condFieldIds.contains(fieldId)){ + condFieldIds.remove(fieldId); + } + //第1个sheet中未找到必填字段列[合同],请添加必填字段列后重新导入。 + if(mustFieldIds.contains(fieldId)){ + mustFieldIds.remove(fieldId); + } + excelFieldIds.add(fieldId); + } + if (!"".equals(keyfield)) { + String notexist=""; + for(Map.Entry map:keyfieldmap.entrySet()){ + if (map.getValue()==null) {//模板中没有该字段 + String name=mainFieldInfo.get(map.getKey()); + notexist+=name+","; + } + } + notexist=notexist.replaceAll(",$", ""); + if (!"".equals(notexist)) { + setProgressCanImport(key,false); + //第{sheetIndex}个sheet中未找到重复验证字段列[{repVerifyField}],请添加重复验证字段列后重新导入。 + String tip = SystemEnv.getHtmlLabelName(504179, user.getLanguage()); + tip = tip.replace("{sheetIndex}","1") + .replace("{repVerifyField}",notexist); + writeProgressMsg(key,tip, "0"); + throw new Exception(tip); + } + } + + + if(!"".equals(conditionfield) && !conditionFlag){ + setProgressCanImport(key,false); + //第{sheetIndex}个sheet中未找到重复验证字段列[{repVerifyField}],请添加重复验证字段列后重新导入。 + String tip = SystemEnv.getHtmlLabelName(507416, user.getLanguage()); + tip = tip.replace("{sheetIndex}","1") + .replace("{conditionfield}",mainFieldInfo.get(conditionfieldtemp)); + writeProgressMsg(key,tip, "0"); + throw new Exception(tip); + } + + if(condFieldIds.size() > 0 ){ + StringBuffer conditionLabels = new StringBuffer(); + Iterator it = condFieldIds.iterator(); + while(it.hasNext()){ + conditionLabels.append(",").append(mainFieldInfo.get(it.next())); + } + setProgressCanImport(key,false); + //第{sheetIndex}个sheet中未找到导入必填条件列[{mustConditionCol}],请添加导入必填条件列后重新导入。 + String tip = SystemEnv.getHtmlLabelName(504176, user.getLanguage()); + tip = tip.replace("{sheetIndex}","1") + .replace("{mustConditionCol}",conditionLabels.substring(1)); + writeProgressMsg(key,tip, "0"); + throw new Exception(tip); + } + + + if(mustFieldIds.size() > 0 ){ + StringBuffer fieldLabels = new StringBuffer(); + Iterator it = mustFieldIds.iterator(); + while(it.hasNext()){ + fieldLabels.append(",").append(mainFieldInfo.get(it.next())); + } + setProgressCanImport(key,false); + //第{sheetIndex}个sheet中未找到导入必填字段列[{mustFieldCol}],请添加导入必填字段列后重新导入。 + String tip = SystemEnv.getHtmlLabelName(504177, user.getLanguage()); + tip = tip.replace("{sheetIndex}","1") + .replace("{mustFieldCol}",fieldLabels.substring(1)); + writeProgressMsg(key,tip, "0"); + throw new Exception(tip); + } + + if(idColCount==0){ + setProgressCanImport(key,false); + //第{sheetIndex}个sheet中未找到[{colName}]列,请添加后重新导入。 + String tip = SystemEnv.getHtmlLabelName(504178, user.getLanguage()); + tip = tip.replace("{sheetIndex}","1") + .replace("{colName}","ID"); + writeProgressMsg(key,tip, "0"); + throw new Exception(tip); + } + impFieldIds.add(excelFieldIds); + } + + private void verifyExcelDetailHeader(String key,Sheet[] allSheets,int modeId,User user,FieldInfo FieldInfo,List> impFieldIds) throws Exception{ + ArrayList detailtablefieldlables=FieldInfo.getDetailTableFieldNames();//显示名 + ArrayList detailTableDbFieldNames=FieldInfo.getDetailDBFieldNames();//字段名 + ArrayList detailtablefieldids=FieldInfo.getDetailTableFields(); + ArrayList>> detailFieldsInfo = new ArrayList<>(); + if(detailtablefieldlables.size()!=allSheets.length-1){//sheet个数验证 + setProgressCanImport(key,false); + String Errmsg = MessageFormat.format(SystemEnv.getHtmlLabelName(132272, user.getLanguage()),allSheets.length,detailtablefieldlables.size()+1); + writeProgressMsg(key,SystemEnv.getHtmlLabelName(132273, user.getLanguage()), "0"); + throw new Exception(Errmsg); + } + + ExpExcelUtil.refreshImpUserState(user.getUID(),key);//刷新导入状态 + + //导入设置了必填,验证选择框框列和必填字段列是否存在 + Set modeCondFieldIds = new HashSet<>();//该模块的所有必填条件列 + Set modeMustFieldIds = new HashSet<>();//该模块的所有必填字段列 + RecordSet rs = new RecordSet(); + String sql = "SELECT mefd.selectids,mefd.fieldid FROM mode_excelField mef,mode_excelfielddetail mefd,workflow_billfield wbf WHERE mef.id=mefd.mainid and mefd.selectids=wbf.id and "+CommonConstant.DB_ISNULL_FUN+"(wbf.viewtype,0)=1 and mef.modeid=?"; + rs.executeQuery(sql,modeId); + while(rs.next()){ + String selectIds = Util.null2String(rs.getString("selectids")); + String fieldId = Util.null2String(rs.getString("fieldid")); + if(!"".equals(selectIds)){ + modeCondFieldIds.add(selectIds); + } + modeMustFieldIds.addAll(Arrays.asList(fieldId.split(","))); + } + + ExpExcelUtil.refreshImpUserState(user.getUID(),key);//刷新导入状态 + + List> detailCondFieldIds = new ArrayList<>();//每个明细表必填条件列 + List> detailMustFieldIds = new ArrayList<>();//每个明细表必填字段列 + Map fieldsInfo = new HashMap<>(); + for(int i=0;i> detailField = new HashMap<>(); + ArrayList detailfieldnames = (ArrayList)detailtablefieldlables.get(i); + ArrayList detailfieldids = (ArrayList)detailtablefieldids.get(i); + ArrayList detailDbFieldName = (ArrayList)detailTableDbFieldNames.get(i); + Set condFieldIds = new HashSet<>(); + Set mustFieldIds = new HashSet<>(); + boolean hasfield=false; + for(int j=0;j fieldIdSet; + if(detailField.containsKey(showLabel)){ + fieldIdSet = detailField.get(showLabel); + }else{ + fieldIdSet = new HashSet<>(); + } + fieldIdSet.add(fieldId); + detailField.put(showLabel,fieldIdSet); + + if(detailField.containsKey(showLabel+"_"+fieldName)){ + fieldIdSet = detailField.get(showLabel+"_"+fieldName); + }else{ + fieldIdSet = new HashSet<>(); + } + fieldIdSet.add(fieldId); + detailField.put(showLabel+"_"+fieldName,fieldIdSet); + if(modeCondFieldIds.contains(fieldId)){ + condFieldIds.add(fieldId); + } + if(modeMustFieldIds.contains(fieldId)){ + mustFieldIds.add(fieldId); + } + hasfield=true; + } + if(hasfield){ + detailCondFieldIds.add(condFieldIds); + detailMustFieldIds.add(mustFieldIds); + detailFieldsInfo.add(detailField); + } + } + + for(int i=0;i excelFieldIds = new ArrayList<>(); + Map excelField = new HashMap<>();//excel中是否有重复列名,key:字段id,value:该字段在excel中的第几列 + Map excelLabel = new HashMap<>();//key:字段id,value:excel中的显示名 + Set condFieldIds = new HashSet<>(); + Set mustFieldIds = new HashSet<>(); + Sheet detailSheet = allSheets[i+1]; + int cols = POIUtil.getLastCellNum(detailSheet); + Map> detailField = new HashMap<>(); + ArrayList detailFieldIds = (ArrayList)detailtablefieldids.get(i); + if(i repeatFieldIds = getRepeatElement(detailFieldIds);//模板中相同显示名的列及数量 + for(int j=0;j1){ + setProgressCanImport(key,false); + String Errmsg = SystemEnv.getHtmlLabelName(504172, user.getLanguage()); + Errmsg = Errmsg.replace("{sheetIndex}",String.valueOf(i+2)) + .replace("{colCount}",String.valueOf(mainIdColCount)) + .replace("{colName}","MAINID"); + writeProgressMsg(key,Errmsg, "0"); + throw new Exception(Errmsg); + } + excelFieldIds.add("-2001"); + continue; + } + + if(!detailField.containsKey(content)){ + setProgressCanImport(key,false); + String Errmsg = SystemEnv.getHtmlLabelName(504173, user.getLanguage()); + Errmsg = Errmsg.replace("{sheetIndex}",String.valueOf(i+2)) + .replace("{colIndex}",String.valueOf(j+1)) + .replace("{content}",content); + writeProgressMsg(key,Errmsg, "0"); + throw new Exception(Errmsg); + } + + Set fieldIds = detailField.get(content); + if(fieldIds.size()>1){ + setProgressCanImport(key,false); + //504174 第{sheetIndex}个sheet中表头第{colIndex}列:{content},在标准模板中找到{fieldCount}个对应字段,请按照以下格式修改列名后重新导入:显示名_数据库名称。 + //506661 第{sheetIndex}个sheet中表头第{colIndex}列:{content},存在{fieldCount}个列名重复的对应字段,请按照以下格式修改列名后重新导入:显示名_数据库名称。 + String Errmsg = SystemEnv.getHtmlLabelName(506661, user.getLanguage()); + Errmsg = Errmsg.replace("{sheetIndex}",String.valueOf(i+2)) + .replace("{colIndex}",String.valueOf(j+1)) + .replace("{content}",content) + .replace("{fieldCount}",String.valueOf(fieldIds.size())); + writeProgressMsg(key,Errmsg, "0"); + throw new Exception(Errmsg); + } + + String fieldId = fieldIds.iterator().next(); + if(!excelLabel.containsKey(fieldId)){ + excelLabel.put(fieldId,content); + } + if(excelField.containsKey(fieldId)){ + int col = excelField.get(fieldId); + setProgressCanImport(key,false); + //第{sheetIndex}个sheet中表头第{colIndex1}列:{colName1},第{colIndex1}列:{colName2},列名重复,请按照以下格式修改列名后重新导入:显示名_数据库名称。 + String Errmsg = SystemEnv.getHtmlLabelName(504175, user.getLanguage()); + Errmsg = Errmsg.replace("{sheetIndex}",String.valueOf(i+2)) + .replace("{colIndex1}",String.valueOf(col)) + .replace("{colName1}",excelLabel.get(fieldId)) + .replace("{colIndex2}",String.valueOf(j+1)) + .replace("{colName2}",content); + writeProgressMsg(key,Errmsg, "0"); + throw new Exception(Errmsg); + }else{ + excelField.put(fieldId,j+1); + } + + + //第1个sheet中未找到导入必填条件列[状态],请添加导入必填条件列后重新导入。 + if(condFieldIds.contains(fieldId)){ + condFieldIds.remove(fieldId); + } + + //第1个sheet中未找到必填字段列[合同],请添加必填字段列后重新导入。 + if(mustFieldIds.contains(fieldId)){ + mustFieldIds.remove(fieldId); + } + excelFieldIds.add(fieldId); + } + + //第1个sheet中未找到导入必填条件列[状态],请添加导入必填条件列后重新导入。 + if(condFieldIds.size() > 0 ){ + StringBuffer tip = new StringBuffer(); + Iterator it = condFieldIds.iterator(); + while(it.hasNext()){ + tip.append(",").append(fieldsInfo.get(it.next())); + } + setProgressCanImport(key,false); + //第{sheetIndex}个sheet中未找到导入必填条件列[{mustConditionCol}],请添加导入必填条件列后重新导入。 + String Errmsg = SystemEnv.getHtmlLabelName(504176, user.getLanguage()); + Errmsg = Errmsg.replace("{sheetIndex}",String.valueOf(i+2)) + .replace("{mustConditionCol}",tip.substring(1)); + writeProgressMsg(key,Errmsg, "0"); + throw new Exception(Errmsg); + } + + if(mustFieldIds.size()>0){ + StringBuffer tip = new StringBuffer(); + Iterator it = mustFieldIds.iterator(); + while(it.hasNext()){ + tip.append(",").append(fieldsInfo.get(it.next())); + } + setProgressCanImport(key,false); + //第{sheetIndex}个sheet中未找到导入必填字段列[{mustFieldCol}],请添加导入必填字段列后重新导入。 + String Errmsg = SystemEnv.getHtmlLabelName(504177, user.getLanguage()); + Errmsg = Errmsg.replace("{sheetIndex}",String.valueOf(i+2)) + .replace("{mustFieldCol}",tip.substring(1)); + writeProgressMsg(key,Errmsg, "0"); + throw new Exception(Errmsg); + } + + if(mainIdColCount==0){ + setProgressCanImport(key,false); + //第{sheetIndex}个sheet中未找到[{colName}]列,请添加后重新导入。 + String Errmsg = SystemEnv.getHtmlLabelName(504178, user.getLanguage()); + Errmsg = Errmsg.replace("{sheetIndex}",String.valueOf((i+2))) + .replace("{colName}","MAINID"); + writeProgressMsg(key,Errmsg, "0"); + throw new Exception(Errmsg); + } + impFieldIds.add(excelFieldIds); + } + } + + /** + * 得到list中重复的元素 + * @param list + * @return + */ + public Map getRepeatElement(List list){ + Map repeatElements = new HashMap<>(); + for (int i=0;i 60) { + if (seconds > 3600) { + hour = seconds / 3600; + minute = seconds % 3600 / 60; + second = seconds % 3600 % 60 % 60; + } else { + second = seconds % 60; + minute = seconds / 60; + } + } else { + second = seconds; + } + result = parseStr(hour) + ":" + parseStr(minute) + ":" + + parseStr(second); + return result; + } + + private static String parseStr(int time) { + if (time >= 10) { + return time + ""; + } + return "0" + time; + } + + public static void putMessage(String smallkey,String pubkey,String msgStr) { + progressMap.put(smallkey+"_"+pubkey, msgStr); + + Map dataMap = new HashMap(); + dataMap.put(CANIMPORT, StringHelper.null2String(progressMap.get(CANIMPORT+"_"+pubkey))); + dataMap.put(CANIMPORTMSG, StringHelper.null2String(progressMap.get(CANIMPORTMSG+"_"+pubkey))); + dataMap.put(STATUS, StringHelper.null2String(progressMap.get(STATUS+"_"+pubkey))); + dataMap.put(STEP, StringHelper.null2String(progressMap.get(STEP+"_"+pubkey))); + dataMap.put(STARTTIME, StringHelper.null2String(progressMap.get(STARTTIME+"_"+pubkey))); + + dataMap.put(ERRMSG, StringHelper.null2String(progressMap.get(ERRMSG+"_"+pubkey))); + dataMap.put(TIME, StringHelper.null2String(progressMap.get(TIME+"_"+pubkey))); + dataMap.put(ENDTIME, StringHelper.null2String(progressMap.get(ENDTIME+"_"+pubkey))); + dataMap.put(IMPADDR, StringHelper.null2String(progressMap.get(IMPADDR+"_"+pubkey))); + dataMap.put(MSG, StringHelper.null2String(progressMap.get(MSG+"_"+pubkey))); + dataMap.put(SEARCHID, StringHelper.null2String(progressMap.get(SEARCHID+"_"+pubkey))); + dataMap.put(ERRORFLAG, StringHelper.null2String(progressMap.get(ERRORFLAG+"_"+pubkey))); + ExpExcelUtil.putObject(MODEIMP+"_"+pubkey, dataMap,true); + } + + + + + public static void setProgressCanImport(String key,boolean canImport) { + key = StringHelper.null2String(key); + putMessage(CANIMPORT,key, canImport?"1":"0"); + } + + public static void setProgressCanImport(String key,boolean canImport,String msg) { + key = StringHelper.null2String(key); + progressMap.put(CANIMPORT+"_"+key, canImport?"1":"0"); + putMessage(CANIMPORTMSG,key, msg); + } + + public static boolean getProgressCanImport(String key) { + key = StringHelper.null2String(key); + boolean f = true; + boolean isInMap = false; + if(progressMap.containsKey(CANIMPORT+"_"+key)){ + isInMap = true; + String str = Util.null2String(progressMap.get(CANIMPORT+"_"+key)); + if("0".equals(str)){ + f = false; + } + } + return f; + } + + public static void writeProgressMsg(String key,String msg,String status) { + progressMap.put(MSG+"_"+key, StringHelper.null2String(msg)); + putMessage(STATUS,key, StringHelper.null2String(status)); + } + + public static void writeProgressMsgAndStep(String key,String msg,String status,int step) { + progressMap.put(MSG+"_"+key, StringHelper.null2String(msg)); + progressMap.put(STATUS+"_"+key, StringHelper.null2String(status)); + putMessage(STEP,key, StringHelper.null2String(step)); + } + + public void writeErrorRow(){ + writeLog("--------------------- start -------------------------"); + for(int i=0;i 0) + { + Iterator itor = errorTable.iterator(); + int xx = 0; + RecordSet rs = new RecordSet(); + while (itor.hasNext()) { + String errormsg = ""; + String tablename = ""; + String fieldname = ""; + String detailmation = ""; + xx++; + String v2 = (String) itor.next(); + String[] strs = v2.split("[+]"); + if(strs.length==2){ //行出错 + String flagMsg = ""; + int index = strs[1].indexOf("~~weaverSplit~~"); + if(index!=-1){ + flagMsg = strs[1].substring(index+"~~weaverSplit~~".length()); + if(!"".equals(flagMsg)){ + flagMsg = ","+flagMsg; + } + strs[1] = strs[1].substring(0,index); + } + errormsg=fengeString + + SystemEnv.getHtmlLabelName(15323, user.getLanguage())//第 + + fengeString + + strs[0] + + fengeString + + SystemEnv.getHtmlLabelName(27591, user.getLanguage())//个 + + fengeString + + "sheet" + + fengeString + + SystemEnv.getHtmlLabelName(15323, user.getLanguage())//第 + + fengeString + + strs[1] + + fengeString + + SystemEnv.getHtmlLabelName(27592, user.getLanguage())//行 + + fengeString + +fengeString + + SystemEnv.getHtmlLabelName(27593, user.getLanguage())//导入出错 + +flagMsg; + }else if(strs.length>2){ //数据不合法 + errormsg=fengeString + + SystemEnv.getHtmlLabelName(15323, user.getLanguage())//第 + + fengeString + + strs[0] + + fengeString + + SystemEnv.getHtmlLabelName(27591, user.getLanguage())//个 + + fengeString + + "sheet" + + fengeString + + SystemEnv.getHtmlLabelName(15323, user.getLanguage())//第 + + fengeString + + strs[1] + + fengeString + + SystemEnv.getHtmlLabelName(27592, user.getLanguage())//行 + + fengeString + + fengeString + + (strs[2].equals("")?"": (SystemEnv.getHtmlLabelName(15323, user.getLanguage())//第 + + fengeString + + strs[2] + + fengeString + + SystemEnv.getHtmlLabelName(18621, user.getLanguage())//列 + + fengeString)) + +fengeString + + SystemEnv.getHtmlLabelName(27593, user.getLanguage())+",
"//导入出错 + +strs[3] + +fengeString; + } + if(strs.length >= 4 && strs.length < 10){ + if(!strs[3].equals(SystemEnv.getHtmlLabelName(132247, 7)) && strs[3].indexOf(SystemEnv.getHtmlLabelName(385578, 7)) == -1){// 导入验证错误 列为必填 + if(errormsg.indexOf(SystemEnv.getHtmlLabelName(132251, user.getLanguage()))>-1){ //132251 不存在无法更新 + errormsg += "!"; + }else{ + if(strs[3].equals("")){ + errormsg+=SystemEnv.getHtmlLabelName(514873, user.getLanguage())+"!"; //514873 导入数据存在空行 + }else{ + errormsg+=SystemEnv.getHtmlLabelName(132306, user.getLanguage())+"!"; //132306 不存在 + } + } + } + if(strs.length > 6){ + tablename = strs[7]; + fieldname = strs[4]+"("+strs[5]+","+strs[6]+")"; + detailmation = strs[8]; + }else { + tablename = strs[4]; + detailmation = strs[5]; + } + }else if(strs.length == 10){ + if(!strs[3].equals("导入验证错误") && strs[3].indexOf("列为必填") == -1){ + if(errormsg.indexOf(SystemEnv.getHtmlLabelName(132251, user.getLanguage()))>-1){ //132251 不存在无法更新 + errormsg += "!"; + }else{ + errormsg+=strs[4]+"!"; + } + } + tablename = strs[8]; + fieldname = strs[5]+"("+strs[6]+","+strs[7]+")"; + if (strs[5].equals(Util.getSeparator()+"")) {//重复验证字段为组合验证可能会出现多个字段的情况,需要在加入前拼接格式,这里直接取, + fieldname=strs[7]; + } + detailmation = strs[9]; + } + if(fieldname.equals("(,)")){ + fieldname = ""; + } + String insertsql = "insert into mode_impfailurelog(modeid,errormsg,tablename,tablefield,detailmation,searchid) values(?,?,?,?,?,?)"; +// ('"+modeid+"','"+errormsg+"','"+tablename+ +// "','"+fieldname+"','"+detailmation+"','"+searchid+"')"; + rs.executeUpdate(insertsql,modeid,errormsg,tablename,fieldname,detailmation,searchid); + } + } + } + + /** + * 批量导入必填列 + * @param modeId 模块id + * @param fieldName 重复验证字段字段名称 + * @param importtype 导入类型 + */ + public int getMandatoryFieldCount(int modeId,String fieldName,int importtype){ + Set set = new HashSet<>(); + //导入必填字段 + RecordSet rs = new RecordSet(); + String sql = "SELECT mefd.fieldid FROM mode_excelField mef,mode_excelfielddetail mefd WHERE mef.id=mefd.mainid and mef.modeid=?"; + rs.executeQuery(sql,modeId); + while(rs.next()){ + String fieldid = Util.null2String(rs.getString("fieldid")); + if(!"".equals(fieldid)){ + set.addAll(Arrays.asList(fieldid.split(","))); + } + } + + //重复验证字段 + if("".equals(fieldName)){ + sql = "SELECT wbf.id FROM workflow_billfield wbf,modeinfo mi WHERE mi.formid=wbf.billid and "+ CommonConstant.DB_ISNULL_FUN+"(viewtype,0)=0 and mi.id=? and wbf.fieldname=?"; + rs.executeQuery(sql,modeId,fieldName); + if(rs.next()){ + set.add(rs.getString("id")); + } + } + return set.size(); + } + + /** + * 如果是真实结束的行,与excel API 中统计总行树在同一行,那么不提示空行 + */ + public boolean isTipMessage(int realRow,Sheet sheet){ + + boolean isTip = false; + int rsCols =POIUtil.getLastCellNum(sheet); //列数 + int rsRows = POIUtil.getLastRowNum(sheet); //行数 + for (int i = realRow+1; i < rsRows && !isTip; i++) { //统计行中为空的单元格数 + for (int j = 0; j < rsCols; j++) { + String val = POIUtil.getValue(sheet, i, j); + if (!StringHelper.isEmpty(val)){ + isTip = true; + break; + } + } + } + + return isTip; + } + + /** + * 判断模块默认共享是否有模块明细表字段 + * @param modeid + * @return + */ + private boolean getIsDetailRight(int modeid){ + boolean result = false; + RecordSet rs = new RecordSet(); + String sql = "select count(*) count from workflow_billfield where id in(select relatedid from moderightinfo where modeid=? and sharetype=1000) and viewtype=1"; + rs.executeQuery(sql, modeid); + if (rs.next()) { + int count = Util.getIntValue(rs.getString("count")); + result=count>0; + } + return result; + } + + private void closeStream(InputStream stream){ + if (stream!=null) { + try { + stream.close(); + } catch (IOException e) { + writeLog(e); + }finally { + if (stream!=null) { + try { + stream.close(); + } catch (IOException e) { + writeLog(e); + } + } + } + } + } + + /** + * 备份表结构及数据 + * @param sourceTable 要备份的数据表 + * @param modeid 模块id + * @param isMain 是否是主表 + * @param backindex 备份索引 + * @param sqlwhere 要备份数据被的哪些数据 + * @return + */ + private boolean BackUpTable(String sourceTable,int modeid,boolean isMain,int backindex,String sqlwhere){ + RecordSet rs = new RecordSet(); + String sql=""; + String suffix=this.suffix+backindex; + String backTable=sourceTable+suffix; + if (rs.getDBType().indexOf("sqlserver")>=0) { + sql="select * into "+backTable+" from "+sourceTable+" "+sqlwhere; + }else if("mysql".equals(rs.getDBType())){ + sql="create table "+backTable+" like "+sourceTable; + rs.executeUpdate(sql); + sql="insert into "+backTable+" select * from "+sourceTable; + } + else if (rs.getDBType().indexOf("postgresql")>=0) { + sql="select * into "+backTable+" from "+sourceTable+" "+sqlwhere; + } + else { + sql="create table "+backTable+" as select * from "+sourceTable+" "+sqlwhere; + } + boolean result = rs.executeUpdate(sql); + if (!result) { + super.writeLog("备份表失败,sql:"+sql); + } + if (isMain) {//是主表 + //formmodeisrecover 标识该条数据是否还原过 0未还原 1已还原 + sql=" alter table "+backTable +" add formmodeisrecover int "; + rs.executeUpdate(sql); + //formmodelogid mode_impfailurelog日志表id,标识是哪次日志操作恢复的 + sql=" alter table "+backTable +" add formmodelogid int "; + rs.executeUpdate(sql); + sql="update "+backTable+" set formmodeisrecover=0"; + rs.executeUpdate(sql); + } + return result; + } + + /** + * 获取备份次数 + * @param modeid + * @return + */ + private synchronized int getAndUpdateBackIndex(int modeid){ + RecordSet rs = new RecordSet(); + int backindex=1; + String sql = "select currbackindex from mode_databatchimport where modeid=?"; + rs.executeQuery(sql, modeid); + if (rs.next()) { + backindex=Util.getIntValue(rs.getString("currbackindex"), 0)+1; + }else { + sql="insert into mode_databatchimport (modeid,currbackindex) values(?,?)"; + rs.executeUpdate(sql, modeid,0); + } + sql="update mode_databatchimport set currbackindex=? where modeid=?"; + rs.executeUpdate(sql, backindex,modeid); + return backindex; + } +} diff --git a/src/weaver/hrm/settings/BirthdayReminder.java b/src/weaver/hrm/settings/BirthdayReminder.java new file mode 100644 index 0000000..9ecdd83 --- /dev/null +++ b/src/weaver/hrm/settings/BirthdayReminder.java @@ -0,0 +1,652 @@ +/** + * BirthdayReminder Created on 2005-1-14 17:34:17 + * + * Copyright(c) 2001-2004 Weaver Software Corp.All rights reserved. + */ +package weaver.hrm.settings; + +import java.io.IOException; +import java.util.*; + +import com.cloudstore.dev.api.bean.MessageBean; +import com.cloudstore.dev.api.bean.MessageType; +import com.cloudstore.dev.api.util.Util_Message; +import com.engine.hrm.util.HrmTransMethod; + +import com.engine.msgcenter.biz.ConfigManager; +import com.engine.msgcenter.biz.WeaMessageTypeConfig; +import com.google.common.collect.Sets; +import weaver.conn.RecordSet; +import weaver.general.TimeUtil; +import weaver.general.Util; +import weaver.hrm.User; +import weaver.hrm.appdetach.AppDetachComInfo; +import weaver.hrm.company.DepartmentComInfo; +import weaver.hrm.company.SubCompanyComInfo; +import weaver.hrm.moduledetach.ManageDetachComInfo; +import weaver.hrm.resource.ResourceComInfo; +import weaver.workflow.msg.PoppupRemindInfoUtil; +/** + * Description: BirthdayReminder + * Company: 泛微软件 + * + * @author xiaofeng.zhang + * @version 1.0 2005-1-14 + */ +/** + * 生日提醒 + */ +public class BirthdayReminder extends ChgPasswdReminder { + private HashMap htRecieverResource = new HashMap(); + public void remindAdministrator(int period)throws Exception + { + if (isSended(1))return; + //提醒来源范围 + RecordSet rs = new RecordSet(); + String sql = " SELECT * FROM HrmBirthdayShare "; + rs.executeSql(sql); + while(rs.next()) + { + String sharetype = rs.getString("sharetype"); + String relatedshare = "";//对象 + String sharelevel = ""; //提醒级别 + String seclevel = ""; //安全等级 + String seclevelto = ""; //安全等级 + String level = "0"; //角色或者岗位的级别 + String org = "0"; //岗位指定的分部或者部门 + String lowerLevel ="0" ; //包含下级 + if(sharetype.equals("1")){ + //人力资源 + relatedshare = rs.getString("userid"); + }else if(sharetype.equals("2")){ + //分部 + relatedshare = rs.getString("subcompanyid"); + lowerLevel = rs.getString("lowerLevel"); + }else if(sharetype.equals("3")){ + //部门 + relatedshare = rs.getString("departmentid"); + lowerLevel = rs.getString("lowerLevel"); + }else if(sharetype.equals("4")){ + //角色 + relatedshare = rs.getString("roleid"); + level = rs.getString("rolelevel"); + }else if(sharetype.equals("7")){ + //岗位 + relatedshare = rs.getString("jobtitleid"); + level = rs.getString("jobtitlelevel"); + if(level.equals("1")) org = rs.getString("jobsubcompany"); + if(level.equals("2")) org = rs.getString("jobdepartment"); + }else if(sharetype.equals("5")){ + //所有人 + relatedshare = rs.getString("foralluser"); + } + if(sharetype.equals("1")){ + }else{ + seclevelto = HrmTransMethod.getStringValue( rs.getString("seclevelto"),"100"); + seclevel = HrmTransMethod.getStringValue( rs.getString("seclevel"),"0"); + } + sharelevel = rs.getString("sharelevel"); + remindAdministrator(period, sharetype, relatedshare, sharelevel, seclevel, seclevelto,lowerLevel, level,org); + } + //send message + sendMessage(period); + } + /*** + * 提醒人力资源管理员 + * @param period + * @param sharetype 提醒类别 + * @param relatedshare 对象 + * @param sharelevel 提醒来源范围 + * @param seclevel 对象安全级别 + * @throws Exception + */ + public void remindAdministrator(int period, String sharetype, String relatedshare, String sharelevel, String seclevel, String seclevelto, String lowerLevel, String level, String org) throws Exception { + //是否需要提醒 + ChgPasswdReminder reminder=new ChgPasswdReminder(); + RemindSettings settings=reminder.getRemindSettings(); + if(!settings.getBirthvalidadmin().equals("1"))return; + String today = TimeUtil.getCurrentDateString(); + //ResourceComInfo rsComInfo = new ResourceComInfo(); + RecordSet recordset = new RecordSet(); + boolean isoracle = (recordset.getDBType()).equals("oracle"); + //查找生日要到了的员工 + String sql = " select * from HrmResource " + + " where (accounttype is null or accounttype=0) " + + " and (status = 0 or status = 1 or status = 2 or status = 3) " ; + //增加提醒对象 + if (sharetype.equals("1")) { + // 人力资源 + sql += " and id = " + relatedshare; + } else if (sharetype.equals("2")) { + // 分部 + sql += " and seclevel>=" + seclevel +" and seclevel<=" + seclevelto; + if(lowerLevel.equals("1"))//包含下级 + { + sql+= " and subcompanyid1 in ("+SubCompanyComInfo.getAllChildSubcompanyId(relatedshare,relatedshare)+")" ; + }else{ + sql+= " and subcompanyid1 = " + relatedshare ; + } + } else if (sharetype.equals("3")) { + // 部门 + sql += " and seclevel>=" + seclevel +" and seclevel<=" + seclevelto; + if(lowerLevel.equals("1"))//包含下级 + { + sql+= " and departmentid in ("+DepartmentComInfo.getAllChildDepartId(relatedshare, relatedshare)+")" ; + }else{ + sql+= " and departmentid = " + relatedshare ; + } + } else if (sharetype.equals("4")) { + // 角色 + //sql+= " and id in ( select resourceid from HrmRoleMembers where roleid=" + relatedshare + " and rolelevel>="+level+")"+" and seclevel>=" + seclevel +" and seclevel<=" + seclevelto; + String roleSql = " SELECT distinct resourceid FROM ( "+ + " SELECT a.id AS resourceid, b.roleid , b.rolelevel FROM HrmResource a, HrmRoleMembers b "+ + " WHERE (a.id=b.resourceid and b.resourcetype=1) "+ + " UNION ALL "+ + " SELECT a.id AS resourceid, b.roleid , b.rolelevel FROM HrmResourceManager a, HrmRoleMembers b "+ + " WHERE (a.id=b.resourceid and b.resourcetype IN(7,8)) "+ + " UNION ALL "+ + " SELECT a.id AS resourceid, b.roleid , b.rolelevel FROM HrmResource a, HrmRoleMembers b "+ + " WHERE (a.subcompanyid1 = b.resourceid AND a.seclevel>=b.seclevelfrom AND a.seclevel<=b.seclevelto AND b.resourcetype=2) "+ + " UNION ALL "+ + " SELECT a.id AS resourceid, b.roleid , b.rolelevel FROM HrmResource a, HrmRoleMembers b "+ + " WHERE (a.departmentid = b.resourceid AND a.seclevel>=b.seclevelfrom AND a.seclevel<=b.seclevelto AND b.resourcetype=3) "+ + " UNION ALL "+ + " SELECT a.id AS resourceid, b.roleid , b.rolelevel FROM HrmResource a, HrmRoleMembers b "+ + " WHERE (a.jobtitle = b.resourceid AND b.resourcetype=5 AND (b.jobtitlelevel=1 OR (b.jobtitlelevel=2 AND a.subcompanyid1 IN(b.subdepid)) OR (b.jobtitlelevel=3 AND a.departmentid IN(b.subdepid))))) t "+ + " WHERE roleid=" + relatedshare + " and rolelevel>="+level+" "; + sql+= " and id in ("+roleSql+")"+" and seclevel>=" + seclevel +" and seclevel<=" + seclevelto; + } else if (sharetype.equals("7")) { + // 岗位 + sql+= " and jobtitle = "+relatedshare+" "+" and seclevel>=" + seclevel +" and seclevel<=" + seclevelto; + if(level.equals("1")){ + sql+= " and subcompanyid1= " + org ; + }else if(level.equals("2")){ + sql+= " and departmentid = " + org ; + } + } else if (sharetype.equals("5")) { + // 所有人 + sql += " and seclevel>=" + seclevel +"and seclevel<=" + seclevelto; + } + recordset.executeSql(sql); + String year1 = today.substring(0, 4); + String year2 = TimeUtil.dateAdd(today, period).substring(0, 4); + RecordSet recordset1 = new RecordSet(); + ArrayList remindedResourceList = getRemindedResourceid(period); + while (recordset.next()) { + String hrm = recordset.getString("id"); + String subId = recordset.getString("subcompanyid1"); + String depId = recordset.getString("departmentid"); + // 基准是对象,先获取所有的对象,然后根据对象的 + // 查找生日要到了的员工 + sql = " select * from HrmResource " + + " where (accounttype is null or accounttype=0) " + + " and (status = 0 or status = 1 or status = 2 or status = 3) " + + " and birthday is not null"; + if(!isoracle) sql+=" and birthday<>''"; + // 增加提醒来源范围 + if (sharelevel.equals("0")) { + // 本部门 指的是和当前对象相同部门的对象 + sql += " and HrmResource.departmentid = " + depId; + } else if (sharelevel.equals("1")) { + // 本部门及上级部门 + sql += " and exists ( select * from hrmdepartment where HrmResource.departmentid= hrmdepartment.id " + + " and hrmdepartment.id in (" + + DepartmentComInfo.getAllParentDepartId(depId, depId) + + "))"; + } else if (sharelevel.equals("2")) { + // 本部门及下级部门 + sql += " and exists ( select * from hrmdepartment where HrmResource.departmentid= hrmdepartment.id " + + " and hrmdepartment.id in (" + + DepartmentComInfo.getAllChildDepartId(depId, depId) + + "))"; + } else if (sharelevel.equals("3")) { + // 本分部 + sql += " and HrmResource.subcompanyid1 = " + subId; + } else if (sharelevel.equals("4")) { + // 本分部及上级分部 + sql += " and exists ( select * from HrmSubCompany where HrmResource.subcompanyid1= HrmSubCompany.id " + + " and HrmSubCompany.id in (" + + SubCompanyComInfo.getAllParentSubcompanyId(subId, + subId) + "))"; + } else if (sharelevel.equals("5")) { + // 本分部及下级分部 + sql += " and exists ( select * from HrmSubCompany where HrmResource.subcompanyid1= HrmSubCompany.id " + + " and HrmSubCompany.id in (" + + SubCompanyComInfo.getAllChildSubcompanyId(subId,subId) + "))"; + } + recordset1.executeSql(sql); + String resourceids = ""; + while (recordset1.next()) { + String id = recordset1.getString("id"); + if (remindedResourceList.indexOf(id) > -1) + continue; + String birthday = recordset1.getString("birthday"); + if(birthday == null||birthday.length()<10||birthday.indexOf("-")<=0){ + continue; + } + if (year1.equals(year2)) { + birthday = year1 + birthday.substring(4); + if (TimeUtil.dateInterval(birthday, TimeUtil.dateAdd(today, period)) >= 0 && TimeUtil.dateInterval(birthday, TimeUtil.dateAdd(today, period)) <= period) { + if(resourceids.length()>0)resourceids+=","; + resourceids+=id; + } + } else { + birthday = year1 + birthday.substring(4); + if (TimeUtil.dateInterval(birthday, TimeUtil.dateAdd(today, period)) >= 0 && TimeUtil.dateInterval(birthday, TimeUtil.dateAdd(today, period)) <= period) { + if(resourceids.length()>0)resourceids+=","; + resourceids+=id; + } + birthday = year2 + birthday.substring(4); + if (TimeUtil.dateInterval(birthday, TimeUtil.dateAdd(today, period)) >= 0 && TimeUtil.dateInterval(birthday, TimeUtil.dateAdd(today, period)) <= period) { + if(resourceids.length()>0)resourceids+=","; + resourceids+=id; + } + } + } + if(htRecieverResource.get(hrm)==null){ +// System.err.println("_1 _hrm---"+hrm+"______resourceids---"+resourceids+"_________"); + htRecieverResource.put(hrm, resourceids); + }else{ + String tmpresourceids = htRecieverResource.get(hrm); + if(tmpresourceids.length()>0)tmpresourceids+=","; + tmpresourceids+=resourceids; +// System.err.println("_2 _hrm---"+hrm+"______resourceids---"+resourceids+"_________"); + htRecieverResource.put(hrm, resourceids); + } + } + } + public void sendMessage(int period)throws Exception{ + ResourceComInfo rsComInfo = new ResourceComInfo(); + for (String receiver : htRecieverResource.keySet()) { + String resourceids=(String)htRecieverResource.get(receiver); + StringBuffer title = new StringBuffer(); + StringBuffer remark = new StringBuffer(); + if(resourceids.length()>0){ + List ls = Util.TokenizerString(resourceids, ","); + Map idMap = new LinkedHashMap(); + for(Object resourceid : ls){ + String id = (String)resourceid; + String birStatus = rsComInfo.getStatus(id); + if(!"0".equals(birStatus) && !"1".equals(birStatus) && !"2".equals(birStatus) && !"3".equals(birStatus)) { + continue; + } + if(!idMap.containsKey(id)) { + idMap.put(id, id); + String name = rsComInfo.getResourcename(id); + ArrayList remindedResourceList = getRemindedResourceid(period); + //记录历史信息 + if(!(remindedResourceList.indexOf(id)>-1))recordAdminRemindHistory(id); + title.append(name); + title.append(" "); + remark.append("" + name + " "); + } + } + String str_title = title.toString() + ""+weaver.systeminfo.SystemEnv.getHtmlLabelName(10003683,weaver.general.ThreadVarLanguage.getLang())+""; + sendMsg(str_title, 1, receiver, remark.toString()); + } + } + } + + + + + public Map removeRepeat(Map map ,String key_orgId ,String birth_userid ) { + boolean isHas = map.containsKey(key_orgId); + if(key_orgId.length()==0) return map; + if(isHas){ + birth_userid = map.get(key_orgId)+","+birth_userid; + map.put(key_orgId, birth_userid); + }else{ + map.put(key_orgId, birth_userid); + } + return map; + } + + /** + * 【员工提醒】消息中心 + * @param congratulation 祝词 + * @param token 替换祝词中的符号 + * @throws Exception + */ + @SuppressWarnings("deprecation") + public void remindEmployer(String congratulation, String token) throws Exception { + //判断今天是否已经推送过 + if (isSended(2)) { + return; + } + + String today = TimeUtil.getCurrentDateString(); + String year = today.substring(0, 4); + ResourceComInfo rsComInfo = new ResourceComInfo(); + DepartmentComInfo departmentComInfo = new DepartmentComInfo(); + SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo(); + + RecordSet recordset = new RecordSet(); + boolean isoracle = (recordset.getDBType()).equals("oracle"); + Map dataMap = new HashMap(); + + //判断提醒范围 + ChgPasswdReminder reminder = new ChgPasswdReminder(); + RemindSettings settings = reminder.getRemindSettings(); + String brithalarmscope = settings.getBrithalarmscope();//提醒范围 + String birthshowfieldWF = settings.getBirthshowfieldWF();//消息中心方式的显示字段 + String congratulation1 = settings.getCongratulation1();//消息中心方式的生日祝词 + //1-本人、2-同部门、4-同分部、5-同部门以及上级部门、6-同部门以及下级部门、7-同分部以及上级分部、8-同分部以及下级分部、3-所有人 + int scope = Integer.parseInt(brithalarmscope); + String birth_userid = ""; + //根据范围查找要过生日的人 + if (brithalarmscope.equals("1")) { + //本人 + String sql = "select id,birthday from HrmResource where (accounttype is null or accounttype=0) and (status = 0 or status = 1 or status = 2 or status = 3) and birthday is not null"; + if (!isoracle) sql += " and birthday<>''"; + recordset.executeSql(sql); + while (recordset.next()) { + String id = recordset.getString("id"); + String birthday = recordset.getString("birthday"); + if (birthday == null || birthday.length() < 10 || birthday.indexOf("-") <= 0) { + continue; + } + birthday = year + birthday.substring(4); + if (TimeUtil.dateInterval(birthday, today) == 0) { + dataMap.put(id, id); + } + } + } else if (scope == 2 || scope == 5 || scope == 6) { //本部门 以上及以下部门 + String sql = "select distinct departmentid, birthday,id from HrmResource where (accounttype is null or accounttype=0) and (status = 0 or status = 1 or status = 2 or status = 3) and birthday is not null"; + if (!isoracle) sql += " and birthday<>''"; + recordset.executeSql(sql); + String departmentid = ""; + while (recordset.next()) { + birth_userid = recordset.getString("id"); + departmentid = Util.null2String(recordset.getString("departmentid")); + if (departmentid.length() == 0) continue; + String birthday = recordset.getString("birthday"); + if (birthday == null || birthday.length() < 10 || birthday.indexOf("-") <= 0) { + continue; + } + birthday = year + birthday.substring(4); + if (TimeUtil.dateInterval(birthday, today) == 0) { + if (scope == 2) dataMap = removeRepeat(dataMap, departmentid, birth_userid); + if (scope == 5) { + String[] deptStrings = DepartmentComInfo.getAllParentDepartId(departmentid, departmentid).split(","); + for (String str : deptStrings) { + dataMap = removeRepeat(dataMap, str, birth_userid); + } + } + if (scope == 6) { + String[] deptStrings = DepartmentComInfo.getAllChildDepartId(departmentid, departmentid).split(","); + for (String str : deptStrings) { + dataMap = removeRepeat(dataMap, str, birth_userid); + } + } + } + } + } else if (scope == 4 || scope == 7 || scope == 8) {//本分部 以上及以下分部 + + String sql = "select distinct subcompanyid1, birthday ,id from HrmResource where (accounttype is null or accounttype=0) and (status = 0 or status = 1 or status = 2 or status = 3) and birthday is not null"; + if (!isoracle) sql += " and birthday<>''"; + recordset.executeSql(sql); + String subcompanyid1 = ""; + while (recordset.next()) { + birth_userid = recordset.getString("id"); + subcompanyid1 = Util.null2String(recordset.getString("subcompanyid1")); + if (subcompanyid1.length() == 0) continue; + String birthday = recordset.getString("birthday"); + if (birthday == null || birthday.length() < 10 || birthday.indexOf("-") <= 0) { + continue; + } + + birthday = year + birthday.substring(4); + if (TimeUtil.dateInterval(birthday, today) == 0) { + if (scope == 4) dataMap = removeRepeat(dataMap, subcompanyid1, birth_userid); + if (scope == 7) { + String[] subcStrings = SubCompanyComInfo.getAllParentSubcompanyId(subcompanyid1, subcompanyid1).split(","); + for (String str : subcStrings) { + dataMap = removeRepeat(dataMap, str, birth_userid); + } + } + if (scope == 8) { + String[] subcStrings = SubCompanyComInfo.getAllChildSubcompanyId(subcompanyid1, subcompanyid1).split(","); + for (String str : subcStrings) { + dataMap = removeRepeat(dataMap, str, birth_userid); + } + } + } + } + } else if (brithalarmscope.equals("3")) { + String sql = "select id,birthday from HrmResource where (accounttype is null or accounttype=0) and (status = 0 or status = 1 or status = 2 or status = 3) and birthday is not null"; + if (!isoracle) sql += " and birthday<>''"; + recordset.executeSql(sql); + StringBuffer birth_Userid = new StringBuffer(); //所有生日人员的userID + while (recordset.next()) { + String birthday = recordset.getString("birthday"); + if (birthday == null || birthday.length() < 10 || birthday.indexOf("-") <= 0) { + continue; + } + birthday = year + birthday.substring(4); + if (TimeUtil.dateInterval(birthday, today) == 0) { + if (birth_Userid.length() != 0) birth_Userid.append("," + recordset.getString("id")); + else birth_Userid.append(recordset.getString("id")); + } + } + if (!birth_Userid.toString().equals("")) { + dataMap.put(birth_Userid.toString(), birth_Userid.toString()); + } + } + Set keys = dataMap.keySet(); + if (keys != null) { + Iterator iterator = keys.iterator(); + StringBuffer title = new StringBuffer(); + StringBuffer remark = new StringBuffer(); + String key = ""; + String value = ""; + while (iterator.hasNext()) { + title = new StringBuffer(); + remark = new StringBuffer(); + key = (String) iterator.next(); + value = dataMap.get(key); + if (value == null || value.equals("")) { + continue; + } + String[] valueArr = value.split(","); + for (int i = 0; i < valueArr.length; i++) { + String userid = valueArr[i]; + String name = rsComInfo.getResourcename(userid); + title.append(name); + if (birthshowfieldWF.indexOf("2") > -1) { + String departmentName = departmentComInfo.getDepartmentName(rsComInfo.getDepartmentID(userid)); + title.append("-").append(departmentName); + } + if (birthshowfieldWF.indexOf("3") > -1) { + String subcompanyName = subCompanyComInfo.getSubcompanyname(rsComInfo.getSubCompanyID(userid)); + title.append("-").append(subcompanyName); + } + if (i != valueArr.length - 1) { + title.append(","); + } + } + remark.append(value); + if (!title.toString().trim().equals("")) { + Set resourceIdList = new HashSet(); + //查找所有员工 + String sql = "select id from HrmResource where (accounttype is null or accounttype=0) and (status = 0 or status = 1 or status = 2 or status = 3)"; + if (brithalarmscope.equals("1")) {//本人 + sql += " and id=" + key; + } else if (brithalarmscope.equals("2") || brithalarmscope.equals("5") || brithalarmscope.equals("6")) { //本部门 以下及以下部门 + sql += " and departmentid = " + key + " "; + } else if (brithalarmscope.equals("4") || brithalarmscope.equals("7") || brithalarmscope.equals("8")) { //本分部 以下及以下分部 + sql += " and subcompanyid1 = " + key + " "; + } else if (brithalarmscope.equals("3")) { + //所有人 + } + recordset.executeSql(sql); + while (recordset.next()) { + resourceIdList.add(recordset.getString("id")); + } + + String str_title = title + ""+weaver.systeminfo.SystemEnv.getHtmlLabelName(10003684,weaver.general.ThreadVarLanguage.getLang())+"" + congratulation; + sql = "insert into HrmBirthRemindMsg(title,resources,reminddate) values('" + str_title + "','" + remark.toString() + "','" + today + "')"; + recordset.executeUpdate(sql); + + //记录发送历史 + recordEmployerRemindHistory(); + + //消息提醒 + String content = congratulation1.replace("$", " " + title.toString() + " "); + String linkUrl = ""; //PC端链接 + String linkMobileUrl = ""; //移动端链接 + try { + MessageBean messageBean = Util_Message.createMessage(MessageType.HR_BIRTHDAY_REMIND, resourceIdList, content, content, linkUrl, linkMobileUrl); + messageBean.setCreater(1);//创建人id + Util_Message.store(messageBean); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + } + + + + public ArrayList getBirthEmployerNames(User user) { + + ArrayList birthEmployers = new ArrayList(); + String[] birthEmployer = null; //部门 机构 姓名 + + //判断提醒范围 + ChgPasswdReminder reminder = new ChgPasswdReminder(); + RemindSettings settings = reminder.getRemindSettings(); + String brithalarmscope = settings.getBrithalarmscope();//提醒范围 + + try { + + AppDetachComInfo adci = new AppDetachComInfo(); + + String today = TimeUtil.getCurrentDateString(); + ResourceComInfo rsComInfo = new ResourceComInfo(); + SubCompanyComInfo subComInfo = new SubCompanyComInfo(); + DepartmentComInfo departComInfo = new DepartmentComInfo(); + String year = today.substring(0, 4); + String monthDays = today.substring(4,10); + RecordSet recordset = new RecordSet(); + //查找生日要到了的员工 + //modify by Ds 生日提醒不显示次账号数据 + + String sql = "select id,subcompanyid1,departmentid,birthday from HrmResource where (accounttype is null or accounttype=0) and (status = 0 or status = 1 or status = 2 or status = 3) and birthday like '%" + monthDays + "'"; + recordset.executeQuery(sql); + + while (recordset.next()) { + String id = recordset.getString("id"); + String departmentid = recordset.getString("departmentid"); + String subcompanyid1 = recordset.getString("subcompanyid1"); + if (brithalarmscope.equals("1")) { + //本人 + if(!id.equals(user.getUID())){ + continue; + } + } else if (brithalarmscope.equals("2") || brithalarmscope.equals("5") || brithalarmscope.equals("6")) { + //本部门 及以上和 以及部门 + String depId = user.getUserDepartment() + ""; + depId = brithalarmscope.equals("2") ? depId : (brithalarmscope.equals("6") ? DepartmentComInfo.getAllParentDepartId(depId, depId) : DepartmentComInfo.getAllChildDepartId(depId, depId)); + if((","+depId+",").indexOf(","+departmentid+",")==-1){ + continue; + } + } else if (brithalarmscope.equals("4") || brithalarmscope.equals("7") || brithalarmscope.equals("8")) { + //本部 及以上和 以及下分部 + String subId = user.getUserSubCompany1() + ""; + subId = brithalarmscope.equals("4") ? subId : (brithalarmscope.equals("8") ? SubCompanyComInfo.getAllParentSubcompanyId(subId, subId) : SubCompanyComInfo.getAllChildSubcompanyId(subId, subId)); + if((","+subId+",").indexOf(","+subcompanyid1+",")==-1){ + continue; + } + } else if (brithalarmscope.equals("3")) { + //所有人 无需处理 + } + if(adci.isUseAppDetach()){ + boolean hasPower = adci.isAllDetachResourceInfo( user,id,departmentid,subcompanyid1); + if (!hasPower) { + continue; + } + } + +// String birthday = recordset.getString("birthday"); + + //检查birthday格式是否非法Begin +// if(birthday == null||birthday.length()<10||birthday.indexOf("-")<=0){ +// continue; +// } + +// String birthdayN = year+birthday.substring(4,10); + +// if (birthdayN.equals(today)) {//modifer by lvyi 2014-10-24 + birthEmployer = new String[4]; + String name = rsComInfo.getResourcename(id); + String com_name = subComInfo.getSubCompanyname(subcompanyid1); + String department_name = departComInfo.getDepartmentname(departmentid); + birthEmployer[0] = name; + birthEmployer[1] = com_name; + birthEmployer[2] = department_name; + birthEmployer[3] = id; + + birthEmployers.add(birthEmployer); +// } + } + } catch (Exception ex) { + new weaver.general.BaseBean().writeLog("员工生日格式错误! ex=" + ex); + } + + return birthEmployers; + } + + private boolean isSended(int type) { + String today = TimeUtil.getCurrentDateString(); + String sql = "select * from HrmRemindHistory where type=" + type + " and reminddate='" + today + "'"; + RecordSet recordset = new RecordSet(); + recordset.executeSql(sql); + + if (recordset.next()) + return true; + else + return false; + + } + + private ArrayList getRemindedResourceid(int period) { + ArrayList remindedResourceList = new ArrayList(); + String today = TimeUtil.getCurrentDateString(); + String sql = "select remindedresourceid from HrmRemindHistory where reminddate>='" + TimeUtil.dateAdd(today, -period) + "'"; + RecordSet recordset = new RecordSet(); + recordset.executeSql(sql); + while (recordset.next()) { + String remindedresourceid = recordset.getString("remindedresourceid"); + remindedResourceList.add(remindedresourceid); + + } + return remindedResourceList; + } + + private void recordAdminRemindHistory(String resourceid) { + String today = TimeUtil.getCurrentDateString(); + String sql = "insert into HrmRemindHistory (type,reminddate,remindedresourceid) values(" + 1 + ",'" + today + "'," + resourceid + ")"; + RecordSet recordset = new RecordSet(); + recordset.executeSql(sql); + } + + private void recordEmployerRemindHistory() { + String today = TimeUtil.getCurrentDateString(); + String sql = "insert into HrmRemindHistory (type,reminddate,remindedresourceid) values(" + 2 + ",'" + today + "',null)"; + RecordSet recordset = new RecordSet(); + recordset.executeSql(sql); + } + + /** + * @param period + * @throws Exception + * @deprecated + */ + public void remind(int period) throws Exception { + //do nothing + return; + } + +} \ No newline at end of file diff --git a/src/weaver/interfaces/hansang/action/BussinessTripAutoSignAction.java b/src/weaver/interfaces/hansang/action/BussinessTripAutoSignAction.java new file mode 100644 index 0000000..98fea79 --- /dev/null +++ b/src/weaver/interfaces/hansang/action/BussinessTripAutoSignAction.java @@ -0,0 +1,84 @@ +package weaver.interfaces.hansang.action; + +import com.engine.kq.biz.KQHolidaySetBiz; +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.Util; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; + +/** + * @author wanxq + * @date 2023年08月30日13:26:43 + * @desc 加班自动打卡 + */ +public class BussinessTripAutoSignAction extends BaseBean implements Action { + + + @Override + public String execute(RequestInfo requestInfo) { + String requestid = requestInfo.getRequestid(); + String tableName = requestInfo.getRequestManager().getBillTableName(); + + try { + RecordSet rs = new RecordSet(); + String sql = " select resourceId,fromDate,fromTime,toDate,toTime from "+tableName+" where requestid=? "; + rs.executeQuery(sql,requestid); + if(rs.next()){ + String resourceId = Util.null2String(rs.getString("resourceId")); + String fromDate = Util.null2String(rs.getString("fromDate")); + String fromTime = Util.null2String(rs.getString("fromTime")); + String toDate = Util.null2String(rs.getString("toDate")); + String toTime = Util.null2String(rs.getString("toTime")); + + int daysDiff = DateUtil.dayDiff(fromDate,toDate)+1; + for(int i=0;i0 "; + rs.executeQuery(sql); + while(rs.next()){ + String userid = Util.null2String(rs.getString("id")); + double workyear = Util.getDoubleValue(rs.getString("workyear"),0); + String companystartdate = Util.null2String(rs.getString("companystartdate")); + String field82 = Util.null2String(rs.getString("field82")); + + double baseAmount = 0; + if(workyear>=1 && workyear<10){ + baseAmount = 40.0; + } + + if(workyear>=10 && workyear<20){ + baseAmount = 80.0; + } + + if(workyear>=20){ + baseAmount = 120.0; + } + + int diffDays = DateUtil.dayDiff(field82,currentYear+"-01-01"); + if(companystartdate.length()>4 && currentYear.equals(companystartdate.substring(0,4))){ + diffDays = DateUtil.dayDiff(field82,companystartdate); + } + + + double realBaseAmount = diffDays*baseAmount/365; + int integerPart = (int)realBaseAmount; + double decimalPart = realBaseAmount-integerPart; + + if(decimalPart<0.5){ + realBaseAmount = (double) integerPart; + }else{ + realBaseAmount = integerPart+0.5; + } + String updateSql = " update kq_balanceOfLeave set baseamount=? where resourceId=? and leaveRulesId=-6 and belongYear=? "; + rs2.executeUpdate(updateSql,realBaseAmount,userid,currentYear); + + } + + } + + + +} diff --git a/src/weaver/interfaces/hansang/job/AttendanceDaysCalculateJob.java b/src/weaver/interfaces/hansang/job/AttendanceDaysCalculateJob.java new file mode 100644 index 0000000..5d9e700 --- /dev/null +++ b/src/weaver/interfaces/hansang/job/AttendanceDaysCalculateJob.java @@ -0,0 +1,96 @@ +package weaver.interfaces.hansang.job; + + +import com.engine.kq.biz.KQHolidaySetBiz; +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.TimeUtil; +import weaver.interfaces.schedule.BaseCronJob; + +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; +import java.util.UUID; + +/** + * @author wanxq + * @date 2023年09月18日10:17:00 + * @desc + */ +public class AttendanceDaysCalculateJob extends BaseCronJob { + + private BaseBean log = new BaseBean(); + + @Override + public void execute() { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + LocalDate yearStartDate = LocalDate.parse(DateUtil.getYear()+"-01-01", formatter); + for(int i=0;i<12;i++){ + LocalDate startDate = yearStartDate.plusMonths(i); + LocalDate endDate = startDate.withDayOfMonth(startDate.lengthOfMonth()); + log.writeLog("AttendanceDaysCalculateJob startDate==>"+startDate+" endDate==>"+endDate); + + int workdays = 0; + long daysDiff = ChronoUnit.DAYS.between(startDate, endDate)+1; + for(int j=0;j"+tempdate+" changeType==>"+changeType+" weekend==>"+DateUtil.getWeek(tempdate)); + if (changeType != 2 && changeType != 1 && (DateUtil.getWeek(tempdate) == 6 || DateUtil.getWeek(tempdate) == 7)) { + isHoliday = true; + } + if (changeType == 3) { + isHoliday = true; + } + + if(!isHoliday){ + workdays++; + log.writeLog("AttendanceDaysCalculateJob workday==>"+tempdate); + } + } + + insertData(workdays,startDate.toString()); + } + } + + public void insertData(int workdays,String month){ + RecordSet rs = new RecordSet(); + //删除建模表中当前算薪月的数据 + rs.executeUpdate("delete from uf_ykcqr where xzszy=? ",month); + + int formmodeid = getModeIdByName("应扣出勤日"); + String modeuuid = UUID.randomUUID().toString(); + int modedatacreater = 1; + String modedatacreatedate = TimeUtil.getCurrentDateString(); + String modedatacreatetime = TimeUtil.getOnlyCurrentTimeString(); + String insertSql = " insert into uf_ykcqr(xzszy,yzkts,formmodeid,modedatacreater,modedatacreatedate," + + "modedatacreatetime,modeuuid) values(?,?,?,?,?,?,?) "; + rs.executeUpdate(insertSql,month,workdays, + formmodeid,modedatacreater,modedatacreatedate,modedatacreatetime,modeuuid); + } + + + + + /** + * 根据建模名称获取建模id,建模权限同步的使用 + * @param modeName 建模名称 + * @return int 建模id + */ + public static int getModeIdByName(String modeName){ + RecordSet rs = new RecordSet(); + String sql = " SELECT ID FROM MODEINFO WHERE MODENAME = ? "; + rs.executeQuery(sql, modeName); + if (rs.next()) { + return rs.getInt("id"); + } + return -1; + } + + + +} diff --git a/src/weaver/interfaces/hansang/job/DepartRefreshKqReportJob.java b/src/weaver/interfaces/hansang/job/DepartRefreshKqReportJob.java new file mode 100644 index 0000000..d3a8e70 --- /dev/null +++ b/src/weaver/interfaces/hansang/job/DepartRefreshKqReportJob.java @@ -0,0 +1,53 @@ +package weaver.interfaces.hansang.job; + + +import com.engine.kq.biz.KQFormatData; +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.interfaces.schedule.BaseCronJob; + +/** + * @author wanxq + * @date 2023年10月20日13:38:45 + * @desc 离职更新考勤报表 + */ +public class DepartRefreshKqReportJob extends BaseCronJob { + + @Override + public void execute() { + + String currentDate = DateUtil.getCurrentDate(); + RecordSet rs = new RecordSet(); + RecordSet rs2 = new RecordSet(); + KQFormatData kqFormatData = new KQFormatData(); + //更新合同结束日期 + String lzSql = " select id,field82 from cus_fielddata where scopeid=3 and field82=? "; + rs.executeQuery(lzSql,currentDate); + while(rs.next()){ + String id = Util.null2String(rs.getString("id")); + + String updateSql = " update hrmresource set enddate=? where id=? and (enddate='' or enddate is null) "; + rs2.executeUpdate(updateSql,currentDate,id); + + //刷新考勤报表 + kqFormatData.formatKqDate(id,currentDate); + } + + //更新合同开始日期 + String rzSql = " select id from hrmresource where companystartdate=? "; + rs.executeQuery(rzSql,currentDate); + while(rs.next()){ + String id = Util.null2String(rs.getString("id")); + + String updateSql = " update hrmresource set startdate=? where id=? and (startdate='' or startdate is null) "; + rs2.executeUpdate(updateSql,currentDate,id); + } + + + } + + + + +} diff --git a/src/weaver/interfaces/hansang/job/EntryDaysCalculateJob.java b/src/weaver/interfaces/hansang/job/EntryDaysCalculateJob.java new file mode 100644 index 0000000..2e73065 --- /dev/null +++ b/src/weaver/interfaces/hansang/job/EntryDaysCalculateJob.java @@ -0,0 +1,147 @@ +package weaver.interfaces.hansang.job; + + +import com.engine.kq.biz.KQHolidaySetBiz; +import com.engine.kq.biz.KQWorkTime; +import com.weaver.formmodel.util.DateHelper; +import org.apache.commons.lang.StringUtils; +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.formmode.setup.ModeRightInfo; +import weaver.general.BaseBean; +import weaver.general.TimeUtil; +import weaver.general.Util; +import weaver.interfaces.schedule.BaseCronJob; + +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; +import java.util.UUID; + +/** + * @author wanxq + * @date 2023年07月24日14:32:09 + * @desc + */ +public class EntryDaysCalculateJob extends BaseCronJob { + + private BaseBean log = new BaseBean(); + + private String salaryMonth; + + + public void setMonth(String salaryMonth) { + this.salaryMonth = salaryMonth; + } + + @Override + public void execute() { + if(StringUtils.isBlank(salaryMonth)){ + salaryMonth = DateHelper.getCurrentMonth(); + } + + KQWorkTime kqWorkTime = new KQWorkTime(); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + RecordSet rs = new RecordSet(); + + String sql = " select id,companystartdate from hrmresource where companystartdate like '"+salaryMonth+"%' "; + rs.executeQuery(sql); + while(rs.next()){ + int userid = rs.getInt("id"); + LocalDate comStartDate = LocalDate.parse(Util.null2String(rs.getString("companystartdate")),formatter); + LocalDate workEndDate = comStartDate.withDayOfMonth(comStartDate.lengthOfMonth()); + + //判断是法定节假日前还是后 + int holidayDays = getHolidayDays(salaryMonth,comStartDate); + + double workdays = 0; + long daysDiff = ChronoUnit.DAYS.between(comStartDate,workEndDate)+1; + for(int i=0;i"+userid+" tempdate==>"+tempdate+" changeType==>"+changeType+" isWeekend==>"+isWeekend); + if(changeType==-1 && !isWeekend){ + workdays ++; + log.writeLog("EntryDaysCalculateJob userid==>"+userid+" workday==>"+tempdate); + } + + if(changeType==1 || changeType==2){ + workdays ++; + log.writeLog("EntryDaysCalculateJob userid==>"+userid+" workday==>"+tempdate); + } + + } + insertData(userid,workdays); + } + + } + + public void insertData(int userid,double workdays){ + RecordSet rs = new RecordSet(); + //删除建模表中当前算薪月的数据 + rs.executeUpdate("delete from uf_xjkk where xzszy=? and ryid=? ",salaryMonth,userid); + + int formmodeid = getModeIdByName("新进扣款"); + String modeuuid = UUID.randomUUID().toString(); + int modedatacreater = userid; + String modedatacreatedate = TimeUtil.getCurrentDateString(); + String modedatacreatetime = TimeUtil.getOnlyCurrentTimeString(); + String insertSql = " insert into uf_xjkk(ryid,xjkk,xzszy,formmodeid,modedatacreater,modedatacreatedate," + + "modedatacreatetime,modeuuid) values(?,?,?,?,?,?,?,?) "; + rs.executeUpdate(insertSql,userid,workdays,salaryMonth, + formmodeid,modedatacreater,modedatacreatedate,modedatacreatetime,modeuuid); + + rs.executeQuery("select id from uf_xjkk where modeuuid=?",modeuuid); + rs.next(); + int id = rs.getInt("id"); + if(id>0){ + ModeRightInfo right = new ModeRightInfo(); + right.editModeDataShare(userid, formmodeid, id); + } + + } + + /** + * 获取离职日期前的节假日天数 + * @param salaryMonth + * @param comStartDate + * @return + */ + public int getHolidayDays(String salaryMonth,LocalDate comStartDate){ + int holidayDays = 0; + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + RecordSet rs = new RecordSet(); + String sql = " select holidaydate from kq_HolidaySet where groupid=1 and changetype=1 and holidaydate like '"+salaryMonth+"%' "; + rs.execute(sql); + while (rs.next()){ + LocalDate holidaydate = LocalDate.parse(Util.null2String(rs.getString("holidaydate")),formatter); + + if(comStartDate.isBefore(holidaydate)){ + holidayDays++; + } + } + return holidayDays; + } + + + /** + * 根据建模名称获取建模id,建模权限同步的使用 + * @param modeName 建模名称 + * @return int 建模id + */ + public static int getModeIdByName(String modeName){ + RecordSet rs = new RecordSet(); + String sql = " SELECT ID FROM MODEINFO WHERE MODENAME = ? "; + rs.executeQuery(sql, modeName); + if (rs.next()) { + return rs.getInt("id"); + } + return -1; + } + + + +} diff --git a/src/weaver/interfaces/hansang/job/HrmGroupMemberSyn.java b/src/weaver/interfaces/hansang/job/HrmGroupMemberSyn.java new file mode 100644 index 0000000..fdbef36 --- /dev/null +++ b/src/weaver/interfaces/hansang/job/HrmGroupMemberSyn.java @@ -0,0 +1,101 @@ +package weaver.interfaces.hansang.job; + + +import weaver.conn.RecordSet; +import weaver.general.TimeUtil; +import weaver.general.Util; +import weaver.interfaces.schedule.BaseCronJob; + +/** + * @author wanxq + * @date 2023年07月05日08:59:23 + * @desc + */ +public class HrmGroupMemberSyn extends BaseCronJob { + + + @Override + public void execute() { + + RecordSet rs = new RecordSet(); + RecordSet rs2 = new RecordSet(); + String sql = " select xc,xnfzbm,xnfzmc from uf_xlfz where xc is not null "; + rs.execute(sql); + while(rs.next()){ + String xc = Util.null2String(rs.getString("xc")); + String xnfzbm = Util.null2String(rs.getString("xnfzbm")); + String xnfzmc = Util.null2String(rs.getString("xnfzmc")); + + //判断私人组是否存在 + String groupName = "XLFZ"+xnfzbm+"-"+xnfzmc; + String groupid = ""; + String groupSql = " select id from hrmgroup where name='"+groupName+"' and type=0 and owner="+xc+" and (canceled is null or canceled='') "; + + rs2.executeQuery(groupSql); + if(rs2.next()){ + groupid = Util.null2String(rs2.getString("id")); + }else{ + rs2.executeUpdate(" insert into hrmgroup(name,type,owner,sn) values(?,0,?,0.00)",groupName,xc); + rs2.executeQuery(groupSql); + + if(rs2.next()){ + groupid = Util.null2String(rs2.getString("id")); + } + } + + if("".equals(groupid)){ + System.out.println("HrmGroupMemberSyn groupSql===>"+groupSql); + }else{ + //处理私人组中的成员 + handleGroupMembers(groupid,xc); + } + + + + } + } + + /** + * 处理私有组成员 + * @param groupid + * @param xc + */ + public void handleGroupMembers(String groupid,String xc) { + RecordSet rs = new RecordSet(); + RecordSet rs2 = new RecordSet(); + String sql = " select id from cus_fielddata where field89=? "; + rs.executeQuery(sql,xc); + while(rs.next()){ + String memberid = Util.null2String(rs.getString("id")); + + rs2.executeUpdate(" delete from hrmgroupmembers where id in ( select id from (select b.id \n" + + "from hrmgroup a,hrmgroupmembers b \n" + + "where a.id=b.groupid and a.name like 'XLFZ%' and b.userid=? and b.groupid!=?) as temp)",memberid,groupid); + + if(!isInGroup(memberid,groupid)){ + rs2.executeUpdate(" insert into hrmgroupmembers(groupid,userid,usertype,dsporder) values(?,?,0,0) ",groupid,memberid); + } + + + } + + } + + /** + * 判断人员是否在私有组中 + * @param userid + * @param groupid + * @return + */ + public boolean isInGroup(String userid,String groupid){ + RecordSet rs = new RecordSet(); + rs.executeQuery("select * from hrmgroupmembers where userid=? and groupid=? ",userid,groupid); + return rs.next(); + } + + public static void main(String[] args) { + System.out.println(TimeUtil.getCurrentDateString()); + } + + +} diff --git a/src/weaver/interfaces/hansang/job/InternAttDaySynJob.java b/src/weaver/interfaces/hansang/job/InternAttDaySynJob.java new file mode 100644 index 0000000..d09b2f6 --- /dev/null +++ b/src/weaver/interfaces/hansang/job/InternAttDaySynJob.java @@ -0,0 +1,188 @@ +package weaver.interfaces.hansang.job; + + +import com.alibaba.fastjson.JSON; +import com.engine.kq.util.KQDurationCalculatorUtil; +import org.apache.commons.lang.StringUtils; +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.formmode.setup.ModeRightInfo; +import weaver.general.TimeUtil; +import weaver.general.Util; +import weaver.interfaces.schedule.BaseCronJob; + +import java.time.LocalTime; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +/** + * @author wanxq + * @date 2023年08月03日11:15:39 + * @desc 实习生出勤天数计算 + */ +public class InternAttDaySynJob extends BaseCronJob { + private String salaryMonth; + + public String getSalaryMonth() { + return salaryMonth; + } + + public void setSalaryMonth(String salaryMonth) { + this.salaryMonth = salaryMonth; + } + + + @Override + public void execute() { + RecordSet rs = new RecordSet(); + String fromDate = DateUtil.getFirstDayOfMonthToString(); + String toDate = DateUtil.getLastDayOfMonthToString(); + + if(StringUtils.isNotBlank(salaryMonth)){ + fromDate = DateUtil.getFirstDayOfMonth(this.salaryMonth+"-01"); + toDate = DateUtil.getLastDayOfMonth(this.salaryMonth+"-01"); + } + + String sql = " select id,field35 from cus_fielddata cf where field24 in(2,3) "; + rs.execute(sql); + while(rs.next()){ + int userid = Util.getIntValue(rs.getString("id")); + int userAttr = Util.getIntValue(rs.getString("field35")); + calAttendance(userid,userAttr,fromDate,toDate); + } + } + + /** + * 计算人员出勤天数 + * @param resourceid + * @param fromDate + * @param toDate + */ + public void calAttendance(int resourceid,int userAttr,String fromDate,String toDate){ + double attendanceDays = 0; + Map data = getSignInfo(resourceid,fromDate,toDate); + + RecordSet rs = new RecordSet(); + String sql = " select kqdate,workbegindate,workbegintime ,workenddate ,workendtime,workmins, attendanceMins " + + " from kq_format_detail kfd " + + " where resourceid =? and kqdate>=? and kqdate<=? order by kqdate "; + rs.executeQuery(sql,resourceid,fromDate,toDate); + while(rs.next()){ + String kqdate = Util.null2String(rs.getString("kqdate")); + double workmins = rs.getDouble("workmins")<0?0:rs.getDouble("workmins"); + double attendanceMins = rs.getDouble("attendanceMins")<0?0:rs.getDouble("attendanceMins"); + double attendanceHours =Util.getDoubleValue(KQDurationCalculatorUtil.getDurationRound(attendanceMins/(60.0)+"")); + + //办公加班月结的员工,周六周日按原逻辑计算,不算在此规则中 + if(userAttr==0 && (DateUtil.getWeek(kqdate) == 6 || DateUtil.getWeek(kqdate) == 7)){ + continue; + } + + double currentAttDays = 0; + if(data.get(kqdate)!=null && !"".equals(data.get(kqdate))){ + //取当天最早的打卡,判断是上午卡还是下午卡 + String signBeginTime = data.get(kqdate).split("\\|")[0]; + try{ + LocalTime localTime1 = LocalTime.parse(signBeginTime); + LocalTime localTime2 = LocalTime.parse("12:00:00"); + + int comparison = localTime1.compareTo(localTime2); + if (comparison < 0) { + //上午打卡,当天工作时长大于等于8小时算1天,大于等于3.5小时算0.5天 + if(attendanceHours>=8){ + currentAttDays = 1; + }else if(attendanceHours>=3.5){ + currentAttDays = 0.5; + } + + } else { + //下午打卡工作时长必须大于等于4.5小时算0.5天 + if(attendanceHours>=4.5){ + currentAttDays = 0.5; + } + } + rs.writeLog("InternAttDaySynJob calAttendance kqdate==>"+kqdate+" currentAttDays==>"+currentAttDays); + attendanceDays += currentAttDays; + }catch (Exception e){ + e.printStackTrace(); + } + } + } + //更新实习人员出勤表 + String month = fromDate.substring(0,7); + insertData(resourceid,attendanceDays,month); + } + + + public void insertData(int userid,double workdays,String month){ + RecordSet rs = new RecordSet(); + //删除建模表中当前算薪月的数据 + rs.executeUpdate("delete from uf_sxskqsc where sxsry=? and xzszy=? ",userid,month); + + int formmodeid = getModeIdByName("实习生考勤时长"); + String modeuuid = UUID.randomUUID().toString(); + int modedatacreater = 1; + String modedatacreatedate = TimeUtil.getCurrentDateString(); + String modedatacreatetime = TimeUtil.getOnlyCurrentTimeString(); + String insertSql = " insert into uf_sxskqsc(sxsry,sjcqts,xzszy,formmodeid,modedatacreater,modedatacreatedate," + + "modedatacreatetime,modeuuid) values(?,?,?,?,?,?,?,?) "; + rs.executeUpdate(insertSql,userid,workdays,month, + formmodeid,modedatacreater,modedatacreatedate,modedatacreatetime,modeuuid); + + rs.executeQuery("select id from uf_sxskqsc where modeuuid=?",modeuuid); + rs.next(); + int id = rs.getInt("id"); + if(id>0){ + ModeRightInfo right = new ModeRightInfo(); + right.editModeDataShare(userid, formmodeid, id); + } + + } + + + /** + * 根据建模名称获取建模id,建模权限同步的使用 + * @param modeName 建模名称 + * @return int 建模id + */ + public static int getModeIdByName(String modeName){ + RecordSet rs = new RecordSet(); + String sql = " SELECT ID FROM MODEINFO WHERE MODENAME = ? "; + rs.executeQuery(sql, modeName); + if (rs.next()) { + return rs.getInt("id"); + } + return -1; + } + + + + /** + * 查询对应考勤人员每天的打卡数据 + * @param userid + * @param fromDate + * @param toDate + * @return + */ + public Map getSignInfo(int userid, String fromDate, String toDate){ + Map data = new HashMap<>(); + RecordSet rs = new RecordSet(); + String sql = " select signdate,min(signtime) signbegintime,max(signtime) signendtime from HrmScheduleSign " + + " where userid=? and signdate>=? and signdate<=? and signtime>='06:30:00' " + + " group by signdate "; + rs.executeQuery(sql,userid,fromDate,toDate); + while (rs.next()){ + String signDate = Util.null2String(rs.getString("signdate")); + String signBeginTime = Util.null2String(rs.getString("signbegintime")); + String signEndTime = Util.null2String(rs.getString("signendtime")); + data.put(signDate,signBeginTime+"|"+signEndTime); + } + rs.writeLog("InternAttDaySynJob getSignInfo data==>"+ JSON.toJSONString(data)); + return data; + } + + + + +} diff --git a/src/weaver/interfaces/hansang/job/KqAbnormalRemind.java b/src/weaver/interfaces/hansang/job/KqAbnormalRemind.java new file mode 100644 index 0000000..c08061c --- /dev/null +++ b/src/weaver/interfaces/hansang/job/KqAbnormalRemind.java @@ -0,0 +1,143 @@ +package weaver.interfaces.hansang.job; + + +import com.cloudstore.dev.api.bean.MessageBean; +import com.cloudstore.dev.api.bean.MessageType; +import com.cloudstore.dev.api.util.Util_Message; +import com.engine.kq.biz.KQWorkTime; +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.general.TimeUtil; +import weaver.general.Util; +import weaver.interfaces.schedule.BaseCronJob; + +import java.io.IOException; +import java.util.HashSet; +import java.util.Set; + +/** + * @author wanxq + * @date 2023年08月17日10:45:22 + * @desc + */ +public class KqAbnormalRemind extends BaseCronJob { + + @Override + public void execute() { + RecordSet rs = new RecordSet(); + String currentDate = DateUtil.getCurrentDate(); + String currentMonth = currentDate.substring(0,7); + String sql = " select a.id,field112,b.field138 from hrmresource a,cus_fielddata b " + + " where a.id=b.id and a.status<=3 and b.scopeid=3 "; + rs.execute(sql); + while(rs.next()){ + String userid = Util.null2String(rs.getString("id")); + String field112 = Util.null2String(rs.getString("field112")); + String field138 = Util.null2String(rs.getString("field138")); + + if(!"0".equals(field112) && !"0".equals(field138)){ + continue; + } + + boolean isExist = hasAbnormalData(userid,currentMonth,currentDate); + if(isExist){ + Set userIdList = new HashSet<>(); + userIdList.add(userid); + + //内容 + String context = getMsg(userid,currentMonth,currentDate); + sendRemindMsg(userIdList,context); + } + } + } + + + /** + * 发送提醒 + * @param userIdList + */ + public void sendRemindMsg(Set userIdList,String context){ + try { + MessageType messageType = MessageType.newInstance(2022061096); + String title = "考勤异常提醒"; + MessageBean messageBean = Util_Message.createMessage(messageType, userIdList, title, context, "", ""); + messageBean.setCreater(1); + Util_Message.store(messageBean); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public String getMsg(String userid,String kqmonth,String currentDate){ + KQWorkTime kqWorkTime = new KQWorkTime(); + String lastMonthEndDay = TimeUtil.getLastMonthEndDay(); + String msg = "温馨提示:
您的考勤有异常
"; + RecordSet rs = new RecordSet(); + String sql = " select a.kqdate,a.absenteeism,a.absenteeismmins,a.forgotcheck,a.forgotBeginWorkCheck,a.belate,a.leaveeearly,b.signintime,b.signouttime " + + " from kq_format_total a " + + " left join kq_format_detail b on a.resourceid=b.resourceid and a.kqdate=b.kqdate " + + " where (a.kqdate like '"+kqmonth+"%' or a.kqdate=? ) and a.resourceid=? " + + " and (absenteeism>0 or forgotcheck>0 or forgotBeginWorkCheck >0 or a.belate>0 or a.leaveeearly>0) and a.kqdate!=? "; + rs.executeQuery(sql,lastMonthEndDay,userid,currentDate); + while (rs.next()){ + String kqdate = Util.null2String(rs.getString("kqdate")); + String signintime = Util.null2String(rs.getString("signintime")); + String signouttime = Util.null2String(rs.getString("signouttime")); + + signintime = "".equals(signintime)?"无":signintime; + signouttime = "".equals(signouttime)?"无":signouttime; + + //旷工 + int absenteeism = Util.getIntValue(rs.getString("absenteeism"),0); + //漏签 + int forgotcheck = Util.getIntValue(rs.getString("forgotcheck"),0); + int forgotBeginWorkCheck = Util.getIntValue(rs.getString("forgotBeginWorkCheck"),0); + //迟到 + int belate = Util.getIntValue(rs.getString("belate"),0); + //早退 + int leaveeearly = Util.getIntValue(rs.getString("leaveeearly"),0); + + String kqResult = ""; + if( absenteeism>0){ + kqResult = "旷工"; + } + + if( forgotcheck>0 || forgotBeginWorkCheck>0){ + kqResult = "漏签"; + } + + if( belate>0){ + kqResult = "迟到"; + } + + if( leaveeearly>0){ + kqResult = "早退"; + } + msg += "日期:"+kqdate+",上班打卡时间:"+signintime+",下班打卡时间:"+signouttime+",考勤结果:"+kqResult+"
"; + } + return msg; + } + + /** + * 判断是否有异常数据 + * @param userid + * @param kqmonth + * @return + */ + public boolean hasAbnormalData(String userid,String kqmonth,String currentDate){ + RecordSet rs = new RecordSet(); + String lastMonthEndDay = TimeUtil.getLastMonthEndDay(); + String sql = " select * from kq_format_total " + + " where (kqdate like '"+kqmonth+"%' or kqdate=?) and resourceid=? " + + " and (absenteeism>0 or forgotcheck>0 or forgotBeginWorkCheck >0 or belate>0 or leaveeearly>0) and kqdate!=? "; + rs.executeQuery(sql,lastMonthEndDay,userid,currentDate); + return rs.next(); + } + + + public static void main(String[] args) { + System.out.println(TimeUtil.getLastMonthEndDay()); + } + + +} diff --git a/src/weaver/interfaces/hansang/job/KqAutoScheduleJob.java b/src/weaver/interfaces/hansang/job/KqAutoScheduleJob.java new file mode 100644 index 0000000..e4c94e5 --- /dev/null +++ b/src/weaver/interfaces/hansang/job/KqAutoScheduleJob.java @@ -0,0 +1,104 @@ +package weaver.interfaces.hansang.job; + + +import com.engine.kq.biz.KQHolidaySetBiz; +import com.engine.kq.biz.KQWorkTime; +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.file.Prop; +import weaver.general.TimeUtil; +import weaver.general.Util; +import weaver.interfaces.schedule.BaseCronJob; + +import java.time.LocalDate; +import java.time.temporal.TemporalAdjusters; + +/** + * @author wanxq + * @date 2023年06月20日09:25:14 + * @desc + */ +public class KqAutoScheduleJob extends BaseCronJob { + + + @Override + public void execute() { + + String baiban = Util.null2s(Prop.getPropValue("hansang_auto_schedule","baiban"),"2"); + String xiuxiban = Util.null2s(Prop.getPropValue("hansang_auto_schedule","xiuxiban"),"15"); + + RecordSet rs = new RecordSet(); + String sql = " select * from (\n" + + " SELECT a.id AS resourceid, b.groupid, a.status,a.dsporder,a.lastname,a.subcompanyid1, a.departmentid, a.loginid FROM HrmResource a, kq_groupmember b \n" + + " WHERE a.id=b.typevalue and b.type =1 and (b.isdelete is null or b.isdelete <> '1') \n" + + " UNION ALL \n" + + " SELECT a.id AS resourceid, b.groupid, a.status,a.dsporder,a.lastname,a.subcompanyid1, a.departmentid, a.loginid FROM HrmResource a, kq_groupmember b \n" + + " WHERE a.subcompanyid1 = b.typevalue AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto AND b.type=2 and (b.isdelete is null or b.isdelete <> '1') \n" + + " UNION ALL \n" + + " SELECT a.id AS resourceid, b.groupid, a.status,a.dsporder,a.lastname,a.subcompanyid1, a.departmentid, a.loginid FROM HrmResource a, kq_groupmember b \n" + + " WHERE a.departmentid = b.typevalue AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto AND b.type=3 and (b.isdelete is null or b.isdelete <> '1') \n" + + " UNION ALL \n" + + " SELECT a.id AS resourceid, b.groupid, a.status,a.dsporder,a.lastname,a.subcompanyid1, a.departmentid, a.loginid FROM HrmResource a, kq_groupmember b \n" + + " WHERE (a.jobtitle = b.typevalue AND b.type=5 and (b.isdelete is null or b.isdelete <> '1') AND (b.jobtitlelevel=1 OR (b.jobtitlelevel=2 AND a.subcompanyid1 IN(b.jobtitlelevelvalue)) OR (b.jobtitlelevel=3 AND a.departmentid IN(b.jobtitlelevelvalue)))) \n" + + " UNION ALL SELECT a.id AS resourceid, b.groupid, a.status,a.dsporder,a.lastname,a.subcompanyid1, a.departmentid, a.loginid FROM HrmResource a, kq_groupmember b \n" + + " WHERE b.type=6 AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto and (b.isdelete is null or b.isdelete <> '1') ) t\n" + + "where t.groupid = 12 and t.status in(0,1,2,3) and t.loginid is not null and t.loginid<>'' and (t.status = 0 or t.status = 1 or t.status = 2 or t.status = 3) "; + rs.execute(sql); + while(rs.next()){ + String resourceid = Util.null2String(rs.getString("resourceid")); + saveSchedule(resourceid,baiban,xiuxiban); + } + } + + /** + * 自动设置人员的排班 + * @param resourceid + */ + public void saveSchedule(String resourceid,String baiban,String xiuxiban){ + + RecordSet rs = new RecordSet(); + KQWorkTime kqWorkTime = new KQWorkTime(); + + LocalDate now = LocalDate.now(); + now = now.plusMonths(1); + String firstDay = now.with(TemporalAdjusters.firstDayOfMonth()).toString(); + String lastDay = now.with(TemporalAdjusters.lastDayOfMonth()).toString(); + + + + int diffdays = DateUtil.dayDiff(firstDay,lastDay)+1; + for(int i=0;i"+updateSql); + rs.executeUpdate(updateSql, tempdate,serialid,resourceid); + }else { + String insertSql = "insert into kq_shiftschedule (kqdate,serialid,resourceid,groupid) values(?,?,?,?) "; + //rs.writeLog("KqAutoScheduleJob insertSql===>"+insertSql); + rs.executeUpdate(insertSql, new Object[]{tempdate,serialid,resourceid,12}); + } + + } + } + + + +} diff --git a/src/weaver/interfaces/hansang/job/KqGroupMemberSyn.java b/src/weaver/interfaces/hansang/job/KqGroupMemberSyn.java new file mode 100644 index 0000000..f191a07 --- /dev/null +++ b/src/weaver/interfaces/hansang/job/KqGroupMemberSyn.java @@ -0,0 +1,80 @@ +package weaver.interfaces.hansang.job; + + +import cn.hutool.http.HttpUtil; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.cloudstore.dev.api.util.Util_DataCache; +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 org.apache.commons.lang.StringUtils; +import weaver.common.DateUtil; +import weaver.conn.BatchRecordSet; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.TimeUtil; +import weaver.general.Util; +import weaver.interfaces.schedule.BaseCronJob; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.*; + +/** + * @author wanxq + * @date 2023年06月20日09:25:14 + * @desc + */ +public class KqGroupMemberSyn extends BaseCronJob { + + + @Override + public void execute() { + + RecordSet rs = new RecordSet(); + RecordSet rs2 = new RecordSet(); + String currentDate = TimeUtil.getCurrentDateString(); + String sql = " select id,field103,field104 from cus_fielddata where field104 is not null and field103=? "; + System.out.println("KqGroupMemberSyn===>"+sql+" "+currentDate); + rs.executeQuery(sql,currentDate); + while(rs.next()){ + String id = Util.null2String(rs.getString("id")); + String groupid = Util.null2String(rs.getString("field104")); + + if(!isInKqGroup(id,groupid)){ + String insertSql = " insert into kq_groupmember(type,typevalue,groupid) values(?,?,?)"; + System.out.println("KqGroupMemberSyn insertSql===>"+insertSql); + rs2.executeUpdate(insertSql,1,id,groupid); + }else{ + String updateSql = " update kq_groupmember set isdelete=null where typevalue=? and groupid=? "; + System.out.println("KqGroupMemberSyn updateSql===>"+updateSql); + rs2.executeUpdate(updateSql,id,groupid); + } + } + } + + /** + * 判断人员是否在考勤组中 + * @param id + * @param groupid + * @return + */ + public boolean isInKqGroup(String id,String groupid){ + RecordSet rs = new RecordSet(); + String sql = "select * from kq_groupmember where typevalue=? and groupid=? "; + System.out.println("isInKqGroup===>"+sql+" "+id+" "+groupid); + rs.executeQuery(sql,id,groupid); + return rs.next(); + } + + public static void main(String[] args) { + System.out.println(TimeUtil.getCurrentDateString()); + } + + +} diff --git a/src/weaver/interfaces/hansang/job/LeaveDateUpdateJob.java b/src/weaver/interfaces/hansang/job/LeaveDateUpdateJob.java new file mode 100644 index 0000000..4f58913 --- /dev/null +++ b/src/weaver/interfaces/hansang/job/LeaveDateUpdateJob.java @@ -0,0 +1,39 @@ +package weaver.interfaces.hansang.job; + + +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.interfaces.schedule.BaseCronJob; + +/** + * @author wanxq + * @date 2023年10月07日15:52:27 + * @desc 根据自定义离职日期更新标准合同结束日期字段 + */ +public class LeaveDateUpdateJob extends BaseCronJob { + + private String selectMonth; + + @Override + public void execute() { + String currentMonth = DateUtil.getCurrentDate().substring(0,7); + if(selectMonth!=null && !"".equals(selectMonth)){ + currentMonth = selectMonth; + } + + RecordSet rs = new RecordSet(); + String sql = " update cus_fielddata a,hrmresource b set enddate=date_add(field82, INTERVAL -1 DAY) " + + " where a.id=b.id and scopeid=3 and field82 like '"+currentMonth+"%' "; + rs.execute(sql); + + } + + public String getSelectMonth() { + return selectMonth; + } + + public void setSelectMonth(String selectMonth) { + this.selectMonth = selectMonth; + } + +} diff --git a/src/weaver/interfaces/hansang/job/LeaveDaysCalculateJob.java b/src/weaver/interfaces/hansang/job/LeaveDaysCalculateJob.java new file mode 100644 index 0000000..8a0b271 --- /dev/null +++ b/src/weaver/interfaces/hansang/job/LeaveDaysCalculateJob.java @@ -0,0 +1,172 @@ +package weaver.interfaces.hansang.job; + + +import com.engine.kq.biz.KQHolidaySetBiz; +import com.engine.kq.biz.KQWorkTime; +import com.weaver.formmodel.util.DateHelper; +import org.apache.commons.lang.StringUtils; +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.formmode.setup.ModeRightInfo; +import weaver.general.BaseBean; +import weaver.general.TimeUtil; +import weaver.general.Util; +import weaver.interfaces.schedule.BaseCronJob; + +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; +import java.util.UUID; + +/** + * @author wanxq + * @date 2023年07月24日14:32:09 + * @desc + */ +public class LeaveDaysCalculateJob extends BaseCronJob { + private BaseBean log = new BaseBean(); + + private String salaryMonth; + + + public void setMonth(String salaryMonth) { + this.salaryMonth = salaryMonth; + } + + @Override + public void execute() { + if(StringUtils.isBlank(salaryMonth)){ + salaryMonth = DateHelper.getCurrentMonth(); + } + + KQWorkTime kqWorkTime = new KQWorkTime(); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + RecordSet rs = new RecordSet(); + + String sql = " select id,field82 from cus_fielddata " + + "where scopeid=3 and scope='HrmCustomFieldByInfoType' and field82 like '"+salaryMonth+"%' "; + rs.executeQuery(sql); + while(rs.next()){ + int userid = rs.getInt("id"); + String field82 = Util.null2String(rs.getString("field82")); + LocalDate leaveDate = LocalDate.parse(field82,formatter); + + log.writeLog("LeaveDaysCalculateJob leave userid==>"+userid+" leaveDate==>"+leaveDate); + + //判断是法定节假日前还是后 + //int holidayDays = getHolidayDays(salaryMonth,leaveDate); + //log.writeLog("LeaveDaysCalculateJob leave holidayDays==>"+holidayDays); + + double workdays = 0; + LocalDate workStartDate = LocalDate.parse(salaryMonth+"-01",formatter); + long daysDiff = ChronoUnit.DAYS.between(workStartDate, leaveDate); + for(int i=0;i"+userid+" tempdate==>"+tempdate+" changeType==>"+changeType+" isWeekend==>"+isWeekend); + + if(changeType==-1 && !isWeekend){ + workdays ++; + log.writeLog("LeaveDaysCalculateJob userid==>"+userid+" workday==>"+tempdate); + } + + if(changeType==1 || changeType==2){ + workdays ++; + log.writeLog("LeaveDaysCalculateJob userid==>"+userid+" workday==>"+tempdate); + } + + + //判断是否是法定节假日、周末 + //boolean isHoliday = false; + //int changeType = KQHolidaySetBiz.getChangeType("2",tempdate); + //log.writeLog("LeaveDaysCalculateJob userid==>"+userid+" tempdate==>"+tempdate+" changeType==>"+changeType+" weekend==>"+DateUtil.getWeek(tempdate)); + //if (changeType != 2 && (DateUtil.getWeek(tempdate) == 6 || DateUtil.getWeek(tempdate) == 7)) { + // isHoliday = true; + //} + //if (changeType == 1 || changeType == 3) { + // isHoliday = true; + //} + // + //if(!isHoliday){ + // workdays++; + // log.writeLog("LeaveDaysCalculateJob userid==>"+userid+" workday==>"+tempdate); + //} + } + log.writeLog("LeaveDaysCalculateJob userid==>"+userid+" allworkdays==>"+workdays); + //workdays += holidayDays; + + insertData(userid,workdays); + } + + } + + public void insertData(int userid,double workdays){ + RecordSet rs = new RecordSet(); + //删除建模表中当前算薪月的数据 + rs.executeUpdate("delete from uf_lzkk where xzszy=? and ryid=? ",salaryMonth,userid); + + int formmodeid = getModeIdByName("离职扣款"); + String modeuuid = UUID.randomUUID().toString(); + int modedatacreater = userid; + String modedatacreatedate = TimeUtil.getCurrentDateString(); + String modedatacreatetime = TimeUtil.getOnlyCurrentTimeString(); + String insertSql = " insert into uf_lzkk(ryid,lzkk,xzszy,formmodeid,modedatacreater,modedatacreatedate," + + "modedatacreatetime,modeuuid) values(?,?,?,?,?,?,?,?) "; + rs.executeUpdate(insertSql,userid,workdays,salaryMonth, + formmodeid,modedatacreater,modedatacreatedate,modedatacreatetime,modeuuid); + + rs.executeQuery("select id from uf_lzkk where modeuuid=?",modeuuid); + rs.next(); + int id = rs.getInt("id"); + if(id>0){ + ModeRightInfo right = new ModeRightInfo(); + right.editModeDataShare(userid, formmodeid, id); + } + + } + + /** + * 获取离职日期前的节假日天数 + * @param salaryMonth + * @param leaveDate + * @return + */ + public int getHolidayDays(String salaryMonth,LocalDate leaveDate){ + int holidayDays = 0; + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + RecordSet rs = new RecordSet(); + String sql = " select holidaydate from kq_HolidaySet where groupid=1 and changetype=1 and holidaydate like '"+salaryMonth+"%' "; + rs.execute(sql); + while (rs.next()){ + LocalDate holidaydate = LocalDate.parse(Util.null2String(rs.getString("holidaydate")),formatter); + + if(leaveDate.isAfter(holidaydate)){ + holidayDays++; + log.writeLog("leaveDate==>"+leaveDate+" holidaydate ==>"+holidaydate); + } + } + return holidayDays; + } + + + /** + * 根据建模名称获取建模id,建模权限同步的使用 + * @param modeName 建模名称 + * @return int 建模id + */ + public static int getModeIdByName(String modeName){ + RecordSet rs = new RecordSet(); + String sql = " SELECT ID FROM MODEINFO WHERE MODENAME = ? "; + rs.executeQuery(sql, modeName); + if (rs.next()) { + return rs.getInt("id"); + } + return -1; + } + + + +} diff --git a/src/weaver/interfaces/hansang/job/ManagerMemberSyn.java b/src/weaver/interfaces/hansang/job/ManagerMemberSyn.java new file mode 100644 index 0000000..ab0c0e1 --- /dev/null +++ b/src/weaver/interfaces/hansang/job/ManagerMemberSyn.java @@ -0,0 +1,54 @@ +package weaver.interfaces.hansang.job; + + +import weaver.conn.RecordSet; +import weaver.general.TimeUtil; +import weaver.general.Util; +import weaver.interfaces.schedule.BaseCronJob; + +/** + * @author wanxq + * @date 2023年09月12日11:44:24 + * @desc + */ +public class ManagerMemberSyn extends BaseCronJob { + + + @Override + public void execute() { + + RecordSet rs = new RecordSet(); + RecordSet rs2 = new RecordSet(); + String sql = " select id from hrmroles where rolesmark='主管及以上管理者' "; + rs.execute(sql); + if(rs.next()) { + String roleid = Util.null2String(rs.getString("id")); + + //删除不在角色中的人员 + String delSql = " delete from hrmrolemembers a where roleid=? and not exists " + + " ( select 1 from cus_fielddata b where field93 in(23,24,25,26,27,28) and a.resourceid=b.id )"; + rs.executeUpdate(delSql,roleid); + + //添加属于角色中的人员 + String synSql = " select id from cus_fielddata cf where field93 in(23,24,25,26,27,28) " + + " and not exists ( select 1 from hrmrolemembers hr where hr.roleid=? and resourceid=cf.id) "; + rs.executeQuery(synSql,roleid); + while(rs.next()){ + String userid = Util.null2String(rs.getString("id")); + + String insertSql = " insert into hrmrolemembers(roleid,resourceid,rolelevel,resourcetype) values(?,?,?,?) "; + rs2.executeUpdate(insertSql,new Object[]{roleid,userid,2,1}); + } + + } + + } + + + + public static void main(String[] args) { + System.out.println(TimeUtil.getCurrentDateString()); + } + + +} diff --git a/src/weaver/interfaces/hansang/job/NurseLeaveCalculateJob.java b/src/weaver/interfaces/hansang/job/NurseLeaveCalculateJob.java new file mode 100644 index 0000000..9fbfff0 --- /dev/null +++ b/src/weaver/interfaces/hansang/job/NurseLeaveCalculateJob.java @@ -0,0 +1,65 @@ +package weaver.interfaces.hansang.job; + + +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.interfaces.schedule.BaseCronJob; + +import java.text.DecimalFormat; +import java.time.format.DateTimeFormatter; + +/** + * @author wanxq + * @date 2023年08月17日14:17:51 + * @desc 护理假基数计算 + */ +public class NurseLeaveCalculateJob extends BaseCronJob { + + @Override + public void execute() { + + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + DecimalFormat df = new DecimalFormat("#.00"); + String currentYear = DateUtil.getYear(); + //当前日期减出生日期小于3年才计算育儿假 + RecordSet rs = new RecordSet(); + String sql = " select id,companystartdate from hrmresource h where status<=3 and companystartdate is not null "; + rs.executeQuery(sql); + while (rs.next()){ + String id = Util.null2String(rs.getString("id")); + String companystartdate = Util.null2String(rs.getString("companystartdate")); + + double jqts = 0; + if(!"".equals(companystartdate)){ + String companystartyear = companystartdate.substring(0,4); + if(currentYear.equals(companystartyear)){ + int diffDays = DateUtil.dayDiff(companystartdate,companystartyear+"-12-31")+1; + jqts = Double.valueOf(df.format((double)diffDays/365*5)); + }else { + jqts = 5; + } + setLeaveTypeDays(id,jqts,currentYear); + } + } + } + + /** + * 设置人员护理假 + * @param ry + * @param jqts + * @param belongyear + */ + public void setLeaveTypeDays(String ry, double jqts,String belongyear) { + RecordSet rs = new RecordSet(); + String sql = " update kq_balanceofleave set baseAmount=? " + + " where leaveRulesId=? and resourceId=? and belongyear=? "; + rs.executeUpdate(sql,jqts,37,ry,belongyear); + } + + public static void main(String[] args) { + System.out.println("2021-01-27".substring(0,4)); + } + + +} diff --git a/src/weaver/interfaces/hansang/job/OutSignUserSynJob.java b/src/weaver/interfaces/hansang/job/OutSignUserSynJob.java new file mode 100644 index 0000000..f060a73 --- /dev/null +++ b/src/weaver/interfaces/hansang/job/OutSignUserSynJob.java @@ -0,0 +1,50 @@ +package weaver.interfaces.hansang.job; + + +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.interfaces.schedule.BaseCronJob; + +/** + * @author wanxq + * @date 2023年07月31日17:24:18 + * @desc 定时将外勤打卡人员同步到角色中 + */ +public class OutSignUserSynJob extends BaseCronJob { + + + @Override + public void execute() { + + + RecordSet rs = new RecordSet(); + RecordSet rs2 = new RecordSet(); + String sql = " select id from hrmroles where rolesmark='外勤打卡人员' "; + rs.execute(sql); + if(rs.next()){ + String roleid = Util.null2String(rs.getString("id")); + + //从角色中删除已经不是外勤打卡的人员 + String deleteSql = " delete from hrmrolemembers where roleid=? " + + " and resourceid in( " + + " select id from ( " + + " select id from cus_fielddata cf where (field37!=1 or field37 is null) and scope='HrmCustomFieldByInfoType' and scopeid=-1 " + + " and exists (select 1 from hrmrolemembers hr where hr.roleid=? and resourceid=cf.id) )t " + + " )"; + rs.executeUpdate(deleteSql,roleid,roleid); + + //同步需要外勤打卡的人员 + String synSql = " select id from cus_fielddata cf where field37=1 " + + " and not exists ( select 1 from hrmrolemembers hr where hr.roleid=? and resourceid=cf.id)"; + rs.executeQuery(synSql,roleid); + while(rs.next()){ + String userid = Util.null2String(rs.getString("id")); + + String insertSql = " insert into hrmrolemembers(roleid,resourceid,rolelevel,resourcetype) values(?,?,?,?) "; + rs2.executeUpdate(insertSql,new Object[]{roleid,userid,2,1}); + } + } + } + + +} diff --git a/src/weaver/interfaces/hansang/job/OvertimeCalculateJob.java b/src/weaver/interfaces/hansang/job/OvertimeCalculateJob.java new file mode 100644 index 0000000..370ff24 --- /dev/null +++ b/src/weaver/interfaces/hansang/job/OvertimeCalculateJob.java @@ -0,0 +1,121 @@ +package weaver.interfaces.hansang.job; + + +import com.engine.kq.biz.KQAttFlowSetBiz; +import com.engine.kq.biz.KQFlowActiontBiz; +import com.engine.kq.enums.KqSplitFlowTypeEnum; +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.User; +import weaver.interfaces.schedule.BaseCronJob; + +import java.util.HashMap; +import java.util.Map; + +/** + * @author wanxq + * @date 2023年08月17日14:17:51 + * @desc + */ +public class OvertimeCalculateJob extends BaseCronJob { + + @Override + public void execute() { + + // 如果是出差没有刷新报表,可以通过下面的连接批量处理 + String fromDate = DateUtil.getYesterday(); + String toDate = fromDate; + doCalculate(fromDate,toDate,"",""); + + } + + + public void doCalculate(String fromDate,String toDate,String resourceid,String isForce){ + boolean isForce1 = false; + boolean isUpgrade1 = false; + User user = new User(1); + KQAttFlowSetBiz kqAttFlowSetBiz = new KQAttFlowSetBiz(); + KQFlowActiontBiz kqFlowActiontBiz = new KQFlowActiontBiz(); + Map params = new HashMap<>(); + params.put("typeselect", "6"); + params.put("tabKey", "3"); + params.put("kqtype", 3); + params.put("isMyKQ", "1"); + params.put("isNoAccount", "1"); + params.put("fromDate", fromDate); + params.put("toDate", toDate); + params.put("not_start_node", "1"); + if(resourceid.length()>0){ + params.put("resourceId", resourceid); + } + if(isForce.length()>0 && "true".equals(isForce)){ + isForce1 = true; + } + + Map sqlMap = kqAttFlowSetBiz.getFLowSql(params,user); + String backfields = " * "; + String fromSql = Util.null2String(sqlMap.get("from")); + String sqlWhere = Util.null2String(sqlMap.get("where")); + String allSql = "select "+ backfields + fromSql+sqlWhere; + RecordSet rs = new RecordSet(); + RecordSet rs1 = new RecordSet(); + rs.writeLog("allSql:" + allSql + "
"); + rs.executeQuery(allSql); + Map infoMap = new HashMap<>(); + while (rs.next()) { + String currentnodetype = rs.getString("currentnodetype"); + if(!"3".equals(currentnodetype)) { + continue; + } + String requestId = rs.getString("requestid"); + String workflowId = rs.getString("workflowid"); + infoMap.put(requestId, workflowId); + } + rs.writeLog("infoMap:" + infoMap.toString() + "
"); + for(Map.Entry entry : infoMap.entrySet()) { + String requestid = entry.getKey(); + String workflowid = entry.getValue(); + //先根据requestid删除中间表里的数据,再做啥插入操作 + String delSql = "delete from "+ KqSplitFlowTypeEnum.OVERTIME.getTablename()+" where requestid = "+requestid; + rs.executeUpdate(delSql); + + //加班有两个表 + delSql = "delete from kq_flow_overtime where requestid = "+requestid; +// out.println("先删除中间表数据 : " + delSql+"
"); + rs1.executeUpdate(delSql); + + + 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); + } + + try { + Map result = kqFlowActiontBiz.handleKQFlowAction(proc_set_id, usedetails, Util.getIntValue(requestid), kqtype, + Util.getIntValue(workflowid), isForce1, isUpgrade1, map); + + rs.writeLog("requestid:" + requestid + "执行完毕
"); + if (!result.isEmpty()) { + rs.writeLog("do action on kqtype 失败:" + result + "
"); + } + } catch (Exception e) { + e.printStackTrace(); + } + + + } + } + + } + +} diff --git a/src/weaver/interfaces/hansang/job/OvertimeSignCalculateJob.java b/src/weaver/interfaces/hansang/job/OvertimeSignCalculateJob.java new file mode 100644 index 0000000..d9bce43 --- /dev/null +++ b/src/weaver/interfaces/hansang/job/OvertimeSignCalculateJob.java @@ -0,0 +1,153 @@ +package weaver.interfaces.hansang.job; + + +import com.engine.kq.biz.KQHolidaySetBiz; +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.interfaces.schedule.BaseCronJob; + +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; + +/** + * @author wanxq + * @date 2023年08月17日14:17:51 + * @desc 处理加班跨天情况考勤日历打卡数据异常问题 + */ +public class OvertimeSignCalculateJob extends BaseCronJob { + + @Override + public void execute() { + + RecordSet rs = new RecordSet(); + RecordSet rs2 = new RecordSet(); + + //DepartmentComInfo deptComInfo = new DepartmentComInfo(); + //ArrayList allChildDept = new ArrayList(); + //allChildDept.add("44"); + //allChildDept.add("77"); + //deptComInfo.getAllChildDeptByDepId(allChildDept,"44"); + //deptComInfo.getAllChildDeptByDepId(allChildDept,"77"); + //String deptids = StringUtils.join(allChildDept, ","); + + + String currentMonth = DateUtil.getCurrentDate().substring(0,7); + int timescope = Util.getIntValue(rs.getPropValue("cus_kq_conf","scope"),2); + + + String sql = " select resourceId,fromDate,fromTime ,toDate ,toTime ,departmentId " + + " from formtable_main_75 " + + " where fromDate like '"+currentMonth+"%' " + + " and datediff(toDate,fromDate)=1 " + + " union " + + " select jbry,ksrq,kssj,jsrq,jssj,szbm " + + " from formtable_main_76 a,formtable_main_76_dt1 b " + + " where a.id=b.mainid and ksrq like '"+currentMonth+"%' " + + " and datediff(jsrq,ksrq)=1 "; + rs.executeQuery(sql); + while(rs.next()){ + String resourceId = Util.null2String(rs.getString("resourceId")); + String fromDate = Util.null2String(rs.getString("fromDate")); + String fromTime = Util.null2String(rs.getString("fromTime")); + String toDate = Util.null2String(rs.getString("toDate")); + String toTime = Util.null2String(rs.getString("toTime")); + + boolean isHoliday = false; + int changeType = KQHolidaySetBiz.getChangeType("2",fromDate); + if (changeType != 2 && (DateUtil.getWeek(fromDate) == 6 || DateUtil.getWeek(fromDate) == 7)) { + isHoliday = true; + } + if (changeType == 1 || changeType == 3) { + isHoliday = true; + } + + if(isHoliday){ + //计算上班打卡时间 + String startTime = minusHour(fromTime,timescope); + String endTime = addHour(fromTime,timescope); + String signinTime = getSigninTime(resourceId,fromDate,startTime,endTime); + + //计算下班打卡时间 + startTime = minusHour(toTime,2); + endTime = addHour(toTime,2); + String signoutTime = getSignoutTime(resourceId,toDate,startTime,endTime); + + String updateSql = " update kq_format_detail set signindate=?,signintime=?, signoutdate=?,signouttime=? where kqdate=? "; + rs2.executeUpdate(updateSql,fromDate,signinTime,toDate,signoutTime,fromDate); + + } + + } + + } + + + /** + * 获取上班打卡时间 + * @param userid + * @param signdate + * @param startTime + * @param endTime + * @return + */ + public String getSigninTime(String userid,String signdate,String startTime,String endTime){ + String signtime = ""; + RecordSet rs = new RecordSet(); + String sql = " select min(signtime) signtime from hrmschedulesign " + + "where userid=? and signdate=? and signtime>=? and signtime<=? "; + rs.executeQuery(sql,userid,signdate,startTime,endTime); + if(rs.next()){ + signtime = Util.null2String(rs.getString("signtime")); + } + return signtime; + } + + + /** + * 获取下班打卡时间 + * @param userid + * @param signdate + * @param startTime + * @param endTime + * @return + */ + public String getSignoutTime(String userid,String signdate,String startTime,String endTime){ + String signtime = ""; + RecordSet rs = new RecordSet(); + String sql = " select max(signtime) signtime from hrmschedulesign " + + "where userid=? and signdate=? and signtime>=? and signtime<=? "; + rs.executeQuery(sql,userid,signdate,startTime,endTime); + if(rs.next()){ + signtime = Util.null2String(rs.getString("signtime")); + } + return signtime; + } + + + /** + * 时间加 + * @param time + * @param hour + * @return + */ + public String addHour(String time,long hour){ + DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm"); + LocalTime localTime = LocalTime.parse(time,dtf).plusHours(hour); + return localTime.toString(); + } + + /** + * 时间减 + * @param time + * @param hour + * @return + */ + public String minusHour(String time,long hour){ + DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm"); + LocalTime localTime = LocalTime.parse(time,dtf).minusHours(hour); + return localTime.toString(); + } + + +} diff --git a/src/weaver/interfaces/hansang/job/ParentalLeaveCalculateJob.java b/src/weaver/interfaces/hansang/job/ParentalLeaveCalculateJob.java new file mode 100644 index 0000000..c78ab3d --- /dev/null +++ b/src/weaver/interfaces/hansang/job/ParentalLeaveCalculateJob.java @@ -0,0 +1,142 @@ +package weaver.interfaces.hansang.job; + + +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.interfaces.schedule.BaseCronJob; + +import java.text.DecimalFormat; +import java.time.format.DateTimeFormatter; + +/** + * @author wanxq + * @date 2023年08月17日14:17:51 + * @desc + */ +public class ParentalLeaveCalculateJob extends BaseCronJob { + + @Override + public void execute() { + + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + DecimalFormat df = new DecimalFormat("#.00"); + //当前日期减出生日期小于3年才计算育儿假 + RecordSet rs = new RecordSet(); + String sql = " select ry,csrq,xm,DATE_ADD(csrq, INTERVAL 3 YEAR) jsrq,companystartdate " + + " from uf_jt a " + + " left join hrmresource b on a.ry=b.id " + + " where gx=2 and DATE_ADD(csrq, INTERVAL 3 YEAR) >=curdate() order by csrq and status<=3 "; + rs.executeQuery(sql); + while (rs.next()){ + String ry = Util.null2String(rs.getString("ry")); + String csrq = Util.null2String(rs.getString("csrq")); + String jsrq = Util.null2String(rs.getString("jsrq")); + String companystartdate = Util.null2String(rs.getString("companystartdate")); + + + + String birthYear = csrq.substring(0,4); + String endYear = jsrq.substring(0,4); + String currentYear = DateUtil.getYear(); + + String currentYearFirstDay = DateUtil.getFirstDayOfYear(); + String currentYearLastDay = DateUtil.getLastDayOfYear(); + + double jqts = 0; + + // companystartdate: 2023-03-13 csrq:2023-06-01 + + //入职日期小于子女出生日期,育儿假基数:当前年12月31日减子女出生日期/365*10为育儿假基数(天) + if(DateUtil.compDate(csrq,companystartdate)<0){ + if(birthYear.equals(currentYear)){ + int diffDays = DateUtil.dayDiff(currentYearLastDay,csrq); + jqts = Double.valueOf(df.format((double)diffDays/365*10)); + }else if(endYear.equals(currentYear)){ + int diffDays = DateUtil.dayDiff(jsrq,currentYearFirstDay); + jqts = Double.valueOf(df.format((double)diffDays/365*10)); + }else{ + jqts = 10; + } + + }else{//入职日期大于等于子女出生日期,育儿假基数:当前年12月31日减入职日期/365*10为育儿假基数(天) + if(birthYear.equals(currentYear)){ + int diffDays = DateUtil.dayDiff(currentYearLastDay,companystartdate); + jqts = Double.valueOf(df.format((double)diffDays/365*10)); + }else if(endYear.equals(currentYear)){ + int diffDays = DateUtil.dayDiff(jsrq,currentYearFirstDay); + jqts = Double.valueOf(df.format((double)diffDays/365*10)); + }else{ + jqts = 10; + } + + } + rs.writeLog("ry==>"+ry+" csrq=>"+csrq+" jsrq==>"+jsrq+" companystartdate=>"+companystartdate+" jqts==>"+jqts); + setLeaveTypeDays(ry,jqts,currentYear); + } + } + + /** + * 设置人员的育儿假天数 + * @param ry + * @param jqts + * @param belongyear + */ + public void setLeaveTypeDays(String ry, double jqts,String belongyear) { + RecordSet rs = new RecordSet(); + String sql = " update kq_balanceofleave set baseAmount=? " + + " where leaveRulesId=? and resourceId=? and belongyear=? "; + rs.writeLog("setLeaveTypeDays sql==>"+sql+" jqts==>"+jqts+" ry==>"+ry+" belongyear==>"); + rs.executeUpdate(sql,jqts,36,ry,belongyear); + } + + + public static void main(String[] args) { + DecimalFormat df = new DecimalFormat("#.00"); + double jqts = 0; + + String ry = "601"; + String csrq = "2021-06-29"; + String jsrq = "2024-06-29"; + String companystartdate = "2011-03-21"; + + String birthYear = csrq.substring(0,4); + String endYear = jsrq.substring(0,4); + String currentYear = DateUtil.getYear(); + + String currentYearFirstDay = DateUtil.getFirstDayOfYear(); + String currentYearLastDay = DateUtil.getLastDayOfYear(); + + + // companystartdate: 2023-03-13 csrq:2023-06-01 + + //入职日期小于子女出生日期,育儿假基数:当前年12月31日减子女出生日期/365*10为育儿假基数(天) + if(DateUtil.compDate(csrq,companystartdate)<0){ + if(birthYear.equals(currentYear)){ + int diffDays = DateUtil.dayDiff(currentYearLastDay,csrq); + jqts = Double.valueOf(df.format((double)diffDays/365*10)); + }else if(endYear.equals(currentYear)){ + int diffDays = DateUtil.dayDiff(jsrq,currentYearFirstDay); + jqts = Double.valueOf(df.format((double)diffDays/365*10)); + }else{ + jqts = 10; + } + + }else{//入职日期大于等于子女出生日期,育儿假基数:当前年12月31日减入职日期/365*10为育儿假基数(天) + if(birthYear.equals(currentYear)){ + int diffDays = DateUtil.dayDiff(currentYearLastDay,companystartdate); + jqts = Double.valueOf(df.format((double)diffDays/365*10)); + }else if(endYear.equals(currentYear)){ + int diffDays = DateUtil.dayDiff(jsrq,currentYearFirstDay); + jqts = Double.valueOf(df.format((double)diffDays/365*10)); + }else{ + jqts = 10; + } + + } + System.out.println(jqts); + } + + + +} diff --git a/src/weaver/interfaces/hansang/job/RecommendBonusCalculateJob.java b/src/weaver/interfaces/hansang/job/RecommendBonusCalculateJob.java new file mode 100644 index 0000000..c58d9dd --- /dev/null +++ b/src/weaver/interfaces/hansang/job/RecommendBonusCalculateJob.java @@ -0,0 +1,154 @@ +package weaver.interfaces.hansang.job; + + +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.formmode.setup.ModeRightInfo; +import weaver.general.TimeUtil; +import weaver.general.Util; +import weaver.interfaces.schedule.BaseCronJob; + +import java.util.UUID; + +/** + * @author wanxq + * @date 2023年08月08日15:30:32 + * @desc 内推奖金计算 + */ +public class RecommendBonusCalculateJob extends BaseCronJob { + + + @Override + public void execute() { + RecordSet rs = new RecordSet(); + String sql = "select distinct c.field73 from hrmresource b left join cus_fielddata c on b.id= c.id \n" + + "where status<=3 and c.field73 is not null and c.field35 in(2,3) and c.SCOPEID = -1"; + rs.execute(sql); + while(rs.next()){ + //推荐人 + int userid = Util.getIntValue(rs.getString("field73")); + calBonus(userid); + } + } + + /** + * 计算推荐人奖金 + * @param userid + */ + public void calBonus(int userid){ + try { + double tjje = 0; + RecordSet rs = new RecordSet(); + String lastMonthEndDay = TimeUtil.getLastMonthEndDay(); + //若推荐人为(陈涛、笪莹、徐奇3位HRBP),则只发放一次满60天的奖金 + boolean ishrbp = isHrbp(userid); + String sql = " select a.id,companystartdate,certificatenum from cus_fielddata a,hrmresource b " + + " where a.id=b.id and status<=3 and datediff('"+lastMonthEndDay+"',companystartdate)>=60 and field73=? "; + rs.executeQuery(sql,userid); + while(rs.next()){ + int id = Util.getIntValue(rs.getString("id")); + String certificatenum = Util.null2String(rs.getString("certificatenum")); + String companyStartDate = Util.null2String(rs.getString("companystartdate")); + + int days = DateUtil.dayDiff(companyStartDate,lastMonthEndDay)+1; + int cs = (days/30)-1; + String entryDate = DateUtil.addDate(lastMonthEndDay,-180); + int entryTimes = getEntryTimes(certificatenum,entryDate); + if(ishrbp){ + if(cs==1 && entryTimes<=1){ + tjje += 200; + } + }else{ + if(cs>0 && cs<=36 && entryTimes<=1){ + tjje += 200; + } + } + } + + if(tjje>0){ + //更新内推机制表 + String month = lastMonthEndDay.substring(0,7); + insertData(userid,tjje,month); + } + + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + public void insertData(int userid,double tjje,String month){ + RecordSet rs = new RecordSet(); + //删除建模表中当前算薪月的数据 + rs.executeUpdate("delete from uf_ntjz where tjr=? and xzszy=? ",userid,month); + + int formmodeid = getModeIdByName("内推机制"); + String modeuuid = UUID.randomUUID().toString(); + int modedatacreater = 1; + String modedatacreatedate = TimeUtil.getCurrentDateString(); + String modedatacreatetime = TimeUtil.getOnlyCurrentTimeString(); + String insertSql = " insert into uf_ntjz(xzszy,tjr,tjje,xzszyqsrq,formmodeid,modedatacreater,modedatacreatedate," + + "modedatacreatetime,modeuuid) values(?,?,?,?,?,?,?,?,?) "; + rs.executeUpdate(insertSql,month,userid,tjje,month+"-01", + formmodeid,modedatacreater,modedatacreatedate,modedatacreatetime,modeuuid); + + rs.executeQuery("select id from uf_ntjz where modeuuid=?",modeuuid); + rs.next(); + int id = rs.getInt("id"); + if(id>0){ + ModeRightInfo right = new ModeRightInfo(); + right.editModeDataShare(userid, formmodeid, id); + } + + } + + + /** + * 根据建模名称获取建模id,建模权限同步的使用 + * @param modeName 建模名称 + * @return int 建模id + */ + public static int getModeIdByName(String modeName){ + RecordSet rs = new RecordSet(); + String sql = " SELECT ID FROM MODEINFO WHERE MODENAME = ? "; + rs.executeQuery(sql, modeName); + if (rs.next()) { + return rs.getInt("id"); + } + return -1; + } + + + /** + * 查询180天入职次数 + * @param idCard + * @param companyStartDate + * @return + */ + public int getEntryTimes(String idCard,String companyStartDate){ + int entryTimes = 0; + RecordSet rs = new RecordSet(); + String sql = " select count(1) cs from hrmresource where certificatenum=? and companystartdate>=? "; + rs.executeQuery(sql,idCard,companyStartDate); + if(rs.next()){ + entryTimes = Util.getIntValue(rs.getString("cs"),0); + } + return entryTimes; + } + + /** + * 判断是否是HRBP + * @param resourceid + * @return + */ + public boolean isHrbp(int resourceid){ + RecordSet rs = new RecordSet(); + rs.executeQuery(" select 1 from hrmroles a,hrmrolemembers b where a.id=b.roleid and rolesmark='推荐机制_HRBP' and resourceid=? ",resourceid); + return rs.next(); + } + + + + +} diff --git a/src/weaver/interfaces/hansang/job/RegularDaysCalculateJob.java b/src/weaver/interfaces/hansang/job/RegularDaysCalculateJob.java new file mode 100644 index 0000000..b0e06b6 --- /dev/null +++ b/src/weaver/interfaces/hansang/job/RegularDaysCalculateJob.java @@ -0,0 +1,152 @@ +package weaver.interfaces.hansang.job; + + +import com.engine.kq.biz.KQHolidaySetBiz; +import com.engine.kq.biz.KQWorkTime; +import com.weaver.formmodel.util.DateHelper; +import org.apache.commons.lang.StringUtils; +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.formmode.setup.ModeRightInfo; +import weaver.general.BaseBean; +import weaver.general.TimeUtil; +import weaver.general.Util; +import weaver.interfaces.schedule.BaseCronJob; + +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; +import java.util.UUID; + +/** + * @author wanxq + * @date 2023年07月24日14:32:09 + * @desc + */ +public class RegularDaysCalculateJob extends BaseCronJob { + + private BaseBean log = new BaseBean(); + + private String salaryMonth; + + + public void setMonth(String salaryMonth) { + this.salaryMonth = salaryMonth; + } + + @Override + public void execute() { + if(StringUtils.isBlank(salaryMonth)){ + salaryMonth = DateHelper.getCurrentMonth(); + } + + KQWorkTime kqWorkTime = new KQWorkTime(); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + RecordSet rs = new RecordSet(); + + String sql = " select id,field18 from cus_fielddata " + + "where scopeid=3 and scope='HrmCustomFieldByInfoType' and field18 like '"+salaryMonth+"%' "; + rs.executeQuery(sql); + while(rs.next()){ + int userid = rs.getInt("id"); + LocalDate regularDate = LocalDate.parse(Util.null2String(rs.getString("field18")),formatter); + + double workdays = 0; + if(regularDate.toString().equals(salaryMonth+"-01")){ + workdays = 0; + }else { + //判断是法定节假日前还是后 + LocalDate workStartDate = LocalDate.parse(salaryMonth+"-01",formatter); + long daysDiff = ChronoUnit.DAYS.between(workStartDate, regularDate); + for(int i=0;i"+userid+" tempdate==>"+tempdate+" changeType==>"+changeType+" isWeekend==>"+isWeekend); + + if(changeType==-1 && !isWeekend){ + workdays ++; + log.writeLog("RegularDaysCalculateJob userid==>"+userid+" workday==>"+tempdate); + } + + if(changeType==1 || changeType==2){ + workdays ++; + log.writeLog("RegularDaysCalculateJob userid==>"+userid+" workday==>"+tempdate); + } + + } + } + insertData(userid,workdays); + } + + } + + public void insertData(int userid,double workdays){ + RecordSet rs = new RecordSet(); + //删除建模表中当前算薪月的数据 + rs.executeUpdate("delete from uf_zzts where xzszy=? and ryid=? ",salaryMonth,userid); + + int formmodeid = getModeIdByName("转正天数"); + String modeuuid = UUID.randomUUID().toString(); + int modedatacreater = userid; + String modedatacreatedate = TimeUtil.getCurrentDateString(); + String modedatacreatetime = TimeUtil.getOnlyCurrentTimeString(); + String insertSql = " insert into uf_zzts(ryid,zzts,xzszy,formmodeid,modedatacreater,modedatacreatedate," + + "modedatacreatetime,modeuuid) values(?,?,?,?,?,?,?,?) "; + rs.executeUpdate(insertSql,userid,workdays,salaryMonth, + formmodeid,modedatacreater,modedatacreatedate,modedatacreatetime,modeuuid); + + rs.executeQuery("select id from uf_zzts where modeuuid=?",modeuuid); + rs.next(); + int id = rs.getInt("id"); + if(id>0){ + ModeRightInfo right = new ModeRightInfo(); + right.editModeDataShare(userid, formmodeid, id); + } + + } + + /** + * 获取离职日期前的节假日天数 + * @param salaryMonth + * @param leaveDate + * @return + */ + public int getHolidayDays(String salaryMonth,LocalDate leaveDate){ + int holidayDays = 0; + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + RecordSet rs = new RecordSet(); + String sql = " select holidaydate from kq_HolidaySet where groupid=1 and changetype=1 and holidaydate like '"+salaryMonth+"%' "; + rs.execute(sql); + while (rs.next()){ + LocalDate holidaydate = LocalDate.parse(Util.null2String(rs.getString("holidaydate")),formatter); + + if(leaveDate.isAfter(holidaydate)){ + holidayDays++; + } + } + return holidayDays; + } + + + /** + * 根据建模名称获取建模id,建模权限同步的使用 + * @param modeName 建模名称 + * @return int 建模id + */ + public static int getModeIdByName(String modeName){ + RecordSet rs = new RecordSet(); + String sql = " SELECT ID FROM MODEINFO WHERE MODENAME = ? "; + rs.executeQuery(sql, modeName); + if (rs.next()) { + return rs.getInt("id"); + } + return -1; + } + + + + +} diff --git a/src/weaver/interfaces/hansang/job/SalaryTaxMemSynJob.java b/src/weaver/interfaces/hansang/job/SalaryTaxMemSynJob.java new file mode 100644 index 0000000..b4a4da6 --- /dev/null +++ b/src/weaver/interfaces/hansang/job/SalaryTaxMemSynJob.java @@ -0,0 +1,107 @@ +package weaver.interfaces.hansang.job; + + +import dm.jdbc.util.IdGenerator; +import weaver.conn.RecordSet; +import weaver.general.TimeUtil; +import weaver.general.Util; +import weaver.interfaces.schedule.BaseCronJob; + +/** + * @author wanxq + * @date 2023年08月01日10:26:38 + * @desc 定时同步个税扣缴义务人 + */ +public class SalaryTaxMemSynJob extends BaseCronJob { + + private String selectMonth; + + + @Override + public void execute() { + + + RecordSet rs = new RecordSet(); + RecordSet rs2 = new RecordSet(); + + //查询上月入职人员 + String lastMonth = TimeUtil.getLastMonthEndDay().substring(0,7); + if(selectMonth!=null && !"".equals(selectMonth)){ + lastMonth = selectMonth; + } + + + String sql = " select a.id,companystartdate,subcompanyid1,field35 from hrmresource a,cus_fielddata b " + + " where companystartdate like '"+lastMonth+"%' " + + " and a.id=b.id and field35 is not null"; + rs.writeLog("SalaryTaxMemSynJob sql====>"+sql); + rs.execute(sql); + while(rs.next()){ + int userid = rs.getInt("id"); + int subcomid = rs.getInt("subcompanyid1"); + int field35 = rs.getInt("field35"); + Long id = IdGenerator.generate(); + + int tax_agent_id = -1; + /* + ① 直/间接 等于 办公加班月结、办公加班非月结 且 分部 等于 汉桑(南京)科技股份有限公司 时,人员同步至 (办公)-汉桑(南京)科技股份有限公司 账套中。 + ② 直/间接 等于 制造人员、劳务人员、临时工 且 分部 等于 汉桑(南京)科技股份有限公司 时,人员同步至 (非办公)-汉桑(南京)科技股份有限公司 账套中。 + ③ 直/间接 等于 办公加班月结、办公加班非月结 且 分部 等于 南京音范影音科技有限公司 时,人员同步至 南京音范影音科技有限公司 账套中。 + */ + if(field35==0 || field35==1){ + if(subcomid==4){ + tax_agent_id = 1; + }else{ + tax_agent_id = 2; + } + }else{ + if(subcomid==4){ + tax_agent_id = 4; + } + } + + //判断是当前人员否存在账套中 + String existSql = " select id from hrsa_tax_agent_manage_range " + + " where tax_agent_id=? and delete_type=0 " + + " and target_id=? and target_type=1 and include_type=1 "; + rs2.executeQuery(existSql,tax_agent_id,userid); + String currentime = TimeUtil.getCurrentTimeString(); + if(rs2.next()){ + String dataid = Util.null2String(rs.getString("id")); + String updateSql = " update hrsa_tax_agent_manage_range set employee_status=?,update_time=? where id=? "; + rs2.executeUpdate(updateSql,"[\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\"]",currentime,dataid); + + }else{ + String insertSql = " insert into hrsa_tax_agent_manage_range(id,tax_agent_id,employee_id,tax_agent_sub_admin_id," + + "target_type,target_id,employee_status,include_type,creator,create_time,update_time,delete_type,tenant_key,range_type) " + + "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + rs2.executeUpdate(insertSql,new Object[]{id,tax_agent_id,0,0,1,userid,"[\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\"]", + 1,1,currentime,currentime,0,"all_teams",1}); + } + } + } + + + /** + * 判断个税扣缴义务人是否在当前账套中 + * @param userid + * @param taxAgentId + * @return + */ + public boolean isExist(int userid,int taxAgentId){ + RecordSet rs = new RecordSet(); + String sql = " select id from hrsa_tax_agent_manage_range " + + " where tax_agent_id=? and delete_type=0 " + + " and target_id=? and target_type=1 and include_type=1 "; + rs.executeQuery(sql,taxAgentId,userid); + return rs.next(); + } + + public String getSelectMonth() { + return selectMonth; + } + + public void setSelectMonth(String selectMonth) { + this.selectMonth = selectMonth; + } +} diff --git a/src/weaver/interfaces/hansang/job/SickLeaveSalaryCalculateJob.java b/src/weaver/interfaces/hansang/job/SickLeaveSalaryCalculateJob.java new file mode 100644 index 0000000..b53ab55 --- /dev/null +++ b/src/weaver/interfaces/hansang/job/SickLeaveSalaryCalculateJob.java @@ -0,0 +1,212 @@ +package weaver.interfaces.hansang.job; + + +import com.engine.kq.biz.KQWorkTime; +import org.apache.commons.lang.StringUtils; +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.formmode.setup.ModeRightInfo; +import weaver.general.TimeUtil; +import weaver.general.Util; +import weaver.interfaces.schedule.BaseCronJob; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +/** + * @author wanxq + * @date 2023年08月07日14:22:14 + * @desc 病假薪资比例计算 + */ +public class SickLeaveSalaryCalculateJob extends BaseCronJob { + private String salaryMonth; + + public String getSalaryMonth() { + return salaryMonth; + } + + public void setSalaryMonth(String salaryMonth) { + this.salaryMonth = salaryMonth; + } + + @Override + public void execute() { + RecordSet rs = new RecordSet(); + String fromDate = DateUtil.getFirstDayOfMonthToString(); + String toDate = DateUtil.getLastDayOfMonthToString(); + + if(StringUtils.isNotBlank(salaryMonth)){ + fromDate = DateUtil.getFirstDayOfMonth(this.salaryMonth+"-01"); + toDate = DateUtil.getLastDayOfMonth(this.salaryMonth+"-01"); + } + + //查询算薪月有请病假的人员 + String sql = " select distinct resourceid from kq_flow_split_leave \n" + + " where newleavetype in(4,27) and belongdate >=? and belongdate<=? "; + rs.executeQuery(sql,fromDate,toDate); + while(rs.next()){ + int userid = Util.getIntValue(rs.getString("resourceid")); + calContinueLeaveDays(userid,fromDate,toDate); + } + } + + + /** + * 查询人员的病假信息 + * @param resourceid + * @param calEndDate + * @return + */ + public Map getLeaveInfo(int resourceid,String calEndDate){ + Map leaveInfo = new HashMap<>(); + String calStartDate = TimeUtil.getDateString(DateUtil.addMonth(TimeUtil.getCalendar(calEndDate),-7)); + RecordSet rs = new RecordSet(); + String sql = " select belongdate,requestid from kq_flow_split_leave " + + " where resourceid=? and belongdate >=? and belongdate<=? and newleavetype in(4,27) "; + rs.executeQuery(sql,resourceid,calStartDate,calEndDate); + while(rs.next()){ + String belongdate = Util.null2String(rs.getString("belongdate")); + String requestid = Util.null2String(rs.getString("requestid")); + leaveInfo.put(belongdate,requestid); + } + return leaveInfo; + } + + public void calContinueLeaveDays(int resourceid,String salaryFirstDate,String salaryLastDate){ + //查询算薪月最后一次请假日期 + RecordSet rs = new RecordSet(); + String sql = " select max(belongdate) lastdate from kq_flow_split_leave " + + " where resourceid=? and belongdate >=? and belongdate<=? "; + rs.executeQuery(sql,resourceid,salaryFirstDate,salaryLastDate); + if(rs.next()){ + String lastDate = Util.null2String(rs.getString("lastdate")); + //查询从请假日开始往期6个月的请假信息 + Map leaveInfo = getLeaveInfo(resourceid,lastDate); + + double level = 0; + for(int i=1;i<7;i++){ + String calStartDate = TimeUtil.getDateString(DateUtil.addMonth(TimeUtil.getCalendar(lastDate),-1)); + double leaveRate = getLeaveRate(resourceid,calStartDate,lastDate,leaveInfo); + rs.writeLog("SickLeaveSalaryCalculateJob resourceid==》"+resourceid+" calStartDate==>"+calStartDate+" calEndDate==>"+lastDate+" leaveRate==>"+leaveRate); + level += leaveRate; + if(leaveRate!=1){ + break; + } + lastDate = calStartDate; + } + + //如果满6个月要判断是否是6个月以上(往前找到第一个工作日判断是否是请假) + if(level==6){ + KQWorkTime kqWorkTime = new KQWorkTime(); + boolean flag = true; + while(flag){ + lastDate = DateUtil.addDate(lastDate,-1); + boolean isWorkDay = kqWorkTime.isWorkDay(resourceid + "", lastDate); + if(isWorkDay){ + flag = false; + } + rs.writeLog(" lastdate==>"+lastDate+" isWorkDay==>"+isWorkDay); + } + if(leaveInfo.containsKey(lastDate)){ + level ++; + } + } + + double kkbl = 0; + if(level<=1){ + kkbl = 0.3; + }else if(level<=3){ + kkbl = 0.4; + }else if(level<=6){ + kkbl = 0.5; + }else{ + kkbl = 1; + } + + //更新病假扣款比例表 + String month = salaryLastDate.substring(0,7); + insertData(resourceid,kkbl,month); + } + + } + + /** + * 判断日期区间内是否连续休病假 + * @param resourceid + * @param fromDate + * @param toDate + * @param leaveInfo + * @return + */ + public double getLeaveRate(int resourceid,String fromDate,String toDate,Map leaveInfo){ + double leaveRate = 0; + KQWorkTime kqWorkTime = new KQWorkTime(); + int workdays = 0; + int leavedays = 0; + boolean interrupt = false; + int diffdays = DateUtil.dayDiff(fromDate,toDate); + for(int i=0;i0){ + ModeRightInfo right = new ModeRightInfo(); + right.editModeDataShare(userid, formmodeid, id); + } + + } + + + /** + * 根据建模名称获取建模id,建模权限同步的使用 + * @param modeName 建模名称 + * @return int 建模id + */ + public static int getModeIdByName(String modeName){ + RecordSet rs = new RecordSet(); + String sql = " SELECT ID FROM MODEINFO WHERE MODENAME = ? "; + rs.executeQuery(sql, modeName); + if (rs.next()) { + return rs.getInt("id"); + } + return -1; + } + + +} diff --git a/src/weaver/interfaces/hansang/job/UserCardInfoUpdateJob.java b/src/weaver/interfaces/hansang/job/UserCardInfoUpdateJob.java new file mode 100644 index 0000000..54869d7 --- /dev/null +++ b/src/weaver/interfaces/hansang/job/UserCardInfoUpdateJob.java @@ -0,0 +1,94 @@ +package weaver.interfaces.hansang.job; + + +import weaver.conn.RecordSet; +import weaver.interfaces.schedule.BaseCronJob; + +/** + * @author wanxq + * @date 2023年09月19日09:44:44 + * @desc 自动更新人员卡片信息 + */ +public class UserCardInfoUpdateJob extends BaseCronJob { + + + @Override + public void execute() { + RecordSet rs = new RecordSet(); + + //更新成本中心、成本中心名称 + String cbzxsql = " update cus_fielddata a, hrmresource b,hrmdepartmentdefined c set a.field117 = c.cbbmdmcw,a.field118=c.cbbmcw " + + " where a.id = b.id and b.departmentid=c.deptid and a.scopeid=3 and a.scope='hrmcustomfieldbyinfotype' and b.status<=3 " + + " and (a.field117 is null or a.field117='' or a.field118 is null or a.field118='') "; + rs.executeUpdate(cbzxsql); + + //更新人员卡片中文名字段 + String xmsql = " update cus_fielddata a, hrmresource b " + + " set a.field116 = substr(b.lastname,instr(b.lastname,'-')+1) " + + " where a.id = b.id and a.scopeid=-1 and a.scope='hrmcustomfieldbyinfotype' and b.status<=3 and (a.field116 is null or a.field116='') "; + rs.executeUpdate(xmsql); + + //更新员工角色 根据直间接刷新:办公月结人员、办公非月结人员为Default,制造人员为制造人员,劳务人员为劳务人员 + String jssql = " update cus_fielddata a, hrmresource b set a.field37 = case when field35<=1 then 0 when field35=2 then 2 when field35=3 then 4 else null end " + + " where a.id = b.id and a.scopeid=-1 and a.scope='hrmcustomfieldbyinfotype' and b.status<=3 and (a.field37 is null or a.field37='') "; + rs.executeUpdate(jssql); + + //更新是否打卡,默认是 + String dksql = " update cus_fielddata a, hrmresource b set a.field112 = 0 " + + " where a.id = b.id and a.scopeid=3 and a.scope='hrmcustomfieldbyinfotype' and b.status<=3 and (a.field112 is null or a.field112='') "; + rs.executeUpdate(dksql); + + //更新参加工作日期:默认入职日期 + String workSql = " update hrmresource set workstartdate=companystartdate where status<=3 and (workstartdate is null or workstartdate='') "; + rs.executeUpdate(workSql); + + //更新试用期结束日期、转正日期:非办公默认入职日期加一个自然月 + String syqSql = " update cus_fielddata a, hrmresource b,cus_fielddata c set b.probationenddate = date_add(date_add(b.companystartdate,INTERVAL 1 MONTH), INTERVAL -1 DAY) " + + " where a.id = b.id and a.id=c.id and a.scopeid=3 and a.scope='hrmcustomfieldbyinfotype' " + + " and (a.field82>date_add(b.companystartdate,INTERVAL 1 MONTH) or a.field82 is null or a.field82='') "+ + " and c.field35 in(2,3,4) and (b.probationenddate is null or b.probationenddate='') "; + rs.executeUpdate(syqSql); + + //String zzrqSql = " update cus_fielddata a, hrmresource b,cus_fielddata c set a.field18 = date_add(b.companystartdate,INTERVAL 1 MONTH) " + + // " where a.id = b.id and a.id=c.id and a.scopeid=3 and a.scope='hrmcustomfieldbyinfotype' " + + // " and (a.field82>date_add(b.companystartdate,INTERVAL 1 MONTH) or a.field82 is null or a.field82='') "+ + // " and c.field35 in(2,3,4) and (a.field18 is null or a.field18='') "; + //rs.executeUpdate(zzrqSql); + + //更新社保缴纳地 默认:南京 + String sbsql = " update cus_fielddata a, hrmresource b set a.field114 = 1 " + + " where a.id = b.id and a.scopeid=1 and a.scope='hrmcustomfieldbyinfotype' and b.status<=3 and (a.field114 is null or a.field114='') "; + rs.executeUpdate(sbsql); + + //更新公积金缴纳地 默认:南京 + String gjjsql = " update cus_fielddata a, hrmresource b set a.field115 = 2 " + + " where a.id = b.id and a.scopeid=1 and a.scope='hrmcustomfieldbyinfotype' and b.status<=3 and (a.field115 is null or a.field115='') "; + rs.executeUpdate(gjjsql); + + //更新薪资岗位:根据岗位同步 + String xzgwsql = " update cus_fielddata a, hrmresource b set a.field72 = b.jobtitle " + + "where a.id = b.id and a.scopeid=1 and a.scope='hrmcustomfieldbyinfotype' and b.status<=3 and (a.field72 is nul or a.field72='') "; + rs.executeUpdate(xzgwsql); + + //更新人员年龄 + String ageSql = " update cus_fielddata a, hrmresource b set a.field136= floor(datediff(now(), birthday)/365) " + + "where a.id = b.id and a.scopeid=1 and a.scope='hrmcustomfieldbyinfotype' and b.status<=3 "; + rs.executeUpdate(ageSql); + + //更新个税扣缴义务人 + //当直/间接等于制造人员、劳务人员、临时工时且个税扣缴义务人为空时,个税扣缴义务人更新为:4:(非办公)汉桑(南京)科技股份有限公司 + String kjywrSql = " update cus_fielddata set field137=4 where scopeid=-1 and field35 in(2,3,4) and (field137='' or field137 is null) "; + rs.executeUpdate(kjywrSql); + + //更新薪资等级 +// String xzdjsql = "update cus_fielddata a, hrmresource b,cus_fielddata c set a.field67 = 3\n" + +// " where a.id = b.id and a.id = c.id and a.scopeid=1 and a.scope='hrmcustomfieldbyinfotype'\n" + +// " and b.status<=3 and c.field35 in(2,3,4) and (a.field67 is null or a.field67='')"; +// rs.executeUpdate(xzdjsql); + } + + + + + +} diff --git a/src/weaver/interfaces/hansang/util/ReportTransMethod.java b/src/weaver/interfaces/hansang/util/ReportTransMethod.java new file mode 100644 index 0000000..0bb53b2 --- /dev/null +++ b/src/weaver/interfaces/hansang/util/ReportTransMethod.java @@ -0,0 +1,65 @@ +package weaver.interfaces.hansang.util; + +import com.alibaba.fastjson.JSONObject; +import com.engine.kq.biz.KQReportBiz; +import com.engine.kq.util.KQDurationCalculatorUtil; +import weaver.general.Util; + +import java.util.HashMap; +import java.util.Map; + +/** + * @author wanxq + * @date 2023/7/10 + * @desc + */ +public class ReportTransMethod { + + public double getAttendanceMins(String deptid,String fromDate,String toDate){ + double attMins = 0.0; + + KQReportBiz kqReportBiz = new KQReportBiz(); + Map params = new HashMap<>(); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("isNoAccount","1"); + jsonObject.put("attendanceSerial",""); + jsonObject.put("status","9"); + jsonObject.put("viewScope","0"); + jsonObject.put("typeselect","6"); + jsonObject.put("fromDate",fromDate); + jsonObject.put("toDate",toDate); + params.put("data",jsonObject); + + //Map flowData = kqReportBiz.getDailyFlowData(params,user); + // + //String sql = "select a.id,a.lastname,b.subcompanyid, b.departmentid, a.workcode,b.jobtitle,a.dsporder," + + // " b.kqdate, b.workdays,b.workMins,b.serialid, b.attendancedays,b.attendanceMins," + + // " b.beLate,b.beLateMins,b.graveBeLate,b.graveBeLateMins,b.leaveEearly,b.leaveEarlyMins," + + // " b.signdays,b.signmins "+ + // " from hrmresource a, kq_format_total b " + + // " where a.id= b.resourceid and b.kqdate >='"+fromDate+"' and b.kqdate <='"+toDate+"' and b.departmentid=? "; + // + // + //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)); + // + + + return attMins; + } +} + diff --git a/src/weaver/interfaces/hskq/action/BmChangeAction.java b/src/weaver/interfaces/hskq/action/BmChangeAction.java new file mode 100644 index 0000000..d939012 --- /dev/null +++ b/src/weaver/interfaces/hskq/action/BmChangeAction.java @@ -0,0 +1,352 @@ + +package weaver.interfaces.hskq.action; + +import com.alibaba.fastjson.JSONObject; +import com.engine.common.util.ServiceUtil; +import com.engine.hrm.service.OrganizationService; +import com.engine.hrm.service.impl.OrganizationServiceImpl; +import com.engine.hrm.util.face.HrmFaceCheckManager; +import org.apache.commons.lang3.StringUtils; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.Util; +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.interfaces.workflow.action.Action; +import weaver.matrix.MatrixUtil; +import weaver.rtx.OrganisationCom; +import weaver.soa.workflow.request.Property; +import weaver.soa.workflow.request.RequestInfo; +import java.math.BigDecimal; +import java.text.SimpleDateFormat; +import java.util.*; + +/** + * 部门调整Action + */ +public class BmChangeAction implements Action { + + static String dateFormat = "yyyy-MM-dd"; + static SimpleDateFormat format = new SimpleDateFormat(dateFormat); + + public OrganizationService getOrganizationService(User user) { + return ServiceUtil.getService(OrganizationServiceImpl.class, user); + } + + public BmChangeAction() { + } + + @Override + public String execute(RequestInfo info) { + new BaseBean(); + BaseBean bb = new BaseBean(); + bb.writeLog("部门调整Action进入"); + RecordSet rs = new RecordSet(); + RecordSet rsDept = new RecordSet(); + int userid = info.getRequestManager().getUser().getUID(); + String wfid = info.getWorkflowid(); + String reqid = info.getRequestid(); + String tablaName = info.getRequestManager().getBillTableName(); + User userLcc = new User(1); + try { + //获取主表数据 + Map mainInfo = getMainInfo(info); + //操作类型 + String czlx = Util.null2String(mainInfo.get("czlx")); + //申请人 + String sqr = Util.null2String(mainInfo.get("sqr")); + + if("0".equals(czlx)){ + //新增 + String insertSql = "select bmjl,qc,jc,bmyw,bmbh,sjbm,szgs,xssx,bmzg,bmzj,cbbmdm,cbbmmc,bmjb,kqwy,zxwy,hrbp,qyrq,fcrq \n" + + "from "+tablaName+"_dt1 where mainid = (select id from "+tablaName+" where requestId = "+reqid+")"; + rs.executeQuery(insertSql); + while (rs.next()){ + //全称 + String qc = Util.null2String(rs.getString("qc")); + String jc = Util.null2String(rs.getString("jc")); + String bmyw = Util.null2String(rs.getString("bmyw")); + String sjbm = Util.null2String(rs.getString("sjbm")); + String bmzg = Util.null2String(rs.getString("bmzg")); + String bmzj = Util.null2String(rs.getString("bmzj")); + String cbbmdm = Util.null2String(rs.getString("cbbmdm")); + String cbbmmc = Util.null2String(rs.getString("cbbmmc")); + String bmjb = Util.null2String(rs.getString("bmjb")); + String kqwy = Util.null2String(rs.getString("kqwy")); + String zxwy = Util.null2String(rs.getString("zxwy")); + String hrbp = Util.null2String(rs.getString("hrbp")); + String qyrq = Util.null2String(rs.getString("qyrq")); + String fcrq = Util.null2String(rs.getString("fcrq")); + String xssx = Util.null2String(rs.getString("xssx")); + String bmjl = Util.null2String(rs.getString("bmjl")); + bb.writeLog("部门"+qc+"新增"); + Map deptParamMap = new HashMap<>(); + if (StringUtils.isEmpty(sjbm) || sjbm.equals("0")) { + deptParamMap.put("subcompanyid1", "4"); + } else { + rsDept.execute("SELECT subcompanyid1 FROM hrmdepartment WHERE id = " + sjbm); + if (rsDept.next()) { + deptParamMap.put("subcompanyid1", rsDept.getString("subcompanyid1")); + } + } + deptParamMap.put("departmentmark", jc); + deptParamMap.put("departmentname", qc); + deptParamMap.put("supdepid", sjbm); + deptParamMap.put("coadjutant", ""); + deptParamMap.put("departmentcode", ""); + deptParamMap.put("bmfzr", ""); + deptParamMap.put("showorder", xssx); + List errorList = new ArrayList<>(); + Map deptResultMap = getOrganizationService(userLcc).addDepartment(deptParamMap, userLcc); + if (!String.valueOf(deptResultMap.get("status")).equals("1")) { + info.getRequestManager().setMessagecontent((String) deptResultMap.get("message")); + bb.writeLog("部门表数据保存失败, 原因:" + deptResultMap.get("message")); + errorList.add(jc+"部门表数据新增失败:"+deptResultMap.get("message")); +// return Action.FAILURE_AND_CONTINUE; + } + String deptId = String.valueOf(deptResultMap.get("id")); + // 添加部门自定义表数据 + RecordSet deptDefinedRs = new RecordSet(); + deptDefinedRs.execute("DELETE FROM hrmdepartmentdefined WHERE DEPTID = " + deptId); + String deptDefinedSql = "INSERT INTO hrmdepartmentdefined (DEPTID, bmzj, bmjl, cbbmcw, cbbmdmcw , bmjb," + + "hrbp, zxwy, kqwy, qyrq, fcrq, bmyw, bmzg) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)"; + boolean deptDefinedResult = deptDefinedRs.executeUpdate(deptDefinedSql, deptId, bmzj, bmjl, cbbmmc, cbbmdm , bmjb, + hrbp, zxwy, kqwy, qyrq, fcrq, bmyw, bmzg); + bb.writeLog("部门自定义表保存结果:" + deptDefinedResult); + // 如果部门自定义表保存失败,则将已保存的部门表数据也删除 + if (!deptDefinedResult) { + info.getRequestManager().setMessagecontent(deptDefinedRs.getExceptionMsg()); + bb.writeLog("部门自定义表保存失败原因:" + deptDefinedRs.getExceptionMsg()); + deleteDeptById(deptId); + errorList.add(jc+"部门自定义表数据新增失败:"+deptDefinedRs.getExceptionMsg()); +// return Action.FAILURE_AND_CONTINUE; + } + //同步部门数据到矩阵 + MatrixUtil.updateDepartmentData(deptId); + if(errorList.size()>0){ + info.getRequestManager().setMessagecontent(JSONObject.toJSONString(errorList)); + bb.writeLog("部门新增存在失败的数据:" + JSONObject.toJSONString(errorList)); + return Action.FAILURE_AND_CONTINUE; + } + } + }else if("1".equals(czlx)){ + //封存 + Map result = new HashMap<>(); + List errorList = new ArrayList<>(); + String insertSql = "select bm,fcrq \n" + + "from "+tablaName+"_dt2 where mainid = (select id from "+tablaName+" where requestId = "+reqid+")"; + rs.executeQuery(insertSql); + while (rs.next()){ + String deptId = Util.null2String(rs.getString("bm")); + String fcrq = Util.null2String(rs.getString("fcrq")); + bb.writeLog("部门deptId"+deptId+"封存"); + result = cancel(deptId,userLcc,bb,fcrq); + if ("-1".equals(result.get("status"))) { + bb.writeLog("部门封存失败:" + result.get("message")); + errorList.add(result.get("message")); +// return Action.FAILURE_AND_CONTINUE; + } + } + if(errorList.size()>0){ + info.getRequestManager().setMessagecontent(JSONObject.toJSONString(errorList)); + bb.writeLog("部门封存存在失败的数据:" + JSONObject.toJSONString(errorList)); + return Action.FAILURE_AND_CONTINUE; + } + + }else if("2".equals(czlx)){ + //调整 + String insertSql = "select xssx,bm,bmjl,qc,jc,bmyw,bmbh,sjbm,ssgs,bbzg,bmzj,cbbmdm,cbbmmc,bmjb,kqwy,zzwy,hrbp,qyrq,fcrq \n" + + "from "+tablaName+"_dt3 where mainid = (select id from "+tablaName+" where requestId = "+reqid+")"; + rs.executeQuery(insertSql); + while (rs.next()){ + String deptId = Util.null2String(rs.getString("bm")); + String bmjl = Util.null2String(rs.getString("bmjl")); + String qc = Util.null2String(rs.getString("qc")); + String jc = Util.null2String(rs.getString("jc")); + String bmyw = Util.null2String(rs.getString("bmyw")); + String sjbm = Util.null2String(rs.getString("sjbm")); + String ssgs = Util.null2String(rs.getString("ssgs")); + String bbzg = Util.null2String(rs.getString("bbzg")); + String bmzj = Util.null2String(rs.getString("bmzj")); + String cbbmdm = Util.null2String(rs.getString("cbbmdm")); + String cbbmmc = Util.null2String(rs.getString("cbbmmc")); + String bmjb = Util.null2String(rs.getString("bmjb")); + String kqwy = Util.null2String(rs.getString("kqwy")); + String zzwy = Util.null2String(rs.getString("zzwy")); + String hrbp = Util.null2String(rs.getString("hrbp")); + String qyrq = Util.null2String(rs.getString("qyrq")); + String fcrq = Util.null2String(rs.getString("fcrq")); + String xssx = Util.null2String(rs.getString("xssx")); + bb.writeLog("部门调整deptId:"+deptId); + if(StringUtils.isNotBlank(deptId)){ + RecordSet updateRs = new RecordSet(); + String updateSql = "update hrmdepartment set DEPARTMENTMARK = ?, DEPARTMENTNAME = ?, SUBCOMPANYID1 = ?," + + "SUPDEPID = ?,modified = ?,modifier = ?,showorder = ? where id = ?"; + boolean deptUpdateCheck = updateRs.executeUpdate(updateSql,jc,qc,ssgs,sjbm,new Date(),sqr,xssx,deptId); + + updateSql = "update hrmdepartmentdefined set bmzj = ?, bmjl = ?, cbbmcw = ?," + + "cbbmdmcw = ?,bmjb = ?,hrbp = ?,zxwy = ?,kqwy = ?,qyrq = ?,fcrq = ?,bmyw = ?,bmzg = ? where deptid = ?"; + boolean deptDefinedCheck = updateRs.executeUpdate(updateSql,bmzj,bmjl,cbbmmc,cbbmdm,bmjb,hrbp,zzwy,kqwy,qyrq,fcrq,bmyw,bbzg,deptId); + bb.writeLog("deptUpdateCheck:"+deptUpdateCheck+"deptDefinedCheck:"+deptDefinedCheck); + //同步部门数据到矩阵 + MatrixUtil.updateDepartmentData(deptId); + } + } + } + } catch (Exception e) { + e.printStackTrace(); + bb.writeLog(e); + bb.writeLog("固定加班时长写入加班台账error" + e.getMessage()); + info.getRequestManager().setMessageid("2000"); + info.getRequestManager().setMessagecontent("固定加班时长写入加班台账error"); + return Action.FAILURE_AND_CONTINUE; + } + return Action.SUCCESS; + } + + /** + * @Description: 系统封存部门 + * @Author: liang.cheng + * @Date: 2023/6/13 2:42 PM + * @param: [id, user] + * @return: java.util.Map + */ + private Map cancel(String id,User user,BaseBean bb,String fcrq){ + Map retmap = new HashMap<>(); + try { + + 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",id+"部门下有在职的人员"); + 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", id+"部门存在下级部门"); + return retmap; + } + rs.executeSql("update hrmdepartment set canceled = '1', "+ DbFunctionUtil.getUpdateSetSql(rs.getDBType(),user.getUID())+" where id ="+ id); + DepartmentComInfo.removeCompanyCache(); + + OrganisationCom.deleteDepartment(Integer.valueOf(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); + + String updateSql = "update hrmdepartmentdefined set fcrq = '"+fcrq+"' where deptid = "+id; + boolean deptDefinedCheck = rs.executeSql(updateSql); + bb.writeLog("deptDefinedCheck:"+deptDefinedCheck); + } catch (Exception e) { + } + return retmap; + } + + /** + * 部门删除 + * @param deptId + */ + public static void deleteDeptById(String deptId){ + RecordSet rs = new RecordSet(); + String sql = "delete from hrmdepartment where id = ?"; + rs.executeUpdate(sql,deptId); + } + + /** + * 部门新建 + * @param reqid + */ + public static void insertDeptByWf(String reqid){ + + + + + + } + + + /** + * 获取主表数据 + * + * @param requestInfo + * @return + */ + private static Map getMainInfo(RequestInfo requestInfo) { + Map map = new HashMap(); + Property[] property = requestInfo.getMainTableInfo().getProperty(); + for (int i = 0; i < property.length; i++) { + map.put(property[i].getName().toLowerCase(), Util.null2String(property[i].getValue())); + } + return map; + } + + /** + * 提供精确的乘法运算。 + * + * @param v1 被加数 + * @param v2 加数 + * @return 两个参数的和 + */ + public static Double multiply(String v1, String v2) { + BigDecimal b1 = new BigDecimal(v1); + BigDecimal b2 = new BigDecimal(v2); + return b1.multiply(b2).doubleValue(); + } + + /** + * 提供精确的除法运算。 + * + * @param v1 被加数 + * @param v2 加数 + * @return 两个参数的和 + */ + public static Double divide(String v1, String v2) { + BigDecimal b1 = new BigDecimal(v1); + BigDecimal b2 = new BigDecimal(v2); + return b1.divide(b2, 2, BigDecimal.ROUND_HALF_UP).doubleValue(); + } + +} diff --git a/src/weaver/interfaces/hskq/action/DkCreateEveryDay.java b/src/weaver/interfaces/hskq/action/DkCreateEveryDay.java new file mode 100644 index 0000000..92cd303 --- /dev/null +++ b/src/weaver/interfaces/hskq/action/DkCreateEveryDay.java @@ -0,0 +1,114 @@ +package weaver.interfaces.hskq.action; + +import com.alibaba.fastjson.JSON; +import weaver.common.DateUtil; +import weaver.conn.BatchRecordSet; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.Util; +import weaver.interfaces.schedule.BaseCronJob; +import java.util.*; + +/** + * Created with IntelliJ IDEA. + * 新入职员工当天打卡数据生成 + * @Auther: chenxu + * @Date: 2024/05/28/14:03 + * @Description: + */ +public class DkCreateEveryDay extends BaseCronJob { + + @Override + public void execute() { + new BaseBean(); + BaseBean bb = new BaseBean(); + RecordSet rs = new RecordSet(); + bb.writeLog("新入职员工当天打卡数据生成!!!"); + String nowdate = DateUtil.getCurrentDate(); + try { + String sql = "select id,lastname from hrmresource where companystartdate = CURDATE() and status <=3"; + rs.executeQuery(sql); + List> lsParams = new ArrayList<>(); + List lsFormatData = new ArrayList<>(); + while (rs.next()){ + Integer isimport = 1; + String userid = Util.null2String(rs.getString("id")); + Integer usertype = 1; + Integer isincom = 1; + String signfrom = "OutDataSourceSyn"; + String signDate = nowdate; + String signTime = "08:30:00"; + List params = new ArrayList<>(); + params.add(userid); + params.add(usertype); + params.add(signDate); + params.add(signTime); + params.add(""); + params.add(isincom); + params.add(isimport); + params.add(signfrom); + params.add(""); + params.add(""); + params.add(""); + 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,"","","","入职当天自动生成"); + bb.writeLog("isdelte:" + isdelte+"isok:"+isok); + } + + bb.writeLog("lsParams:"+JSON.toJSONString(lsParams)); + + List delParams = null; + List> lsDelParams = new ArrayList<>(); + //刷新报表数据 + for(int i=0;lsFormatData!=null&&i(); + delParams.add(formatData[0]); + delParams.add(formatData[1]); + delParams.add(formatData[2]); + lsDelParams.add(delParams); + } + bb.writeLog("lsDelParams:"+JSON.toJSONString(lsDelParams)); + + } catch (Exception e) { + e.printStackTrace(); + bb.writeLog(e); + bb.writeLog("新入职员工当天打卡数据生成--error"+e.getMessage()); + } + } + + + /** + * 删除 + * @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; + } +} diff --git a/src/weaver/interfaces/hskq/action/KqBaseInfoCreateEveryDay.java b/src/weaver/interfaces/hskq/action/KqBaseInfoCreateEveryDay.java new file mode 100644 index 0000000..ff91929 --- /dev/null +++ b/src/weaver/interfaces/hskq/action/KqBaseInfoCreateEveryDay.java @@ -0,0 +1,547 @@ +package weaver.interfaces.hskq.action; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.engine.common.util.ServiceUtil; +import com.engine.kq.biz.KQReportBiz; +import com.engine.kq.service.KQReportService; +import com.engine.kq.service.impl.KQReportServiceImpl; +import weaver.common.DateUtil; +import weaver.conn.BatchRecordSet; +import weaver.conn.RecordSet; +import weaver.formmode.setup.ModeRightInfo; +import weaver.general.BaseBean; +import weaver.general.TimeUtil; +import weaver.general.Util; +import weaver.hrm.User; +import weaver.interfaces.schedule.BaseCronJob; +import weaver.join.hrm.in.HrmResource; +import weaver.systeminfo.SystemEnv; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.*; + +/** + * Created with IntelliJ IDEA. + * 考勤每月汇总信息生成 + * @Auther: chenxu + * @Date: 2024/05/28/14:03 + * @Description: + */ +public class KqBaseInfoCreateEveryDay extends BaseCronJob { + + static String dateFormat = "yyyy-MM-dd"; + static SimpleDateFormat format = new SimpleDateFormat(dateFormat); + + private KQReportService getService(User user) { + return (KQReportService) ServiceUtil.getService(KQReportServiceImpl.class, user); + } + + @Override + public void execute() { + new BaseBean(); + BaseBean bb = new BaseBean(); + RecordSet rs = new RecordSet(); + bb.writeLog("考勤每月汇总信息生成!!!"); + String fromDate = TimeUtil.getDateByOption("3", "0"); + String toDate = fromDate.substring(0,7)+"-31"; + try { + Map apidatas = new HashMap(); + User userLcc = new User(1); + Map params = new HashMap(); + params.put("reportType","month"); + Map paramsData = new HashMap(); + paramsData.put("pageIndex",0); + paramsData.put("typeselect","3"); + paramsData.put("viewScope","0"); + paramsData.put("status","9"); + paramsData.put("isNoAccount","1"); + paramsData.put("attendanceSerial",""); + params.put("data",JSONObject.toJSONString(paramsData)); + apidatas = getService(userLcc).getKQReport(params, userLcc); +// bb.writeLog("apidatas:"+JSONObject.toJSONString(apidatas)); + JSONArray jsonArray = JSON.parseArray(Util.null2String(JSONObject.toJSONString(apidatas.get("datas")))); + bb.writeLog("jsonArray:"+JSONObject.toJSONString(jsonArray)); + for (Iterator iterator = jsonArray.iterator(); iterator.hasNext(); ) { + List> lsParams = new ArrayList<>(); + List> lsDelParams = new ArrayList<>(); + JSONObject next = (JSONObject) iterator.next(); + //人员id + String resourceId = next.getString("resourceId"); + //编号 + String workcode = next.getString("workcode"); + //岗位 + String jobtitleId = next.getString("jobtitleId"); + //部门编码 + String deptcode = next.getString("deptcode"); + //上级部门 + String supdept = next.getString("supdept"); + //部门 + String departmentId = next.getString("departmentId"); + //新增属性 + String ofr08name = next.getString("ofr08name"); + //直\间接 + String ofr07name = next.getString("ofr07name"); + //应出勤天数 + String workdays = next.getString("workdays"); + //应工作时长 + String workmins = next.getString("workmins"); + //实际出勤天数 + String attendancedays = next.getString("attendancedays"); + //实际工作时长 + String attendanceMins = next.getString("attendanceMins"); + //迟到次数 + String beLate = next.getString("beLate"); + //迟到时长 + String beLateMins = next.getString("beLateMins"); + //严重迟到 + String graveBeLate = next.getString("graveBeLate"); + //严重迟到时长 + String graveBeLateMins = next.getString("graveBeLateMins"); + //早退 + String leaveEearly = next.getString("leaveEearly"); + //早退时长 + String leaveEarlyMins = next.getString("leaveEarlyMins"); + //严重早退 + String graveLeaveEarly = next.getString("graveLeaveEarly"); + //严重早退时长 + String graveLeaveEarlyMins = next.getString("graveLeaveEarlyMins"); + //缺勤 + String absenteeism = next.getString("absenteeism"); + //缺勤时长 + String absenteeismMins = next.getString("absenteeismMins"); + //漏签 + String forgotCheck = next.getString("forgotCheck"); + //午餐次数 + String wucancishu = next.getString("wucancishu"); + //晚餐次数 + String jiabancishu = next.getString("jiabancishu"); + //午餐次数含夜班 + String jiabancishuYb = next.getString("jiabancishuYb"); + //晚餐次数含夜班 + String wucancishuYb = next.getString("wucancishuYb"); + //夜班次数 + String ybcs = next.getString("ybcs"); + //法定年假 + String fdnj = next.getString("leaveType_-6"); + //带薪病假 + String dxbj = next.getString("leaveType_4"); + //调休平时加班 + String txpsjb = next.getString("leaveType_5"); + //产假 + String cj = next.getString("leaveType_8"); + //陪产假 + String pcj = next.getString("leaveType_9"); + //福利年假 + String flnj = next.getString("leaveType_13"); + //小产假 + String xcj = next.getString("leaveType_14"); + //产检假 + String cjj = next.getString("leaveType_15"); + //调休周末加班 + String txzmjb = next.getString("leaveType_16"); + //产假刨妇产顺延 + String cjpfc = next.getString("leaveType_17"); + //产假多胞胎顺延 + String cjdbtsy = next.getString("leaveType_18"); + //三八节福利假 + String sbjflj = next.getString("leaveType_19"); + //特殊公出 + String tsgc = next.getString("leaveType_20"); + //放工假 + String fgj = next.getString("leaveType_21"); + //工伤假 + String gsj = next.getString("leaveType_22"); + //事假 + String sj = next.getString("leaveType_26"); + //病假 + String bj = next.getString("leaveType_27"); + //婚假 + String hj = next.getString("leaveType_32"); + //哺乳假 + String brj = next.getString("leaveType_34"); + //丧假 + String sangj = next.getString("leaveType_35"); + //育儿假 + String yrj = next.getString("leaveType_36"); + //独生子女护理假 + String dsznhlj = next.getString("leaveType_37"); + //工作日加班不关联调休 + String gzrjbno = next.getString("workingDayOvertime_nonleave"); + //工作日加班关联调休 + String gzrjb = next.getString("workingDayOvertime_4leave"); + //休息日加班不关联调休 + String xxrjbno = next.getString("restDayOvertime_nonleave"); + //休息日加班关联调休 + String xxrjb = next.getString("restDayOvertime_4leave"); + //节假日加班不关联调休 + String jjrjbno = next.getString("holidayOvertime_nonleave"); + //节假日加班关联调休 + String jjrjb = next.getString("holidayOvertime_4leave"); + //加班汇总 + String jbhz = next.getString("overtimeTotal"); + //出差 + String cc = next.getString("businessLeave"); + //公出 + String gc = next.getString("officialBusiness"); + + + bb.writeLog("userId:"+resourceId+"workdays:"+workdays); + KQReportBiz kqReportBiz = new KQReportBiz(); + Map detialDatas = kqReportBiz.getDetialDatasOnlyTime(resourceId, fromDate, toDate, userLcc); + Map detialOvtimeDatas = kqReportBiz.getDetialOvtimeData(resourceId, fromDate, toDate); + List data = new ArrayList<>(); + String today = DateUtil.getCurrentDate(); + bb.writeLog("detialDatas:"+JSONObject.toJSONString(detialDatas)+"detialOvtimeDatas:"+JSONObject.toJSONString(detialOvtimeDatas)); + List all = new ArrayList<>(); + all.add(fromDate); + List back = days(fromDate,toDate); + all.addAll(back); + all.add(toDate); + for(String date:all){ + if (DateUtil.compDate(today, date) > 0) { + data.add(""); + } else { + if (detialDatas.get(resourceId + "|" + date) != null) { + double atttime = Util.getDoubleValue((String) detialDatas.get(resourceId + "|" + date),0); + bb.writeLog("date:"+date+"atttime:"+atttime); + if(detialOvtimeDatas.get(resourceId + "|" + date) !=null ){ + atttime += (double) detialOvtimeDatas.get(resourceId + "|" + date); + bb.writeLog("atttimeNew:"+atttime); + } + data.add(atttime); + } else { + data.add(SystemEnv.getHtmlLabelName(26593, userLcc.getLanguage())); + } + } + } + bb.writeLog("dataText:"+JSONObject.toJSONString(data)); + List par = new ArrayList<>(); + List parDel = new ArrayList<>(); + par.add(resourceId); + par.add(workcode); + par.add(jobtitleId); + par.add(deptcode); + par.add(supdept); + par.add(departmentId); + par.add(ofr08name); + par.add(ofr07name); + par.add(workdays); + par.add(workmins); + par.add(attendancedays); + par.add(attendanceMins); + par.add(beLate); + par.add(beLateMins); + par.add(graveBeLate); + par.add(graveBeLateMins); + par.add(leaveEearly); + par.add(leaveEarlyMins); + par.add(graveLeaveEarly); + par.add(graveLeaveEarlyMins); + par.add(absenteeism); + par.add(absenteeismMins); + par.add(forgotCheck); + par.add(wucancishu); + par.add(jiabancishu); + par.add(jiabancishuYb); + par.add(wucancishuYb); + par.add(ybcs); + par.add(fdnj); + par.add(dxbj); + par.add(txpsjb); + par.add(cj); + par.add(pcj); + par.add(flnj); + par.add(xcj); + par.add(cjj); + par.add(txzmjb); + par.add(cjpfc); + par.add(cjdbtsy); + par.add(sbjflj); + par.add(tsgc); + par.add(fgj); + par.add(gsj); + par.add(sj); + par.add(bj); + par.add(hj); + par.add(brj); + par.add(sangj); + par.add(yrj); + par.add(dsznhlj); + par.add(gzrjbno); + par.add(xxrjbno); + par.add(jjrjbno); + par.add(gzrjb); + par.add(xxrjb); + par.add(jjrjb); + par.add(jbhz); + par.add(cc); + par.add(gc); + //年月 + String ny = fromDate.substring(0,7); + par.add(ny); + //入职日期 + String rzrq = findRzrq(resourceId); + //转正日期 + String zzrq = getField18(resourceId); + //离职日期 + String lzrq = getField82(resourceId); + par.add(rzrq); + par.add(zzrq); + par.add(lzrq); + //人员状态 + String ryzt = getStatus(resourceId); + par.add(ryzt); + //考勤月 + String kqy = ny+"-01"; + par.add(kqy); + //日历 + for (int i = 0; i < all.size(); i++) { + par.add(data.get(i)); + } + + + parDel.add(resourceId); + parDel.add(ny); + lsDelParams.add(parDel); + + BatchRecordSet bRs = new BatchRecordSet(); + bb.writeLog("开始同步数据"); + bb.writeLog("lsDelParams:"+JSON.toJSONString(lsDelParams)); + + String sql = ""; + //删除本次同步数据 + sql = " delete from uf_kqhzbx where xm = ? and ny = ?"; + bRs.executeBatchSql(sql, lsDelParams); + + int modeid = getFormModeIdByCubeName("uf_kqhzbx"); + SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd"); + SimpleDateFormat sdfTime = new SimpleDateFormat("HH:mm:ss"); + String modedatacreatedate = sdfDate.format(new java.util.Date()); + String modedatacreatetime = sdfTime.format(new Date()); + + par.add(modeid); + par.add(resourceId); + par.add("0"); + par.add(modedatacreatedate); + par.add(modedatacreatetime); + lsParams.add(par); + + sql = " insert into uf_kqhzbx (xm, bh, gw, bmbm, sjbm, bm, xzzx, zjj, ycqtst, ygzscxs, " + + "sjcqtst,sjgzscxs,cdc,cdscxs,yzcdc,yzcdscxs,ztc,ztscxs,yzztc,yzztscxs," + + "qqc,qqscxs,lqc,wuccsc,wanccsc,wuccshybc,wanccshybc,ybcsc,fdnjxs,flnjxs," + + "sjxs,dxbjt,bjt,hjt,sjt,xcjt,cjjt,pcjt,dxpsjbxs,dxzmjbxs," + + "brjxs,cjt,cjpfcsyt,cjdbtsyt,sbjfljt,tsgct,fgjxs,gsjt,yejt,dsznhljt," + + "bgldxgzrjbxs,bgldxxxrjbxs,bgldxjjrjbxs,gldxgzrjbxs,gldxxxrjbxs,gldxjjrjbxs,jbzjxs,cct,gcxs," + + "ny,rzrq,zzrq,lzrq,ryzt,kqy,h1,h2,h3,h4,h5,h6," + + "h7,h8,h9,h10,h11,h12,h13,h14,h15,h16," + + "h17,h18,h19,h20,h21,h22,h23,h24,h25,h26," + + "h27,h28,h29,h30,h31,FORMMODEID,MODEDATACREATER,MODEDATACREATERTYPE,MODEDATACREATEDATE,MODEDATACREATETIME) " + + " values(?,?,?,?,?,?,?,?,?,?," + + "?,?,?,?,?,?,?,?,?,?," + + "?,?,?,?,?,?,?,?,?,?," + + "?,?,?,?,?,?,?,?,?,?," + + "?,?,?,?,?,?,?,?,?,?," + + "?,?,?,?,?,?,?,?,?," + + "?,?,?,?,?,?,?,?,?,?,?,?," + + "?,?,?,?,?,?,?,?,?,?," + + "?,?,?,?,?,?,?,?,?,?," + + "?,?,?,?,?,?,?,?,?,?)"; + bRs.executeBatchSql(sql,lsParams); + + String idNew = ""; + RecordSet findNew = new RecordSet(); + String sqlFindnew ="select Id from uf_kqhzbx where xm = "+resourceId+" and ny = '"+ny+"' order by" + + " modedatacreatedate desc,modedatacreatetime desc"; + findNew.execute(sqlFindnew); + bb.writeLog("findSqlNew:"+sqlFindnew); + if (findNew.next()){ + idNew = weaver.general.Util.null2String(findNew.getString("id")); + } + bb.writeLog("idNew:"+idNew); + // 权限重构 + int dataId = Integer.valueOf(idNew); + ModeRightInfo modeRightInfo = new ModeRightInfo(); + modeRightInfo.editModeDataShare(Integer.valueOf(resourceId), modeid, dataId); + } + + } catch (Exception e) { + e.printStackTrace(); + bb.writeLog(e); + bb.writeLog("新入职员工当天打卡数据生成--error"+e.getMessage()); + } + } + + + /** + * 根据建模表名获取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"); + } + + /** + * 找到人员入职日期 + * + * @return + */ + public static String findRzrq(String jbr) { + RecordSet rs = new RecordSet(); + String sql = "select id,companystartdate from hrmresource where id ="+jbr; + rs.executeQuery(sql); + String companystartdate = ""; + if (rs.next()) { + companystartdate = Util.null2String(rs.getString("companystartdate")); + } + return companystartdate; + } + + /** + * 获取转正日期 + * @param userid + * @return + */ + private static String getField18(String userid){ + RecordSet rs = new RecordSet(); + String sql = "select field18 from cus_fielddata where id = "+userid+" and scope = 'HrmCustomFieldByInfoType' and scopeid = 3"; + rs.executeQuery(sql); + String field18 = ""; + if (rs.next()){ + field18 = Util.null2String(rs.getString("field18")); + } + return field18; + } + + /** + * 获取离职日期 + * @param userid + * @return + */ + private static String getField82(String userid){ + RecordSet rs = new RecordSet(); + String sql = "select field82 from cus_fielddata where id = "+userid+" and scope = 'HrmCustomFieldByInfoType' and scopeid = 3"; + rs.executeQuery(sql); + String field82 = ""; + if (rs.next()){ + field82 = Util.null2String(rs.getString("field82")); + } + return field82; + } + + /** + * 获取人员状态 + * @param userid + * @return + */ + private static String getStatus(String userid){ + RecordSet rs = new RecordSet(); + String sql = "select status from hrmresource where id = "+userid; + rs.executeQuery(sql); + String status = ""; + if (rs.next()){ + status = Util.null2String(rs.getString("status")); + } + return status; + } + + + public static void main(String[] args) { + String fromDate = TimeUtil.getDateByOption("3", "0"); + String toDate = fromDate.substring(0,7)+"-31"; + Map detialDatas = new HashMap<>(); + Map detialOvtimeDatas = new HashMap<>(); + detialDatas.put("432|2024-06-02","0.0"); + detialDatas.put("432|2024-06-01","0.0"); + boolean isEnd = false; + List data = new ArrayList<>(); + String today = DateUtil.getCurrentDate(); + Calendar cal = DateUtil.getCalendar(); + List all = new ArrayList<>(); + all.add(fromDate); + List back = days(fromDate,toDate); + all.addAll(back); + all.add(toDate); + for(String date:all){ + if (DateUtil.compDate(today, date) > 0) { + data.add(""); + } else { + if (detialDatas.get("432" + "|" + date) != null) { + double atttime = Util.getDoubleValue((String) detialDatas.get("432" + "|" + date),0); + if(detialOvtimeDatas.get("432" + "|" + date) !=null ){ + atttime += (double) detialOvtimeDatas.get("432" + "|" + date); + } + data.add(atttime); + } else { + data.add("other"); + } + } + } + System.out.println("dataText:"+JSONObject.toJSONString(data)); + List par = new ArrayList<>(); + for (int i = 0; i < all.size(); i++) { + par.add(data.get(i)); + } + System.out.println(par.toString()); + + + + } + + /** + * 获取两个日期之间所有的日期 + * @param date1 + * @param date2 + * @return + */ + public static ArrayList days(String date1, String date2) { + ArrayList L = new ArrayList(); + if (date1.equals(date2)) { + System.out.println("两个日期相等!"); + return L; + } + + String tmp; + if (date1.compareTo(date2) > 0) { // 确保 date1的日期不晚于date2 + tmp = date1; + date1 = date2; + date2 = tmp; + } + + tmp = format.format(str2Date(date1).getTime() + 3600 * 24 * 1000); + + int num = 0; + while (tmp.compareTo(date2) < 0) { + L.add(tmp); + num++; + tmp = format.format(str2Date(tmp).getTime() + 3600 * 24 * 1000); + } + + if (num == 0) + System.out.println("两个日期相邻!"); + return L; + } + + private static Date str2Date(String str) { + if (str == null) + return null; + + try { + return format.parse(str); + } catch (ParseException e) { + e.printStackTrace(); + } + return null; + } + +} diff --git a/src/weaver/interfaces/hskq/util/BatchIdsParams.java b/src/weaver/interfaces/hskq/util/BatchIdsParams.java new file mode 100644 index 0000000..284b291 --- /dev/null +++ b/src/weaver/interfaces/hskq/util/BatchIdsParams.java @@ -0,0 +1,35 @@ +package weaver.interfaces.hskq.util; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import weaver.general.StringUtil; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +/** + * @Author liang.cheng + * @Date 2023/6/3 2:22 PM + * @Description: + * @Version 1.0 + */ + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class BatchIdsParams { + + private String ids; + + public List getIds() { + if(StringUtil.isEmpty(ids)){ + return new ArrayList<>(); + } + return Arrays.stream(ids.split(",")).map(Integer::parseInt).collect(Collectors.toList()); + } +} diff --git a/src/weaver/interfaces/leshanvc/cronjob/ApplyCronJob.java b/src/weaver/interfaces/leshanvc/cronjob/ApplyCronJob.java new file mode 100644 index 0000000..735f276 --- /dev/null +++ b/src/weaver/interfaces/leshanvc/cronjob/ApplyCronJob.java @@ -0,0 +1,258 @@ +package weaver.interfaces.leshanvc.cronjob; + +import com.weaver.general.BaseBean; +import com.weaver.general.Util; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import weaver.conn.RecordSet; +import weaver.hrm.User; +import weaver.hrm.resource.ResourceComInfo; +import weaver.interfaces.schedule.BaseCronJob; +import weaver.soa.workflow.request.MainTableInfo; +import weaver.soa.workflow.request.Property; +import weaver.soa.workflow.request.RequestInfo; +import weaver.soa.workflow.request.RequestService; +import weaver.workflow.request.RequestComInfo; +import weaver.workflow.workflow.WorkflowComInfo; + +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.HashMap; +import java.util.Map; + +/** + * 定时任务:执行《转正申请流程》 + */ +public class ApplyCronJob extends BaseCronJob { + /** + * 入职日期 + */ + private String companystartdate; + /** + * 部门编码 + */ + private String departmentcode; + /** + * 状态 + */ + private String status; + /** + * 工作流id + */ + private String workflowId; + /** + * 流程创建人 + */ + private String workFlowCreatorId; + + private static User user; + + @Override + public void execute() { + BaseBean bs = new BaseBean(); + bs.writeLog("--定时任务:执行《转正申请流程》--"); + // 处理传入参数 + if (StringUtils.isBlank(companystartdate)) { + companystartdate = "20"; + } +// if (StringUtils.isBlank(departmentcode)) { +// departmentcode = "805"; +// } + if (StringUtils.isBlank(status)) { + status = "0"; + } + // 创建人 + user = new User(Util.getIntValue(workFlowCreatorId)); + String userId = String.valueOf(user.getUID()); + String userName = user.getLastname(); + + String IsNextFlow = "1"; + RecordSet rs = new RecordSet(); + // 获取流程相关信息 + rs.execute("select WORKFLOWNAME from workflow_base where id='" + workflowId + "'"); + String workFlowName = null; + if (rs.next()) { + workFlowName = Util.null2String(rs.getString("WORKFLOWNAME")); + } + // 查询线长字段ID + rs.executeQuery("select fieldid from cus_formfield cf where `SCOPE` = 'HrmCustomFieldByInfoType' and SCOPEID ='-1' and HRM_FIELDLABLE ='线长' "); + String fieldId = "field"; + if (rs.next()) { + fieldId = fieldId + rs.getString("fieldid"); + } + // 计划任务需要处理的逻辑 +// String hrmSql = "select a.id as sqr,a.id as zzr,a.departmentid as szbm, a.loginid as gh,a.companystartdate as rzrq,a.subcompanyid1 as gsmc,managerid,"+fieldId+" as xc from hrmresource a " + +// "left join hrmdepartment b on a.departmentid=b.id " + +// "left join cus_fielddata c on a.id=c.id "+ +// "where a.status in (" + status + ") and left(b.DEPARTMENTCODE,3) in (" + departmentcode + ") and c.SCOPE = 'HrmCustomFieldByInfoType' and c.SCOPEID = -1 and to_days(now())-to_days(companystartdate)>'" + companystartdate + "'"; + String hrmSql = "select a.id as sqr,a.id as zzr,a.departmentid as szbm, a.loginid as gh,a.companystartdate as rzrq,a.subcompanyid1 as gsmc,managerid,"+fieldId+" as xc from hrmresource a " + + "left join hrmdepartment b on a.departmentid=b.id " + + "left join cus_fielddata c on a.id=c.id "+ + "where a.status in (" + status + ") and c.field35 in (2,3,4) and c.SCOPE = 'HrmCustomFieldByInfoType' and c.SCOPEID = -1 and to_days(now())-to_days(companystartdate)>'" + companystartdate + "'"; + + bs.writeLog("待转正人员查询sql:" + hrmSql); + rs.executeQuery(hrmSql); + while (rs.next()) { + Map requestMainMap = new HashMap<>(); + //申请人 + requestMainMap.put("sqr", Util.null2String(userId)); + // 转正人 + String zzr = Util.null2String(rs.getString("zzr")); + requestMainMap.put("zzr", zzr); + // 公司名称 + requestMainMap.put("gsmc", Util.null2String(rs.getString("gsmc"))); + // 所属部门 + requestMainMap.put("szbm", Util.null2String(rs.getString("szbm"))); + // 人员编号 + requestMainMap.put("gh", Util.null2String(rs.getString("gh"))); + // 入职日期 + requestMainMap.put("rzrq", Util.null2String(rs.getString("rzrq"))); + // 转正日期 + requestMainMap.put("zzrq", Util.null2String(rs.getString("zzrq"))); + // 转正类型 + requestMainMap.put("zzlx", "1"); + // 线长是否建议转正 + requestMainMap.put("xcsfjyzz", "1"); + // 工作效率评价 + requestMainMap.put("gzxlpj", "0"); + // 工作质量评价 + requestMainMap.put("gzzlpj", "0"); + // 配合度评价 + requestMainMap.put("phdpj", "0"); + // 人际关系评价 + requestMainMap.put("rjgxpj", "0"); + // 审批状态 + requestMainMap.put("spzt", "1"); + // 直接上级 + requestMainMap.put("zjsj", Util.null2String(rs.getString("managerid"))); + requestMainMap.put("sqrq", getDate(0)); + // 线长 + requestMainMap.put("xc", Util.null2String(rs.getString("xc"))); + + String requestName = workFlowName + "-" + userName + "-" + getDate(0); + + if (!isHave(workflowId, zzr)) { + bs.writeLog("无在途流程,开始创建" + workFlowName); + WorkflowCreateByRequestMap(userId, workflowId, requestName, IsNextFlow, requestMainMap); + } else { + bs.writeLog(requestName + "(转正人:" + zzr + "),创建失败,存在在途流程"); + } + } + } + + /** + * 判断是否有在途流程 + */ + private Boolean isHave(String workflowId,String zzr) { + RecordSet recordSet = new RecordSet(); + String sql = "select * from workflow_requestbase a \n" + + "inner join formtable_main_51 b on a.REQUESTID=b.REQUESTID where a.WORKFLOWID="+workflowId+" and b.zzr="+zzr; + recordSet.executeQuery(sql); + return recordSet.next() ? true : false; + } + + /** + * @param @param creatorId 创建人Id + * @param @param workflowId 流程Id + * @param @param requestName 请求标题 + * @param @param IsNextFlow 是否提交到下一节点 + * @param @param requestMap Map格式的主表数据=<字段名称,字段值> + * @param @return 设定文件 + * @return String 返回类型 + * @throws + * @Title: 自动创建流程 + */ + private String WorkflowCreateByRequestMap(String creatorId, String workflowId, String requestName, String IsNextFlow, Map requestMainMap) { + BaseBean bs = new BaseBean(); + String requestid = ""; + RequestInfo requestInfo = new RequestInfo(); + // 创建人Id + requestInfo.setCreatorid(creatorId); + // 工作流Id + requestInfo.setWorkflowid(workflowId); + // 请求标题 + requestInfo.setDescription(requestName); + if (!"".equals(IsNextFlow)) { + requestInfo.setIsNextFlow(IsNextFlow); + } + //主表字段 + MainTableInfo mainTableInfo = new MainTableInfo(); + Property[] propertyArray = new Property[requestMainMap.size()]; + int p = 0; + for (Map.Entry entry : requestMainMap.entrySet()) { + propertyArray[p] = new Property(); + propertyArray[p].setName(Util.null2String(entry.getKey())); + propertyArray[p].setValue(Util.null2String(entry.getValue())); + bs.writeLog("\r\n---p=" + p + "---Key=" + entry.getKey() + "---Value=" + entry.getValue()); + p++; + } + bs.writeLog("-----创建流程传递的参数个数p=" + p); + mainTableInfo.setProperty(propertyArray); + requestInfo.setMainTableInfo(mainTableInfo); + RequestService service = new RequestService(); + try { + //流程 + try { + //创建请求id + requestid = service.createRequest(requestInfo); + } catch (Exception e) { + bs.writeLog("转正申请流程触发异常" + e.getMessage()); + } + //记录日志 + StringBuffer sbf = new StringBuffer("\r\n-----xwd创建工作流记录日志开始"); + WorkflowComInfo wfcif = new WorkflowComInfo(); + RequestComInfo rcif = new RequestComInfo(); + ResourceComInfo rscif = new ResourceComInfo(); + sbf.append("\r\n-----姓名:" + rscif.getLastname(rcif.getRequestCreater(requestid))); + sbf.append("\r\n-----时间:" + rcif.getRequestCreateTime(requestid)); + sbf.append("\r\n-----创建流程:" + wfcif.getWorkflowname(workflowId)); + sbf.append("\r\n-----请求:" + rcif.getRequestname(requestid)); + sbf.append("\r\n-----请求:" + requestid); + sbf.append("\r\n-----创建工作流记录日志结束"); + bs.writeLog("" + sbf.toString()); + } catch (Exception e) { + bs.writeLog("错误:" + e); + } + return requestid; + } + + private String getDate(int day) { + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");//设置格式 + Calendar calendar = Calendar.getInstance(); //创建Calendar 的实例 + calendar.add(Calendar.DAY_OF_MONTH, day); //当前时间减去一天,即一天前的时间 + return simpleDateFormat.format(calendar.getTime()); + } + + public String getCompanystartdate() { + return companystartdate; + } + + public void setCompanystartdate(String companystartdate) { + this.companystartdate = companystartdate; + } + + public String getDepartmentcode() { + return departmentcode; + } + + public void setDepartmentcode(String departmentcode) { + this.departmentcode = departmentcode; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getWorkflowId() { + return workflowId; + } + + public void setWorkflowId(String workflowId) { + this.workflowId = workflowId; + } +} diff --git a/src/weaver/interfaces/leshanvc/cronjob/AutoCancelDepartmentJob.java b/src/weaver/interfaces/leshanvc/cronjob/AutoCancelDepartmentJob.java new file mode 100644 index 0000000..ab139ee --- /dev/null +++ b/src/weaver/interfaces/leshanvc/cronjob/AutoCancelDepartmentJob.java @@ -0,0 +1,65 @@ +package weaver.interfaces.leshanvc.cronjob; + +import com.engine.common.util.ServiceUtil; +import com.engine.hrm.service.impl.OrganizationServiceImpl; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.hrm.User; +import weaver.interfaces.schedule.BaseCronJob; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 自动启用、封存部门计划任务 + * + * @author:dxfeng + * @createTime: 2023/03/06 + * @version: 1.0 + */ +public class AutoCancelDepartmentJob extends BaseCronJob { + @Override + public void execute() { + User user = new User(1); + String currentDate = DateUtil.getCurrentDate(); + List disableList = new ArrayList<>(); + List enableList = new ArrayList<>(); + RecordSet rs = new RecordSet(); + // 查询待封存的部门ID + String sql = "select deptid from hrmdepartmentdefined where fcrq = ? "; + rs.executeQuery(sql, currentDate); + while (rs.next()) { + disableList.add(rs.getString("deptid")); + } + + // 查询待启用的部门ID + sql = "select deptid from hrmdepartmentdefined where qyrq = ? "; + rs.executeQuery(sql, currentDate); + while (rs.next()) { + enableList.add(rs.getString("deptid")); + } + + + // 批量禁用部门 + if (CollectionUtils.isNotEmpty(disableList)) { + Map params = new HashMap<>(); + params.put("id", StringUtils.join(disableList, ",")); + Map result = ServiceUtil.getService(OrganizationServiceImpl.class, user).doDepartmentCancel(params, user); + new BaseBean().writeLog(result); + } + + // 批量启用部门 + if (CollectionUtils.isNotEmpty(enableList)) { + Map params = new HashMap<>(); + params.put("id", StringUtils.join(enableList, ",")); + Map result = ServiceUtil.getService(OrganizationServiceImpl.class, user).doDepartmentISCanceled(params, user); + new BaseBean().writeLog(result); + } + } + +} diff --git a/src/weaver/interfaces/leshanvc/cronjob/SyncQualificationsJob.java b/src/weaver/interfaces/leshanvc/cronjob/SyncQualificationsJob.java new file mode 100644 index 0000000..a01bfdb --- /dev/null +++ b/src/weaver/interfaces/leshanvc/cronjob/SyncQualificationsJob.java @@ -0,0 +1,71 @@ +package weaver.interfaces.leshanvc.cronjob; + +import com.weaver.general.Util; +import org.apache.commons.collections.CollectionUtils; +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.interfaces.schedule.BaseCronJob; + +import java.util.ArrayList; +import java.util.List; + +/** + * 同步任职资格定时任务 + * + * @author:dxfeng + * @createTime: 2023/02/10 + * @version: 1.0 + */ +public class SyncQualificationsJob extends BaseCronJob { + /** + * 当前时间 + */ + private static final String CURRENT_DATE = DateUtil.getCurrentDate(); + + @Override + public void execute() { + RecordSet rs = new RecordSet(); + List qualificationList = new ArrayList<>(); + String sql; + // 查询“认证时间”大于等于“当前日期”的数据 + sql = "select rzsj,ry,zzrdj,zzrdd from uf_rzzg where rzsj >='" + CURRENT_DATE + "'"; + rs.execute(sql); + while (rs.next()) { + qualificationList.add(new Qualification(rs.getString("ry"), rs.getString("zzrdj"), rs.getString("zzrdd"))); + } + // 同步浏览按钮数据 + if (CollectionUtils.isNotEmpty(qualificationList)) { + for (Qualification qualification : qualificationList) { + sql = "update cus_fielddata set field94 = '" + Util.null2String(qualification.getLevelId()) + "',field95 ='" + Util.null2String(qualification.getGradeId()) + "' where scope ='HrmCustomFieldByInfoType' and scopeid ='3' and id = '" + qualification.getUserId() + "'"; + rs.executeUpdate(sql); + } + } + } + + static class Qualification { + // 人员ID + private final String userId; + // 职级ID + private final String gradeId; + // 职等ID + private final String levelId; + + Qualification(String userId, String gradeId, String levelId) { + this.userId = userId; + this.gradeId = gradeId; + this.levelId = levelId; + } + + public String getUserId() { + return userId; + } + + public String getGradeId() { + return gradeId; + } + + public String getLevelId() { + return levelId; + } + } +} diff --git a/src/weaver/interfaces/leshanvc/cronjob/SyncResignJob.java b/src/weaver/interfaces/leshanvc/cronjob/SyncResignJob.java new file mode 100644 index 0000000..2dcc3ab --- /dev/null +++ b/src/weaver/interfaces/leshanvc/cronjob/SyncResignJob.java @@ -0,0 +1,111 @@ +package weaver.interfaces.leshanvc.cronjob; + +import org.apache.commons.collections.CollectionUtils; +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.interfaces.schedule.BaseCronJob; + +import java.util.ArrayList; +import java.util.List; + +/** + * 同步离职信息计划任务 + * + * @author:dxfeng + * @createTime: 2023/03/03 + * @version: 1.0 + */ +public class SyncResignJob extends BaseCronJob { + /** + * 建模表审批状态:已审批 + */ + private static final String PASS_STATUS = "2"; + + /** + * hrmresource表,离职状态 + */ + private static final String RESIGN_STATUS = "5"; + + + @Override + public void execute() { + RecordSet rs = new RecordSet(); + List resignInfoList = new ArrayList<>(); + + rs.executeQuery("select lzry,jhlzrq,qdlzrq,lzyyxz from uf_lzgl a inner join hrmresource b on a.lzry =b.ID and b.STATUS != ? where spzt = ? and qdlzrq < ? ", RESIGN_STATUS, PASS_STATUS, DateUtil.getCurrentDate()); + while (rs.next()) { + resignInfoList.add(new ResignInfo(rs.getString("lzry"), rs.getString("jhlzrq"), rs.getString("qdlzrq"), rs.getString("lzyyxz"))); + } + if (CollectionUtils.isNotEmpty(resignInfoList)) { + for (ResignInfo resignInfo : resignInfoList) { + // 更新人员卡片自定义字段 + rs.executeUpdate("update cus_fielddata set field31 = ?, field82 = ?, field50 = ? where scope ='HrmCustomFieldByInfoType' and scopeid ='3' and id = ? ", resignInfo.getPlanDate(), resignInfo.getResignDate(), resignInfo.getResignReason(), resignInfo.getResourceId()); + // 更新人员为离职状态 + rs.executeUpdate("update hrmresource set status = ? where id = ? ", RESIGN_STATUS, resignInfo.getResourceId()); + } + } + } + + + private static class ResignInfo { + + /** + * 离职人员 + */ + private String resourceId; + /** + * 计划离职日期 + */ + private String planDate; + /** + * 实际离职日期 + */ + private String resignDate; + /** + * 离职原因 + */ + private String resignReason; + + public ResignInfo(String resourceId, String planDate, String resignDate, String resignReason) { + this.resourceId = resourceId; + this.planDate = planDate; + this.resignDate = resignDate; + this.resignReason = resignReason; + } + + public String getPlanDate() { + return Util.null2String(planDate); + } + + public void setPlanDate(String planDate) { + this.planDate = planDate; + } + + public String getResignDate() { + return Util.null2String(resignDate); + } + + public void setResignDate(String resignDate) { + this.resignDate = resignDate; + } + + public String getResignReason() { + return Util.null2String(resignReason); + } + + public void setResignReason(String resignReason) { + this.resignReason = resignReason; + } + + public String getResourceId() { + return resourceId; + } + + public void setResourceId(String resourceId) { + this.resourceId = resourceId; + } + } + + +} diff --git a/src/weaver/interfaces/leshanvc/cronjob/SyncStatusByDate.java b/src/weaver/interfaces/leshanvc/cronjob/SyncStatusByDate.java new file mode 100644 index 0000000..2f4d598 --- /dev/null +++ b/src/weaver/interfaces/leshanvc/cronjob/SyncStatusByDate.java @@ -0,0 +1,43 @@ +package weaver.interfaces.leshanvc.cronjob; + +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.interfaces.schedule.BaseCronJob; + +import java.util.ArrayList; +import java.util.List; + +/** + * @Author ml + * @Date 2023/4/10 9:15 + * @Description 离职日期<当前日期时,更新人员状态 + * @Since version-1.0 + */ +public class SyncStatusByDate extends BaseCronJob { + private static BaseBean baseBean = new BaseBean(); + + private static RecordSet recordSet = new RecordSet(); + + @Override + public void execute() { + baseBean.writeLog("定时任务更新人员状态"); + try { + recordSet.executeQuery("select id from cus_fielddata where field82 < current_date() " + + "and scope = 'HrmCustomFieldByInfoType' and scopeid='3' and ifnull(field82,'')!=''"); + List list = new ArrayList<>(); + while (recordSet.next()) { + list.add(recordSet.getString("id")); + } + + for (String id : list){ + recordSet.execute("update hrmresource set status = '5' where id="+id); + recordSet.next(); + } + + } catch (Exception e) { + baseBean.writeLog(e); + } + + + } +} diff --git a/src/weaver/interfaces/leshanvc/formmode/EntryCommitBtnShowTemplate.java b/src/weaver/interfaces/leshanvc/formmode/EntryCommitBtnShowTemplate.java new file mode 100644 index 0000000..4fe4c1f --- /dev/null +++ b/src/weaver/interfaces/leshanvc/formmode/EntryCommitBtnShowTemplate.java @@ -0,0 +1,38 @@ +package weaver.interfaces.leshanvc.formmode; + +import weaver.conn.RecordSet; +import weaver.formmode.interfaces.PopedomCommonAction; + +public class EntryCommitBtnShowTemplate implements PopedomCommonAction { + /** + * 说明 + * 修改时 + * 类名要与文件名保持一致 + * class文件存放位置与路径保持一致。 + * 请把编译后的class文件,放在对应的目录中才能生效 + * 注意 同一路径下java代码名不能相同。 + * + * 得到是否显示操作项 + * @param modeid 模块id + * @param customid 查询列表id + * @param uid 当前用户id + * @param billid 表单数据id + * @param buttonname 按钮名称 + * @retrun "true"或者"false"true显示/false不显示 + */ + @Override + public String getIsDisplayOperation(String modeid, String customid,String uid, String billid, String buttonname) { + RecordSet rs = new RecordSet(); + String sql = "select rzzt from uf_rzgl where id=?"; + rs.executeQuery(sql,billid); + if (rs.next()) { + String status = rs.getString("rzzt"); + if("0".equals(status)){ + return "true"; + }else{ + return "false"; + } + } + return "true"; + } +} diff --git a/src/weaver/interfaces/leshanvc/formmode/LeaveCheckInCutPayBtnShow.java b/src/weaver/interfaces/leshanvc/formmode/LeaveCheckInCutPayBtnShow.java new file mode 100644 index 0000000..e986135 --- /dev/null +++ b/src/weaver/interfaces/leshanvc/formmode/LeaveCheckInCutPayBtnShow.java @@ -0,0 +1,45 @@ +package weaver.interfaces.leshanvc.formmode; + +import weaver.conn.RecordSet; +import weaver.formmode.interfaces.PopedomCommonAction; + +/** + * @Author ml + * @Date 2023/3/14 17:18 + * @Description 离职登记扣款按钮显示 + * @Since version-1.0 + */ +public class LeaveCheckInCutPayBtnShow implements PopedomCommonAction { + /** + * 说明 + * 修改时 + * 类名要与文件名保持一致 + * class文件存放位置与路径保持一致。 + * 请把编译后的class文件,放在对应的目录中才能生效 + * 注意 同一路径下java代码名不能相同。 + * + * 得到是否显示操作项 + * @param modeid 模块id + * @param customid 查询列表id + * @param uid 当前用户id + * @param billid 表单数据id + * @param buttonname 按钮名称 + * @retrun "true"或者"false"true显示/false不显示 + */ + @Override + public String getIsDisplayOperation(String modeid, String customid,String uid, String billid, String buttonname) { + RecordSet rs = new RecordSet(); + String sql = "select spzt from uf_lzgl where id=?"; + rs.executeQuery(sql,billid); + String res = "true"; + if (rs.next()) { + String status = rs.getString("spzt"); + if("2".equals(status)){ + res = "true"; + }else{ + res = "false"; + } + } + return res; + } +} diff --git a/src/weaver/interfaces/leshanvc/formmode/NonOfficeUploadExpand.java b/src/weaver/interfaces/leshanvc/formmode/NonOfficeUploadExpand.java new file mode 100644 index 0000000..751917d --- /dev/null +++ b/src/weaver/interfaces/leshanvc/formmode/NonOfficeUploadExpand.java @@ -0,0 +1,111 @@ +package weaver.interfaces.leshanvc.formmode; + +import com.alibaba.fastjson.JSONObject; +import org.apache.commons.lang3.StringUtils; +import weaver.conn.RecordSet; +import weaver.formmode.customjavacode.AbstractModeExpandJavaCodeNew; +import weaver.general.BaseBean; +import weaver.general.PasswordUtil; +import weaver.general.Util; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; +import weaver.interfaces.leshanvc.workflow.util.ResourceSyncUtil; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.HashMap; +import java.util.Map; + +/** + * @Author ml + * @Date 2023/4/3 15:57 + * @Description 非办公上岗 + * @Since version-1.0 + */ +public class NonOfficeUploadExpand extends AbstractModeExpandJavaCodeNew { + private static BaseBean baseBean = new BaseBean(); + + @Override + public Map doModeExpand(Map param) { + Map result = new HashMap(); +// try { +// User user = (User) param.get("user"); +// int billid = -1;//数据id +// int modeid = -1;//模块id +// RequestInfo requestInfo = (RequestInfo) param.get("RequestInfo"); +// boolean canEdit = HrmUserVarify.checkUserRight("HrmResourceEdit:Edit", user); +// if (!canEdit) { +// baseBean.writeLog("人员新增失败,当前用户不具备权限"); +// result.put("errmsg", "人员新增失败,当前用户不具备权限"); +// result.put("flag", "false"); +// return result; +// } +// if (requestInfo != null) { +// billid = Util.getIntValue(requestInfo.getRequestid()); +// modeid = Util.getIntValue(requestInfo.getWorkflowid()); +// if (billid > 0 && modeid > 0) { +// //------请在下面编写业务逻辑代码------ +// RecordSet rs = new RecordSet(); +//// String ids = param.get("CheckedCheckboxIds").toString(); +// String requestId = requestInfo.getRequestid(); +// rs.executeQuery("select sfzhm,xm,xb,mz,csrq,jtzz,ksyxq,jzyxq,sfrhmc from uf_sfzxxgl where id=?", requestId); +// Map paraMap = new HashMap<>(); +// String defId = null; +// if (rs.next()) { +// if (StringUtils.isNotBlank(rs.getString("sfrhmc"))) { +// result.put("errmsg", "该人员已录入花名册!!"); +// result.put("flag", "false"); +// return result; +// } +// paraMap.put("certificatenum", Util.null2String(rs.getString("sfzhm"))); +// paraMap.put("lastname", Util.null2String(rs.getString("xm"))); +// paraMap.put("sex", Util.null2String(rs.getString("xb"))); +// paraMap.put("folk", Util.null2String(rs.getString("mz"))); +// paraMap.put("birthday", Util.null2String(rs.getString("csrq"))); +// paraMap.put("regresidentplace", Util.null2String(rs.getString("jtzz"))); +// paraMap.put("status", "0"); +// paraMap.put("ksyxq", Util.null2String(rs.getString("ksyxq"))); +// paraMap.put("jzyxq", Util.null2String(rs.getString("jzyxq"))); +// Map retMap = ResourceSyncUtil.addResource(user, paraMap); +// if (!"1".equals(retMap.get("status"))) { +// baseBean.writeLog("人员新增失败,请联系管理员"); +// result.put("msg", "人员新增失败,请联系管理员"); +// return result; +// } else { +// defId = retMap.get("id").toString(); +// } +// } +// String queryHrmSql = "select workcode from hrmresource h where h.id = '" + defId + "'"; +// rs.executeQuery(queryHrmSql); +// RecordSet recordSet = new RecordSet(); +// String encrptPassword = ""; +// String salt = ""; +// if (rs.next()) { +// if (StringUtils.isNotBlank(rs.getString("workcode"))) { +// String[] encrypts = PasswordUtil.encrypt(rs.getString("workcode")); +// encrptPassword = encrypts[0]; +// salt = encrypts[1]; +// } +// recordSet.execute("update hrmresource set loginid='" + rs.getString("workcode") + "',password='" + encrptPassword + "',salt='" + +// salt + "',certificatenum='" + Util.null2String(paraMap.get("certificatenum")) + "',folk='"+paraMap.get("folk")+"'," + +// "birthday='"+paraMap.get("birthday")+"',regresidentplace='"+paraMap.get("regresidentplace")+"' where id=" + defId); +// } else { +// result.put("msg", "未查到对应人员Id,请联系管理员"); +// return result; +// } +// +// // 自定义表cus_fielddata +// String insertCusFieldData = "insert cus_fielddata(scope,scopeid,id,field81,field103,field82) " + +// "values ('HrmCustomFieldByInfoType','1'," + defId + ",'0','" + paraMap.get("ksyxq") + "','" + paraMap.get("jzyxq") + "')"; +// rs.execute(insertCusFieldData); +// // 更新状态 +// String updateStatus = "update uf_sfzxxgl set sfrhmc = '1' where id = ?"; +// rs.executeUpdate(updateStatus, requestId); +// } +// } +// } catch (Exception e) { +// result.put("errmsg", "自定义出错信息"); +// result.put("flag", "false"); +// } + return result; + } +} diff --git a/src/weaver/interfaces/leshanvc/formmode/RegisterSaveExpand.java b/src/weaver/interfaces/leshanvc/formmode/RegisterSaveExpand.java new file mode 100644 index 0000000..4228e26 --- /dev/null +++ b/src/weaver/interfaces/leshanvc/formmode/RegisterSaveExpand.java @@ -0,0 +1,87 @@ +package weaver.interfaces.leshanvc.formmode; + +import com.alibaba.fastjson.JSONObject; +import weaver.conn.RecordSet; +import weaver.formmode.customjavacode.AbstractModeExpandJavaCodeNew; +import weaver.general.Util; +import weaver.hrm.User; +import weaver.soa.workflow.request.RequestInfo; + +import java.util.HashMap; +import java.util.Map; + +/** + * @Author ml + * @Date 2023/3/14 18:09 + * @Description 登记提交保存按钮 + * @Since version-1.0 + */ +public class RegisterSaveExpand extends AbstractModeExpandJavaCodeNew { + /** + * hrmresource表,离职状态 + */ + private static final String RESIGN_STATUS = "5"; + + /** + * 执行模块扩展动作 + * @param param + * param包含(但不限于)以下数据 + * user 当前用户 + * importtype 导入方式(仅在批量导入的接口动作会传输) 1 追加,2覆盖,3更新,获取方式(int)param.get("importtype") + * 导入链接中拼接的特殊参数(仅在批量导入的接口动作会传输),比如a=1,可通过param.get("a")获取参数值 + * 页面链接拼接的参数,比如b=2,可以通过param.get("b")来获取参数 + * @return + */ + public Map doModeExpand(Map param) { + Map result = new HashMap(); + try { + User user = (User)param.get("user"); + int billid = -1;//数据id + int modeid = -1;//模块id + RequestInfo requestInfo = (RequestInfo)param.get("RequestInfo"); + if(requestInfo!=null){ + billid = Util.getIntValue(requestInfo.getRequestid()); + modeid = Util.getIntValue(requestInfo.getWorkflowid()); + if(billid>0&&modeid>0){ + //------请在下面编写业务逻辑代码------ + RecordSet rs = new RecordSet(); + //JSON转换,获取离职管理表中 + String JSONStr = (String) param.get("JSONStr"); + JSONObject jsonObject = (JSONObject) JSONObject.parse(JSONStr); + // 申请人 + String sqr = jsonObject.getString(queryField(rs,"sqr")); + // 计划离职日期 + String jhlzrq = jsonObject.getString(queryField(rs,"jhlzrq")); + // 确定离职日期 + String qdlzrq = jsonObject.getString(queryField(rs,"qdlzrq")); + // 离职原因 + String lzyyxz = jsonObject.getString(queryField(rs,"lzyyxz")); + + // 更新人员卡片自定义字段 + rs.executeUpdate("update cus_fielddata set field31 = ?, field82 = ?, field50 = ? where scope ='HrmCustomFieldByInfoType' and scopeid ='3' and id = ? ", jhlzrq, qdlzrq, lzyyxz, sqr); + + // 更新人员为离职状态 + rs.executeUpdate("update hrmresource set status = ? where id = ? ", RESIGN_STATUS, sqr); + } + } + } catch (Exception e) { + result.put("errmsg","自定义出错信息"); + result.put("flag", "false"); + } + return result; + } + + /** + * 查询表单对应字段 + */ + private String queryField(RecordSet rs,String fieldName) { + rs.executeQuery("select b.id from workflow_bill a \n" + + "INNER JOIN workflow_billfield b on a.id=b.billid\n" + + "where a.tablename='uf_lzgl' and b.fieldname='" + fieldName + "'"); + String field = "field"; + if (rs.next()) { + field += rs.getString("id"); + } + return field; + } +} diff --git a/src/weaver/interfaces/leshanvc/workflow/action/BatchWorkOverTimeAction.java b/src/weaver/interfaces/leshanvc/workflow/action/BatchWorkOverTimeAction.java new file mode 100644 index 0000000..f7bad4f --- /dev/null +++ b/src/weaver/interfaces/leshanvc/workflow/action/BatchWorkOverTimeAction.java @@ -0,0 +1,141 @@ +package weaver.interfaces.leshanvc.workflow.action; + +import org.apache.commons.lang3.StringUtils; +import weaver.conn.RecordSet; +import weaver.interfaces.workflow.action.Action; +import weaver.sm.Util; +import weaver.soa.workflow.request.Cell; +import weaver.soa.workflow.request.RequestInfo; +import weaver.soa.workflow.request.DetailTable; +import weaver.soa.workflow.request.Row; +import weaver.workflow.request.RequestManager; + +import java.util.ArrayList; +import java.util.List; + +/** + * @Author ml + * @Date 2023/3/20 17:44 + * @Description 批量加班申请流程 + * @Since version-1.0 + */ +public class BatchWorkOverTimeAction implements Action { + + @Override + public String execute(RequestInfo requestInfo) { + List list = new ArrayList<>(); + RequestManager requestManager = requestInfo.getRequestManager(); + int requestId = requestManager.getRequestid(); + int billId = requestManager.getBillid();//表单数据ID + //取明细数据 + try { + DetailTable[] detailTable = requestInfo.getDetailTableInfo().getDetailTable();// 获取所有明细表 + if (detailTable.length > 0) { + // 指定明细表 + for (DetailTable dt : detailTable) { + Row[] s = dt.getRow();// 当前明细表的所有数据,按行存储 + // 指定行 + for (Row r : s) { + Cell[] c = r.getCell();// 每行数据再按列存储 + HrmInfo hrmInfo = new HrmInfo(); + // 指定列 + for (Cell c1 : c) { + String name = c1.getName();// 明细字段名称 + String value = c1.getValue();// 明细字段的值 + switch (name) { + case "jbry": + hrmInfo.setResId(value); + break; + case "jbsch": + hrmInfo.setDuration(Double.parseDouble(value)); + break; + case "dyyljjbxs": + hrmInfo.setMonthOverTime(Double.parseDouble(value)); + break; + case "dyljjbcexs": + hrmInfo.setOverTimeAllowance(Double.parseDouble(value)); + default: + break; + } + } + list.add(hrmInfo); + } + } + } + //平均加班时长 + double avgDuration = list.stream().mapToDouble(HrmInfo::getDuration).average().orElse(0d); + Boolean gtFlag = false;// 当月累计加班 大于2h + Boolean betweenFlag = false;// 2h<=平均<当月累计超额 + Boolean ltFlag = avgDuration < 2 ? true : false;// 小于2h + for (HrmInfo h : list) { + gtFlag = h.getDuration() + h.getMonthOverTime() >= h.getOverTimeAllowance() ? true : false; + if (gtFlag) { + break; + } + betweenFlag = avgDuration >= 2 && avgDuration < h.getOverTimeAllowance() ? true : false; + if (betweenFlag) { + break; + } + } + // 加班时长审批(流程字段) + String jbscsp = ""; + if (gtFlag) { + jbscsp = "2"; + } else if (betweenFlag && StringUtils.isBlank(jbscsp)) { + jbscsp = "1"; + } else if (ltFlag) { + jbscsp = "0"; + } + RecordSet rs = new RecordSet(); + rs.executeUpdate("update formtable_main_76 set jbscsp = ? where requestid = ? ", jbscsp, requestId); + } catch (Exception e) { + requestInfo.getRequestManager().setMessageid("11111" + requestInfo.getRequestid() + "22222"); + requestInfo.getRequestManager().setMessagecontent("【批量加班申请流程action】报错,请联系管理员!"); + return Action.FAILURE_AND_CONTINUE; + } + return Action.SUCCESS; + } + + private static class HrmInfo { + private String resId; + //时长 + private double duration; + //加班额度 + private double overTimeAllowance; + //当月加班时长 + private double monthOverTime; + + public String getResId() { + return resId; + } + + public void setResId(String resId) { + this.resId = resId; + } + + public double getDuration() { + return duration; + } + + public void setDuration(double duration) { + this.duration = duration; + } + + public double getOverTimeAllowance() { + return overTimeAllowance; + } + + public void setOverTimeAllowance(double overTimeAllowance) { + this.overTimeAllowance = overTimeAllowance; + } + + public double getMonthOverTime() { + return monthOverTime; + } + + public void setMonthOverTime(double monthOverTime) { + this.monthOverTime = monthOverTime; + } + } + +} diff --git a/src/weaver/interfaces/leshanvc/workflow/action/MessagePushWeChatWorkAction.java b/src/weaver/interfaces/leshanvc/workflow/action/MessagePushWeChatWorkAction.java new file mode 100644 index 0000000..597ba0d --- /dev/null +++ b/src/weaver/interfaces/leshanvc/workflow/action/MessagePushWeChatWorkAction.java @@ -0,0 +1,223 @@ +package weaver.interfaces.leshanvc.workflow.action; + +import com.engine.kq.biz.KQOvertimeRulesBiz; +import com.engine.kq.util.KQDurationCalculatorUtil; +import com.engine.leshanvc.enums.MessageContentEnum; +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.interfaces.leshanvc.workflow.util.FunctionInterfaceMessage; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; + +import com.cloudstore.dev.api.bean.MessageBean; +import com.cloudstore.dev.api.bean.MessageType; +import com.cloudstore.dev.api.util.Util_Message; + +import java.io.IOException; +import java.text.DecimalFormat; +import java.text.SimpleDateFormat; +import java.util.*; + +/** + * @Author weaver_cl + * @Description: + * @Date 2023/2/10 + * @Version V1.0 + **/ +public class MessagePushWeChatWorkAction implements Action { + + private static String messageType; + + private static String title; + + private static String linkUrl; + + private static String linkMobileUrl; + + + + @Override + public String execute(RequestInfo requestInfo) { + RecordSet rs = new RecordSet(); + FunctionInterfaceMessage functionInterfaceMessage = new FunctionInterfaceMessage(); + String tableName = requestInfo.getRequestManager().getBillTableName(); + String requestId = requestInfo.getRequestid(); + + rs.executeQuery("select resourceId from " + tableName + " where requestid = ?", requestId); + rs.next(); + String resourceId = Util.null2String(rs.getString("resourceId")); + Set userIdList = new HashSet<>(); + userIdList.add(resourceId); + + Map map = getFirstAndLastDayMonth(); + double hour = getLastFlowOverTime(map.get("firstDay"), map.get("lastDay"), resourceId); + List list = Arrays.asList(MessageContentEnum.ONE, MessageContentEnum.TWO, MessageContentEnum.THREE, + MessageContentEnum.FOUR, MessageContentEnum.FIVE); + + Optional optional = list.stream().filter(messageContentEnum -> rangeInDefined(hour, messageContentEnum.getMin(), messageContentEnum.getMax())).findAny(); + MessageContentEnum messageContentEnum = optional.orElse(null); + if (Objects.nonNull(messageContentEnum)) { + String context = functionInterfaceMessage.doOperation(messageContentEnum.getValue(), 1); + messagePush(context, userIdList); + } + + if (isContinuousWork(resourceId)) { + String context = functionInterfaceMessage.doOperation(null, 2); + messagePush(context, userIdList); + } + + + return SUCCESS; + } + + + /** + * 消息推送 + * + * @param context + * @param userIdList + */ + private static void messagePush(String context, Set userIdList) { + + MessageType message = MessageType.newInstance(Integer.parseInt(messageType)); + try { + MessageBean messageBean = Util_Message.createMessage(message, userIdList, title, context, linkUrl, linkMobileUrl); + messageBean.setCreater(1); + //message.setBizState("0");// 需要修改消息为已处理等状态时传入,表示消息最初状态为待处理 + Util_Message.store(messageBean); + + } catch (IOException e) { + e.printStackTrace(); + } + } + + /** + * 加班时长(个人本月) + * + * @param fromDate + * @param toDate + * @param resourceid + */ + private static double getLastFlowOverTime(String fromDate, String toDate, String resourceid) { + RecordSet rs = new RecordSet(); + DecimalFormat df = new DecimalFormat("0.00"); + //当前加班单位 + int uintType = KQOvertimeRulesBiz.getMinimumUnit(); + //当前天跟小时计算关系 + double hoursToDay = KQOvertimeRulesBiz.getHoursToDay(); + rs.executeQuery("select sum(cast(duration_min as decimal(18,4))) as val from kq_flow_overtime where" + + " belongdate >= ? and belongdate <= ? and resourceid = ?", fromDate, toDate, resourceid); + rs.next(); + 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) + "")); + } +// df.setMaximumFractionDigits(5); +// return df.format(value); + return value; + + } + + /** + * 获取月初和月尾 + * 日期字符串 + * + * @return + */ + private static Map getFirstAndLastDayMonth() { + Map map = new HashMap<>(); + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); + Calendar cale; + String firstday, lastday; + // 获取前月的第一天 + cale = Calendar.getInstance(); + cale.add(Calendar.MONTH, 0); + cale.set(Calendar.DAY_OF_MONTH, 1); + firstday = format.format(cale.getTime()); + map.put("firstDay", firstday); + // 获取前月的最后一天 + cale = Calendar.getInstance(); + cale.add(Calendar.MONTH, 1); + cale.set(Calendar.DAY_OF_MONTH, 0); + lastday = format.format(cale.getTime()); + map.put("lastDay", lastday); + return map; + } + + /** + * 判断某个值是否在某个区间内(区间闭合,包含所在的起始值和结束值) + * + * @param current 特定数值 + * @param min 区间起始位 + * @param max 区间结束位 + * @return true 在;false 不在 + */ + public static boolean rangeInDefined(double current, int min, int max) { + return Math.max(min, current) == Math.min(current, max); + } + + + /** + * 连续加班工作6天 + * + * @param resourceid + * @return + */ + public static boolean isContinuousWork(String resourceid) { + int continuityDays = 6; + Set workDayList = new HashSet<>(); + RecordSet rs = new RecordSet(); + // 查询近6天的数据 + String sql = "select distinct fromDate,toDate from kq_flow_overtime where date_sub(CURDATE(),INTERVAL " + continuityDays + " DAY) <= DATE(fromDate) and resourceid = ?"; + rs.executeQuery(sql, resourceid); + while (rs.next()) { + String fromDate = rs.getString("fromDate"); + String toDate = rs.getString("toDate"); + if (fromDate.equals(toDate)) { + workDayList.add(fromDate); + } else { + while (!fromDate.equals(toDate) && workDayList.size() < continuityDays) { + workDayList.add(fromDate); + fromDate = DateUtil.addDate(fromDate, 1); + } + workDayList.add(toDate); + } + } + return workDayList.size() == continuityDays; + } + + public static String getMessageType() { + return messageType; + } + + public static void setMessageType(String messageType) { + MessagePushWeChatWorkAction.messageType = messageType; + } + + public static String getTitle() { + return title; + } + + public static void setTitle(String title) { + MessagePushWeChatWorkAction.title = title; + } + + public static String getLinkUrl() { + return linkUrl; + } + + public static void setLinkUrl(String linkUrl) { + MessagePushWeChatWorkAction.linkUrl = linkUrl; + } + + public static String getLinkMobileUrl() { + return linkMobileUrl; + } + + public static void setLinkMobileUrl(String linkMobileUrl) { + MessagePushWeChatWorkAction.linkMobileUrl = linkMobileUrl; + } +} diff --git a/src/weaver/interfaces/leshanvc/workflow/action/OutSplitAction.java b/src/weaver/interfaces/leshanvc/workflow/action/OutSplitAction.java new file mode 100644 index 0000000..69bf406 --- /dev/null +++ b/src/weaver/interfaces/leshanvc/workflow/action/OutSplitAction.java @@ -0,0 +1,48 @@ +package weaver.interfaces.leshanvc.workflow.action; + +import com.engine.kq.log.KQLog; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.Util; +import weaver.interfaces.leshanvc.workflow.util.ConvertDurationUtil; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; + + +/** + * @author:dxfeng + * @createTime: 2023/02/17 + * @version: 1.0 + */ +public class OutSplitAction extends BaseBean implements Action { + private KQLog kqLog = new KQLog(); + + @Override + public String execute(RequestInfo request) { + String requestid = request.getRequestid(); + int requestidInt = Util.getIntValue(requestid, 0); + + + try { + RecordSet rs = new RecordSet(); + String sql = "select * from kq_flow_split_out where requestid = ? "; + rs.executeQuery(sql, requestidInt); + if (rs.next()) { + String durationrule = rs.getString("durationrule"); + if ("3".equals(durationrule)) { + String duration = rs.getString("duration"); + String halfHour = ConvertDurationUtil.handelHalfHour(duration); + rs.executeUpdate("update kq_flow_split_out set duration = ? where requestid =?", halfHour, requestidInt); + } + } + } catch (Exception e) { + request.getRequestManager().setMessageid("11111" + request.getRequestid() + "22222"); + request.getRequestManager().setMessagecontent("【公出流程action】报错,请联系管理员!"); + return Action.FAILURE_AND_CONTINUE; + } + + return Action.SUCCESS; + + } + +} diff --git a/src/weaver/interfaces/leshanvc/workflow/action/ShuttleRouteSyncAction.java b/src/weaver/interfaces/leshanvc/workflow/action/ShuttleRouteSyncAction.java new file mode 100644 index 0000000..6c57dc3 --- /dev/null +++ b/src/weaver/interfaces/leshanvc/workflow/action/ShuttleRouteSyncAction.java @@ -0,0 +1,62 @@ +package weaver.interfaces.leshanvc.workflow.action; + +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; + +/** + * @Author weaver_cl + * @Description: + * @Date 2023/2/21 + * @Version V1.0 + **/ +public class ShuttleRouteSyncAction implements Action{ + + private String fieldName; + + private String scope; + + private String scopeId; + + @Override + public String execute(RequestInfo requestInfo) { + RecordSet rs = new RecordSet(); + String tableName = requestInfo.getRequestManager().getBillTableName(); + String requestId = requestInfo.getRequestid(); + + rs.executeQuery("select sqr,bclx from " + tableName + " where requestid = ?", requestId); + rs.next(); + int sqr = Util.getIntValue(rs.getString("sqr")); + int bclx = Util.getIntValue(rs.getString("bclx")); + + rs.executeUpdate("update cus_fielddata set "+fieldName+"=? where scope = ? and scopeid = ? and id = ?", + bclx, scope,scopeId,sqr); + + return SUCCESS; + } + + public String getFieldName() { + return fieldName; + } + + public void setFieldName(String fieldName) { + this.fieldName = fieldName; + } + + public String getScope() { + return scope; + } + + public void setScope(String scope) { + this.scope = scope; + } + + public String getScopeId() { + return scopeId; + } + + public void setScopeId(String scopeId) { + this.scopeId = scopeId; + } +} diff --git a/src/weaver/interfaces/leshanvc/workflow/action/SyncHrmInfoToCardAction.java b/src/weaver/interfaces/leshanvc/workflow/action/SyncHrmInfoToCardAction.java new file mode 100644 index 0000000..12b9d79 --- /dev/null +++ b/src/weaver/interfaces/leshanvc/workflow/action/SyncHrmInfoToCardAction.java @@ -0,0 +1,420 @@ +package weaver.interfaces.leshanvc.workflow.action; + +import org.apache.commons.lang3.StringUtils; +import weaver.conn.RecordSet; +import weaver.formmode.setup.ModeRightInfo; +import weaver.general.BaseBean; +import weaver.general.Util; +import weaver.hrm.User; +import weaver.hrm.tools.HrmDateCheck; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.Property; +import weaver.soa.workflow.request.RequestInfo; +import weaver.workflow.request.RequestManager; + +import javax.servlet.http.HttpServletRequest; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Date; +import java.util.UUID; + +/** + * @Author ml + * @Date 2023/3/24 10:28 + * @Description 员工信息自助更新 + * @Since version-1.0 + */ +public class SyncHrmInfoToCardAction implements Action { + private static String mainTable; + private static String detailTable1; + private static String detailTable2; + private static String detailTable3; + private static String detailTable4; + + private static RecordSet recordSet = new RecordSet(); + private BaseBean baseBean = new BaseBean(); + private static final String publicField = "formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime,modedatamodifydatetime,MODEUUID,"; + + + @Override + public String execute(RequestInfo requestInfo) { + RequestManager requestManager = requestInfo.getRequestManager(); + BaseBean baseBean = new BaseBean(); + baseBean.writeLog("***员工信息自助更新action***"); + String requestId = requestInfo.getRequestid();//请求ID + String zzxxlx = null; + //取主表数据 + try { + Property[] properties = requestInfo.getMainTableInfo().getProperty();// 获取表单主字段信息 + for (Property property : properties) { + String name = property.getName();// 主字段名称 + String value = Util.null2String(property.getValue());// 主字段对应的值 + if (name.equals("zzxxlx")) { + zzxxlx = value; + break; + } + } + if (StringUtils.isNotBlank(zzxxlx)) { + String[] strings = zzxxlx.split(","); + for (String s : strings) { + handleHrmInfoToCard(recordSet, s, requestId); + } + } + } catch (Exception e) { + baseBean.writeLog(e); + requestInfo.getRequestManager().setMessageid("****" + requestInfo.getRequestid() + "****"); + requestInfo.getRequestManager().setMessagecontent("【员工信息自助更新action】报错,请联系管理员!"); + return Action.FAILURE_AND_CONTINUE; + } + return Action.SUCCESS; + } + + void handleHrmInfoToCard(RecordSet rs, String s, String requestId) { + String updateSql = null; + String insertSql = null; + String selectSql = null; + String resourceId = null; + switch (s) { + case "0": + //更具人员id和学历 判断 插入或更新 建模表主表 + rs.execute("select a.sqr ,b.school ,b.speciality ,b.startdate ,b.enddate ,b.educationlevel ,b.studydesc,b.xllx,b.fj from " + mainTable + " a\n" + + "inner join " + detailTable1 + " b on a.id = b.mainid \n" + + "where requestid ='" + requestId + "' "); + while (rs.next()) { + String sqr = Util.null2String(rs.getString("sqr")); + String school = Util.null2String(rs.getString("school")); + String speciality = Util.null2String(rs.getString("speciality")); + String startdate = Util.null2String(rs.getString("startdate")); + String enddate = Util.null2String(rs.getString("enddate")); + String educationlevel = Util.null2String(rs.getString("educationlevel")); + String studydesc = Util.null2String(rs.getString("studydesc")); + String xllx = Util.null2String(rs.getString("xllx")); + String fj = Util.null2String(rs.getString("fj")); + String workcode = getWorkcode(sqr); + resourceId = sqr; + if("1".equals(xllx)){ + //更新花名册表 + updateSql = "update hrmeducationinfo set school= '"+school+"',speciality='"+speciality+"',startdate='"+startdate+"',enddate='"+enddate+"',educationlevel='"+educationlevel+"',studydesc='"+studydesc+"' where RESOURCEID ='"+sqr+"' "; + insertSql = "INSERT INTO HrmEducationInfo (resourceid, startdate, enddate, school, speciality , educationlevel, studydesc)\n" + + "VALUES ('"+sqr+"', '"+startdate+"', '"+enddate+"', '"+school+"', '"+speciality+"' , '"+educationlevel+"', '"+studydesc+"')"; + selectSql = "select * from HrmEducationInfo where RESOURCEID='"+sqr+"'"; + + String hrmupdate = "update hrmresource set educationlevel = '"+educationlevel+"' where id = '"+sqr+"'"; +// String cusupdate = "update cus_fielddata set field108 = '"+fj+"' where id = '"+sqr+"' and scope = 'HrmCustomFieldByInfoType' and scopeid = 1"; + updateHrmInfo(selectSql,updateSql,insertSql,hrmupdate); + } + +// updateSql = "update uf_hrmeducationinfo set school= '" + school + "',speciality='" + speciality + "',startdate='" + startdate + "',enddate='" + enddate + "',educationlevel='" + educationlevel + "',studydesc='" + studydesc + "',workcode= '" + workcode + "',xllx= '" + xllx + "',fj='" + fj + "' ,modedatamodifydatetime=curtime() where RESOURCEID ='" + sqr + "' and educationlevel = '" + educationlevel + "'"; +// insertSql = "INSERT INTO uf_hrmeducationinfo (resourceid, startdate, enddate, school, speciality , educationlevel, studydesc, workcode, xllx, fj,formmodeid,modedatacreatedate,modedatacreater)\n" + +// "VALUES ('" + sqr + "', '" + startdate + "', '" + enddate + "', '" + school + "', '" + speciality + "' , '" + educationlevel + "', '" + studydesc + "', '" + workcode + "', '" + xllx + "', '" + fj + "' ,37,date_format(now(),'%Y-%m-%d'),curtime())"; +// selectSql = "select * from uf_hrmeducationinfo where RESOURCEID='" + sqr + "' and educationlevel = '" + educationlevel + "'"; +// +// updateHrmEducationInfo(selectSql,updateSql,insertSql,""); + + String businessFields = "resourceid, startdate, enddate, school, speciality , educationlevel, studydesc, workcode, xllx, fj"; + String businessFieldValues = "'"+ sqr + "', '" + startdate + "', '" + enddate + "', '" + school + "', '" + speciality + "' , '" + educationlevel + "', '" + studydesc + "', '" + workcode + "', '" + xllx + "', '" + fj + "' "; + insertUfData("uf_hrmeducationinfo",businessFields,businessFieldValues); + } + break; + case "1": + rs.executeQuery("select sqr, hyzk from " + mainTable + " where requestid = ?", requestId); + if (rs.next()) { + String sqr = Util.null2String(rs.getString("sqr")); + String hyzk = Util.null2String(rs.getString("hyzk")); + resourceId = sqr; + updateSql = "update hrmresource set MARITALSTATUS='" + hyzk + "' where id= '" + sqr + "'"; + } + updateHrmInfo(selectSql,updateSql,insertSql,""); + break; + case "2": + rs.executeQuery("select sqr,lxrxm,gx,lxfs,dz,bz from " + mainTable + " where requestid = ?", requestId); + if (rs.next()) { + String sqr = Util.null2String(rs.getString("sqr")); + String lxrxm = Util.null2String(rs.getString("lxrxm")); + String gx = Util.null2String(rs.getString("gx")); + String lxfs = Util.null2String(rs.getString("lxfs")); + String dz = Util.null2String(rs.getString("dz")); + String bz = Util.null2String(rs.getString("bz")); + resourceId = sqr; + + String lxrxmField = getField("1", "联系人姓名"); + String gxField = getField("1", "关系"); + String lxfsField = getField("1", "联系方式"); + String dzField = getField("1", "地址"); + String bzField = getField("1", "备注"); + updateSql = "update cus_fielddata set " + lxrxmField + "='" + lxrxm + "', " + gxField + "='" + gx + "', " + lxfsField + "='" + lxfs + "', " + dzField + "='" + dz + "', " + bzField + "='" + bz + "' where SCOPE ='HrmCustomFieldByInfoType' and SCOPEID ='1' and id='" + sqr + "'"; + insertSql = "insert into cus_fielddata (scope,scopeid,id," + lxrxmField + "," + gxField + "," + lxfsField + "," + dzField + "," + bzField + ") " + + "values('HrmCustomFieldByInfoType','1','" + sqr + "','" + lxrxm + "','" + gx + "','" + lxfs + "','" + dz + "','" + bz + "') "; + selectSql = "select * from cus_fielddata where SCOPE ='HrmCustomFieldByInfoType' and SCOPEID ='1' and id='" + sqr + "'"; + } + updateHrmInfo(selectSql,updateSql,insertSql,""); + break; + case "3":// 工资福利 + rs.executeQuery("select a.sqr ,b.yhzh ,b.khh ,b.khhdz from " + mainTable + " a \n" + + "inner join " + detailTable2 + " b on a.id =b.mainid \n" + + "where a.requestid ='" + requestId + "'"); + while (rs.next()) { + String sqr = Util.null2String(rs.getString("sqr")); + String yhzh = Util.null2String(rs.getString("yhzh")); + String khh = Util.null2String(rs.getString("khh")); + String khhdz = Util.null2String(rs.getString("khhdz")); + resourceId = sqr; + +// updateSql = "update uf_gzfl set yhzh='" + yhzh + "',yhhm='" + khh + "',khhdz='" + khhdz + "',modedatamodifydatetime = curtime(),modedatamodifier='" + sqr + "' where ry='" + sqr + "'"; +// insertSql = "insert into uf_gzfl (yhhm,yhzh,ry,khhdz,formmodeid,modedatacreatedate,modedatacreater) " + +// "values ('" + khh + "','" + yhzh + "','" + sqr + "','" + khhdz + "',30,date_format(now(),'%Y-%m-%d'),'" + sqr + "')"; +// selectSql = "select * from uf_gzfl where ry='" + sqr + "'"; + + String businessFields = "yhhm,yhzh,ry,khhdz"; + String businessFieldValues = "'" + khh + "','" + yhzh + "','" + sqr + "','" + khhdz + "'"; + insertUfData("uf_gzfl",businessFields,businessFieldValues); + } + break; + case "4"://家庭信息 + rs.executeQuery("select a.sqr ,b.ry ,b.gx ,b.lxfs ,b.zz ,b.csrq ,b.xb from " + mainTable + " a\n" + + "inner join " + detailTable3 + " b on a.id = b.mainid \n" + + "where a.requestid ='" + requestId + "' "); + while (rs.next()) { + String sqr = Util.null2String(rs.getString("sqr")); + String ry = Util.null2String(rs.getString("ry")); + String gx = Util.null2String(rs.getString("gx")); + String lxfs = Util.null2String(rs.getString("lxfs")); + String zz = Util.null2String(rs.getString("zz")); + String csrq = Util.null2String(rs.getString("csrq")); + String xb = Util.null2String(rs.getString("xb")); + resourceId = sqr; + +// updateSql = "update uf_jt set xm = '" + ry + "' ,gx = '" + gx + "' ,lxfs = '" + lxfs + "' ,zz = '" + zz + "' ,csrq= '" + csrq + "' ,xb = '" + xb + "',modedatamodifydatetime=curtime() where ry = '" + sqr + "' "; +// insertSql = "insert into uf_jt (xm,gx,lxfs,zz,csrq,xb,ry,formmodeid,modedatacreatedate,modedatacreatetime,modedatacreater) values" + +// " ('" + ry + "','" + gx + "','" + lxfs + "','" + zz + "','" + csrq + "','" + xb + "','" + sqr + "',4,date_format(now(),'%Y-%m-%d'),curtime(),'" + sqr + "')"; +// selectSql = "select * from uf_jt where ry = '" + sqr + "' "; + + String businessFields = "xm,gx,lxfs,zz,csrq,xb,ry"; + String businessFieldValues = "'" + ry + "','" + gx + "','" + lxfs + "','" + zz + "','" + csrq + "','" + xb + "','" + sqr + "'"; + insertUfData("uf_jt",businessFields,businessFieldValues); + } + break; + case "5"://人力资源工作经历表(入职前) + rs.executeQuery("select a.sqr ,b.gsmc ,b.kssj ,b.jssj ,b.zw ,b.gzms ,b.leavereason from " + mainTable + " a\n" + + "inner join " + detailTable4 + " b on a.id = b.mainid \n" + + "where requestid ='" + requestId + "'"); + while (rs.next()) { + String sqr = Util.null2String(rs.getString("sqr")); + String gsmc = Util.null2String(rs.getString("gsmc")); + String kssj = Util.null2String(rs.getString("kssj")); + String jssj = Util.null2String(rs.getString("jssj")); + String zw = Util.null2String(rs.getString("zw")); + String gzms = Util.null2String(rs.getString("gzms")); + resourceId = sqr; + + String leavereason = Util.null2String(rs.getString("leavereason")); + updateSql = "update hrmworkresume set company = '" + gsmc + "' ,startdate = '" + kssj + "' ,enddate = '" + jssj + "' ," + + "jobtitle = '" + zw + "',workdesc = '" + gzms + "' ,leavereason = '" + leavereason + "' where resourceid = '" + sqr + "'"; + insertSql = "INSERT INTO hrmworkresume\n" + + "(RESOURCEID, STARTDATE, ENDDATE, COMPANY, JOBTITLE, WORKDESC, LEAVEREASON)\n" + + "VALUES('" + sqr + "', '" + kssj + "', '" + jssj + "', '" + gsmc + "', '" + gzms + "', NULL, '" + leavereason + "')"; + selectSql = "select * from hrmworkresume where resourceid = '" + sqr + "'"; + updateHrmInfo(selectSql,updateSql,insertSql,""); + } + break; + case "6": + rs.executeQuery("select sqr, shglqsr from " + mainTable + " where requestid = '" + requestId + "'"); + if (rs.next()) { + String sqr = Util.null2String(rs.getString("sqr")); + String shglqsr = Util.null2String(rs.getString("shglqsr")); + resourceId = sqr; + + updateSql = "update hrmresource set workstartdate = '" + shglqsr + "' where id = '" + sqr + "'"; + updateHrmInfo(selectSql,updateSql,insertSql,""); + } + break; + default: + break; + } +// boolean flag = false; +// if(!"0".equals(s)){ +// if (selectSql != null) { +// new BaseBean().writeLog("---selectSql:"+selectSql); +// rs.execute(selectSql); +// if (rs.next()) { +// flag = true; +// } +// if (flag) { +// rs.execute(updateSql); +// new BaseBean().writeLog("---updateSql:"+updateSql); +// } else { +// rs.execute(insertSql); +// new BaseBean().writeLog("---insertSql:"+insertSql); +// } +// } else { +// if (updateSql != null) { +// rs.execute(updateSql); +// } +// } +// } + if (resourceId != null ) { + new HrmDateCheck().calWorkInfo(resourceId); + } + } + + + + + private void updateHrmInfo(String selectSql,String updateSql,String insertSql,String hrmupdate){ + RecordSet rs = new RecordSet(); + boolean flag = false; + new BaseBean().writeLog("--updateHrmInfo-selectSql:"+selectSql); + + new BaseBean().writeLog("--updateHrmInfo-updateSql:"+updateSql); + + new BaseBean().writeLog("--updateHrmInfo-insertSql:"+insertSql); + + new BaseBean().writeLog("--updateHrmInfo-hrmupdate:"+hrmupdate); + + if (selectSql != null) { + rs.execute(selectSql); + if (rs.next()) { + flag = true; + } + if (flag) { + rs.execute(updateSql); + } else { + rs.execute(insertSql); + } + } else { + if (updateSql != null) { + rs.execute(updateSql); + } + } + if(!"".equals(hrmupdate)){ + rs.execute(hrmupdate); + } + } + + private String getField(String scopeId, String labelName) { + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery("select FIELDID from cus_formfield where SCOPE ='HrmCustomFieldByInfoType' and SCOPEID = ? and HRM_FIELDLABLE =?", scopeId, labelName); + return recordSet.next() ? "field" + Util.null2String(recordSet.getString("FIELDID")) : null; + } + + private String getWorkcode(String userid) { + String workcode = ""; + RecordSet rs = new RecordSet(); + rs.execute("select workcode from hrmresource where id = '" + userid + "'"); + while (rs.next()) { + workcode = Util.null2String(rs.getString("workcode")); + } + return workcode; + } + + /** + * @Author ml + * @Date 2024/3/12 19:24 + * @Description 获取公共部分字段数据 + * @Param [tableName] + * @Return java.lang.String + */ + private static String getPublicFieldData(String tableName) { + RecordSet rs = new RecordSet(); + // 权限重构所需字段 + SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd"); + SimpleDateFormat format2 = new SimpleDateFormat("HH:mm:ss"); + SimpleDateFormat format3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String currentDate = format1.format(new Date()); + String currentTime = format2.format(new Date()); + String currentDateTime = format3.format(new Date()); + String modeDataCreater = "1"; + String modeDataCreaterType = "0"; + String formmodeid = ""; + String sql = "select k.id from modeinfo k inner join workflow_bill l on formid = l.id where l.tablename = '" + tableName + "'"; + rs.execute(sql); + if (rs.next()) { + formmodeid = com.wbi.util.Util.null2String(rs.getString("id")); + } + return "'" + formmodeid + "','" + modeDataCreater + "','" + modeDataCreaterType + "','" + currentDate + "','" + currentTime + "','" + currentDateTime + "',"; + } + + + public boolean insertUfData(String tableName, String businessFields, String businessFieldValues) { + + RecordSet recordSet = new RecordSet(); + String publicFieldData = getPublicFieldData(tableName); + String fields = publicField + businessFields; + String modeUuid = UUID.randomUUID().toString(); + String fieldsData = publicFieldData + "'" + modeUuid + "'," + businessFieldValues; + String insertSql = "insert into " + tableName + "(" + fields + ") values(" + fieldsData + ")"; + baseBean.writeLog("建模数据插入sql:", insertSql); + try { + recordSet.execute(insertSql); + recordSet.execute("select id from " + tableName + " where modeUuid='" + modeUuid + "'"); + if (recordSet.next()) { + /*重构权限*/ + // 建模数据的id + int bid = com.wbi.util.Util.getIntValue(recordSet.getString("id")); + // ModeRightInfo对应的类:weaver.formmode.setup.ModeRightInfo + ModeRightInfo modeRightInfo = new ModeRightInfo(); + modeRightInfo.setNewRight(true); + // 新建的时候添加共享 + modeRightInfo.editModeDataShare(1, getFormModeId(tableName), bid); + } + } catch (Exception e) { + baseBean.writeLog("建模数据插入--ERROR:", e); + return false; + } + return true; + } + + /** + * 获取模块Id + * @param tableName + * @return + */ + private static int getFormModeId(String tableName) { + int formModeId; + RecordSet recordSet = new RecordSet(); + recordSet.execute("select b.id from workflow_bill a,modeinfo b where a.id=b.formid and a.tablename='" + tableName + "'"); + recordSet.next(); + formModeId = Util.getIntValue(recordSet.getString("id")); + return formModeId; + } + + public static String getMainTable() { + return mainTable; + } + + public static void setMainTable(String mainTable) { + SyncHrmInfoToCardAction.mainTable = mainTable; + } + + public static String getDetailTable1() { + return detailTable1; + } + + public static void setDetailTable1(String detailTable1) { + SyncHrmInfoToCardAction.detailTable1 = detailTable1; + } + + public static String getDetailTable2() { + return detailTable2; + } + + public static void setDetailTable2(String detailTable2) { + SyncHrmInfoToCardAction.detailTable2 = detailTable2; + } + + public static String getDetailTable3() { + return detailTable3; + } + + public static void setDetailTable3(String detailTable3) { + SyncHrmInfoToCardAction.detailTable3 = detailTable3; + } + + public static String getDetailTable4() { + return detailTable4; + } + + public static void setDetailTable4(String detailTable4) { + SyncHrmInfoToCardAction.detailTable4 = detailTable4; + } +} diff --git a/src/weaver/interfaces/leshanvc/workflow/action/UpdateStatusAfterRegularAction.java b/src/weaver/interfaces/leshanvc/workflow/action/UpdateStatusAfterRegularAction.java new file mode 100644 index 0000000..e2b3b6c --- /dev/null +++ b/src/weaver/interfaces/leshanvc/workflow/action/UpdateStatusAfterRegularAction.java @@ -0,0 +1,50 @@ +package weaver.interfaces.leshanvc.workflow.action; + +import org.apache.commons.lang3.StringUtils; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.Util; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.Property; +import weaver.soa.workflow.request.RequestInfo; + +/** + * @Author ml + * @Date 2023/4/3 9:45 + * @Description 转正申请(非办公)办结时,更新人员状态、转正日期 + * @Since version-1.0 + */ +public class UpdateStatusAfterRegularAction implements Action { + BaseBean baseBean = new BaseBean(); + + @Override + public String execute(RequestInfo requestInfo) { + baseBean.writeLog("转正申请(非办公)办结更新人员状态action"); + RecordSet rs = new RecordSet(); + String tableName = requestInfo.getRequestManager().getBillTableName(); + String requestId = requestInfo.getRequestid(); + + String updateHrmResource = "update hrmresource set status=1 where id=?"; + String updateCusFieldData = "update cus_fielddata set field18=? where scope='HrmCustomFieldByInfoType' and scopeid='3' and id=?"; + + String zzr = null; + String zzrq = null; + try { + rs.executeQuery("select zzr,zzrq from "+tableName+" where requestid=?",requestId); + if (rs.next()) { + zzr = Util.null2String(rs.getString("zzr")); + zzrq = Util.null2String(rs.getString("zzrq")); + } + if (StringUtils.isNotBlank(zzr)) { + rs.executeUpdate(updateHrmResource,zzr); + rs.executeUpdate(updateCusFieldData,zzrq,zzr); + } + } catch (Exception e) { + baseBean.writeLog(e); + requestInfo.getRequestManager().setMessageid("错误流程requestID" + requestInfo.getRequestid()); + requestInfo.getRequestManager().setMessagecontent("【转正申请(非办公)办结action】报错,请联系管理员!"); + return Action.FAILURE_AND_CONTINUE; + } + return Action.SUCCESS; + } +} diff --git a/src/weaver/interfaces/leshanvc/workflow/entity/FieldMapEntity.java b/src/weaver/interfaces/leshanvc/workflow/entity/FieldMapEntity.java new file mode 100644 index 0000000..1e41893 --- /dev/null +++ b/src/weaver/interfaces/leshanvc/workflow/entity/FieldMapEntity.java @@ -0,0 +1,19 @@ +package weaver.interfaces.leshanvc.workflow.entity; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class FieldMapEntity { + + private String ecField; + private String wfField; + private String ecValue; + private String wfValue; + private String ecType; +} diff --git a/src/weaver/interfaces/leshanvc/workflow/util/CodeRuleUtil.java b/src/weaver/interfaces/leshanvc/workflow/util/CodeRuleUtil.java new file mode 100644 index 0000000..a6b613d --- /dev/null +++ b/src/weaver/interfaces/leshanvc/workflow/util/CodeRuleUtil.java @@ -0,0 +1,21 @@ +package weaver.interfaces.leshanvc.workflow.util; + +import com.engine.hrm.entity.RuleCodeType; +import com.engine.hrm.util.CodeRuleManager; + +public class CodeRuleUtil { + /** + * 自动编号 + * + * @param ruleCodeType + * @param code + * @return + */ + public static String generateCode(RuleCodeType ruleCodeType, String code) { + try { + return CodeRuleManager.getCodeRuleManager().generateRuleCode(ruleCodeType, code); + } catch (Exception e) { + throw new RuntimeException(e); + } + } +} diff --git a/src/weaver/interfaces/leshanvc/workflow/util/ConvertDurationUtil.java b/src/weaver/interfaces/leshanvc/workflow/util/ConvertDurationUtil.java new file mode 100644 index 0000000..8867fbf --- /dev/null +++ b/src/weaver/interfaces/leshanvc/workflow/util/ConvertDurationUtil.java @@ -0,0 +1,29 @@ +package weaver.interfaces.leshanvc.workflow.util; + +/** + * @author:dxfeng + * @createTime: 2023/02/17 + * @version: 1.0 + */ +public class ConvertDurationUtil { + + /** + * 转换公出时间以半小时为最小单位 + * + * @param duration + * @return + */ + public static String handelHalfHour(String duration) { + double outHour = Double.parseDouble(duration); + double conversionHours = 0.0; + double halfHourInt = 0.5; + int step = (int) (outHour / halfHourInt); + double leftMins = outHour - halfHourInt * step; + if (leftMins > 0) { + conversionHours = halfHourInt * step + halfHourInt; + } else { + conversionHours = halfHourInt * step; + } + return Double.toString(conversionHours); + } +} diff --git a/src/weaver/interfaces/leshanvc/workflow/util/FunctionInterfaceMessage.java b/src/weaver/interfaces/leshanvc/workflow/util/FunctionInterfaceMessage.java new file mode 100644 index 0000000..b8102ce --- /dev/null +++ b/src/weaver/interfaces/leshanvc/workflow/util/FunctionInterfaceMessage.java @@ -0,0 +1,40 @@ +package weaver.interfaces.leshanvc.workflow.util; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.Function; + +/** + * @Author weaver_cl + * @Description: + * @Date 2023/2/13 + * @Version V1.0 + **/ +public class FunctionInterfaceMessage { + + private Map> MessageMap; + + + private void init(){ + MessageMap = new HashMap<>(); + MessageMap.put(1,this::workTimeNotice); + MessageMap.put(2,this::workDayNotice); + } + + public String doOperation(Integer params,Integer status) { + this.init(); + return MessageMap.get(status).apply(params); + + } + + private String workTimeNotice(Integer hour){ + return "您本月已累计加班超"+hour+"小时,请注意休息。"; + } + + private String workDayNotice(Integer params){ + return "您已连续工作达6天,请注意休息。"; + } + + + +} diff --git a/src/weaver/interfaces/leshanvc/workflow/util/ResourceSyncUtil.java b/src/weaver/interfaces/leshanvc/workflow/util/ResourceSyncUtil.java new file mode 100644 index 0000000..726fd5d --- /dev/null +++ b/src/weaver/interfaces/leshanvc/workflow/util/ResourceSyncUtil.java @@ -0,0 +1,1106 @@ +package weaver.interfaces.leshanvc.workflow.util; + +import com.api.doc.detail.util.DocDownloadCheckUtil; +import com.api.hrm.service.HrmResourceBaseService; +import com.api.hrm.util.ServiceUtil; +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.service.impl.HrmCommonServiceImpl; +import com.engine.common.util.LogUtil; +import com.engine.hrm.entity.RuleCodeType; +import com.engine.hrm.util.CodeRuleManager; +import com.engine.hrm.util.HrmWeakPasswordUtil; +import com.engine.hrm.util.face.HrmFaceCheckManager; +import com.engine.hrm.util.face.ValidateFieldManager; +import com.engine.hrm.util.face.bean.CheckItemBean; +import com.weaver.general.BaseBean; +import ln.LN; +import org.apache.commons.lang3.StringUtils; +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.conn.RecordSetTrans; +import weaver.crm.CrmShareBase; +import weaver.file.Prop; +import weaver.general.GCONST; +import weaver.general.PasswordUtil; +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.companyvirtual.DepartmentVirtualComInfo; +import weaver.hrm.finance.SalaryManager; +import weaver.hrm.passwordprotection.manager.HrmResourceManager; +import weaver.hrm.privacy.PrivacyComInfo; +import weaver.hrm.privacy.UserPrivacyComInfo; +import weaver.hrm.resource.ResourceComInfo; +import weaver.hrm.settings.ChgPasswdReminder; +import weaver.hrm.settings.RemindSettings; +import weaver.hrm.tools.HrmDateCheck; +import weaver.interfaces.hrm.HrmServiceManager; +import weaver.license.PluginUserCheck; +import weaver.rsa.security.RSA; +import weaver.rtx.OrganisationCom; +import weaver.rtx.OrganisationComRunnable; +import weaver.system.CusFormSetting; +import weaver.system.CusFormSettingComInfo; +import weaver.system.SysRemindWorkflow; +import weaver.systeminfo.SystemEnv; +import weaver.systeminfo.setting.HrmUserSettingComInfo; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class ResourceSyncUtil { + private static final char SEPARATOR = Util.getSeparator(); + private static final String TODAY = DateUtil.getCurrentDate(); + + public static Map addResource(User user, Map params) { + + Map retmap = new HashMap<>(); + RecordSet rs = new RecordSet(); + String sql; + try { + 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 retmap; + } + String loginid = Util.null2String(params.get("loginid")); + String accounttype = Util.null2s(Util.fromScreen3(Util.null2String(params.get(("accounttype"))), user.getLanguage()), "0"); + if ("1".equals(accounttype)) { + 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 retmap; + } + + + if (!"".equals(loginid) && "0".equals(accounttype)) { + sql = "select count(1) from hrmresourceallview where loginid='" + loginid + "' "; + rs.execute(sql); + if (rs.next()) { + if (rs.getInt(1) > 0) { + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(15094, user.getLanguage())); + return retmap; + } + } + } + + String departmentid = Util.null2String(params.get("departmentid")); + String subcompanyid = departmentComInfo.getSubcompanyid1(departmentid); + if (!"".equals(loginid) && !"0".equals(subcompanyid) && new HrmResourceManager().noMore(subcompanyid)) { + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(81926, user.getLanguage())); + return retmap; + } + + + ResourceComInfo ResourceComInfo = new ResourceComInfo(); + Map result = addResourceBase(user, params); + + String addResourceBaseCode = result.get("status"); + if ("-1".equals(addResourceBaseCode)) { + retmap.put("status", "-1"); + retmap.put("message", result.get("message")); + return retmap; + } + + + int id = Util.getIntValue(result.get("id")); + String password = Util.null2String(params.get("password")); + //是否开启了RSA加密 + String openRSA = Util.null2String(Prop.getPropValue("openRSA", "isrsaopen")); + if ("1".equals(openRSA)) { + password = new RSA().decrypt(password); + } + ChgPasswdReminder reminder = new ChgPasswdReminder(); + RemindSettings settings = reminder.getRemindSettings(); + + //判断是否开启了【启用初始密码】 + String defaultPasswordEnable = Util.null2String(settings.getDefaultPasswordEnable()); + //【初始密码】 + String defaultPassword = Util.null2String(settings.getDefaultPassword()); + //如果管理员设置的密码为空。并且开启了【启用初始密码】,且初始密码不为空,则默认取初始密码作为密码 + if ("".equals(password) && "1".equals(defaultPasswordEnable) && !"".equals(defaultPassword)) { + password = defaultPassword; + } + + //判断是否开启了【禁止弱密码保存】 + String weakPasswordDisable = Util.null2s(settings.getWeakPasswordDisable(), "0"); + if ("1".equals(weakPasswordDisable)) { + if (!"".equals(password)) {//密码为空的情况 + //判断是否为弱密码 + HrmWeakPasswordUtil hrmWeakPasswordUtil = new HrmWeakPasswordUtil(); + if (hrmWeakPasswordUtil.isWeakPsd(password)) { + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(515420, user.getLanguage())); + return retmap; + } + } + } + + int seclevel = Util.getIntValue(Util.null2String(params.get("seclevel")), 0); + if (id > 0) {//保存系统信息 + SimpleBizLogger logger = new SimpleBizLogger(); + 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(params.get("workstartdate"));//参加工作日期 + String companystartdate = Util.null2String(params.get("companystartdate"));//入职日期 + String dsporder = Util.fromScreen3(Util.null2String(params.get("dsporder")), user.getLanguage()); + if (dsporder.length() == 0) { + dsporder = "" + id; + } + if ("0".equals(accounttype)) { + + String encrptPassword = ""; + String salt = ""; + if (org.apache.commons.lang3.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; + } + updateWorkInfo(String.valueOf(id), user, params); + + rs.execute(sql); + + HrmFaceCheckManager.setUserPassowrd(id + "", password); + HrmFaceCheckManager.sync(id + "", HrmFaceCheckManager.getOptUpdate(), "HrmResourceAddService_saveSimple_update", 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 weaver.general.BaseBean().getPropValue(GCONST.getConfigFile(), "ecologybbs.linkUrl"); + if (!"0".equals(password)) { + if (!"".equals(bbsLingUrl)) { + new Thread(new weaver.bbs.BBSRunnable(loginid, password)).start(); + } + } + + retmap.put("id", id); + retmap.put("status", "1"); + } catch (Exception e) { + new BaseBean().writeLog("保存新建人员simple错误:" + e); + retmap.put("status", "-1"); + retmap.put("message", "" + weaver.systeminfo.SystemEnv.getHtmlLabelName(22620, weaver.general.ThreadVarLanguage.getLang()) + ""); + } + return retmap; + } + + private static Map addResourceBase(User user, Map params) { + Map retmap = new HashMap<>(); + try { + retmap.put("id", "0"); + 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(); + DepartmentVirtualComInfo DepartmentVirtualComInfo = new DepartmentVirtualComInfo(); + + StringBuilder para; + String cmd = Util.null2String(params.get("cmd")); + String id = Util.null2String(params.get("id")); + String workcode = Util.fromScreen3(Util.null2String(params.get("workcode")), user.getLanguage()); + String lastname = Util.fromScreen3(Util.null2String(params.get("lastname")), user.getLanguage()).trim(); + String sex = Util.fromScreen3(Util.null2String(params.get("sex")), user.getLanguage()); + String resourceimageid = Util.null2String(params.get("resourceimageid")); + if (resourceimageid.length() > 0) { + resourceimageid = "" + DocDownloadCheckUtil.getDownloadfileidstr(resourceimageid); + } + String departmentid = Util.fromScreen3(Util.null2String(params.get("departmentid")), user.getLanguage()); + String costcenterid = Util.fromScreen3(Util.null2String(params.get("costcenterid")), user.getLanguage()); + String jobtitle = Util.fromScreen3(Util.null2String(params.get("jobtitle")), user.getLanguage()); + String joblevel = Util.fromScreen3(Util.null2String(params.get("joblevel")), user.getLanguage()); + String jobactivitydesc = Util.fromScreen3(Util.null2String(params.get("jobactivitydesc")), user.getLanguage()); + String managerid = Util.fromScreen3(Util.null2String(params.get("managerid")), user.getLanguage()); + String assistantid = Util.fromScreen3(Util.null2String(params.get("assistantid")), user.getLanguage()); + String status = Util.fromScreen3(Util.null2String(params.get("status")), user.getLanguage()); + String locationid = Util.fromScreen3(Util.null2String(params.get("locationid")), user.getLanguage()); + String workroom = Util.fromScreen3(Util.null2String(params.get("workroom")), user.getLanguage()); + String telephone = Util.fromScreen3(Util.null2String(params.get("telephone")), user.getLanguage()); + String mobile = Util.fromScreen3(Util.null2String(params.get("mobile")), user.getLanguage()); + String mobileshowtype = Util.fromScreen3(Util.null2String(params.get("mobileshowtype")), user.getLanguage()); + String mobilecall = Util.fromScreen3(Util.null2String(params.get("mobilecall")), user.getLanguage()); + String fax = Util.fromScreen3(Util.null2String(params.get("fax")), user.getLanguage()); + String jobcall = Util.fromScreen3(Util.null2String(params.get("jobcall")), user.getLanguage()); + String email = Util.fromScreen3(Util.null2String(params.get("email")), user.getLanguage()); + String dsporder = Util.fromScreen3(Util.null2String(params.get("dsporder")), user.getLanguage()); + String accounttype = Util.fromScreen3(Util.null2String(params.get("accounttype")), user.getLanguage()); + String systemlanguage = Util.null2String(params.get("systemlanguage")); + if ("".equals(systemlanguage) || "0".equals(systemlanguage)) { + systemlanguage = "7"; + } + String belongto = Util.fromScreen3(Util.null2String(params.get("belongto")), user.getLanguage()); + //应聘人员id + String rcid = Util.null2String(params.get("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 ("0".equals(accounttype)) { + belongto = "-1"; + } + String departmentvirtualids = Util.null2String(params.get("departmentvirtualids"));//虚拟部门id; + + //Td9325,解决多账号次账号没有登陆Id在浏览框组织结构中无法显示的问题。 + boolean falg = false; + String loginid = ""; + if ("1".equals(accounttype)) { + rs.execute("select loginid from HrmResource where id =" + belongto); + if (rs.next()) { + loginid = rs.getString("loginid"); + } + if (!"".equals(loginid)) { + String maxidsql = "select max(id) as id from HrmResource where loginid like '" + loginid + "%'"; + rs.execute(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(); + 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.execute(sql); + String managerstr = ""; + 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 + ","); + } + + 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 ("postgresql".equalsIgnoreCase(rst.getDBType())) { + if (joblevel.length() == 0) { + joblevel = null; + } + if (dsporder.length() == 0) { + dsporder = null; + } + } + workcode = CodeRuleManager.getCodeRuleManager().generateRuleCode(RuleCodeType.USER, subcmpanyid1, departmentid, jobtitle, workcode); + para = new StringBuilder("" + 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.toString()); + 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); + } + 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 = new StringBuilder("" + id); + for (int i = 0; i < 5; i++) { + int idx = i; + if (formdefined) { + idx++; + } + String datefield = Util.null2String(params.get("datefield" + idx)); + String numberfield = "" + Util.getDoubleValue(Util.null2String(params.get("numberfield" + idx)), 0); + String textfield = Util.null2String(params.get("textfield" + idx)); + String tinyintfield = "" + Util.getIntValue(Util.null2String(params.get("tinyintfield" + idx)), 0); + para.append(SEPARATOR).append(datefield).append(SEPARATOR).append(numberfield).append(SEPARATOR).append(textfield).append(SEPARATOR).append(tinyintfield); + } + rs.executeProc("HrmResourceDefine_Update", para.toString()); + 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.execute(deletePriSql); + for (Map.Entry me : mapShowSets.entrySet()) { + String fieldName = me.getKey(); + String fieldVal = Util.null2String(mapShowSets.get(fieldName)); + if ("1".equals(fieldVal)) { + String tmpPK = id + "__" + fieldName; + String tmpPvalue = Util.null2String(params.get(fieldName + "showtype")); + insertSql = "insert into userprivacysetting (combinedid,userid,ptype,pvalue) values('" + tmpPK + "','" + id + "','" + fieldName + "','" + tmpPvalue + "')"; + rs.execute(insertSql); + } + } + upc.removeUserPrivacyCache(); + } catch (Exception e) { + e.printStackTrace(); + } + + + // 改为只进行该人缓存信息的添加 + ResourceComInfo.addResourceInfoCache(id); + SalaryManager.initResourceSalary(id); + + para = new StringBuilder("" + id + SEPARATOR + managerid + SEPARATOR + departmentid + SEPARATOR + subcmpanyid1 + SEPARATOR + "0" + SEPARATOR + managerstr); + rs.executeProc("HrmResource_Trigger_Insert", para.toString()); + + String sql_1 = ("insert into HrmInfoStatus (itemid,hrmid) values(1," + id + ")"); + rs.execute(sql_1); + String sql_2 = ("insert into HrmInfoStatus (itemid,hrmid) values(2," + id + ")"); + rs.execute(sql_2); + String sql_3 = ("insert into HrmInfoStatus (itemid,hrmid) values(3," + id + ")"); + rs.execute(sql_3); + String sql_10 = ("insert into HrmInfoStatus (itemid,hrmid) values(10," + id + ")"); + rs.execute(sql_10); + + 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 += ":" + lastname; + + //modifier by lvyi 2013-12-31 + if ("1".equals(settings.getEntervalid())) {//入职提醒 + String thesql = "select hrmids from HrmInfoMaintenance where id<4 or id = 10"; + rs.execute(thesql); + StringBuilder members = new StringBuilder(); + while (rs.next()) { + String hrmid_tmp = Util.null2String(rs.getString("hrmids"));//TD9392 + if (hrmid_tmp.length() != 0) { + members.append(",").append(rs.getString("hrmids")); + } + } + if (!"".equals(members.toString())) { + members = new StringBuilder(members.substring(1)); + members = new StringBuilder(new HrmResourceBaseService().duplicateRemoval(members.toString(), user.getUID() + "")); + SWFAccepter = members.toString(); + SWFTitle = SystemEnv.getHtmlLabelName(15670, user.getLanguage()); + SWFTitle += ":" + lastname; + SWFTitle += "-" + CurrentUserName; + SWFTitle += "-" + TODAY; + 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.contains(".")) { + height = height.substring(0, height.indexOf(".")); + } + String weight = Util.null2String(rs.getString("weight")); + if (weight.contains(".")) { + 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 = new StringBuilder("" + 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.toString()); + } + } + //更新虚拟组织部门id + if (departmentvirtualids.length() > 0) { + //保存前先删除需要删除的数据,因为有managerid 所以不能全部删除再保存 + sql = "delete from hrmresourcevirtual where resourceid=" + id + " and departmentid not in (" + departmentvirtualids + ")"; + rs.execute(sql); + + String[] departmentvirtualid = departmentvirtualids.split(","); + for (String s : departmentvirtualid) { + rs.execute(" select count(*) from HrmResourceVirtual where departmentid ='" + s + "' and resourceid = " + id); + if (rs.next()) { + //如果已存在 无需处理 + if (rs.getInt(1) > 0) { + continue; + } + } + + //写入 + int tmpid = 0; + rs.execute("select max(id) from HrmResourceVirtual "); + if (rs.next()) { + tmpid = rs.getInt(1) + 1; + } + String subcompanyid = DepartmentVirtualComInfo.getSubcompanyid1(s); + sql = " insert into HrmResourceVirtual (id,resourceid,subcompanyid,departmentid ) " + + " values (" + tmpid + "," + id + "," + subcompanyid + "," + s + ")"; + rs.execute(sql); + } + } + + LogUtil.writeBizLog(logger.getBizLogContexts()); + + 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与第三方接口单条数据同步方法结束 + + //新增人员实时同步到CoreMail邮件系统 + //CoreMailAPI.synUser(id); + retmap.put("status", "1"); + retmap.put("id", id); + } catch (Exception e) { + new BaseBean().writeLog("新建人员基本信息错误:" + e); + retmap.put("status", "-1"); + } + return retmap; + } + + public static Map editResourceBase(User user, Map params) { + Map retMap = new HashMap<>(); + try { + String id = Util.null2String(params.get("id")); + // 判断是否为本人操作 + boolean canEdit = HrmUserVarify.checkUserRight("HrmResourceEdit:Edit", user); + if (!canEdit && !Util.null2String(user.getUID()).equals(id)) { + retMap.put("status", "-1"); + retMap.put("message", "" + weaver.systeminfo.SystemEnv.getHtmlLabelName(22620, weaver.general.ThreadVarLanguage.getLang()) + ""); + return retMap; + } + RecordSet rs = new RecordSet(); + DepartmentComInfo DepartmentComInfo = new DepartmentComInfo(); + ResourceComInfo ResourceComInfo = new ResourceComInfo(); + HrmServiceManager HrmServiceManager = new HrmServiceManager(); + CrmShareBase CrmShareBase = new CrmShareBase(); + + StringBuilder para; + + if (id.length()==0) { + retMap.put("status", "-1"); + retMap.put("message", ""+weaver.systeminfo.SystemEnv.getHtmlLabelName(22620,weaver.general.ThreadVarLanguage.getLang())+""); + return retMap; + } + String workcode = Util.fromScreen3(Util.null2String(params.get("workcode")), user.getLanguage()); + String lastname = Util.fromScreen3(Util.null2String(params.get("lastname")), user.getLanguage()).trim(); + String sex = Util.fromScreen3((Util.null2String(params.get("sex"))), user.getLanguage()); + String resourceimageid = Util.null2String(params.get("resourceimageid")); + if(resourceimageid.length()>0) { + resourceimageid = "" + DocDownloadCheckUtil.getDownloadfileidstr(resourceimageid); + } + String resourceimageBase64 = Util.null2String(params.get("resourceimageBase64")); + if(resourceimageBase64.length()>0){ + resourceimageid = ServiceUtil.saveResourceImage(resourceimageBase64); + } + String oldresourceimageid = Util.null2String(params.get("oldresourceimage")); + if ("".equals(resourceimageid)) { + resourceimageid = oldresourceimageid; + } + String departmentid = Util.fromScreen3(Util.null2String(params.get("departmentid")), user.getLanguage()); + String costcenterid = Util.fromScreen3(Util.null2String(params.get("costcenterid")), user.getLanguage()); + String jobtitle = Util.fromScreen3(Util.null2String(params.get("jobtitle")), user.getLanguage()); + String joblevel = Util.fromScreen3(Util.null2String(params.get("joblevel")), user.getLanguage()); + String jobactivitydesc = Util.fromScreen3(Util.null2String(params.get("jobactivitydesc")), user.getLanguage()); + String managerid = Util.fromScreen3(Util.null2String(params.get("managerid")), user.getLanguage()); + String assistantid = Util.fromScreen3(Util.null2String(params.get("assistantid")), user.getLanguage()); + String status = Util.fromScreen3(Util.null2String(params.get("status")), user.getLanguage()); + String locationid = Util.fromScreen3(Util.null2String(params.get("locationid")), user.getLanguage()); + String workroom = Util.fromScreen3(Util.null2String(params.get("workroom")), user.getLanguage()); + String telephone = Util.fromScreen3(Util.null2String(params.get("telephone")), user.getLanguage()); + String mobile = Util.fromScreen3(Util.null2String(params.get("mobile")), user.getLanguage()); + String mobileshowtype = Util.fromScreen3(Util.null2String(params.get("mobileshowtype")), user.getLanguage()); + String mobilecall = Util.fromScreen3(Util.null2String(params.get("mobilecall")), user.getLanguage()); + String fax = Util.fromScreen3(Util.null2String(params.get("fax")), user.getLanguage()); + String email = Util.fromScreen3(Util.null2String(params.get("email")), user.getLanguage()); + String dsporder = Util.fromScreen3(Util.null2String(params.get("dsporder")), user.getLanguage()); + String jobcall = Util.fromScreen3(Util.null2String(params.get("jobcall")), user.getLanguage()); + String systemlanguage = Util.fromScreen3(Util.null2String(params.get("systemlanguage")), user.getLanguage()); + if ("".equals(systemlanguage) || "0".equals(systemlanguage)) { + systemlanguage = "7"; + } + String accounttype = Util.fromScreen3(Util.null2String(params.get("accounttype")), user.getLanguage()); + String belongto = Util.fromScreen3(Util.null2String(params.get("belongto")), user.getLanguage()); + if (dsporder.length() == 0) { + dsporder = id; + } + if ("0".equals(accounttype)) { + 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(); + 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.execute("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 ("1".equals(thisAccounttype) && "0".equals(accounttype)) { + oldbelongto = rs.getString("belongto"); + } + } + + if ("1".equals(accounttype) && "".equalsIgnoreCase(loginid)) { + rs.execute("select loginid from HrmResource where id =" + belongto); + if (rs.next()) { + loginid = rs.getString(1); + } + + if (!"".equals(loginid)) { + loginid = loginid + (id + 1); + falg = true; + } + } + String sql = "select * from HrmResource where id = " + Util.getIntValue(id); + rs.execute(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"; + } + + if (StringUtils.isNotEmpty(workcode)) { + CodeRuleManager.getCodeRuleManager().checkReservedIfDel(RuleCodeType.USER.getValue(), workcode); + } + para = new StringBuilder("" + 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.toString()); + 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.execute(deletePriSql); + for (Map.Entry me : mapShowSets.entrySet()) { + String fieldName = me.getKey(); + String fieldVal = Util.null2String(mapShowSets.get(fieldName)); + if ("1".equals(fieldVal)) { + String tmpPK = id + "__" + fieldName; + String tmpPvalue = Util.null2String(params.get(fieldName + "showtype")); + insertSql = "insert into userprivacysetting (combinedid,userid,ptype,pvalue) values('" + tmpPK + "','" + id + "','" + fieldName + "','" + tmpPvalue + "')"; + rs.execute(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.execute(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 = new StringBuilder("" + id + SEPARATOR + managerstr); + rst.executeProc("HrmResource_UpdateManagerStr", para.toString()); + 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.execute(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 = new StringBuilder(resourceid + SEPARATOR + nowmanagerstr2); + rst.executeProc("HrmResource_UpdateManagerStr", para.toString()); + rst.commit(); + ResourceComInfo.updateResourceInfoCache(resourceid); //更新缓存 + } catch (Exception e) { + rst.rollback(); + e.printStackTrace(); + } + } + } + + String subcmpanyid1 = DepartmentComInfo.getSubcompanyid1(departmentid); + para = new StringBuilder("" + id + SEPARATOR + subcmpanyid1); + rst = new RecordSetTrans(); + rst.setAutoCommit(false); + try { + rst.executeProc("HrmResource_UpdateSubCom", para.toString()); + 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; + CusFormSettingComInfo CusFormSettingComInfo = new weaver.system.CusFormSettingComInfo(); + CusFormSetting CusFormSetting = CusFormSettingComInfo.getCusFormSetting("hrm", "HrmResourceBase"); + if (CusFormSetting != null) { + if (CusFormSetting.getStatus() == 2) { + //自定义布局页面 + formdefined = true; + } + } + para = new StringBuilder("" + id); + for (int i = 0; i < 5; i++) { + int idx = i; + if (formdefined) { + idx++; + } + String datefield = Util.null2String(params.get("datefield" + idx)); + String numberfield = "" + Util.getDoubleValue(Util.null2String(params.get("numberfield" + idx)), 0); + String textfield = Util.null2String(params.get("textfield" + idx)); + String tinyintfield = "" + Util.getIntValue(Util.null2String(params.get("tinyintfield" + idx)), 0); + para.append(SEPARATOR).append(datefield).append(SEPARATOR).append(numberfield).append(SEPARATOR).append(textfield).append(SEPARATOR).append(tinyintfield); + } + rs.executeProc("HrmResourceDefine_Update", para.toString()); + + new Thread(new OrganisationComRunnable("user", "editbasicinfo", id + "-" + status)).start(); + // 改为自进行修正 + ResourceComInfo.updateResourceInfoCache(id); + + try { + //OA与第三方接口单条数据同步方法开始 + HrmServiceManager.SynInstantHrmResource(id, "2"); + //OA与第三方接口单条数据同步方法结束 + } catch (Exception e) { + new BaseBean().writeLog("OA与第三方接口单条数据同步失败" + e); + } + + + //处理次账号修改为主账号时,检查次账号所属 主账号的 其他设置是否需要修改 add by kzw QC159888 + try { + if (!"".equals(oldbelongto)) { + HrmUserSettingComInfo userSetting = new HrmUserSettingComInfo(); + String belongtoshow = userSetting.getBelongtoshowByUserId(oldbelongto); + if ("1".equals(belongtoshow)) { + rs.execute("select id from hrmresource where belongto = " + oldbelongto); + if (!rs.next()) { + String setId = userSetting.getId(oldbelongto); + rs.execute("update HrmUserSetting set belongtoshow=0 where id=" + setId); + userSetting.removeHrmUserSettingComInfoCache(); + } + } + } + } catch (Exception e) { + new BaseBean().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()); + + HrmFaceCheckManager.sync(id, HrmFaceCheckManager.getOptUpdate(), "hrm_e9_HrmResourceBaseService_editResourceBase", HrmFaceCheckManager.getOaResource()); + + retMap.put("status", "1"); + retMap.put("id", id); + } catch (Exception e) { + new BaseBean().writeLog(e); + retMap.put("status", "-1"); + retMap.put("message", ""+weaver.systeminfo.SystemEnv.getHtmlLabelName(22620,weaver.general.ThreadVarLanguage.getLang())+""); + } + return retMap; + } + + private static void updateWorkInfo(String id, User user, Map params) { + try { + RecordSet rs = new RecordSet(); + String sql; + String companystartdate = Util.fromScreen3(Util.null2String(params.get("companystartdate")), user.getLanguage()); + String workstartdate = Util.fromScreen3(Util.null2String(params.get("workstartdate")), user.getLanguage()); + + List lsParams = new ArrayList<>(); + lsParams.add(companystartdate.length() == 0 ? null : companystartdate); + lsParams.add(workstartdate.length() == 0 ? null : workstartdate); + lsParams.add(id); + sql = " update hrmresource set companystartdate=?,workstartdate=? where id=?"; + rs.executeUpdate(sql, lsParams); + HrmDateCheck hrmDateCheck = new HrmDateCheck(); + hrmDateCheck.calWorkInfo(id); + } catch (Exception e) { + new BaseBean().writeLog(e); + } + } + + public static Map convertEcResourceParams(Map params){ + // 先查询原有EC人员信息,再封装传参 + Map convertParams = new HashMap<>(); + String jclResourceId = Util.null2String(params.get("id")); + // 更新人员时,初始化人员参数 + if (StringUtils.isNotBlank(jclResourceId)) { + RecordSet rs = new RecordSet(); + rs.execute("select * from hrmresource where id = '" + jclResourceId + "'"); + int colcount = rs.getColCounts(); + if (rs.next()) { + for (int i = 1; i <= colcount; i++) { + convertParams.put(rs.getColumnName(i).toLowerCase(), Util.null2String(rs.getString(i))); + } + } + } + + + // 部门ID + convertParams.put("departmentid",params.get("ec_department")); + // EC岗位 + String jclJobId = Util.null2String(params.get("job_title")); + String ecJobId = "1"; + if (StringUtils.isNotBlank(jclJobId)) { + RecordSet rs = new RecordSet(); + rs.executeQuery("select ec_jobTitle from from jcl_org_job t left join hrmjobtitles h on t.ec_jobTitle = h.id\n" + + " where t.delete_type = 0 and t.id='"+jclJobId+"'"); + while (rs.next()){ + ecJobId = Util.null2String(rs.getString("ec_jobTitle")); + } + } + convertParams.put("jobtitle",ecJobId); + + convertParams.put("workcode",params.get("work_code")); + convertParams.put("lastname",params.get("last_name")); + convertParams.put("sex",params.get("sex")); + convertParams.put("status",params.get("status")); + convertParams.put("accounttype",params.get("account_type")); + convertParams.put("belongto",params.get("belong_to")); + convertParams.put("locationid",params.get("location_id")); + convertParams.put("dsporder",params.get("show_order")); + convertParams.put("companystartdate",params.get("company_start_date")); + convertParams.put("workstartdate",params.get("work_start_date")); + convertParams.put("resourceimageid",params.get("resource_image_id")); + convertParams.put("jobactivitydesc",params.get("job_activity_desc")); + + convertParams.put("mobile",params.get("mobile")); + convertParams.put("telephone",params.get("telephone")); + convertParams.put("email",params.get("email")); + + // 直接上级 + convertParams.put("managerid", params.get("manager_id")); + + + return convertParams; + } +} diff --git a/src/weaver/workflow/dmlaction/commands/actions/DMLAction.java b/src/weaver/workflow/dmlaction/commands/actions/DMLAction.java new file mode 100644 index 0000000..ad7425f --- /dev/null +++ b/src/weaver/workflow/dmlaction/commands/actions/DMLAction.java @@ -0,0 +1,1936 @@ +package weaver.workflow.dmlaction.commands.actions; + +import java.lang.reflect.Array; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.math.BigDecimal; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.beanutils.BeanUtils; +import org.apache.commons.lang.StringUtils; + +import weaver.conn.ConnStatement; +import weaver.conn.ConnStatementDataSource; +import weaver.conn.RecordSet; +import weaver.conn.RecordSetDataSource; +import weaver.conn.RecordSetTrans; +import weaver.general.BaseBean; +import weaver.general.GCONST; +import weaver.general.Util; +import weaver.hrm.company.DepartmentComInfo; +import weaver.hrm.company.SubCompanyComInfo; +import weaver.hrm.resource.ResourceComInfo; +import weaver.integration.logging.Logger; +import weaver.integration.logging.LoggerFactory; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.Cell; +import weaver.soa.workflow.request.DetailTable; +import weaver.soa.workflow.request.Property; +import weaver.soa.workflow.request.RequestInfo; +import weaver.soa.workflow.request.Row; +import weaver.workflow.dmlaction.DBTypeUtil; +import weaver.workflow.request.RequestManager; +import weaver.workflow.workflow.GetShowCondition; + +public class DMLAction extends BaseBean implements Action { + private static Logger newlog = LoggerFactory.getLogger(DMLAction.class); + private int workflowid; + private int nodeid; + private int nodelinkid; + private int ispreoperator; + private int actionid; + private String isNewMark;// 表示是70新的节点后动作开发的标识 + private String baseid;// 表示是70新的节点后动作的集成浏览按钮的id + private Map attr; + + public String getBaseid() { + return baseid; + } + + public void setBaseid(String baseid) { + this.baseid = baseid; + } + + public int getActionid() { + return actionid; + } + + public void setActionid(int actionid) { + this.actionid = actionid; + } + + public int getWorkflowid() { + return workflowid; + } + + public void setWorkflowid(int workflowid) { + this.workflowid = workflowid; + } + + public int getNodeid() { + return nodeid; + } + + public void setNodeid(int nodeid) { + this.nodeid = nodeid; + } + + public int getNodelinkid() { + return nodelinkid; + } + + public void setNodelinkid(int nodelinkid) { + this.nodelinkid = nodelinkid; + } + + public int getIspreoperator() { + return ispreoperator; + } + + public void setIspreoperator(int ispreoperator) { + this.ispreoperator = ispreoperator; + } + + /** + * 执行dmlaction + */ + public String execute(RequestInfo request) { + + if (workflowid <= 0 || (nodeid < 0 && nodelinkid < 0)) { + return this.SUCCESS; + } + try { + RecordSetTrans rst = request.getRsTrans(); + RecordSet rs = new RecordSet(); + // 获取dmlaction 属性 + List dmlList = this.getDmlActionSet(rst, rs); + + + newlog.info("获取dmlaction 属性 dmlList : " + dmlList.size()); + Property[] properties = request.getMainTableInfo().getProperty();// 获取表单主字段信息 + int requestid = request.getRequestManager().getRequestid(); + int billid = request.getRequestManager().getBillid(); + int formid = request.getRequestManager().getFormid(); + int isbill = request.getRequestManager().getIsbill(); + newlog.info("requestid:" + requestid + " billid:" + billid); + newlog.info("properties.length:" + properties.length); + /*int plength = properties.length; + properties = (Property[]) expand(properties, plength + 2); + + Property Property = new Property(); + Property.setName("requestid"); + Property.setValue(String.valueOf(requestid)); + properties[plength] = Property; + + Property = new Property(); + Property.setName("id"); + Property.setValue(String.valueOf(billid)); + properties[plength + 1] = Property;*/ + properties = this.setPropertys(properties, request); + List propertiesList = new ArrayList(); + RequestManager manager = request.getRequestManager(); + attr = new HashMap(); + loadProperty(manager.getUser());// 装载节点操作者相关信息 + loadProperty(manager);// 装载流程当前请求信息 + loadMainInfotoProp(properties, request.getDetailTableInfo() + .getDetailTable()); + if (dmlList.size() > 0) { + String fieldname = ""; + List fieldtypeList = new ArrayList(); + List fieldnameList = new ArrayList(); + List fieldvalueList = new ArrayList(); + List sqlsetList = new ArrayList(); + for (int i = 0; i < dmlList.size(); i++) { + sqlsetList.clear(); + propertiesList.clear(); + sqlsetList = (List) dmlList.get(i); + newlog.info("***************************************dml action start***************************************"); + newlog.info("获取数据值 sqlsetList : " + sqlsetList + + " sqlsetList.size() : " + sqlsetList.size()); + if (null != sqlsetList && sqlsetList.size() > 12) { + String dmlactionname=""; + try { + String sqlsetid = (String) sqlsetList.get(0); + String datasourceid = (String) sqlsetList.get(1); + String dmltype = (String) sqlsetList.get(2); + String dmlsql = (String) sqlsetList.get(3); + String dmlfieldtypes = (String) sqlsetList.get(4); + String dmlfieldnames = (String) sqlsetList.get(5); + String dmlcuswhere = (String) sqlsetList.get(6); + String dmlmainsqltype = (String) sqlsetList.get(7); + String dmlcussql = (String) sqlsetList.get(8); + dmlactionname = (String) sqlsetList.get(9); + + if(dmltype.equals("insert")){ + dmlcuswhere=""; + } + + String dmlcuswherebak = dmlcuswhere; + String dmlcussqlbak = dmlcussql; + + int dmlsource = Util.getIntValue(Util.null2String(sqlsetList.get(10)),-1); + String dmlsourcetype = Util.null2String(sqlsetList.get(11)); + int dmlsourceorder = Util.getIntValue(Util.null2String(sqlsetList.get(12)),0); + + Map fieldIdeMap = new HashMap(); //fieldid + Map fieldHtmlTypeMap = new HashMap(); //field htmltype + Map fieldTypeMap = new HashMap(); //field type + Map fieldDbTypeMap = new HashMap(); //field dbtype + + + //获取当前action对应的表单字段的信息,包含主表和明细表(如果有) + getFieldsInfo(rst, rs, formid, isbill,fieldIdeMap,fieldHtmlTypeMap, fieldTypeMap,fieldDbTypeMap,dmlsource); + + //获取映射信息 + Map> fieldMapSet = getFieldMapSet(rst, rs, sqlsetid,null); + if("detail".equals(dmlsourcetype)){ + String detailTable = getDetailTable(rst, rs, formid, isbill, dmlsource); //获取明细表名称 + propertiesList = loadDetail(properties, request, detailTable); //加载明细表数据 + }else{ + propertiesList.add(properties); //主表数据 + } + fieldtypeList.clear(); + fieldnameList.clear(); + + fieldnameList = Util.TokenizerString(dmlfieldnames, + "|"); + fieldtypeList = Util.TokenizerString(dmlfieldtypes, + "|"); + + for(Property [] props : propertiesList){ + fieldvalueList.clear(); + // 获取数据值 + this.getFieldValues(rst,rs,fieldname, props,fieldIdeMap, + fieldHtmlTypeMap, fieldTypeMap,fieldDbTypeMap,fieldMapSet, + fieldtypeList, fieldnameList, + fieldvalueList,request); + newlog.info("获取数据值 fieldtypeList : " + fieldtypeList + + " fieldnameList : " + fieldnameList + + " fieldvalueList : " + fieldvalueList); + // 替换自定义条件sql的值 + String dmlcuswhere2 = this.setDmlCusSqlOrWhereValues( + fieldname, props, dmlcuswherebak); + // 替换自定dml sql的值 + String dmlcussql2 = this.setDmlCusSqlOrWhereValues( + fieldname, props, dmlcussqlbak); + // 以sql的形式执行dmlaction + dmlcussql2 = loadTableInfo(dmlcussql2, requestid, + formid, isbill, rst, rs, dmltype); + dmlcussql2 = setDmlCusSqlValues(dmlcussql2); + dmlcussql2 = dmlcussql2.replaceAll("\r", " ").replaceAll("\n", " ");//处理sql语句中的回车换行符 +// this.executeDMLAction(rst, rs, datasourceid, +// dmltype, dmlsql, fieldtypeList, +// fieldvalueList, dmlcuswhere2.trim(), +// dmlmainsqltype, dmlcussql2.trim()); + this.executeDMLActionNew(rst, rs, datasourceid, + dmltype, dmlsql, fieldtypeList, + fieldvalueList, dmlcuswhere2.trim(), + dmlmainsqltype, dmlcussql2.trim()); + } + } catch (Exception e) { + e.printStackTrace(); + newlog.error("dmlaction e : " + e); + return StringUtils.isBlank(dmlactionname)?"-1":"-1,"+dmlactionname+" \n ErrorMsg : "+e; + } + } + newlog.info("***************************************dml action end***************************************"); + } + } + } catch (Exception e) { + e.printStackTrace(); + newlog.error("dml action执行出错 dmlaction e : " + e); + return "-1"; + } + return this.SUCCESS; + } + private Property[] setPropertys(Property[] properties,RequestInfo request) + { + int requestid = request.getRequestManager().getRequestid(); + int workflowid = request.getRequestManager().getWorkflowid(); + int billid = request.getRequestManager().getBillid(); + int formid = request.getRequestManager().getFormid(); + int nodeid = request.getRequestManager().getNodeid(); + String nodetype = request.getRequestManager().getNodetype(); + String requestname = request.getRequestManager().getRequestname(); + String remark = request.getRequestManager().getRemark(); + int creater = request.getRequestManager().getCreater(); + ResourceComInfo ResourceComInfo = null; + try + { + ResourceComInfo = new ResourceComInfo(); + } + catch(Exception e) + { + + } + String createrdepartment = ResourceComInfo.getDepartmentID(""+creater); + int userid = request.getRequestManager().getUserId(); + String lastname = ResourceComInfo.getLastname(""+userid); + String usersubcompany = ResourceComInfo.getSubCompanyID(""+userid); + String userdepartment = ResourceComInfo.getDepartmentID(""+userid); + String managerid = ResourceComInfo.getManagerID(""+userid); + String managerstr = ResourceComInfo.getManagersIDs(""+userid); + newlog.info("requestid:"+requestid+" billid:"+billid); + newlog.info("properties.length:"+properties.length); + + int plength = properties.length; + properties = (Property[]) expand(properties,plength+16); + + Property Property = new Property(); + Property.setName("id"); + Property.setValue(String.valueOf(billid)); + properties[plength] = Property; + + Property = new Property(); + Property.setName("requestid"); + Property.setValue(String.valueOf(requestid)); + properties[plength+1] = Property; + + + Property = new Property(); + Property.setName("s.workflowid"); + Property.setValue(String.valueOf(workflowid)); + properties[plength+2] = Property; + + + /*流程类型ID s.workflowid int + 表单ID s.formid int + 当前节点ID s.nodeid int + 当前节点类型 s.nodetype int + 请求标题 s.requestname varchar + 签字意见 s.remark varchar + 请求创建人 s.creater int + 请求创建人部门 s.createrdepartment int + 节点操作者姓名 s.lastname int + 用户ID s.userid int + 节点操作者分部 s.usersubcompany int + 节点操作者部门 s.userdepartment int + 节点操作者上级 s.managerid int + 节点操作者所有上级 s.managerstr varchar*/ + + Property = new Property(); + Property.setName("s.formid"); + Property.setValue(String.valueOf(formid)); + properties[plength+3] = Property; + + Property = new Property(); + Property.setName("s.nodeid"); + Property.setValue(String.valueOf(nodeid)); + properties[plength+4] = Property; + + Property = new Property(); + Property.setName("s.nodetype"); + Property.setValue(String.valueOf(nodetype)); + properties[plength+5] = Property; + + Property = new Property(); + Property.setName("s.requestname"); + Property.setValue(String.valueOf(requestname)); + properties[plength+6] = Property; + + Property = new Property(); + Property.setName("s.remark"); + Property.setValue(String.valueOf(remark)); + properties[plength+7] = Property; + + Property = new Property(); + Property.setName("s.creater"); + Property.setValue(String.valueOf(creater)); + properties[plength+8] = Property; + + Property = new Property(); + Property.setName("s.createrdepartment"); + Property.setValue(String.valueOf(createrdepartment)); + properties[plength+9] = Property; + + Property = new Property(); + Property.setName("s.lastname"); + Property.setValue(String.valueOf(lastname)); + properties[plength+10] = Property; + + Property = new Property(); + Property.setName("s.userid"); + Property.setValue(String.valueOf(userid)); + properties[plength+11] = Property; + + Property = new Property(); + Property.setName("s.usersubcompany"); + Property.setValue(String.valueOf(usersubcompany)); + properties[plength+12] = Property; + + Property = new Property(); + Property.setName("s.userdepartment"); + Property.setValue(String.valueOf(userdepartment)); + properties[plength+13] = Property; + + Property = new Property(); + Property.setName("s.managerid"); + Property.setValue(String.valueOf(managerid)); + properties[plength+14] = Property; + + Property = new Property(); + Property.setName("s.managerstr"); + Property.setValue(String.valueOf(managerstr)); + properties[plength+15] = Property; + return properties; + } + /** + * 获取dmlaction 属性 + * + * @param rst + * @param rs + * @return + * @throws Exception + */ + private List getDmlActionSet(RecordSetTrans rst, RecordSet rs) + throws Exception { + List dmlList = new ArrayList(); + StringBuffer sqlsb = new StringBuffer(); + sqlsb.append("select t.id,"); + sqlsb.append(" f.datasourceid,"); + sqlsb.append(" f.dmltype,"); + sqlsb.append(" t.dmlsql,"); + sqlsb.append(" t.dmlfieldtypes,"); + sqlsb.append(" t.dmlfieldnames,"); + sqlsb.append(" t.dmlcuswhere,"); + sqlsb.append(" t.dmlmainsqltype,"); + sqlsb.append(" t.dmlcussql,"); + sqlsb.append(" f.dmlactionname,"); + + sqlsb.append(" f.dmlsource,"); + sqlsb.append(" f.dmlsourcetype,"); + sqlsb.append(" f.dmlsourceorder"); + + sqlsb.append(" from workflowactionset s, formactionset f,formactionsqlset t"); + if (rs.getDBType().equals("oracle")){ + sqlsb.append(" where s.interfaceid = to_char(f.id) and f.id=t.actionid "); + } + else if (rs.getDBType().equals("postgresql")){ + sqlsb.append(" where s.interfaceid = to_char(f.id) and f.id=t.actionid "); + } + else if(rs.getDBType().equals("mysql")){ + sqlsb.append(" where s.interfaceid = concat(f.id,'') and f.id=t.actionid "); + } else { + sqlsb.append(" where s.interfaceid = cast(f.id as varchar) and f.id=t.actionid "); + } + sqlsb.append(" and s.workflowid =" + workflowid); + /** + * nodeid -2 强制收回附加操作 + * nodeid -3 流程删除附加操作 + */ + if (nodeid > 0 || nodeid == -2 || nodeid == -3) { + sqlsb.append(" and s.nodeid =" + nodeid); + if ((null != rs && rs.getDBType().equals("oracle")) + || (null != rst && rst.getDBType().equals("oracle"))) { + sqlsb.append(" and nvl(s.ispreoperator, 0) = " + + ispreoperator); + } else if(rs.getDBType().equals("mysql")){ + sqlsb.append(" and ifnull(s.ispreoperator, 0) = " + ispreoperator); + } else { + sqlsb.append(" and isnull(s.ispreoperator, 0) = " + + ispreoperator); + } + } + if (nodelinkid > 0) { + sqlsb.append(" and s.nodelinkid = " + nodelinkid); + } + if (actionid > 0) { + sqlsb.append(" and t.actionid=" + actionid); + } + sqlsb.append(" order by s.actionorder"); + + newlog.info("获取dmlaction 属性 sqlsb : " + sqlsb.toString()); + if (null != rst) { + rst.executeSql(sqlsb.toString()); + if (rst.next()) { + List sqlsetList = this.setSqlsetList(rst, null); + if (sqlsetList.size() > 0) { + dmlList.add(sqlsetList); + } + } + } else if (null != rs) { + rs.executeSql(sqlsb.toString()); + if (rs.next()) { + List sqlsetList = this.setSqlsetList(null, rs); + if (sqlsetList.size() > 0) { + dmlList.add(sqlsetList); + } + } + } + return dmlList; + } + + /** + * 将dmlaction属性进行组装 + * + * @param rst + * @param rs + * @return + */ + private List setSqlsetList(RecordSetTrans rst, RecordSet rs) { + List sqlsetList = new ArrayList(); + if (null != rst) { + sqlsetList.add(rst.getString("id")); + sqlsetList.add(rst.getString("datasourceid")); + sqlsetList.add(rst.getString("dmltype")); + sqlsetList.add(rst.getString("dmlsql")); + sqlsetList.add(rst.getString("dmlfieldtypes")); + sqlsetList.add(rst.getString("dmlfieldnames")); + sqlsetList.add(rst.getString("dmlcuswhere")); + sqlsetList.add(rst.getString("dmlmainsqltype")); + sqlsetList.add(rst.getString("dmlcussql")); + sqlsetList.add(rst.getString("dmlactionname")); + + sqlsetList.add(rst.getString("dmlsource")); + sqlsetList.add(rst.getString("dmlsourcetype")); + sqlsetList.add(rst.getString("dmlsourceorder")); + } else if (null != rs) { + sqlsetList.add(rs.getString("id")); + sqlsetList.add(rs.getString("datasourceid")); + sqlsetList.add(rs.getString("dmltype")); + sqlsetList.add(rs.getString("dmlsql")); + sqlsetList.add(rs.getString("dmlfieldtypes")); + sqlsetList.add(rs.getString("dmlfieldnames")); + sqlsetList.add(rs.getString("dmlcuswhere")); + sqlsetList.add(rs.getString("dmlmainsqltype")); + sqlsetList.add(rs.getString("dmlcussql")); + sqlsetList.add(rs.getString("dmlactionname")); + + sqlsetList.add(rs.getString("dmlsource")); + sqlsetList.add(rs.getString("dmlsourcetype")); + sqlsetList.add(rs.getString("dmlsourceorder")); + } + return sqlsetList; + } + + /** + * 获取值 + * @param fieldname + * @param properties + * @param htmlTypeMap + * @param typeMap + * @param fieldtypeList + * @param fieldnameList + * @param fieldvalueList + * @throws Exception + */ + private void getFieldValues(RecordSetTrans rst,RecordSet rs, String fieldname, Property[] properties,Map fieldIdMap, + Map htmlTypeMap, Map typeMap,Map fieldDbtypeMap,Map> fieldMapSet, List fieldtypeList, + List fieldnameList, List fieldvalueList,RequestInfo requestInfo) throws Exception { + // 填充空数据 + for (int i = 0; i < fieldnameList.size(); i++) { + fieldvalueList.add(""); + } + // 获取各字段值 + for (int j = 0; j < properties.length; j++) { + // 主表数据 + String name = properties[j].getName().toLowerCase(); + String value = Util.null2String(properties[j].getValue()); + for (int f = 0; f < fieldnameList.size(); f++) { + fieldname = ""; + fieldname = (String) fieldnameList.get(f); + fieldname = fieldname.toLowerCase(); + String fielddbtype = Util.null2String(fieldtypeList.get(f)); + if(fieldname.indexOf("=") != -1){ //2017-04-20,add by fmj,DML支持明细表 + String [] names = fieldname.split("=", -1); //此时fieldname的值是 dmlfield=formfield,这种格式 + String tempname = ""; + if(names.length == 2){ + tempname = names[1]; + } + if(tempname.equals(name)){ + String fieldvalueid = fieldIdMap.get(tempname); + String htmltype = htmlTypeMap.get(tempname); + String fieldtype = typeMap.get(tempname); + String dbtype = fieldDbtypeMap.get(tempname); + Map fieldMap = fieldMapSet.get(fieldname); + String tempvalue = transtValue(rst, rs, requestInfo, fieldname, fieldvalueid, fieldname, value, htmltype, fieldtype, dbtype, fieldMap, properties); + fieldvalueList.set(f, tempvalue); + } + }else{ + if (name.compareTo(fieldname) == 0) { + fieldvalueList.set(f, value); + } + } + } + } + newlog.info("字段数量与字段值数量 fieldvalueList : " + fieldvalueList + + " fieldnameList : " + fieldnameList); + // 字段数量与字段值数量不一致 + if (fieldvalueList.size() <= 0 + || (fieldvalueList.size() != fieldnameList.size())) { + //newlog.info("字段数量与字段值数量不一致!"); + fieldnameList.clear(); + fieldtypeList.clear(); + fieldvalueList.clear(); + } + } + + /** + * 替换自定义条件sql的值 + * + * @param fieldname + * @param properties + * @param dmlsql + * @return + */ + private String setDmlCusSqlOrWhereValues(String fieldname, + Property[] properties, String dmlsql) { + // 获取各字段值 + for (int j = 0; j < properties.length; j++) { + // 主表数据 + String name = properties[j].getName().toLowerCase(); + String value = Util.null2String(properties[j].getValue()); + /* #538173 概述:[90][客户回归]流程流转集成-解决自定义SQL中的流程字段含有单引号,触发DML报错的问题 -start*/ + dmlsql = DBTypeUtil.replaceStringIgnoreCase(dmlsql, "\\{\\?" + name + "\\}", org.apache.commons.lang.StringEscapeUtils.escapeSql(value.replace("\\","\\\\"))); + /* #538173 概述:[90][客户回归]流程流转集成-解决自定义SQL中的流程字段含有单引号,触发DML报错的问题 -end*/ + } + return dmlsql; + } + + /** + * 替换自定义DMLsql的值 + * + * @param dmlsql + * @return + */ + private String setDmlCusSqlValues(String dmlsql) { + for (String key : attr.keySet()) { + dmlsql = DBTypeUtil.replaceStringIgnoreCase(dmlsql, "\\$" + key + "\\$", Util + .null2String(attr.get(key))); + } + return dmlsql; + } + + /** + * 以sql的形式执行dmlaction + * + * @param rst + * @param rs + * @param datasourceid + * @param dmltype + * @param dmlsql + * @param fieldtypeList + * @param fieldvalueList + * @param dmlcuswhere + * @param dmlcussql + * @throws Exception + */ + private void executeDMLAction(RecordSetTrans rst, RecordSet rs, + String datasourceid, String dmltype, String dmlsql, + List fieldtypeList, List fieldvalueList, String dmlcuswhere, + String dmlmainsqltype, String dmlcussql) throws Exception { + ConnStatementDataSource connStatementDataSource = null; + ConnStatement connStatement = null; + try { + String dbtype = DBTypeUtil.getDataSourceDbtype(rs, datasourceid); + + if ("".equals(datasourceid)) { + connStatement = new ConnStatement(); + } else { + connStatementDataSource = new ConnStatementDataSource( + datasourceid); + } + newlog.info("以sql的形式执行dmlaction dmltype : " + dmltype + " dmlsql : " + + dmlsql + " dmlcuswhere : " + dmlcuswhere + + " dmlmainsqltype : " + dmlmainsqltype + " dmlcussql : " + + dmlcussql + " fieldvalueList : " + fieldvalueList.size()); + + if (!"".equals(dmlcuswhere)) { + if(StringUtils.isNotBlank(dmlsql)){ + if (dmlsql.toLowerCase().indexOf(" where ") > -1) { + dmlsql += " and " + dmlcuswhere; + } else { + dmlsql += " where " + dmlcuswhere; + } + } + if(StringUtils.isNotBlank(dmlcussql)){ + if (dmlcussql.toLowerCase().indexOf(" where ") > -1) { + dmlcussql += " and " + dmlcuswhere; + } else { + dmlcussql += " where " + dmlcuswhere; + } + } + } + + // 如果为update或者delete,必须有条件 + if (dmltype.equals("update") || dmltype.equals("delete")) { + // 先执行设置的sql + if (!"".equals(dmlsql) + && (dmlsql.toLowerCase().indexOf(" where ") > -1 || !"" + .equals(dmlcuswhere))) { + this.executesql(dbtype, connStatementDataSource, + connStatement, dmlsql, fieldtypeList, + fieldvalueList); + } + // 再执行自定义dmlsql + if ((dmlcussql.toLowerCase().indexOf(" where ") > -1 && Util.getIntValue( + dmlmainsqltype, 0) == 0) + || (!dmlcussql.equals("") && Util.getIntValue( + dmlmainsqltype, 0) == 1)) { + this.executesql(dbtype, connStatementDataSource, + connStatement, dmlcussql, null, null); + } + } else { + if (fieldvalueList.size() > 0 && !"".equals(dmlsql)) { + // insert sql + this.executesql(dbtype, connStatementDataSource, + connStatement, dmlsql, fieldtypeList, + fieldvalueList); + } + // 再执行自定义dmlsql + if (!"".equals(dmlcussql)) { + this.executesql(dbtype, connStatementDataSource, + connStatement, dmlcussql, null, null); + } + } + } catch (Exception e) { + e.printStackTrace(); + newlog.error("执行sql出错 e : " + e); + throw new Exception(e.getMessage()); + } finally { + try { + if (null != connStatementDataSource) { + connStatementDataSource.close(); + connStatementDataSource = null; + } + if (null != connStatement) { + connStatement.close(); + connStatement = null; + } + } catch (Exception e) { + e.printStackTrace(); + newlog.error("关闭连接出错 e : " + e); + } + } + } + + /** + * 以sql的形式执行dmlaction + * @param rst + * @param rs + * @param datasourceid + * @param dmltype + * @param dmlsql + * @param fieldtypeList + * @param fieldvalueList + * @param dmlcuswhere + * @param dmlmainsqltype + * @param dmlcussql + * @throws Exception + */ + private void executeDMLActionNew(RecordSetTrans rst, RecordSet rs, + String datasourceid, String dmltype, String dmlsql, + List fieldtypeList, List fieldvalueList, String dmlcuswhere, + String dmlmainsqltype, String dmlcussql) throws Exception { + //ConnStatementDataSource connStatementDataSource = null; + //ConnStatement connStatement = null; + try { + String dbtype = DBTypeUtil.getDataSourceDbtype(rs, datasourceid); + + newlog.info("以sql的形式执行dmlaction dmltype : " + dmltype + " dmlsql : " + + dmlsql + " dmlcuswhere : " + dmlcuswhere + + " dmlmainsqltype : " + dmlmainsqltype + " dmlcussql : " + + dmlcussql + " fieldvalueList : " + fieldvalueList.size()); + + if (!"".equals(dmlcuswhere)) { + if(StringUtils.isNotBlank(dmlsql)){ + if (dmlsql.toLowerCase().indexOf(" where ") > -1) { + dmlsql += " and " + dmlcuswhere; + } else { + dmlsql += " where " + dmlcuswhere; + } + } + if(StringUtils.isNotBlank(dmlcussql)){ + if (dmlcussql.toLowerCase().indexOf(" where ") > -1) { + dmlcussql += " and " + dmlcuswhere; + } else { + dmlcussql += " where " + dmlcuswhere; + } + } + } + + // 如果为update或者delete,必须有条件 + if (dmltype.equals("update") || dmltype.equals("delete")) { + // 先执行设置的sql + if (!"".equals(dmlsql)&& (dmlsql.toLowerCase().indexOf(" where ") > -1 || !"".equals(dmlcuswhere))) { + this.executesqlNew(dbtype,datasourceid, dmlsql, fieldtypeList,fieldvalueList); + }else{ + newlog.error("执行类型:"+dmltype+">>>"+"没有设置where条件,不执行赋值sql!"); + } + // 再执行自定义dmlsql + if ((dmlcussql.toLowerCase().indexOf(" where ") > -1 && Util.getIntValue(dmlmainsqltype, 0) == 0)|| (!dmlcussql.equals("") && Util.getIntValue(dmlmainsqltype, 0) == 1)) { + this.executesqlNew(dbtype,datasourceid , dmlcussql, null, null); + }else{ + newlog.error("执行类型:"+dmltype+">>>"+"没有设置where条件,不执行自定义sql!"); + } + } else { + if (fieldvalueList.size() > 0 && !"".equals(dmlsql)) { + // insert sql + this.executesqlNew(dbtype, datasourceid,dmlsql, fieldtypeList,fieldvalueList); + } + // 再执行自定义dmlsql + if (!"".equals(dmlcussql)) { + this.executesqlNew(dbtype,datasourceid , dmlcussql, null, null); + } + } + } catch (Exception e) { + e.printStackTrace(); + newlog.error("执行sql出错 e : " , e); + throw new Exception(e.getMessage()); + } finally { + try { +// if (null != connStatementDataSource) { +// connStatementDataSource.close(); +// connStatementDataSource = null; +// } +// if (null != connStatement) { +// connStatement.close(); +// connStatement = null; +// } + } catch (Exception e) { + e.printStackTrace(); + newlog.error("关闭连接出错 e : " , e); + } + } + } + + /** + * 执行sql + * + * @param connStatementDataSource + * @param connStatement + * @param sql + * @param fieldtypeList + * @param fieldvalueList + * @throws Exception + */ + private void executesql(String dbtype, + ConnStatementDataSource connStatementDataSource, + ConnStatement connStatement, String sql, List fieldtypeList, + List fieldvalueList) throws Exception { + try { + sql = sql.replaceAll("\r", " ").replaceAll("\n", " ");//处理sql语句中的回车换行符 + newlog.info("执行sql : " + sql); + if (null != connStatementDataSource) { + connStatementDataSource.setStatementSql(sql); + } else if (null != connStatement) { + connStatement.setStatementSql(sql); + } + if (null != fieldtypeList && fieldtypeList.size() > 0) { + for (int i = 0; i < fieldtypeList.size(); i++) { + String fielddbtype = (String) fieldtypeList.get(i); + String fieldvalue = (String) fieldvalueList.get(i); + boolean ischeck = DBTypeUtil.checkFieldDBType(fielddbtype, + dbtype); + String settype = DBTypeUtil.getThistype(); + newlog.info("dbtype : " + dbtype + " fielddbtype : " + + fielddbtype + " fieldvalue : " + fieldvalue + + " settype : " + settype); + this.setValueWithDBTypeInStatment(i + 1, + connStatementDataSource, connStatement, settype, + fieldvalue); + } + } + int count = 0; + if (null != connStatementDataSource) { + count = connStatementDataSource.executeUpdate(); + } else if (null != connStatement) { + count = connStatement.executeUpdate(); + } + newlog.error("影响行数 : " + count); + + } catch (Exception e) { + e.printStackTrace(); + newlog.error("执行sql出错 e : " + e); + throw new Exception(e.getMessage()); + } + } + + /** + * 执行sql + * @param dbtype + * @param sql + * @param fieldtypeList + * @param fieldvalueList + * @throws Exception + */ + private void executesqlNew(String dbtype,String datasourceid,String sql, List fieldtypeList,List fieldvalueList) throws Exception { + try { + sql = sql.replaceAll("\r", " ").replaceAll("\n", " ");//处理sql语句中的回车换行符 + if(dbtype.contains("mysql")){ + sql=sql.replace("\\","\\\\"); + } + if(sql.endsWith(";")){ + sql=sql.substring(0,sql.length()-1); + } + newlog.info("执行sql : " + sql); + + + if (null != fieldtypeList && fieldtypeList.size() > 0) { + for (int i = 0; i < fieldtypeList.size(); i++) { + String fielddbtype = (String) fieldtypeList.get(i); + String fieldvalue = (String) fieldvalueList.get(i); + boolean ischeck = DBTypeUtil.checkFieldDBType(fielddbtype, + dbtype); + String settype = DBTypeUtil.getThistype(); + if(fielddbtype.equalsIgnoreCase("time")&&!"".equals(fieldvalue)&&fieldvalue.length()==5){ + fieldvalue=fieldvalue+":00"; + fieldvalueList.remove(i); + fieldvalueList.add(i,fieldvalue); + } + fieldvalueList=setValueWithDBType(fieldvalueList,settype,fieldvalue,i); + + + newlog.info("dbtype : " + dbtype + " fielddbtype : " + + fielddbtype + " fieldvalue : " + fieldvalue + + " settype : " + settype); + + } + } + + //int count = 0; + boolean flag=false; + + RecordSet rs=new RecordSet(); + rs.setChecksql(false); + if (null != fieldtypeList && fieldtypeList.size() > 0) { + List tempfieldvalueList=new ArrayList(); + tempfieldvalueList.add(fieldvalueList); + if(!datasourceid.equals("")){ //数据源 + flag=rs.executeBatchSql(sql, tempfieldvalueList,datasourceid); + }else{ //本地数据库 + flag=rs.executeBatchSql(sql, tempfieldvalueList); + } + }else{ + if(!datasourceid.equals("")){ //数据源 + flag=rs.executeSql(sql, datasourceid); + + }else{ + flag=rs.execute(sql); + } + } + + newlog.error("是否执行成功: " + flag); + if(!flag){ + throw new Exception(rs.getExceptionMsg()); + } + + } catch (Exception e) { + e.printStackTrace(); + newlog.error("执行sql出错 : ",e); + throw new Exception(e.getMessage()); + } + } + + /** + * 将数据填充至statment中 + * + * @param connStatementDataSource + * @param connStatement + * @param settype + * @param fieldvalue + * @throws Exception + */ + private void setValueWithDBTypeInStatment(int index, + ConnStatementDataSource connStatementDataSource, + ConnStatement connStatement, String settype, String fieldvalue) + throws Exception { + + // setString 1 + // setInt 2 + // setFloat 3 + // setDate 4 + // setBigDecimal 5 + // setBinaryStream 6 + // setBytes 7 + // setCharacterStream 8 + // setObject 9 + // setNull 10 + // setClob 11 + // setBlob 12 + if (null != connStatementDataSource) { + if ("1".equals(settype)) { + connStatementDataSource.setString(index, fieldvalue); + } else if ("2".equals(settype)) { + if(null!=fieldvalue&&!fieldvalue.isEmpty()){ + connStatementDataSource.setInt(index, Util.getIntValue( + fieldvalue, 0)); + }else{ + connStatementDataSource.setString(index, null); + } + } else if ("3".equals(settype)) { + if(null!=fieldvalue&&!fieldvalue.isEmpty()){ + connStatementDataSource.setFloat(index, Util.getFloatValue( + fieldvalue, 0)); + }else{ + connStatementDataSource.setString(index, null); + } + } else if ("4".equals(settype)) { + java.sql.Date date = null; + try { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + Date dt = sdf.parse(fieldvalue); + date = new java.sql.Date(dt.getTime()); + } catch (Exception e) { + e.printStackTrace(); + newlog.error("转换日期型出错 : fieldvalue : " + fieldvalue); + } + connStatementDataSource.setDate(index, date); + } else if ("5".equals(settype)) { + BigDecimal fieldvalueb = null; + try { + + if(null!=fieldvalue&&!fieldvalue.isEmpty()){ + fieldvalueb = new BigDecimal(fieldvalue); + connStatementDataSource.setBigDecimal(index, fieldvalueb); + }else{ + connStatementDataSource.setBigDecimal(index,null);//qc325384 [80][90][客户]流程流转集成-注册DML接口,update类型,对于SQL中字段为decimal类型,执行报错 + } + + } catch (Exception e) { + e.printStackTrace(); + newlog.error("转换数值型出错 : fieldvalue : " + fieldvalue); + } + + } else if ("6".equals(settype)) { + connStatementDataSource.setBinaryStream(index, null, 0); + } else if ("7".equals(settype)) { + connStatementDataSource.setBytes(index, fieldvalue.getBytes()); + } else if ("8".equals(settype)) { + connStatementDataSource.setCharacterStream(index, fieldvalue); + } else if ("9".equals(settype)) { + connStatementDataSource.setObject(index, null); + } else if ("10".equals(settype)) { + //connStatementDataSource.setNull(index); + connStatementDataSource.setString(index, fieldvalue); + } else if ("11".equals(settype)) { + connStatementDataSource.setClob(index, null); + } else if ("12".equals(settype)) { + connStatementDataSource.setBlob(index, null); + } + } + if (null != connStatement) { + if ("1".equals(settype)) { + connStatement.setString(index, fieldvalue); + + } else if ("2".equals(settype)) { + if(null!=fieldvalue&&!fieldvalue.isEmpty()){ + connStatement.setInt(index, Util.getIntValue(fieldvalue, 0)); + }else{ + connStatement.setString(index, null); + } + } else if ("3".equals(settype)) { + if(null!=fieldvalue&&!fieldvalue.isEmpty()){ + connStatement + .setFloat(index, Util.getFloatValue(fieldvalue, 0)); + }else{ + connStatement.setString(index, null); + } + + } else if ("4".equals(settype)) { + java.sql.Date date = null; + try { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + Date dt = sdf.parse(fieldvalue); + date = new java.sql.Date(dt.getTime()); + } catch (Exception e) { + e.printStackTrace(); + newlog.error("转换日期型出错 : fieldvalue : " + fieldvalue); + } + connStatement.setDate(index, date); + } else if ("5".equals(settype)) { + BigDecimal fieldvalueb = null; + try { + if(null!=fieldvalue&&!fieldvalue.isEmpty()){ + fieldvalueb = new BigDecimal(fieldvalue); + connStatement.setBigDecimal(index, fieldvalueb); + }else{ + //connStatement.setBigDecimal(index,null); + connStatement.setBigDecimal(index,null);//qc325384 [80][90][客户]流程流转集成-注册DML接口,update类型,对于SQL中字段为decimal类型,执行报错 + } + + } catch (Exception e) { + e.printStackTrace(); + newlog.error("转换数值型出错 : fieldvalue : " + fieldvalue); + } + } else if ("6".equals(settype)) { + connStatement.setBinaryStream(index, null, 0); + } else if ("7".equals(settype)) { + connStatement.setBytes(index, fieldvalue.getBytes()); + } else if ("8".equals(settype)) { + connStatement.setCharacterStream(index, fieldvalue); + } else if ("9".equals(settype)) { + connStatement.setObject(index, null); + } else if ("10".equals(settype)) { + //connStatement.setNull(index); + connStatement.setString(index, fieldvalue); + } else if ("11".equals(settype)) { + connStatement.setClob(index, null); + } else if ("12".equals(settype)) { + connStatement.setBlob(index, null); + } + } + } + private List setValueWithDBType(List fieldvalueList, String settype, String fieldvalue,int index) + { + + // setString 1 + // setInt 2 + // setFloat 3 + // setDate 4 + // setBigDecimal 5 + // setBinaryStream 6 + // setBytes 7 + // setCharacterStream 8 + // setObject 9 + // setNull 10 + // setClob 11 + // setBlob 12 + if (null != fieldvalueList) { + if ("1".equals(settype)) { + //connStatementDataSource.setString(index, fieldvalue); + //fieldvalueList.add(index); + } else if ("2".equals(settype)) { + if(null!=fieldvalue&&!fieldvalue.isEmpty()){ + //connStatementDataSource.setInt(index, Util.getIntValue( + // fieldvalue, 0)); + fieldvalueList.remove(index); + fieldvalueList.add(index,Util.getIntValue(fieldvalue, 0)); + }else{ + //connStatementDataSource.setString(index, null); + fieldvalueList.remove(index); + fieldvalueList.add(index,null); + } + } else if ("3".equals(settype)) { + if(null!=fieldvalue&&!fieldvalue.isEmpty()){ + //connStatementDataSource.setFloat(index, Util.getFloatValue( + // fieldvalue, 0)); + fieldvalueList.remove(index); + fieldvalueList.add(index,Util.getFloatValue(fieldvalue, 0)); + }else{ + //connStatementDataSource.setString(index, null); + fieldvalueList.remove(index); + fieldvalueList.add(index,0.0); + } + } else if ("4".equals(settype)) { + java.sql.Date date = null; + try { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + Date dt = sdf.parse(fieldvalue); + date = new java.sql.Date(dt.getTime()); + fieldvalueList.remove(index); + fieldvalueList.add(index,date); + } catch (Exception e) { + e.printStackTrace(); + newlog.error("转换日期型 : fieldvalue : " + fieldvalue); + } + //connStatementDataSource.setDate(index, date); + } else if ("5".equals(settype)) { + BigDecimal fieldvalueb = null; + try { + + if(null!=fieldvalue&&!fieldvalue.isEmpty()){ + fieldvalueb = new BigDecimal(fieldvalue); + //connStatementDataSource.setBigDecimal(index, fieldvalueb); + fieldvalueList.remove(index); + fieldvalueList.add(index,fieldvalueb); + }else{ + //connStatementDataSource.setBigDecimal(index,null);//qc325384 [80][90][客户]流程流转集成-注册DML接口,update类型,对于SQL中字段为decimal类型,执行报错 + fieldvalueList.remove(index); + fieldvalueList.add(index,null); + } + + } catch (Exception e) { + e.printStackTrace(); + newlog.error("转换数值型出错 : fieldvalue : " + fieldvalue); + } + + } else if ("6".equals(settype)) { + //connStatementDataSource.setBinaryStream(index, null, 0); + } else if ("7".equals(settype)) { + //connStatementDataSource.setBytes(index, fieldvalue.getBytes()); + } else if ("8".equals(settype)) { + //connStatementDataSource.setCharacterStream(index, fieldvalue); + } else if ("9".equals(settype)) { + //connStatementDataSource.setObject(index, null); + } else if ("10".equals(settype)) { + //connStatementDataSource.setNull(index); + //connStatementDataSource.setString(index, fieldvalue); + } else if ("11".equals(settype)) { + //connStatementDataSource.setClob(index, null); + } else if ("12".equals(settype)) { + //connStatementDataSource.setBlob(index, null); + } + } + return fieldvalueList; + + } + + public String getIsNewMark() { + return isNewMark; + } + + public void setIsNewMark(String isNewMark) { + this.isNewMark = isNewMark; + } + + /** + * 动态增加数组长度 + * + * @param array + * @param newSize + * @return + */ + public Object expand(Object array, int newSize) { + + if (array == null) { + + return null; + + } + + Class c = array.getClass(); + + if (c.isArray()) { + + int len = Array.getLength(array); + + if (len >= newSize) { + + return array; + + } else { + + Class cc = c.getComponentType(); + + Object newArray = Array.newInstance(cc, newSize); + + System.arraycopy(array, 0, newArray, 0, len); + + return newArray; + + } + + } else { + + // throw new ClassCastException("need array"); + return array; + + } + + } + + private void loadMainInfotoProp(Property[] propertys, + DetailTable[] detailTables) { + for (Property property : propertys) { + attr.put("main." + property.getName().toLowerCase(), property + .getValue()); + } + if (detailTables != null) { + for (int i = 0; i < detailTables.length; i++) { + Row[] rows = detailTables[i].getRow(); + for (int j = 0; j < rows.length; j++) { + Cell[] cells = rows[j].getCell(); + for (Cell cell : cells) { + attr.put("detail_" + i + "_" + j + "" + cell.getName(), + cell.getValue()); + } + } + } + } + } + + /** + * 拼装明细表数据 + * @param properties 主表数据 + * @param requestInfo + * @param dtableName 明细表名称 + * @return + */ + private List loadDetail(Property[] properties,RequestInfo requestInfo,String dtableName){ + List propertiesList = new ArrayList(); + DetailTable [] detailTables = requestInfo.getDetailTableInfo().getDetailTable(); + try{ + if(detailTables != null && detailTables.length > 0){ + for(DetailTable detailTable : detailTables){ + String tableName = Util.null2String(detailTable.getTableDBName()); + if(tableName != null && tableName.equalsIgnoreCase(dtableName)){ //取对应的明细表的数据 + int rowCount = detailTable.getRowCount(); + for(int i = 0 ;i < rowCount; i++){ + List propertyList = new ArrayList(); + for(Property property : properties){ + Property prop = new Property(); + BeanUtils.copyProperties(prop, property); + propertyList.add(prop); + } + + Row row = detailTable.getRow(i); + + Property tempprop = new Property(); + tempprop.setName("d.id"); + tempprop.setValue(row.getId()); + tempprop.setType(""); + propertyList.add(tempprop); + + Cell [] cells = row.getCell(); + for(Cell cell : cells){ + String name = Util.null2String(cell.getName()); + String value = Util.null2String(cell.getValue()); + String type = Util.null2String(cell.getType()); + if(!"".equals(name)){ + name = "d." + name; + Property prop = new Property(); + prop.setName(name); + prop.setValue(value); + prop.setType(type); + propertyList.add(prop); + } + } + + Property [] props = propertyList.toArray(new Property[1]); + propertiesList.add(props); + } + } + } + } + }catch (Exception e) { + newlog.error("加载明细表数据出错:" + e); + } + return propertiesList; + } + + /** + * + * @Description : 动态装载DML sql自定义属性值 + * @param src + * 节点操作者/请求基本信息对象 + */ + public void loadProperty(Object src) { + if(null==src) + { + return; + } + Method[] methods = src.getClass().getDeclaredMethods(); + String pfx = ""; + if (src.getClass().equals(weaver.hrm.User.class)) {// 用户信息在属性前面加user.前缀 + pfx = "user."; + } + String key, value = ""; + for (Method method : methods) { + String methodName = method.getName(); + if (methodName.startsWith("get") + && (method.getModifiers() == Modifier.PUBLIC) + && (method.getParameterTypes().length == 0)) {// 访问不带参数公共方法 + method.setAccessible(true); + methodName = methodName.substring(3);// 去掉get + key = pfx + methodName.toLowerCase(); + try { + value = String.valueOf(method.invoke(src, null)); + } catch (IllegalArgumentException e) { + newlog.error("获取" + src.getClass().getName() + "信息失败!", e); + } catch (IllegalAccessException e) { + newlog.error("获取" + src.getClass().getName() + "信息失败!", e); + } catch (InvocationTargetException e) { + newlog.error("获取" + src.getClass().getName() + "信息失败!", e); + } + attr.put(key, Util.null2String(value)); + } + } + } + + private String loadTableInfo(String dmlsql, int requestid, int formid, + int billid, RecordSetTrans rst, RecordSet rs, String dmltype) + throws Exception { + if (dmlsql.indexOf("$detail_table?") >= 0) { + if (dmltype.equals("update") || dmltype.equals("delete")) { + if (dmlsql.indexOf("$detail_pk$") < 0) { + newlog.info("执行的sql有误,必须存在$detail_pk$!"); + return dmlsql + " and 1=2"; + } + } else { + if (dmlsql.indexOf("detail_main_pkfd") < 0 + || dmlsql.indexOf("detail_main_pkfd_v") < 0) { + newlog.info("执行的sql有误,必须存在$detail_main_pkfd$、$detail_main_pkfd_v$!"); + return dmlsql + " and 1=2"; + } + } + String mainsql = "select detailtablename,tablename,detailkeyfield from workflow_bill where id=" + + formid; + String detail_tablename = " workflow_formdetail ";// 明细表表面 + String detail_pk = " requestid=" + requestid + " ";// 明细表主键字段名 + final String pk = "$detail_table?"; + String index = dmlsql.substring(dmlsql.indexOf(pk) + pk.length(), + dmlsql.indexOf(pk) + pk.length() + 1);// 明细表索引 + // 0代表第一个明细表1表示第二个 + int orderid = Util.getIntValue(index, 0);// 自定义表单需要+1从开始 + final String fsi = "$detail_index?"; + String detail_index = "";// 明细数据索引0代表第0个 + if (dmlsql.indexOf(fsi) >= 0) { + detail_index = dmlsql.substring(dmlsql.indexOf(fsi) + + fsi.length(), dmlsql.indexOf(fsi) + fsi.length() + 1);// 表示明细表的第N条明细 + // 从0开始 + dmlsql = dmlsql.substring(0, dmlsql.indexOf(fsi)) + + " 1=1 " + + dmlsql.substring(dmlsql.indexOf(fsi) + fsi.length() + + 2); + } + int i = 0; + if (billid == 1) { + orderid++; + if (rst != null) { + rst.executeSql(mainsql); + rst.next(); + String detailtablename = rst.getString("detailtablename"); + String maintable = rst.getString("tablename"); + String detailkeyfield = rst.getString("detailkeyfield"); + attr.put("detail_main_pkfd", detailkeyfield);// 主表跟明细表关联关系字段名称 + rst.executeSql("select id from " + maintable + + " where requestid=" + requestid); + rst.next(); + attr.put("detail_main_pkfd_v", rst.getString("id"));// 主表跟明细表关联关系字段值 + detail_pk = " " + detailkeyfield + "=" + + rst.getString("id") + " "; + attr.put("detail_pk", detail_pk); + if (maintable.trim().toLowerCase().startsWith( + "formtable_main_")) {// 自定义单据 + rst + .executeSql("select tablename from workflow_billdetailtable where billid=" + + formid + " and orderid=" + orderid); + rst.next(); + attr.put("detail_table?" + index, rst + .getString("tablename")); + if (!detail_index.equals("")) { + rst.executeSql("select id from " + + rst.getString("tablename") + " where " + + detail_pk + " order by id asc"); + while (rst.next()) { + String index_id = rst.getString("id"); + if (detail_index.equals("" + i)) { + dmlsql += " and id=" + index_id + " ";// 表示第几个明细表从0开始 + break; + } + i++; + } + } + } else {// 系统单据 + attr.put("detail_table?" + index, detailtablename); + if (!detail_index.equals("")) { + rst.executeSql("select id from " + detailtablename + + " where " + detail_pk + + " order by id asc"); + while (rst.next()) { + String index_id = rst.getString("id"); + if (detail_index.equals("" + i)) { + dmlsql += " and id=" + index_id + " ";// 表示第几个明细表从0开始 + break; + } + i++; + } + } + } + } else if (rs != null) { + rs.executeSql(mainsql); + rs.next(); + String detailtablename = rs.getString("detailtablename");// 明细表表面 + String maintable = rs.getString("tablename");// 主表表明 + String detailkeyfield = rs.getString("detailkeyfield");// 主表跟明细表关联关系字段名称 + attr.put("detail_main_pkfd", detailkeyfield); + rs.executeSql("select id from " + maintable + + " where requestid=" + requestid); + rs.next(); + attr.put("detail_main_pkfd_v", rs.getString("id"));// 主表跟明细表关联关系字段值 + detail_pk = " " + detailkeyfield + "=" + + rs.getString("id") + " "; + attr.put("detail_pk", detail_pk); + if (maintable.trim().toLowerCase().startsWith( + "formtable_main_")) {// 自定义单据 + rs + .executeSql("select tablename from workflow_billdetailtable where billid=" + + formid + " and orderid=" + orderid); + rs.next(); + attr.put("detail_table?" + index, rs + .getString("tablename")); + if (!detail_index.equals("")) { + rs.executeSql("select id from " + + rs.getString("tablename") + " where " + + detail_pk + " order by id asc"); + while (rs.next()) { + String index_id = rs.getString("id"); + if (detail_index.equals("" + i)) { + dmlsql += " and id=" + index_id + " ";// 表示第几个明细表 + break; + } + i++; + } + } + } else {// 系统单据 + attr.put("detail_table?" + index, detailtablename); + if (!detail_index.equals("")) { + rs.executeSql("select id from " + detailtablename + + " where " + detail_pk + + " order by id asc"); + while (rs.next()) { + String index_id = rs.getString("id"); + if (detail_index.equals("" + i)) { + dmlsql += " and id=" + index_id + " ";// 表示第几个明细表从0开始 + break; + } + i++; + } + } + } + } + } else {// 老表单 + attr.put("detail_table?" + index, detail_tablename); + attr.put("detail_pk", detail_pk); + attr.put("detail_main_pkfd", "requestid");// 主表跟明细表关联关系字段名称 + attr.put("detail_main_pkfd_v", "" + requestid);// 主表跟明细表关联关系字段值 + if (!detail_index.equals("")) { + if (rst != null) { + rst.executeSql("select id from " + detail_tablename + + " where groupid=" + orderid + + " order by id asc"); + while (rst.next()) { + String index_id = rst.getString("id"); + if (detail_index.equals("" + i)) { + dmlsql += " and id=" + index_id + " ";// 表示第几个明细表从0开始 + break; + } + i++; + } + } else if (rs != null) { + rs.executeSql("select id from " + detail_tablename + + " where groupid=" + orderid + + " order by id asc"); + while (rs.next()) { + String index_id = rs.getString("id"); + if (detail_index.equals("" + i)) { + dmlsql += " and id=" + index_id + " ";// 表示第几个明细表从0开始 + break; + } + i++; + } + } + } + + } + if (dmltype.equals("update") || dmltype.equals("delete")) { + if (billid == 0) { + dmlsql += " and groupid=" + orderid + " ";// 表示第几个明细表 + } + } + } + return dmlsql; + } + + + /** + * 获取明细表的名称 + * @param rst + * @param rs + * @param formid + * @param isbill + * @param tableid + * @return + * @throws Exception + */ + private String getDetailTable(RecordSetTrans rst,RecordSet rs,int formid,int isbill,int tableid) throws Exception{ + String formDetailTable = ""; + if(isbill == 1){ + String tsql = "select tablename from workflow_billdetailtable where id = " + tableid; + if(rst != null){ + rst.executeSql(tsql); + if(rst.next()){ + formDetailTable = Util.null2String(rst.getString("tablename")); + } + }else{ + rs.executeSql(tsql); + if(rs.next()){ + formDetailTable = Util.null2String(rs.getString("tablename")); + } + } + }else{ + formDetailTable = tableid + ""; + } + + return formDetailTable; + } + + /** + * 查询字段的信息,主要是htmltype,type信息 + * @param rst + * @param rs + * @param formid + * @param isbill + * @param fieldHtmlTypeMap + * @param fieldTypeMap + * @param tableid + * @throws Exception + */ + private void getFieldsInfo(RecordSetTrans rst,RecordSet rs,int formid,int isbill,Map fieldIdMap,Map fieldHtmlTypeMap,Map fieldTypeMap,Map fieldDbTypeMap, int tableid) throws Exception{ + String sql = ""; + /****查询主表字段信息********/ + if(isbill==0){ + //表单主字段 + sql = " select d.id,d.fieldname,d.fieldhtmltype,d.type,d.fielddbtype " + + " from workflow_formfield a,workflow_formdict d " + + " where a.isdetail is null and a.fieldid=d.id and a.formid="+formid; + }else if(isbill==1){ + //单据主字段 + sql = " select id,fieldname,fieldhtmltype,type,fielddbtype " + + " from workflow_billfield where viewtype=0 and billid="+formid; + } + + if(rst != null){ + rst.executeSql(sql); + while(rst.next()){ + String fieldid = Util.null2String(rst.getString("id")); + String fieldname = Util.null2String(rst.getString("fieldname")).toLowerCase(); + String fieldhtmltype = Util.null2String(rst.getString("fieldhtmltype")); + String type = Util.null2String(rst.getString("type")); + String fielddbtype = Util.null2String(rst.getString("fielddbtype")); + fieldHtmlTypeMap.put(fieldname, fieldhtmltype); + fieldTypeMap.put(fieldname, type); + fieldIdMap.put(fieldname, fieldid); + fieldDbTypeMap.put(fieldname, fielddbtype); + } + }else{ + rs.executeSql(sql); + while(rs.next()){ + String fieldid = Util.null2String(rs.getString("id")); + String fieldname = Util.null2String(rs.getString("fieldname")).toLowerCase(); + String fieldhtmltype = Util.null2String(rs.getString("fieldhtmltype")); + String type = Util.null2String(rs.getString("type")); + String fielddbtype = Util.null2String(rs.getString("fielddbtype")); + fieldHtmlTypeMap.put(fieldname, fieldhtmltype); + fieldTypeMap.put(fieldname, type); + fieldIdMap.put(fieldname, fieldid); + fieldDbTypeMap.put(fieldname, fielddbtype); + } + } + + /**********查询明细表字段************/ + if(tableid >= 0){ + if(isbill==0){ + //表单明细字段 + sql = " select d.id,d.fieldname,d.fieldhtmltype,d.type,d.fielddbtype " + + " from workflow_formfield a,workflow_formdict d " + + " where a.isdetail=1 and a.fieldid=d.id and a.formid="+formid; + if(rs.getDBType().equals("oracle")){ + sql += " and nvl(a.groupid,0) = " + tableid; + }else if(rs.getDBType().equals("mysql")){ + sql += " and ifnull(a.groupid,0) = " + tableid; + } else{ + sql += " and isnull(a.groupid,0) = " + tableid; + } + }else if(isbill==1){ + String detailtable = ""; + String tsql = "select tablename from workflow_billdetailtable where billid = " + formid + " and id = " + tableid; + if(rst != null){ + rst.executeSql(tsql); + if(rst.next()){ + detailtable = Util.null2String(rst.getString("tablename")); + } + }else{ + rs.executeSql(tsql); + if(rs.next()){ + detailtable = Util.null2String(rs.getString("tablename")); + } + } + + //单据明细字段 + sql = " select id,fieldname,fieldhtmltype,type,fielddbtype " + + " from workflow_billfield " + + " where viewtype=1 and billid = " + formid + " and detailtable = '" + detailtable + "'"; + } + + if(rst != null){ + rst.executeSql(sql); + while(rst.next()){ + String fieldid = Util.null2String(rst.getString("id")); + String fieldname = Util.null2String(rst.getString("fieldname")).toLowerCase(); + String fieldhtmltype = Util.null2String(rst.getString("fieldhtmltype")); + String type = Util.null2String(rst.getString("type")); + String fielddbtype = Util.null2String(rst.getString("fielddbtype")); + + fieldname = "d." + fieldname; + fieldHtmlTypeMap.put(fieldname, fieldhtmltype); + fieldTypeMap.put(fieldname, type); + fieldIdMap.put(fieldname, fieldid); + fieldDbTypeMap.put(fieldname, fielddbtype); + } + }else{ + rs.executeSql(sql); + while(rs.next()){ + String fieldid = Util.null2String(rs.getString("id")); + String fieldname = Util.null2String(rs.getString("fieldname")).toLowerCase(); + String fieldhtmltype = Util.null2String(rs.getString("fieldhtmltype")); + String fielddbtype = Util.null2String(rs.getString("fielddbtype")); + String type = Util.null2String(rs.getString("type")); + + fieldname = "d." + fieldname; + fieldHtmlTypeMap.put(fieldname, fieldhtmltype); + fieldTypeMap.put(fieldname, type); + fieldIdMap.put(fieldname, fieldid); + fieldDbTypeMap.put(fieldname, fielddbtype); + } + } + } + } + + /** + * 获取外部表与流程表单表的映射关系,同时返回数据转换规则等 + * @param sqlsetid + * @return + * @throws Exception + */ + private Map> getFieldMapSet(RecordSetTrans rst,RecordSet rs,String sqlsetid,String maptype) throws Exception{ + Map> map = new HashMap>(); + String sql = " select fieldname,fieldvalue,transttype,extrainfo" + + " from formactionfieldmap" + + " where actionsqlsetid = " + sqlsetid ; + if(maptype != null && !"".equals(maptype)){ + sql += " and maptype = '" + maptype + "'"; + } + if(rst != null){ + rst.executeSql(sql); + while(rst.next()){ + String fieldname = Util.null2String(rst.getString("fieldname")).toLowerCase(); + String fieldvalue = Util.null2String(rst.getString("fieldvalue")).toLowerCase(); + String transttype = Util.null2String(rst.getString("transttype")); + String extrainfo = Util.null2String(rst.getString("extrainfo")); + Map m = new HashMap(); + m.put("transttype", transttype); + m.put("extrainfo", extrainfo); + + String key = fieldname + "=" + fieldvalue; + map.put(key, m); + } + }else{ + rs.executeSql(sql); + while(rs.next()){ + String fieldname = Util.null2String(rs.getString("fieldname")).toLowerCase(); + String fieldvalue = Util.null2String(rs.getString("fieldvalue")).toLowerCase(); + String transttype = Util.null2String(rs.getString("transttype")); + String extrainfo = Util.null2String(rs.getString("extrainfo")); + Map m = new HashMap(); + m.put("transttype", transttype); + m.put("extrainfo", extrainfo); + + String key = fieldname + "=" + fieldvalue; + map.put(key, m); + } + } + return map; + } + + + private String transtValue(RecordSetTrans rst,RecordSet rs,RequestInfo requestInfo,String keyvaluename,String fieldvalueid,String fieldvaluename,String fieldvalue,String htmltype,String fieldtype,String fielddbtype,Map transttypeMap,Property [] properties) throws Exception{ + String value = ""; + int transttype = Util.getIntValue(Util.null2String(transttypeMap.get("transttype")), -1); + String extrainfo = Util.null2String(transttypeMap.get("extrainfo")); + RequestManager requestManager = requestInfo.getRequestManager(); + int isbill = requestManager.getIsbill(); + if(transttype > 0){ + ResourceComInfo resourceComInfo = new ResourceComInfo(); + DepartmentComInfo departmentComInfo = new DepartmentComInfo(); + SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo(); + if(transttype == 1){/*****固定值*****/ + value = extrainfo; + } else if(transttype == 2){/******显示值*******/ + if("3".equals(htmltype)){ //浏览按钮 + GetShowCondition showCondition = new GetShowCondition(); + value = showCondition.getShowCN(htmltype, fieldtype, fieldvalue, isbill + "",fielddbtype); + String value2 = Util.formatMultiLang(value, "7"); + if(!"".equals(value2)) + value=value2; + }else if("5".equals(htmltype)){ //选择框 + + if(!"".equals(fieldvalue)){ + + String[] tempFieldvalueS=fieldvalue.split(","); + for(int i=0;i1&&tempFieldvalueS.length>0)value=value.substring(0,value.length()-1); + } + }else if("6".equals(htmltype)){ //附件上传 + if(!"".equals(fieldvalue)){ + String sql="select id,docsubject,accessorycount from docdetail where id in("+fieldvalue+") order by id asc"; + if(rst != null){ + rst.executeSql(sql); + while(rst.next()){ + value += "," + rst.getString("docsubject"); + } + }else{ + rs.executeSql(sql); + while(rs.next()){ + value += "," + rs.getString("docsubject"); + } + } + + if(!"".equals(value) && value.startsWith(",")){ + value = value.substring(1); + } + } + }else if("7".equals(htmltype)){ //字段类型:特殊字段 + String sql = " select type,fieldid,displayname,linkaddress,descriptivetext " + + " from workflow_specialfield a, workflow_billfield b " + + " where a.fieldid = b.id and a.isform='0' and a.isbill='1' and a.fieldid = " + fieldvalueid; + String ftype = ""; + String linkaddress = ""; + String displayname = ""; + if(rst != null){ + rst.executeSql(sql); + if(rst.next()){ + ftype = Util.null2String(rst.getString("type")); + linkaddress = Util.null2String(rst.getString("linkaddress")); + displayname = Util.null2String(rst.getString("displayname")); + } + }else{ + rs.executeSql(sql); + if(rs.next()){ + ftype = Util.null2String(rs.getString("type")); + linkaddress = Util.null2String(rs.getString("linkaddress")); + displayname = Util.null2String(rs.getString("displayname")); + } + } + + if("1".equals(ftype)){ + if(!"".equals(linkaddress)){ + value = "" + displayname + ""; + }else{ + value = linkaddress; + } + } + } + }else if(transttype == 3){ /********人员编号、部门编号、分部编号********/ + //浏览按钮,单人力、多人力、分权单人力、分权多人力 + if("3".equals(htmltype) && ("1".equals(fieldtype) || "17".equals(fieldtype) || "165".equals(fieldtype) || "166".equals(fieldtype))){ + if(!"".equals(fieldvalue)){ + String [] values = fieldvalue.split(",", -1); + for(String val : values){ + value += "," + resourceComInfo.getWorkcode(val); + } + } + //浏览按钮,部门,多部门,分权单部门,分权多部门 + }else if("3".equals(htmltype) && ("4".equals(fieldtype) || "57".equals(fieldtype) || "167".equals(fieldtype) || "168".equals(fieldtype))){ + if(!"".equals(fieldvalue)){ + String [] values = fieldvalue.split(",", -1); + for(String val : values){ + value += "," + departmentComInfo.getDepartmentCode(val); + } + } + //浏览按钮,分部,多分部,分权单分部,分权多分部 + }else if("3".equals(htmltype) && ("164".equals(fieldtype) || "194".equals(fieldtype) || "169".equals(fieldtype) || "170".equals(fieldtype))){ + if(!"".equals(fieldvalue)){ + String [] values = fieldvalue.split(",", -1); + for(String val : values){ + value += "," + subCompanyComInfo.getSubCompanyCode(val); + } + } + } + + if(!"".equals(value) && value.startsWith(",")){ + value = value.substring(1); + } + }else if(transttype == 4){ /********登录名********/ + //浏览按钮,单人力、多人力、分权单人力、分权多人力 + if("3".equals(htmltype) && ("1".equals(fieldtype) || "17".equals(fieldtype) || "165".equals(fieldtype) || "166".equals(fieldtype))){ + if(!"".equals(fieldvalue)){ + String [] values = fieldvalue.split(",", -1); + for(String val : values){ + value += "," + resourceComInfo.getLoginID(val); + } + } + } + if(!"".equals(value) && value.startsWith(",")){ + value = value.substring(1); + } + }else if(transttype == 5){ /********手机号码********/ + //浏览按钮,单人力、多人力、分权单人力、分权多人力 + if("3".equals(htmltype) && ("1".equals(fieldtype) || "17".equals(fieldtype) || "165".equals(fieldtype) || "166".equals(fieldtype))){ + if(!"".equals(fieldvalue)){ + String [] values = fieldvalue.split(",", -1); + for(String val : values){ + value += "," + resourceComInfo.getMobile(val); + } + } + } + if(!"".equals(value) && value.startsWith(",")){ + value = value.substring(1); + } + }else if(transttype == 6){ /********Email********/ + //浏览按钮,单人力、多人力、分权单人力、分权多人力 + if("3".equals(htmltype) && ("1".equals(fieldtype) || "17".equals(fieldtype) || "165".equals(fieldtype) || "166".equals(fieldtype))){ + if(!"".equals(fieldvalue)){ + String [] values = fieldvalue.split(",", -1); + for(String val : values){ + value += "," + resourceComInfo.getEmail(val); + } + } + } + if(!"".equals(value) && value.startsWith(",")){ + value = value.substring(1); + } + }else if(transttype == 7){/******自定义SQL********/ + extrainfo = extrainfo.toLowerCase(); + if(!"".equals(extrainfo) && extrainfo.indexOf("update") == -1 && extrainfo.indexOf("delete") == -1 && extrainfo.indexOf("insert") == -1){ + extrainfo = setDmlCusSqlOrWhereValues(fieldvaluename, properties, extrainfo); //替换自定义SQL中的参数 + } + + if(!"".equals(extrainfo)){ + newlog.error("转换规则,自定义SQL,fieldvaluename=" + fieldvaluename + ",sql=" + extrainfo); + if(rst != null){ + rst.executeSql(extrainfo); + if(rst.next()){ + value = Util.null2String(rst.getString(1)); + } + }else{ + rs.executeSql(extrainfo); + if(rs.next()){ + value = Util.null2String(rs.getString(1)); + } + } + } + } + } + + if("".equals(value)){ + value = fieldvalue; + } + + return value; + } +} \ No newline at end of file