diff --git a/src/com/engine/kq/bean/KQBalanceOfLeave.java b/src/com/engine/kq/bean/KQBalanceOfLeave.java new file mode 100644 index 0000000..4382945 --- /dev/null +++ b/src/com/engine/kq/bean/KQBalanceOfLeave.java @@ -0,0 +1,431 @@ +package com.engine.kq.bean; + +import com.engine.kq.biz.KQLeaveRulesComInfo; +import com.engine.kq.biz.KQLeaveRulesDetailComInfo; +import com.engine.kq.biz.KQUsageHistoryBiz; +import com.engine.kq.entity.KQUsageHistoryEntity; +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.Util; +import weaver.hrm.resource.ResourceComInfo; +import weaver.systeminfo.SystemEnv; + +import java.util.ArrayList; +import java.util.Calendar; +import java.util.List; + +/** + * 假期余额--用于Excel导入 + */ +public class KQBalanceOfLeave extends BaseBean { + + /** + * 人员ID + */ + private String resourceId; + /** + * 编号 + */ + private String workcode ; + + /** + * 人员姓名 + */ + private String lastName; + /** + * 假期类型ID + */ + private String leaveRulesId; + /** + * 所属年份 + */ + private String belongYear; + /** + * (混合模式下为法定年假)假期余额基数 + */ + private double baseAmount = 0.00; + /** + * (混合模式下为法定年假)已使用的假期余额 + */ + private double usedAmount = 0.00; + /** + * (混合模式下为法定年假)额外的假期余额 + */ + private double extraAmount = 0.00; + /** + * (仅混合模式下使用,为福利年假)假期余额基数 + */ + private double baseAmount2 = 0.00; + /** + * (仅混合模式下使用,为福利年假)已使用的假期余额 + */ + private double usedAmount2 = 0.00; + /** + * (仅混合模式下使用,为福利年假)额外的假期余额 + */ + private double extraAmount2 = 0.00; + /** + * 用户语言 + */ + private int userlanguage = 7; + /** + * 导入Excel的操作者 + */ + private String operator; + + /** + * 验证模板数据有效性--用于Excel导入 + * + * @return + */ + public String valExcelData() { + String errorInfo = ""; + if (!isExist(resourceId, lastName)) { + errorInfo = SystemEnv.getHtmlLabelName(389985, userlanguage);//ID和姓名不匹配 + return errorInfo; + } + return errorInfo; + } + + /** + * 保存数据 + * + * @return + */ + public String save() { + String resultStr = "false"; + try { + /*获取当前日期,当前时间*/ + Calendar today = Calendar.getInstance(); + String currentDate = Util.add0(today.get(Calendar.YEAR), 4) + "-" + + Util.add0(today.get(Calendar.MONTH) + 1, 2) + "-" + + Util.add0(today.get(Calendar.DAY_OF_MONTH), 2); + String currentTime = Util.add0(today.get(Calendar.HOUR_OF_DAY), 2) + ":" + + Util.add0(today.get(Calendar.MINUTE), 2) + ":" + + Util.add0(today.get(Calendar.SECOND), 2); + + /********************************************************************************************************/ + + /*获取人员的相关信息*/ + ResourceComInfo resourceComInfo = new ResourceComInfo(); + + /*分部ID*/ + String subcompanyId = resourceComInfo.getSubCompanyID(this.resourceId); + + /*入职日期*/ + String companyStartDate = resourceComInfo.getCompanyStartDate(this.resourceId); + + /********************************************************************************************************/ + + /*获取假期类型的相关设置*/ + KQLeaveRulesComInfo rulesComInfo = new KQLeaveRulesComInfo(); + + /*请假最小单位*/ + String minimumUnit = rulesComInfo.getMinimumUnit(this.leaveRulesId); + + /********************************************************************************************************/ + + /*获取假期规则(一个假期类型下可能存在多个假期规则)的相关设置*/ + KQLeaveRulesDetailComInfo detailComInfo = new KQLeaveRulesDetailComInfo(); + + /*请假时长计算方式:1-按工作日计算请假时长、2-按自然日计算请假时长*/ + int distributionMode = Util.getIntValue(detailComInfo.getDistributionMode(this.leaveRulesId, subcompanyId), 1); + + /*有效期规则:0-永久有效、1-按自然年(1月1日-12月31日)、2-按入职日期起12个月、3-自定义次年失效日期*/ + int validityRule = validityRule = Util.getIntValue(detailComInfo.getValidityRule(this.leaveRulesId, subcompanyId), 0); + ; + + /*失效日期--月(当有效期规则选择4-自定义次年失效日期时有效)*/ + String expirationMonth = detailComInfo.getExpirationMonth(this.leaveRulesId, subcompanyId); + + /*失效日期--日(当有效期规则选择4-自定义次年失效日期时有效)*/ + String expirationDay = detailComInfo.getExpirationDay(this.leaveRulesId, subcompanyId); + + /*允许延长有效期:0-不允许、1-允许*/ + int extensionEnable = Util.getIntValue(detailComInfo.getExtensionEnable(this.leaveRulesId, subcompanyId), 0); + + /*允许超过有效期天数*/ + int extendedDays = Util.getIntValue(detailComInfo.getExtendedDays(this.leaveRulesId, subcompanyId), 0); + + /********************************************************************************************************/ + + /*员工假期余额变更记录*/ + String insertOrUpdate = ""; + KQUsageHistoryEntity usageHistoryEntity = new KQUsageHistoryEntity();//员工假期余额变更记录实体类 + List usageHistoryEntityList = new ArrayList();//员工假期余额变更记录集合 + + /********************************************************************************************************/ + + double oldBaseAmount = 0.00; + double oldUsedAmount = 0.00; + double oldExtraAmount = 0.00; + double oldBaseAmount2 = 0.00; + double oldUsedAmount2 = 0.00; + double oldExtraAmount2 = 0.00; + + double newBaseAmount = 0.00; + double newUsedAmount = 0.00; + double newExtraAmount = 0.00; + double newBaseAmount2 = 0.00; + double newUsedAmount2 = 0.00; + double newExtraAmount2 = 0.00; + int status = 0; + String expirationDate = ""; + + /*计算有效期 start*/ + if (validityRule == 0) { + /*不限制有效期,默认永久有效*/ + status = 0; + } else if (validityRule == 1) { + /*按自然年(1月1日-12月31日)*/ + if (extensionEnable == 1) { + /*允许延长有效期*/ + expirationDate = DateUtil.addDate(this.belongYear + "-12-31", extendedDays); + if (Util.dayDiff(expirationDate, currentDate) > 1) { + status = 1; + } + } else { + expirationDate = this.belongYear + "-12-31"; + if (Util.dayDiff(expirationDate, currentDate) > 1) { + status = 1; + } + } + } else if (validityRule == 2) { + /*按入职日期起12个月*/ + if (companyStartDate.equals("")) { + status = 1; + } else if (extensionEnable == 1) { + /*允许延长有效期*/ + expirationDate = DateUtil.addDate((Util.getIntValue(this.belongYear) + 1) + companyStartDate.substring(4), extendedDays); + if (Util.dayDiff(expirationDate, currentDate) > 1) { + status = 1; + } + } else { + expirationDate = (Util.getIntValue(this.belongYear) + 1) + companyStartDate.substring(4); + if (Util.dayDiff(expirationDate, currentDate) > 1) { + status = 1; + } + } + } else if (validityRule == 3) { + /*自定义次年失效日期*/ + if (extensionEnable == 1) { + /*允许延长有效期*/ + expirationDate = DateUtil.addDate((Util.getIntValue(this.belongYear) + 1) + "-" + expirationMonth + "-" + expirationDay, extendedDays); + if (Util.dayDiff(expirationDate, currentDate) > 1) { + status = 1; + } + } else { + expirationDate = (Util.getIntValue(this.belongYear) + 1) + "-" + expirationMonth + "-" + expirationDay; + if (Util.dayDiff(expirationDate, currentDate) > 1) { + status = 1; + } + } + } + /*计算有效期 end*/ + + newBaseAmount = this.baseAmount; + newExtraAmount = this.extraAmount; + newUsedAmount = this.usedAmount; + if (distributionMode == 6) { + newBaseAmount2 = this.baseAmount2; + newExtraAmount2 = this.extraAmount2; + newUsedAmount2 = this.usedAmount2; + } + + boolean flag = true;//记录SQL操作是否成功 + String searchSql = "select * from kq_BalanceOfLeave where leaveRulesId=? and resourceId=? and belongYear=?"; + String updateSql = "update kq_BalanceOfLeave set baseAmount=?,extraAmount=?,usedAmount=?,baseAmount2=?,extraAmount2=?,usedAmount2=?,status=?,expirationDate=? where leaveRulesId=? and resourceId=? and belongYear=?"; + String insertSql = "insert into kq_BalanceOfLeave(baseAmount,extraAmount,usedAmount,baseAmount2,extraAmount2,usedAmount2,status,expirationDate,leaveRulesId,resourceId,belongYear) values(?,?,?,?,?,?,?,?,?,?,?) "; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(searchSql, this.leaveRulesId, this.resourceId, this.belongYear); + if (recordSet.next()) { + oldBaseAmount = Util.getDoubleValue(recordSet.getString("baseAmount"), 0.00); + oldExtraAmount = Util.getDoubleValue(recordSet.getString("extraAmount"), 0.00); + oldUsedAmount = Util.getDoubleValue(recordSet.getString("usedAmount"), 0.00); + if (distributionMode == 6) { + oldBaseAmount2 = Util.getDoubleValue(recordSet.getString("baseAmount2"), 0.00); + oldExtraAmount2 = Util.getDoubleValue(recordSet.getString("extraAmount2"), 0.00); + oldUsedAmount2 = Util.getDoubleValue(recordSet.getString("usedAmount2"), 0.00); + } + + /*更新员工假期余额 start*/ + flag = recordSet.executeUpdate(updateSql, String.format("%.2f", newBaseAmount), String.format("%.2f", newExtraAmount), String.format("%.2f", newUsedAmount), String.format("%.2f", newBaseAmount2), String.format("%.2f", newExtraAmount2), String.format("%.2f", newUsedAmount2), status, expirationDate, this.leaveRulesId, this.resourceId, this.belongYear); + resultStr = String.valueOf(flag); + if (!flag) { + resultStr = "false"; + return resultStr; + } + /*更新员工假期余额 end*/ + + insertOrUpdate = "update"; + } else { + /*新增员工假期余额 start*/ + flag = recordSet.executeUpdate(insertSql, String.format("%.2f", newBaseAmount), String.format("%.2f", newExtraAmount), String.format("%.2f", newUsedAmount), String.format("%.2f", newBaseAmount2), String.format("%.2f", newExtraAmount2), String.format("%.2f", newUsedAmount2), status, expirationDate, this.leaveRulesId, this.resourceId, this.belongYear); + resultStr = String.valueOf(flag); + if (!flag) { + return resultStr; + } + /*新增员工假期余额 end*/ + + insertOrUpdate = "insert"; + } + + /*员工假期余额变更记录 start*/ + usageHistoryEntity = new KQUsageHistoryEntity(); + usageHistoryEntity.setLeaveRulesId(this.leaveRulesId); + usageHistoryEntity.setRelatedId(this.resourceId); + usageHistoryEntity.setWfRequestId(""); + usageHistoryEntity.setOperator(this.operator); + usageHistoryEntity.setOperateDate(currentDate); + usageHistoryEntity.setOperateTime(currentTime); + usageHistoryEntity.setOperateType("7"); + usageHistoryEntity.setBelongYear(this.belongYear); + usageHistoryEntity.setOldBaseAmount(String.format("%.2f", oldBaseAmount)); + usageHistoryEntity.setNewBaseAmount(String.format("%.2f", newBaseAmount)); + usageHistoryEntity.setOldExtraAmount(String.format("%.2f", oldExtraAmount)); + usageHistoryEntity.setNewExtraAmount(String.format("%.2f", newExtraAmount)); + usageHistoryEntity.setOldUsedAmount(String.format("%.2f", oldUsedAmount)); + usageHistoryEntity.setNewUsedAmount(String.format("%.2f", newUsedAmount)); + usageHistoryEntity.setOldBaseAmount2(String.format("%.2f", oldBaseAmount2)); + usageHistoryEntity.setNewBaseAmount2(String.format("%.2f", newBaseAmount2)); + usageHistoryEntity.setOldExtraAmount2(String.format("%.2f", oldExtraAmount2)); + usageHistoryEntity.setNewExtraAmount2(String.format("%.2f", newExtraAmount2)); + usageHistoryEntity.setOldUsedAmount2(String.format("%.2f", oldUsedAmount2)); + usageHistoryEntity.setNewUsedAmount2(String.format("%.2f", newUsedAmount2)); + usageHistoryEntity.setOldMinimumUnit(minimumUnit); + usageHistoryEntity.setNewMinimumUnit(minimumUnit); + usageHistoryEntity.setInsertOrUpdate(insertOrUpdate); + + usageHistoryEntityList.add(usageHistoryEntity); + KQUsageHistoryBiz usageHistoryBiz = new KQUsageHistoryBiz(); + flag = usageHistoryBiz.save(usageHistoryEntityList); + resultStr = String.valueOf(flag); + if (!flag) { + return resultStr; + } + /*员工假期余额变更记录 end*/ + } catch (Exception e) { + writeLog(e); + } + return resultStr; + } + + /** + * 判断ID和姓名是否匹配,系统中是否存在此人员 + * + * @param resourceId + * @param lastName + * @return + */ + private boolean isExist(String resourceId, String lastName) { + String sql = "select 1 from HrmResource where id=? "; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql, resourceId); + if (recordSet.next()) { + return true; + } else { + return false; + } + } + + public String getResourceId() { + return resourceId; + } + + public void setResourceId(String resourceId) { + this.resourceId = resourceId; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getLeaveRulesId() { + return leaveRulesId; + } + + public void setLeaveRulesId(String leaveRulesId) { + this.leaveRulesId = leaveRulesId; + } + + public String getBelongYear() { + return belongYear; + } + + public void setBelongYear(String belongYear) { + this.belongYear = belongYear; + } + + public double getBaseAmount() { + return baseAmount; + } + + public void setBaseAmount(double baseAmount) { + this.baseAmount = baseAmount; + } + + public double getUsedAmount() { + return usedAmount; + } + + public void setUsedAmount(double usedAmount) { + this.usedAmount = usedAmount; + } + + public double getExtraAmount() { + return extraAmount; + } + + public void setExtraAmount(double extraAmount) { + this.extraAmount = extraAmount; + } + + public double getBaseAmount2() { + return baseAmount2; + } + + public void setBaseAmount2(double baseAmount2) { + this.baseAmount2 = baseAmount2; + } + + public double getUsedAmount2() { + return usedAmount2; + } + + public void setUsedAmount2(double usedAmount2) { + this.usedAmount2 = usedAmount2; + } + + public double getExtraAmount2() { + return extraAmount2; + } + + public void setExtraAmount2(double extraAmount2) { + this.extraAmount2 = extraAmount2; + } + + public void setUserLanguage(String languageId) { + this.userlanguage = Util.getIntValue(languageId, 7); + } + + public String getOperator() { + return operator; + } + + public void setOperator(String operator) { + this.operator = operator; + } + + public String getWorkcode() { + return workcode; + } + + public void setWorkcode(String workcode) { + this.workcode = workcode; + } +} diff --git a/src/com/engine/kq/biz/KQAttFlowSetBiz.java b/src/com/engine/kq/biz/KQAttFlowSetBiz.java new file mode 100644 index 0000000..406c7e3 --- /dev/null +++ b/src/com/engine/kq/biz/KQAttFlowSetBiz.java @@ -0,0 +1,1121 @@ +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 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.TimeUtil; +import weaver.general.Util; +import weaver.hrm.User; +import weaver.hrm.common.database.dialect.DbDialectFactory; +import weaver.systeminfo.SystemEnv; + +/** + * 考勤流程 设置类 + */ +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"),""); + //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(); + break; + case "1": + isEvection= true; + tableName = KqSplitFlowTypeEnum.EVECTION.getTablename(); + break; + case "2": + isOut= true; + tableName = KqSplitFlowTypeEnum.OUT.getTablename(); + break; + case "3": + tableName = KqSplitFlowTypeEnum.OVERTIME.getTablename(); + 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 fromDate 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 "; + } + + 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 fromDate between'"+fromDate+"' and '"+toDate+"'"; + }else{ + baseSql += " and belongdate between'"+fromDate+"' and '"+toDate+"'"; + } + } + 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 = ""; + 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..58bbf97 --- /dev/null +++ b/src/com/engine/kq/biz/KQBalanceOfLeaveBiz.java @@ -0,0 +1,3996 @@ +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.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); + + /**********************************************************************************************************/ + + //假期类型缓存类 + 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) { + 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"));//额外的假期时长 + //根据释放规则获取已释放的天数/小时数 + 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(); + } + 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); + + /****************************************************************************************************************/ + + //假期类型的缓存类 + 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; + } + } + } + //[调休]的假期类型的最小请假单位: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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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()); + 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); + 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); + 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"); + 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()); + 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); + 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); + 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"); + 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); + 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); + 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"); + 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(!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; + } + //如果批处理年份等于入职年份,那应该以【入职日期】来折算 + if (belongYear.compareTo(companyStartDate.substring(0, 4)) == 0) { + //需要折算 + needConvert = true; + //以【入职日期来折算】 + calendar = DateUtil.getCalendar(companyStartDate); + } + for (int i = 0; i < 1; i++) { + //如果【计算假期基数的日期】小于【假期基数发放日期】,假期基数应该为0 + if (date4CalcAmount.compareTo(baseAmountReleaseDate) < 0) { + return 0; + } else if (date4CalcAmount.compareTo(baseAmountReleaseDate) >= 0) { + baseAmount = baseAmount_releaseDate; + //暂定【假期基数发放日期】一定小于等于【工龄变动日期】、【司龄变动日期】 + //【假期基数发放日期】<=【工龄变动日期】<=【司龄变动日期】 + if (baseAmountReleaseDate.compareTo(ageLimitChangeDate) <= 0 && ageLimitChangeDate.compareTo(ageLimitChangeDate2) <= 0) { + if (calcMethod == 0 && baseAmount_releaseDate.doubleValue() > 0) { + Calendar _calendar1 = DateUtil.getCalendar(baseAmountReleaseDate); + BigDecimal _dayOfYear1 = new BigDecimal("" + (_calendar1.get(Calendar.DAY_OF_YEAR) - 1)); + BigDecimal _actualMaximum = new BigDecimal("" + (_calendar1.getActualMaximum(Calendar.DAY_OF_YEAR))); + + Calendar _calender2 = DateUtil.getCalendar(ageLimitChangeDate); + BigDecimal _dayOfYear2 = new BigDecimal("" + (_calender2.get(Calendar.DAY_OF_YEAR) - 1)); + + Calendar _calender3 = DateUtil.getCalendar(ageLimitChangeDate2); + BigDecimal _dayOfYear3 = new BigDecimal("" + (_calender3.get(Calendar.DAY_OF_YEAR) - 1)); + + baseAmount = ((baseAmount_releaseDate.multiply(_dayOfYear2.subtract(_dayOfYear1))) + .add(baseAmount_ageLimitChangeDate.multiply(_dayOfYear3.subtract(_dayOfYear2))) + .add(baseAmount_ageLimitChangeDate2.multiply(_actualMaximum.subtract(_dayOfYear3)))) + .divide(_actualMaximum, decimalDigit, RoundingMode.HALF_UP); + if (convertMode == 0) { + if (date4CalcAmount.compareTo(baseAmountReleaseDate) >= 0) { + baseAmount = baseAmount_releaseDate.setScale(decimalDigit, RoundingMode.HALF_UP); + } + if (date4CalcAmount.compareTo(ageLimitChangeDate) >= 0) { + baseAmount = baseAmount_ageLimitChangeDate.setScale(decimalDigit, RoundingMode.HALF_UP); + } + if (date4CalcAmount.compareTo(ageLimitChangeDate2) >= 0) { + baseAmount = baseAmount_ageLimitChangeDate2.setScale(decimalDigit, RoundingMode.HALF_UP); + } + } else if (convertMode == 1) { + baseAmount = baseAmount; + } else if (convertMode == 2) { + baseAmount = baseAmount.setScale(0, RoundingMode.UP); + } else if (convertMode == 3) { + baseAmount = baseAmount.setScale(0, RoundingMode.DOWN); + } else if (convertMode == 4) { + baseAmount = baseAmount.divide(new BigDecimal("0.5"), 0, RoundingMode.UP).multiply(new BigDecimal("0.5")); + } else if (convertMode == 5) { + baseAmount = baseAmount.divide(new BigDecimal("0.5"), 0, RoundingMode.DOWN).multiply(new BigDecimal("0.5")); + } + break; + } + //【批处理日期】>=【工龄变动日期】&& (人员在【假期基数发放日期】时对应的假期基数是0 || 【假期基数计算方式=2】时) + if ((date4CalcAmount.compareTo(ageLimitChangeDate) >= 0) + && (baseAmount_releaseDate.doubleValue() <= 0 || calcMethod == 2)) { + if (baseAmount_releaseDate.doubleValue() <= 0 && baseAmount_ageLimitChangeDate.doubleValue() > 0) { + needConvert = true; + 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; + 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; + 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; + 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")); + /** + * 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 (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 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/KQFormatData.java b/src/com/engine/kq/biz/KQFormatData.java new file mode 100644 index 0000000..39ee84a --- /dev/null +++ b/src/com/engine/kq/biz/KQFormatData.java @@ -0,0 +1,1053 @@ +package com.engine.kq.biz; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +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.util.UtilKQ; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.googlecode.aviator.AviatorEvaluator; +import com.googlecode.aviator.Expression; +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.general.BaseBean; +import weaver.general.InitServer; +import weaver.general.Util; +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) { + 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")){ + 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) { + 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); + } + } + }catch (Exception e) { + 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; + + if (workTime != null) { + lsSignTime = workTime.getSignTime();//允许打卡时间 + lsWorkTime = workTime.getWorkTime();//工作时间 + lsRestTime = workTime.getRestTime();//休息时段时间 + oneSign = lsWorkTime!=null&&lsWorkTime.size()==1; + } + + int[] dayMins = new int[2880];//一天所有分钟数 + Arrays.fill(dayMins, -1); + // 一天4次打卡单独做判断,如果是上午下班打卡和下午上班打卡时间重叠,那么上午的下班卡取最早的,下午的上班卡取最晚的。用shiftCount是否等于-1判断,-1就走标准不重叠。2就表示重叠走新的逻辑 + int shiftCount = lsWorkTime == null ? 0 : lsWorkTime.size(); + int shiftI = 0; + String signEndDateTimeZero = ""; + for (int i = 0; lsWorkTime != null && i < lsWorkTime.size(); i++) { + shiftI = i; + TimeScopeEntity signTimeScope = lsSignTime.get(i); + TimeScopeEntity workTimeScope = lsWorkTime.get(i); + String signBeginDateTime = signTimeScope.getBeginTimeAcross() ? nextDate : kqDate; + if(signTimeScope.isBeginTimePreAcross()){ + signBeginDateTime = preDate; + } + signBeginDateTime+=" "+kqTimesArrayComInfo.turn48to24Time(signTimeScope.getBeginTime())+":00"; + String signEndDateTime = signTimeScope.getEndTimeAcross() ? nextDate : kqDate; + signEndDateTime+=" "+kqTimesArrayComInfo.turn48to24Time(signTimeScope.getEndTime())+":59"; + if (shiftCount == 2 && shiftI == 0) { + signEndDateTimeZero = signEndDateTime; + } + if (shiftCount == 2 && shiftI == 1) { + shiftCount = signBeginDateTime.compareTo(signEndDateTimeZero) <= 0 ? shiftCount : -1; + } + } + for (int i = 0; lsWorkTime != null && i < lsWorkTime.size(); i++) { + shiftI = i; + params = new ArrayList<>(); + TimeScopeEntity signTimeScope = lsSignTime.get(i); + TimeScopeEntity workTimeScope = lsWorkTime.get(i); + //TimeScopeEntity restTimeScope = lsRestTime.isEmpty()?null:lsRestTime.get(i); + String workBeginTime = Util.null2String(workTimeScope.getBeginTime()); + String ori_workBeginTime = workBeginTime; + int workBeginIdx = kqTimesArrayComInfo.getArrayindexByTimes(workBeginTime); + boolean workBenginTimeAcross = workTimeScope.getBeginTimeAcross(); + String workEndTime = Util.null2String(workTimeScope.getEndTime()); + String ori_workEndTime = workEndTime; + int workEndIdx = kqTimesArrayComInfo.getArrayindexByTimes(workEndTime); + boolean workEndTimeAcross = workTimeScope.getEndTimeAcross(); + int workMins = workTimeScope.getWorkMins(); + + String workBeginDate = workBenginTimeAcross ? nextDate : kqDate; + String workEndDate = workEndTimeAcross ? nextDate : kqDate; + + Arrays.fill(dayMins, workBeginIdx, workEndIdx, 1);//工作时段标识 1 + + int beginIdx = 0; + int endIdx = 0; + int checkIn = 0; + int checkOut = 0; + String signInId = ""; + String signInDate = ""; + String signInTime = ""; + String signOutId = ""; + String signOutDate = ""; + String signOutTime = ""; + int earlyInMins = 0;//早到分钟数 + int lateOutMins = 0;//晚走分钟数 + int signMins = 0;//签到签退时长 + int tmpAttendanceMins = 0;//出勤分钟数(流程抵扣来的) + int attendanceMins = 0; + int beLateMins = 0; + int graveBeLateMins = 0; + int leaveEarlyMins = 0; + int graveLeaveEarlyMins = 0; + int absenteeismMins = 0; + int 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,shiftCount,shiftI); + 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(beginIdx>=workEndIdx){ + continue; + } + if(endIdx<=workBeginIdx){ + continue; + } + + if(leaveInfo.get(newLeaveType)==null){ + leaveInfo.put(newLeaveType,val); + }else{ + val = (Integer) leaveInfo.get(newLeaveType); + } + + if(beginIdxworkEndIdx)tmpEndIdx=endIdx; + if(tmpEndIdx>tmpBeginIdx){ + leaveInfo.put(newLeaveType,val+(tmpEndIdx-tmpBeginIdx)); + } + } + }else{ + if (endIdx > beginIdx) { + Arrays.fill(dayMins, beginIdx, endIdx, 99);//异常流程抵扣时段标识99 + } + } + } + + + if (workEndTimeAcross && false) {//跨天需要加入一天的流程 + workFlow = null; + if (workFlowInfo.get(nextDateKey) != null) { + workFlow = (List) workFlowInfo.get(nextDateKey); + } + + for (int j = 0; workFlow != null && j < workFlow.size(); j++) { + Map data = (Map) workFlow.get(j); + String flowType = Util.null2String(data.get("flowtype")); + beginIdx = kqTimesArrayComInfo.getArrayindexByTimes(Util.null2String(data.get("begintime")))+1440; + endIdx = kqTimesArrayComInfo.getArrayindexByTimes(Util.null2String(data.get("endtime")))+1440; + if(endIdx>=2880){ + endIdx = 2880; + } + if(flowType.equals(FlowReportTypeEnum.EVECTION.getFlowType())){ + Arrays.fill(dayMins, beginIdx, endIdx, 7);//出差抵扣时段标识 7 + }else if(flowType.equals(FlowReportTypeEnum.OUT.getFlowType())){ + Arrays.fill(dayMins, beginIdx, endIdx, 8);//公出抵扣时段标识 8 + }else if(flowType.equalsIgnoreCase(FlowReportTypeEnum.LEAVE.getFlowType())){ + if (endIdx > beginIdx) { + Arrays.fill(dayMins, beginIdx, endIdx, 5);//流程抵扣时段标识 5 + + } + }else{ + if (endIdx > beginIdx) { + Arrays.fill(dayMins, beginIdx, endIdx, 99);//异常流程抵扣时段标识99 + } + } + } + } + + if(lsRestTime != null && !lsRestTime.isEmpty()){ + for(int k = 0 ; k < lsRestTime.size(); k++){ + TimeScopeEntity restTimeScope = lsRestTime.get(k); + if (restTimeScope!=null) { + String restBeginTime = Util.null2String(restTimeScope.getBeginTime()); + String restEndTime = Util.null2String(restTimeScope.getEndTime()); + beginIdx = kqTimesArrayComInfo.getArrayindexByTimes(restBeginTime); + endIdx = kqTimesArrayComInfo.getArrayindexByTimes(restEndTime); + if (endIdx > beginIdx) { + Arrays.fill(dayMins, beginIdx, endIdx, -11);//休息时间 + } + } + } + int all_rest_cnt = kqTimesArrayComInfo.getCnt(dayMins, workBeginIdx, workEndIdx, -11); + if(all_rest_cnt >= 0){ + workMins = workMins-(all_rest_cnt); + } + } + + for (int j = workBeginIdx; j < workEndIdx; j++) { + switch (dayMins[j]) { + case 1: + tmpAttendanceMins++; + break; + case 2: + beLateMins++; + break; + case 3: + leaveEarlyMins++; + break; + case 4: + 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 isondutyfreecheck =false; + boolean isoffdutyfreecheck =false; + Map model_ShiftRule = kqFormatShiftRule.getModel_ShiftRule(i, workTime.getSerialId()); + Iterator iter = model_ShiftRule.entrySet().iterator(); + while (iter.hasNext()) { + Map.Entry entry = (Map.Entry) iter.next(); + String key = Util.null2String(entry.getKey()); + String value = Util.null2String(entry.getValue()); + if(key.equals("start")&&value.equals("1")){ + isondutyfreecheck = true; + } + if(key.equals("end")&&value.equals("1")){ + isoffdutyfreecheck = true; + } + } + boolean beforeBegin = !new KQFormatBiz().needCal(workBeginDate,workBeginTime); + if(beforeBegin) {//还未到上班时间,不用计算任何状态 + kqLog.writeLog("还未到上班时间,不用计算任何状态"); + beLateMins = 0; + graveBeLateMins = 0; + leaveEarlyMins = 0; + graveLeaveEarlyMins = 0; + absenteeismMins = 0; + forgotCheckMins = 0; + forgotBeginWorkCheckMins = 0; + }else if(!new KQFormatBiz().needCal(workEndDate,workEndTime)) {//还未到下班时间 + kqLog.writeLog("还未到上班时间"); + leaveEarlyMins = 0; + graveLeaveEarlyMins = 0; + forgotCheckMins = 0; + } + + if (workTime.getIsExclude()) {//无需考勤人员没有异常状态 + beLateMins = 0; + graveBeLateMins = 0; + leaveEarlyMins = 0; + graveLeaveEarlyMins = 0; + absenteeismMins = 0; + forgotCheckMins = 0; + forgotBeginWorkCheckMins = 0; + } + //允许下班不打卡 ,如果上班也没有打卡,那么算上班旷工0.5天 + if (isoffdutyfreecheck) { + if (checkIn == 0) {//(无签到),就会有上班漏签,如果有下班卡,那么上班漏签 + if(forgotBeginWorkCheckMins==0&&absenteeismMins>0){ + forgotBeginWorkCheckMins= absenteeismMins ; + } + } + absenteeismMins = 0; + forgotCheckMins = 0; + } + //允许上班不打卡,如果下班也没有打卡,那么算漏签 + if(isondutyfreecheck){ + if (checkOut == 0) {//(无签退) + if(forgotCheckMins==0&&absenteeismMins>0){ + forgotCheckMins= absenteeismMins ; + } + } + absenteeismMins = 0; + forgotBeginWorkCheckMins = 0; + } + if(isondutyfreecheck&&isoffdutyfreecheck){ + 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(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); + } +} diff --git a/src/com/engine/kq/biz/KQOverTimeFlowBiz.java b/src/com/engine/kq/biz/KQOverTimeFlowBiz.java new file mode 100644 index 0000000..b66a78e --- /dev/null +++ b/src/com/engine/kq/biz/KQOverTimeFlowBiz.java @@ -0,0 +1,709 @@ +package com.engine.kq.biz; + +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.general.Util; + +/** + * 加班流程 非工作时长计算 重新搞一把 + * 现在是根据归属来拆分流程 + */ +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(); + + 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 = ""; + //需要知道明日的类型:如果今天是工作日的话,那么今天的加班临界点可能和明日的上班时间冲突,需要知道明日的上班时间进行比较, + // 如果今天是休息日,那么明天如果是工作日的话,默认规则下,明天的上班前都是属于今天的加班区间 + 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]); + } + } + } + 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]); + } + } + } + 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"); + } + } + if(has_cut_point == 0){ + if(changeType == 2){ + overtime_cut_point = cur_beginwork_time; + }else { + 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; + 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; + } + } + 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); + } + }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); + } + } + if(i == betweenDays){ + toTime_index = kqTimesArrayComInfo.getArrayindexByTimes(toTime); + }else{ + toTime_index = kqTimesArrayComInfo.turn24to48TimeIndex(kqTimesArrayComInfo.getArrayindexByTimes(overtime_cut_point)); + 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); + } + } + 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(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){ + //针对跨天的休息时段单独处理排除掉23:59-00:00的时间 + restEnd = 1440; + } + 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 > 0 && cutlength > 0){ + 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..94b1a80 --- /dev/null +++ b/src/com/engine/kq/biz/KQOverTimeRuleCalBiz.java @@ -0,0 +1,2663 @@ +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.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.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); + } + } + }catch (Exception e){ + kqLog.info("加班生成数据报错:KQOverTimeRuleCalBiz:"); + StringWriter errorsWriter = new StringWriter(); + e.printStackTrace(new PrintWriter(errorsWriter)); + kqLog.info(errorsWriter.toString()); + } + } + + /** + * 需审批,以打卡为准,取流程和打卡的交集 + * @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 + * @param uuid + */ + 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 + * @param uuid + */ + 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(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) { + 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 + */ + private 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; + } + } + } + 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 + */ + private 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"); + rs.executeUpdate(delSql); + } + 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/KQOvertimeRulesBiz.java b/src/com/engine/kq/biz/KQOvertimeRulesBiz.java new file mode 100644 index 0000000..cf49cab --- /dev/null +++ b/src/com/engine/kq/biz/KQOvertimeRulesBiz.java @@ -0,0 +1,922 @@ +package com.engine.kq.biz; + +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.google.common.collect.Lists; +import com.google.common.collect.Maps; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.Util; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; +import weaver.systeminfo.SystemEnv; +import weaver.wechat.util.DateUtil; + +import java.math.BigDecimal; +import java.util.*; + +/** + * 加班规则的相关接口 + */ +public class KQOvertimeRulesBiz { + + private static KQLog logger = new KQLog();//用于记录日志信息 + + private static KQOvertimeRulesDetailEntity kqOvertimeRulesDetail = new KQOvertimeRulesDetailEntity();//加班规则实体类 + + /** + * 根据指定人员ID以及指定日期判断这一天是工作日还是休息日还是节假日 + * + * @param resourceId 指定人员ID + * 根据指定人员ID获取考勤组ID,根据考勤组得到对应日期是工作日还是休息日 + * @param date 指定日期 + * 根据日期判断是工作日还是节假日还是休息日(这里综合考虑考勤组和节假日设置,节假日设置的优先级最高) + * @return 1-节假日、2-工作日、3-休息日、-1-数据异常,无效数据 + */ + public static int getChangeType(String resourceId, String date) { + int changeType = -1; + + /*获取考勤组的ID,因为考勤组有有效期,所以需要传入日期*/ + KQGroupMemberComInfo kqGroupMemberComInfo = new KQGroupMemberComInfo(); + String groupId = kqGroupMemberComInfo.getKQGroupId(resourceId, date); + + /*该人员不存在于任意一个考勤组中,请为其设置考勤组*/ + if(groupId.equals("")){ + logger.writeLog("该人员不存在于任意一个考勤组中,请为其设置考勤组。resourceId=" + resourceId + ",date=" + date); + } + + changeType = KQHolidaySetBiz.getChangeType(groupId, date); + if (changeType != 1 && changeType != 2 && changeType != 3) { + KQWorkTime kqWorkTime = new KQWorkTime(); + changeType = kqWorkTime.isWorkDay(resourceId, date) ? 2 : 3; + } + return changeType; + } + + /** + * 判断是否允许加班 + * + * @param resourceId 指定人员 + * 根据人员ID获取人员所在的考勤组ID,找出对应的加班规则ID + * @param date 指定日期 + * 根据日期判断是工作日还是节假日还是休息日 + * @return 0-不允许加班、1-允许加班 + */ + public static int getOvertimeEnable(String resourceId, String date) { + int overtimeEnable = 0; + kqOvertimeRulesDetail = getOvertimeRulesDetail(resourceId, date); + overtimeEnable = kqOvertimeRulesDetail.getOvertimeEnable(); + return overtimeEnable; + } + + /** + * 获取加班方式计算 + * 1-需审批,以审批单为准 + * 2-需审批,以打卡为准,但是不能超过审批时长 + * 3-无需审批,根据打卡时间计算加班时长 + * + * @param resourceId 指定人员 + * 根据人员ID获取人员所在的考勤组ID,找出对应的加班规则ID + * @param date 指定日期 + * 根据日期判断是工作日还是节假日还是休息日 + * @return -1:接口异常,返回的无效数据。 + */ + public static int getComputingMode(String resourceId, String date) { + int computingMode = -1; + kqOvertimeRulesDetail = getOvertimeRulesDetail(resourceId, date); + computingMode = kqOvertimeRulesDetail.getComputingMode(); + return computingMode; + } + + /** + * 获取加班起算时间 + * + * @param resourceId 指定人员 + * 根据人员ID获取人员所在的考勤组ID,找出对应的加班规则ID + * @param date 指定日期 + * 根据日期判断是工作日还是节假日还是休息日 + * @return -1:接口异常,返回的无效数据。 + */ + public static int getStartTime(String resourceId, String date) { + int startTime = -1; + kqOvertimeRulesDetail = getOvertimeRulesDetail(resourceId, date); + startTime = kqOvertimeRulesDetail.getStartTime(); + return startTime; + } + + /** + * 获取最小加班时长 + * + * @param resourceId 指定人员 + * 根据人员ID获取人员所在的考勤组ID,找出对应的加班规则ID + * @param date 指定日期 + * 根据日期判断是工作日还是节假日还是休息日 + * @return -1:接口异常,返回的无效数据。 + */ + public static int getMinimumLen(String resourceId, String date) { + int minimumUnit = -1; + kqOvertimeRulesDetail = getOvertimeRulesDetail(resourceId, date); + minimumUnit = kqOvertimeRulesDetail.getMinimumLen(); + return minimumUnit; + } + + /** + * 是否允许加班补偿 + * 0-不允许加班转调休、1-允许加班转调休 + * + * @param resourceId 指定人员 + * 根据人员ID获取人员所在的考勤组ID,找出对应的加班规则ID + * @param date 指定日期 + * 根据日期判断是工作日还是节假日还是休息日 + * @return + */ + public static int getPaidLeaveEnable(String resourceId, String date) { + int paidLeaveEnable = 0; + kqOvertimeRulesDetail = getOvertimeRulesDetail(resourceId, date); + paidLeaveEnable = kqOvertimeRulesDetail.getPaidLeaveEnable(); + return paidLeaveEnable; + } + + /** + * 获取加班时长转调休时长比例中的分母 + * + * @param resourceId 指定人员 + * 根据人员ID获取人员所在的考勤组ID,找出对应的加班规则ID + * @param date 指定日期 + * 根据日期判断是工作日还是节假日还是休息日 + * @return -1:接口异常,返回的无效数据。 + */ + public static double getLenOfOvertime(String resourceId, String date) { + double lenOfOvertime = -1; + kqOvertimeRulesDetail = getOvertimeRulesDetail(resourceId, date); + lenOfOvertime = kqOvertimeRulesDetail.getLenOfOvertime(); + BigDecimal bigDecimal = new BigDecimal(lenOfOvertime); + lenOfOvertime = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); + return lenOfOvertime; + } + + /** + * 获取加班时长转调休时长比例中的分子 + * + * @param resourceId 指定人员 + * 根据人员ID获取人员所在的考勤组ID,找出对应的加班规则ID + * @param date 指定日期 + * 根据日期判断是工作日还是节假日还是休息日 + * @return -1:接口异常,返回的无效数据。 + */ + public static double getLenOfLeave(String resourceId, String date) { + double lenOfLeave = -1; + kqOvertimeRulesDetail = getOvertimeRulesDetail(resourceId, date); + lenOfLeave = kqOvertimeRulesDetail.getLenOfLeave(); + BigDecimal bigDecimal = new BigDecimal(lenOfLeave); + lenOfLeave = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); + return lenOfLeave; + } + + /** + * 判断是否需要排除休息时间 + * + * @param resourceId 指定人员 + * 根据人员ID获取人员所在的考勤组ID,找出对应的加班规则ID + * @param date 指定日期 + * 根据日期判断是工作日还是节假日还是休息日 + * @return 0-不需要排除休息时间、1-需要排除休息时间 + */ + public static int getHasRestTime(String resourceId, String date) { + int hasRestTime = 0; + kqOvertimeRulesDetail = getOvertimeRulesDetail(resourceId, date); + hasRestTime = kqOvertimeRulesDetail.getHasRestTime(); + return hasRestTime; + } + + /** + * 获取休息时段 + * startType:0-开始时间为本日、1-开始时间为次日 + * startTime:开始时间 + * endType:0-结束时间为本日、1-结束时间为次日 + * endTime:结束时间 + * + * @param resourceId 指定人员 + * 根据人员ID获取人员所在的考勤组ID,找出对应的加班规则ID + * @param date 指定日期 + * 根据日期判断是工作日还是节假日还是休息日 + * @return + */ + public static List getRestTimeList(String resourceId, String date) { + List restTimeList = new ArrayList(); + + /** + * 因为休息时段可以设置次日的数据,所以获取某一天的休息时段的时候,需要先考虑上一个日期所设置的次日的休息时段 + */ + String lastDay = DateUtil.addDay(date, -1, "yyyy-MM-dd"); + kqOvertimeRulesDetail = getOvertimeRulesDetail(resourceId, lastDay); + int overtimeEnable = kqOvertimeRulesDetail.getOvertimeEnable(); + int hasRestTime = kqOvertimeRulesDetail.getHasRestTime(); + if (overtimeEnable == 1 && hasRestTime == 1) { + int dayType = kqOvertimeRulesDetail.getDayType(); + int ruleId = kqOvertimeRulesDetail.getRuleId(); + + String sql = "select * from kq_OvertimeRestTime where ruleId=" + ruleId + " and dayType=" + dayType; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql); + while (recordSet.next()) { + String startType = recordSet.getString("startType"); + String startTime = recordSet.getString("startTime"); + String endType = recordSet.getString("endType"); + String endTime = recordSet.getString("endTime"); + + if (startType.equals("0") && endType.equals("1")) { + String[] str = new String[]{"00:00", endTime}; + restTimeList.add(str); + } else if (startType.equals("1") && endType.equals("1")) { + String[] str = new String[]{startTime, endTime}; + restTimeList.add(str); + } + } + } + + kqOvertimeRulesDetail = getOvertimeRulesDetail(resourceId, date); + overtimeEnable = kqOvertimeRulesDetail.getOvertimeEnable(); + hasRestTime = kqOvertimeRulesDetail.getHasRestTime(); + if (overtimeEnable == 1 && hasRestTime == 1) { + int dayType = kqOvertimeRulesDetail.getDayType(); + int ruleId = kqOvertimeRulesDetail.getRuleId(); + + String sql = "select * from kq_OvertimeRestTime where ruleId=" + ruleId + " and dayType=" + dayType; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql); + while (recordSet.next()) { + String startType = recordSet.getString("startType"); + String startTime = recordSet.getString("startTime"); + String endType = recordSet.getString("endType"); + String endTime = recordSet.getString("endTime"); + + if (startType.equals("0") && endType.equals("0")) { + String[] str = new String[]{startTime, endTime}; + restTimeList.add(str); + } else if (startType.equals("0") && endType.equals("1")) { + String[] str = new String[]{startTime, "24:00"}; + restTimeList.add(str); + } + } + } + return restTimeList; + } + + /** + * 获取加班规则的明细 + * + * @param resourceId 指定人员 + * 根据人员ID获取人员所在的考勤组ID,找出对应的加班规则ID + * @param changeType 日期类型:1-节假日、2-工作日、3-休息日 + * @return + */ + private static KQOvertimeRulesDetailEntity getOvertimeRulesDetail(String resourceId, String date) { + KQOvertimeRulesDetailEntity kqOvertimeRulesDetail = new KQOvertimeRulesDetailEntity(); + try { + /*获取考勤组的ID,因为考勤组有有效期,所以需要传入日期*/ + KQGroupMemberComInfo kqGroupMemberComInfo = new KQGroupMemberComInfo(); + String groupIds = kqGroupMemberComInfo.getKQGroupId(resourceId, date); + if (groupIds.equals("")) { + /*该人员不存在于任意一个考勤组中,请为其设置考勤组*/ + logger.writeLog("该人员不存在于任意一个考勤组中,请为其设置考勤组。resourceId=" + resourceId + ",date=" + date); + } + + int changeType = getChangeType(resourceId, date); + /*获取当前日期的日期类型错误*/ + if (changeType != 1 && changeType != 2 && changeType != 3) { + logger.writeLog("获取当前日期的日期类型错误。resourceId=" + resourceId + ",date=" + date + ",changeType=" + changeType); + } + + int overtimeRuleId = 0;//加班规则的ID + RecordSet recordSet = new RecordSet(); + String sql = "select id from kq_OvertimeRules where (isDelete is null or isDelete !=1) "; + if (recordSet.getDBType().equalsIgnoreCase("sqlserver")) { + sql += " and ','+groupIds+',' like '%," + groupIds + ",%'"; + } else if (recordSet.getDBType().equalsIgnoreCase("mysql")) { + sql += " and concat(',',groupIds,',') like '%," + groupIds + ",%'"; + } else { + sql += " and ','||groupIds||',' like '%," + groupIds + ",%'"; + } + recordSet.executeQuery(sql); + if (recordSet.next()) { + overtimeRuleId = recordSet.getInt("id"); + + sql = "select * from kq_OvertimeRulesDetail where ruleId=" + overtimeRuleId + " and dayType=" + changeType; + recordSet.executeQuery(sql); + if (recordSet.next()) { + int ruleId = recordSet.getInt("ruleId"); + int dayType = recordSet.getInt("dayType"); + int overtimeEnable = recordSet.getInt("overtimeEnable"); + int computingMode = recordSet.getInt("computingMode"); + int startTime = recordSet.getInt("startTime"); + int minimumLen = recordSet.getInt("minimumLen"); + int paidLeaveEnable = recordSet.getInt("paidLeaveEnable"); + double lenOfOvertime = Util.getDoubleValue(recordSet.getString("lenOfOvertime"), 1.00); + double lenOfLeave = Util.getDoubleValue(recordSet.getString("lenOfLeave"), 1.00); + int hasRestTime = Util.getIntValue(recordSet.getString("hasRestTime")); + + kqOvertimeRulesDetail.setRuleId(ruleId); + kqOvertimeRulesDetail.setDayType(dayType); + kqOvertimeRulesDetail.setOvertimeEnable(overtimeEnable); + kqOvertimeRulesDetail.setComputingMode(computingMode); + kqOvertimeRulesDetail.setStartTime(startTime); + kqOvertimeRulesDetail.setMinimumLen(minimumLen); + kqOvertimeRulesDetail.setPaidLeaveEnable(paidLeaveEnable); + kqOvertimeRulesDetail.setLenOfOvertime(lenOfOvertime); + kqOvertimeRulesDetail.setLenOfLeave(lenOfLeave); + kqOvertimeRulesDetail.setHasRestTime(hasRestTime); + } + } else { + logger.writeLog("该人员所属的考勤组没有设置过任何加班规则,请为其设置加班规则。resourceId=" + resourceId + ",date="+date+",changeType=" + changeType); + } + } catch (Exception e) { + logger.writeLog("根据人员ID获取加班规则的规则内容出错。resourceId=" + resourceId + ",date=" + date); + e.printStackTrace(); + } + return kqOvertimeRulesDetail; + } + + /** + * 新建加班规则 + * + * @param params + * @return + */ + public static int addOvertimeRules(Map params, User user) { + /*是否保存成功*/ + boolean flag = false; + + /*新插入的加班规则的ID*/ + int ruleId = -1; + try { + boolean canAdd = HrmUserVarify.checkUserRight("KQOvertimeRulesAdd:Add", user);//是否具有新建权限 + if (!canAdd) { + logger.info(user.getLastname() + "暂时没有权限!"); + return -1; + } + + /*加班规则名称*/ + String name = Util.null2String(params.get("name")); + /*考勤组的ID*/ + String groupIds = Util.null2String(params.get("groupIds")); + + /*工作日是否允许加班:0-不允许、1-允许*/ + int overtimeEnable2 = Util.getIntValue((String) params.get("overtimeEnable2"), 1); + /*工作日的加班方式:1-需审批,以审批单为准、2-需审批,以打卡为准,但是不能超过审批时长、3-无需审批,根据打卡时间计算加班时长*/ + int computingMode2 = Util.getIntValue((String) params.get("computingMode2"), 1); + /*工作日下班多少分钟后开始计算加班*/ + int startTime2 = Util.getIntValue((String) params.get("startTime2"), 30); + /*工作日最小加班时长*/ + int minimumLen2 = Util.getIntValue((String) params.get("minimumLen2"), 30); + /*工作日是否允许加班转调休*/ + int paidLeaveEnable2 = Util.getIntValue((String) params.get("paidLeaveEnable2"), 0); + /*工作日加班转调休比例中的加班时长*/ + int lenOfOvertime2 = Util.getIntValue((String) params.get("lenOfOvertime2"), 1); + /*工作日加班转调休比例中的调休时长*/ + int lenOfLeave2 = Util.getIntValue((String) params.get("lenOfLeave2"), 1); + + /*休息日是否允许加班:0-不允许、1-允许*/ + int overtimeEnable3 = Util.getIntValue((String) params.get("overtimeEnable3"), 1); + /*休息日的加班方式:1-需审批,以审批单为准、2-需审批,以打卡为准,但是不能超过审批时长、3-无需审批,根据打卡时间计算加班时长*/ + int computingMode3 = Util.getIntValue((String) params.get("computingMode3"), 1); + /*休息日的最小加班时长*/ + int minimumLen3 = Util.getIntValue((String) params.get("minimumLen3"), 30); + /*休息日是否允许加班转调休*/ + int paidLeaveEnable3 = Util.getIntValue((String) params.get("paidLeaveEnable3"), 0); + /*休息日加班转调休比例中的加班时长*/ + int lenOfOvertime3 = Util.getIntValue((String) params.get("lenOfOvertime3"), 1); + /*休息日加班转调休比例中的调休时长*/ + int lenOfLeave3 = Util.getIntValue((String) params.get("lenOfLeave3"), 1); + /*休息日是否有休息时间*/ + int hasRestTime3 = Util.getIntValue((String) params.get("hasRestTime3"), 0); + + /*节假日是否允许加班:0-不允许、1-允许*/ + int overtimeEnable1 = Util.getIntValue((String) params.get("overtimeEnable1"), 1); + /*节假日的加班方式:1-需审批,以审批单为准、2-需审批,以打卡为准,但是不能超过审批时长、3-无需审批,根据打卡时间计算加班时长*/ + int computingMode1 = Util.getIntValue((String) params.get("computingMode1"), 1); + /*节假日的最小加班时长*/ + int minimumLen1 = Util.getIntValue((String) params.get("minimumLen1"), 30); + /*节假日是否允许加班转调休*/ + int paidLeaveEnable1 = Util.getIntValue((String) params.get("paidLeaveEnable1"), 0); + /*节假日加班转调休比例中的加班时长*/ + int lenOfOvertime1 = Util.getIntValue((String) params.get("lenOfOvertime1"), 1); + /*节假日加班转调休比例中的调休时长*/ + int lenOfLeave1 = Util.getIntValue((String) params.get("lenOfLeave1"), 1); + /*节假日是否有休息时间*/ + int hasRestTime1 = Util.getIntValue((String) params.get("hasRestTime1"), 0); + + int paidLeaveEnableType2 = Util.getIntValue((String) params.get("paidLeaveEnableType2"), 2); + int paidLeaveEnableType3 = Util.getIntValue((String) params.get("paidLeaveEnableType3"), 2); + int paidLeaveEnableType1 = Util.getIntValue((String) params.get("paidLeaveEnableType1"), 2); + int paidLeaveEnableFlowType2 = Util.getIntValue((String) params.get("paidLeaveEnableFlowType2"), 1); + int paidLeaveEnableFlowType3 = Util.getIntValue((String) params.get("paidLeaveEnableFlowType3"), 1); + int paidLeaveEnableFlowType1 = Util.getIntValue((String) params.get("paidLeaveEnableFlowType1"), 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 tomorrowDate = weaver.common.DateUtil.addDate(currentDate, 1); + + /*校验休息日排除休息时间的设置是否正确*/ + if (hasRestTime3 == 1) { + int restTimeLen3 = Util.getIntValue((String) params.get("restTimeLen3"), 0); + + List fromList = new ArrayList(); + List toList = new ArrayList(); + for (int i = 0; i < restTimeLen3; i++) { + String startType = "0"; + String startTime = Util.getIntValues((String) params.get("startTime3_" + i)); + String endType = "0"; + String endTime = Util.getIntValues((String) params.get("endTime3_" + i)); + + String fromDateTime = (startType.equals("0") ? currentDate : tomorrowDate) + " " + startTime + ":00"; + String toDateTime = (endType.equals("0") ? currentDate : tomorrowDate) + " " + endTime + ":00"; + if (fromDateTime.compareTo(toDateTime) > 0) { + logger.info("结束时间必须大于开始时间,fromDateTime=" + fromDateTime + ",toDateTime=" + toDateTime); + return -1; + } + fromList.add(fromDateTime); + toList.add(toDateTime); + } + /*利用冒泡法对日期时间进行排序*/ + for (int i = 0; i < fromList.size(); i++) { + for (int j = 0; j < fromList.size() - i - 1; j++) { + if (fromList.get(j).compareTo(fromList.get(j + 1)) > 0) { + String str = fromList.get(j); + fromList.set(j, fromList.get(j + 1)); + fromList.set(j + 1, str); + + str = toList.get(j); + toList.set(j, toList.get(j + 1)); + toList.set(j + 1, str); + } + } + } + /*根据排序后的数据判断是否时间段有重叠*/ + for (int i = 0; i < fromList.size() - 1; i++) { + if (fromList.get(i + 1).compareTo(toList.get(i)) < 0) { + logger.info("休息时段不能交叉"); + return -1; + } + } + } + + /*校验休息日排除休息时间的设置是否正确*/ + if (hasRestTime1 == 1) { + int restTimeLen1 = Util.getIntValue((String) params.get("restTimeLen1"), 0); + + List fromList = new ArrayList(); + List toList = new ArrayList(); + for (int i = 0; i < restTimeLen1; i++) { + String startType = "0"; + String startTime = Util.getIntValues((String) params.get("startTime1_" + i)); + String endType = "0"; + String endTime = Util.getIntValues((String) params.get("endTime1_" + i)); + + String fromDateTime = (startType.equals("0") ? currentDate : tomorrowDate) + " " + startTime + ":00"; + String toDateTime = (endType.equals("0") ? currentDate : tomorrowDate) + " " + endTime + ":00"; + if (fromDateTime.compareTo(toDateTime) > 0) { + logger.info("结束时间必须大于开始时间:fromDateTime=" + fromDateTime + ",toDateTime=" + toDateTime); + return -1; + } + fromList.add(fromDateTime); + toList.add(toDateTime); + } + /*利用冒泡法对日期时间进行排序*/ + for (int i = 0; i < fromList.size(); i++) { + for (int j = 0; j < fromList.size() - i - 1; j++) { + if (fromList.get(j).compareTo(fromList.get(j + 1)) > 0) { + String str = fromList.get(j); + fromList.set(j, fromList.get(j + 1)); + fromList.set(j + 1, str); + + str = toList.get(j); + toList.set(j, toList.get(j + 1)); + toList.set(j + 1, str); + } + } + } + /*根据排序后的数据判断是否时间段有重叠*/ + for (int i = 0; i < fromList.size() - 1; i++) { + if (fromList.get(i + 1).compareTo(toList.get(i)) < 0) { + logger.info("休息时段不能交叉"); + return -1; + } + } + } + + String sql = "insert into kq_OvertimeRules(name,groupIds,isDelete) values(?,?,0)"; + RecordSet recordSet = new RecordSet(); + flag = recordSet.executeUpdate(sql, name, groupIds); + if (!flag) { + logger.info("加班规则保存失败");//保存失败 + return -1; + } + + sql = "select max(id) maxId from kq_OvertimeRules"; + recordSet.executeQuery(sql); + if (recordSet.next()) { + ruleId = recordSet.getInt("maxId"); + } + + if (ruleId != 0) { + sql = "insert into kq_OvertimeRulesDetail(ruleId,dayType,overtimeEnable,computingMode,startTime,minimumLen,paidLeaveEnable,lenOfOvertime,lenOfLeave,hasRestTime,paidleaveenabletype,paidleaveenableflowtype) " + + "values(?,?,?,?,?,?,?,?,?,?,?,?)"; + /** + * 保存工作日加班规则 + */ + flag = recordSet.executeUpdate(sql, ruleId, 2, overtimeEnable2, computingMode2, startTime2, minimumLen2, paidLeaveEnable2, lenOfOvertime2, lenOfLeave2, 0,paidLeaveEnableType2,paidLeaveEnableFlowType2); + if (!flag) { + logger.info("工作日加班规则保存失败");//保存失败 + return -1; + } + /** + * 保存休息日加班规则 + */ + flag = recordSet.executeUpdate(sql, ruleId, 3, overtimeEnable3, computingMode3, 0, minimumLen3, paidLeaveEnable3, lenOfOvertime3, lenOfLeave3, hasRestTime3,paidLeaveEnableType3,paidLeaveEnableFlowType3); + if (!flag) { + logger.info("休息日加班规则保存失败");//保存失败 + return -1; + } + + if (hasRestTime3 == 1) { + int restTimeLen3 = Util.getIntValue((String) params.get("restTimeLen3"), 0); + + for (int i = 0; i < restTimeLen3; i++) { + String startType = "0"; + String startTime = Util.getIntValues((String) params.get("startTime3_" + i)); + String endType = "0"; + String endTime = Util.getIntValues((String) params.get("endTime3_" + i)); + + String restTimeSql = "insert into kq_OvertimeRestTime(ruleId,dayType,startType,startTime,endType,endTime) values(?,?,?,?,?,?)"; + flag = recordSet.executeUpdate(restTimeSql, ruleId, 3, startType, startTime, endType, endTime); + if (!flag) { + logger.info("休息日加班规则休息时段保存失败");//保存失败 + return -1; + } + } + } + /** + * 保存节假日加班规则 + */ + flag = recordSet.executeUpdate(sql, ruleId, 1, overtimeEnable1, computingMode1, 0, minimumLen1, paidLeaveEnable1, lenOfOvertime1, lenOfLeave1, hasRestTime1,paidLeaveEnableType1,paidLeaveEnableFlowType1); + if (!flag) { + logger.info("节假日加班规则保存失败"); + return -1; + } + + if (hasRestTime1 == 1) { + int restTimeLen1 = Util.getIntValue((String) params.get("restTimeLen1"), 0); + + for (int i = 0; i < restTimeLen1; i++) { + String startType = "0"; + String startTime = Util.getIntValues((String) params.get("startTime1_" + i)); + String endType = "0"; + String endTime = Util.getIntValues((String) params.get("endTime1_" + i)); + + String restTimeSql = "insert into kq_OvertimeRestTime(ruleId,dayType,startType,startTime,endType,endTime) values(?,?,?,?,?,?)"; + flag = recordSet.executeUpdate(restTimeSql, ruleId, 1, startType, startTime, endType, endTime); + if (!flag) { + logger.info("节假日加班规则休息时段保存失败"); + return -1; + } + } + } + } + } catch (Exception e) { + ruleId = -1; + } + return ruleId; + } + + /************************************************加班单位的相关接口************************************************/ + /** + * 获取最小加班单位 + * 1-按天加班 + * 2-按半天加班 + * 3-按小时加班 + * 4-按整天加班 + * 5-按半小时加班 + * 6-按整小时加班 + * @return -1:接口异常,返回的无效数据。 + */ + public static int getMinimumUnit() { + int minimumUnit = -1; + String sql = "select * from kq_OvertimeUnit where (isDelete is null or isDelete !=1) and id=1"; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql); + if (recordSet.next()) { + minimumUnit = recordSet.getInt("minimumUnit"); + } + return minimumUnit; + } + + /** + * 获取最小加班单位 + * 1-按天加班 + * 2-按半天加班 + * 3-按小时加班 + * 4-按整天加班 + * 5-按半小时加班 + * 6-按整小时加班 + * @return -1:接口异常,返回的无效数据。 + */ + public static Map getMinimumUnitAndConversion() { + Map map = Maps.newHashMap(); + int minimumUnit = -1; + int overtimeConversion = -1; + String sql = "select * from kq_OvertimeUnit where (isDelete is null or isDelete !=1) and id=1"; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql); + if (recordSet.next()) { + minimumUnit = recordSet.getInt("minimumUnit"); + overtimeConversion = recordSet.getInt("overtimeConversion"); + map.put("minimumUnit", ""+minimumUnit); + map.put("overtimeConversion", ""+overtimeConversion); + } + return map; + } + + + /** + * 获取加班单位的日折算时长 + * + * @return -1:接口异常,返回的无效数据。 + */ + public static double getHoursToDay() { + double hoursToDay = -1.00; + String sql = "select * from kq_OvertimeUnit where (isDelete is null or isDelete !=1) and id=1"; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql); + if (recordSet.next()) { + hoursToDay = recordSet.getDouble("hoursToDay"); + } + BigDecimal bigDecimal = new BigDecimal(hoursToDay); + return bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); + } + + /** + * 获取半天显示类型,是时间还是下拉框 + * 半天单位 时间选择方式:1-下拉框选择 、2-具体时间 + * @return + */ + public static String getTimeselection() { + int timeselection = 1; + String sql = "select * from kq_OvertimeUnit where (isDelete is null or isDelete !=1) and id=1"; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql); + if (recordSet.next()) { + timeselection = recordSet.getInt("timeselection"); + } + if(timeselection == 1 || timeselection == 2){ + return ""+timeselection; + }else{ + return "1"; + } + } + + /** + * 获取加班所有需要的数据 + * @param resourceId + * @param date + * @param changeTypeMap + * @return + */ + public static void getOverTimeData(String resourceId, String date, + Map changeTypeMap,Map overRulesDetailMap,Map> restTimeMap,Map computingModeMap) { + int changeType = -1; + + /*获取考勤组的ID,因为考勤组有有效期,所以需要传入日期*/ + KQGroupMemberComInfo kqGroupMemberComInfo = new KQGroupMemberComInfo(); + String groupId = Util.null2s(kqGroupMemberComInfo.getKQGroupId(resourceId, date),""); + + /*该人员不存在于任意一个考勤组中,请为其设置考勤组*/ + if(groupId.length() == 0){ + logger.writeLog("该人员不存在于任意一个考勤组中,请为其设置考勤组。resourceId=" + resourceId + ",date=" + date); + return ; + } + + changeType = KQHolidaySetBiz.getChangeType(groupId, date); + if (changeType != 1 && changeType != 2 && changeType != 3) { + KQWorkTime kqWorkTime = new KQWorkTime(); + changeType = kqWorkTime.isWorkDay(resourceId, date) ? 2 : 3; + } + String change_key = date+"_"+resourceId; + changeTypeMap.put(change_key, changeType); + + List restTimeList = new ArrayList(); + int overtimeRuleId = 0;//加班规则的ID + RecordSet recordSet = new RecordSet(); + String sql = "select id from kq_OvertimeRules where (isDelete is null or isDelete !=1) "; + if (recordSet.getDBType().equalsIgnoreCase("sqlserver")) { + sql += " and ','+groupIds+',' like '%," + groupId + ",%'"; + } else if (recordSet.getDBType().equalsIgnoreCase("mysql")) { + sql += " and concat(',',groupIds,',') like '%," + groupId + ",%'"; + } else { + sql += " and ','||groupIds||',' like '%," + groupId + ",%'"; + } + recordSet.executeQuery(sql); + if (recordSet.next()) { + overtimeRuleId = recordSet.getInt("id"); + + sql = "select * from kq_OvertimeRulesDetail where ruleId=" + overtimeRuleId + " and dayType=" + changeType; + recordSet.executeQuery(sql); + if (recordSet.next()) { + int id = recordSet.getInt("id"); + int ruleId = recordSet.getInt("ruleId"); + int dayType = recordSet.getInt("dayType"); + int overtimeEnable = recordSet.getInt("overtimeEnable"); + int computingMode = recordSet.getInt("computingMode"); + int startTime = recordSet.getInt("startTime"); + int minimumLen = recordSet.getInt("minimumLen"); + int paidLeaveEnable = recordSet.getInt("paidLeaveEnable"); + double lenOfOvertime = Util.getDoubleValue(recordSet.getString("lenOfOvertime"), 1.00); + double lenOfLeave = Util.getDoubleValue(recordSet.getString("lenOfLeave"), 1.00); + int hasRestTime = Util.getIntValue(recordSet.getString("hasRestTime")); + int before_startTime = recordSet.getInt("before_startTime"); + + int paidLeaveEnableType = recordSet.getInt("paidLeaveEnableType"); + int paidLeaveEnableDefaultType = recordSet.getInt("paidLeaveEnableDefaultType"); + int paidLeaveEnableFlowType = recordSet.getInt("paidLeaveEnableFlowType"); + int restTimeType = recordSet.getInt("restTimeType"); + int has_cut_point = Util.getIntValue(Util.null2s(recordSet.getString("has_cut_point"),"0"),0); + if(paidLeaveEnableType <= 0){ + paidLeaveEnableType = 1; + } + if(paidLeaveEnableDefaultType <= 0){ + paidLeaveEnableDefaultType = 1; + } + if(paidLeaveEnableFlowType <= 0){ + paidLeaveEnableFlowType = 1; + } + if(paidLeaveEnableType == 1 && paidLeaveEnable == 0){ + //如果就没有开启关联调休,那么默认的加班转调休方式就是第一种 + paidLeaveEnableDefaultType = 1; + } + if(restTimeType <= 0){ + restTimeType = 1; + } + String cut_point = Util.null2s(recordSet.getString("cut_point"),""); + String key = date+"_"+changeType; + + KQOvertimeRulesDetailEntity kqOvertimeRulesDetail = new KQOvertimeRulesDetailEntity(); + kqOvertimeRulesDetail.setRuleId(ruleId); + kqOvertimeRulesDetail.setDayType(dayType); + kqOvertimeRulesDetail.setOvertimeEnable(overtimeEnable); + kqOvertimeRulesDetail.setComputingMode(computingMode); + kqOvertimeRulesDetail.setStartTime(startTime); + kqOvertimeRulesDetail.setMinimumLen(minimumLen); + kqOvertimeRulesDetail.setPaidLeaveEnable(paidLeaveEnable); + kqOvertimeRulesDetail.setLenOfOvertime(lenOfOvertime); + kqOvertimeRulesDetail.setLenOfLeave(lenOfLeave); + kqOvertimeRulesDetail.setHasRestTime(hasRestTime); + kqOvertimeRulesDetail.setBefore_startTime(before_startTime); + kqOvertimeRulesDetail.setCut_point(cut_point); + kqOvertimeRulesDetail.setHas_cut_point(has_cut_point); + kqOvertimeRulesDetail.setId(id); + kqOvertimeRulesDetail.setPaidLeaveEnableType(paidLeaveEnableType); + kqOvertimeRulesDetail.setPaidLeaveEnableDefaultType(paidLeaveEnableDefaultType); + kqOvertimeRulesDetail.setPaidLeaveEnableFlowType(paidLeaveEnableFlowType); + kqOvertimeRulesDetail.setRestTimeType(restTimeType); + overRulesDetailMap.put(key, kqOvertimeRulesDetail); + computingModeMap.put(key, computingMode); + + /** + * 因为休息时段可以设置次日的数据,所以获取某一天的休息时段的时候,需要先考虑上一个日期所设置的次日的休息时段 + */ + String lastDay = DateUtil.addDay(date, -1, "yyyy-MM-dd"); + KQOvertimeRulesDetailEntity pre_kqOvertimeRulesDetail = getOvertimeRulesDetail(resourceId, lastDay); + int pre_overtimeEnable = pre_kqOvertimeRulesDetail.getOvertimeEnable(); + int pre_hasRestTime = pre_kqOvertimeRulesDetail.getHasRestTime(); + if (pre_overtimeEnable == 1 && pre_hasRestTime == 1) { + int pre_dayType = pre_kqOvertimeRulesDetail.getDayType(); + int pre_ruleId = pre_kqOvertimeRulesDetail.getRuleId(); + + sql = "select * from kq_OvertimeRestTime where ruleId=" + pre_ruleId + " and dayType=" + pre_dayType; + RecordSet recordSet1 = new RecordSet(); + recordSet1.executeQuery(sql); + while (recordSet1.next()) { + String startType = recordSet1.getString("startType"); + String startTime1 = recordSet1.getString("startTime"); + String endType = recordSet1.getString("endType"); + String endTime = recordSet1.getString("endTime"); + + if (startType.equals("0") && endType.equals("1")) { + String[] str = new String[]{"00:00", endTime}; + restTimeList.add(str); + } else if (startType.equals("1") && endType.equals("1")) { + String[] str = new String[]{startTime1, endTime}; + restTimeList.add(str); + } + } + } + + overtimeEnable = kqOvertimeRulesDetail.getOvertimeEnable(); + hasRestTime = kqOvertimeRulesDetail.getHasRestTime(); + restTimeType = kqOvertimeRulesDetail.getRestTimeType(); + if (overtimeEnable == 1 && hasRestTime == 1) { + if(restTimeType == 1){ + sql = "select * from kq_OvertimeRestTime where ruleId=" + ruleId + " and dayType=" + dayType; + RecordSet recordSet1 = new RecordSet(); + recordSet1.executeQuery(sql); + while (recordSet1.next()) { + String startType = recordSet1.getString("startType"); + String startTime1 = recordSet1.getString("startTime"); + String endType = recordSet1.getString("endType"); + String endTime = recordSet1.getString("endTime"); + + if (startType.equals("0") && endType.equals("0")) { + String[] str = new String[]{startTime1, endTime}; + restTimeList.add(str); + } else if (startType.equals("0") && endType.equals("1")) { + String[] str = new String[]{startTime1, "24:00"}; + restTimeList.add(str); + } + } + }else{ + sql = "select * from kq_OvertimeRestlength where ruleId=" + ruleId + " and dayType=" + dayType+" order by dsporder "; + RecordSet recordSet1 = new RecordSet(); + recordSet1.executeQuery(sql); + while (recordSet1.next()) { + String overlength = Util.null2String(recordSet1.getString("overlength")); + String cutlength = Util.null2String(recordSet1.getString("cutlength")); + if(overlength.length() > 0 && cutlength.length() > 0){ + String[] str = new String[]{overlength, cutlength}; + restTimeList.add(str); + } + } + } + } + restTimeMap.put(key, restTimeList); + } + + + } else { + logger.writeLog("该人员所属的考勤组没有设置过任何加班规则,请为其设置加班规则。resourceId=" + resourceId + ",date="+date+",changeType=" + changeType); + } + + return ; + } + + /** + * 按加班时长范围设置转调休时长 + * 按照加班时长从大到小排序 取到最大的满足了,那么调休就直接按照这个来转调休了 + */ + public Map> getBalanceLengthDetailMap(int ruleDetailid){ + Map> balanceLengthDetailMap = Maps.newHashMap(); + RecordSet recordSet = new RecordSet(); + List overtimelengthList = Lists.newArrayList(); + List balancelengthList = Lists.newArrayList(); + String sql = "select * from kq_OvertimeBalanceLengthDetail where rulesdetailid= ? order by overtimelength desc "; + recordSet.executeQuery(sql, ruleDetailid); + while (recordSet.next()){ + String overtimelength = recordSet.getString("overtimelength"); + String balancelength = recordSet.getString("balancelength"); + overtimelengthList.add(overtimelength); + balancelengthList.add(balancelength); + } + if(!overtimelengthList.isEmpty() && !balancelengthList.isEmpty()){ + balanceLengthDetailMap.put("overtimelengthList", overtimelengthList); + balanceLengthDetailMap.put("balancelengthList", balancelengthList); + return balanceLengthDetailMap; + } + return balanceLengthDetailMap; + } + + /** + * 按加班的时间段设置转调休时长 + */ + public Map> getBalanceTimeDetailMap(int ruleDetailid){ + Map> balanceTimethDetailMap = Maps.newHashMap(); + RecordSet recordSet = new RecordSet(); + List idList = Lists.newArrayList(); + List timepointList = Lists.newArrayList(); + List lenOfOvertimeList = Lists.newArrayList(); + List lenOfLeaveList = Lists.newArrayList(); + String sql = "select * from kq_OvertimeBalanceTimeDetail where rulesdetailid= ? order by dsporder "; + recordSet.executeQuery(sql, ruleDetailid); + while (recordSet.next()){ + String id = recordSet.getString("id"); + String timepoint = recordSet.getString("timepoint"); + String lenOfOvertime = recordSet.getString("lenOfOvertime"); + String lenOfLeave = recordSet.getString("lenOfLeave"); + idList.add(id); + timepointList.add(timepoint); + lenOfOvertimeList.add(lenOfOvertime); + lenOfLeaveList.add(lenOfLeave); + } + if(!timepointList.isEmpty() && !lenOfOvertimeList.isEmpty() && !lenOfLeaveList.isEmpty()){ + balanceTimethDetailMap.put("idList", idList); + balanceTimethDetailMap.put("timepointList", timepointList); + balanceTimethDetailMap.put("lenOfOvertimeList", lenOfOvertimeList); + balanceTimethDetailMap.put("lenOfLeaveList", lenOfLeaveList); + return balanceTimethDetailMap; + } + return balanceTimethDetailMap; + } +} diff --git a/src/com/engine/kq/biz/KQScheduleSignBiz.java b/src/com/engine/kq/biz/KQScheduleSignBiz.java new file mode 100644 index 0000000..50b7d25 --- /dev/null +++ b/src/com/engine/kq/biz/KQScheduleSignBiz.java @@ -0,0 +1,435 @@ +package com.engine.kq.biz; + +import com.engine.kq.bean.KQHrmScheduleSign; +import com.engine.kq.log.KQLog; +import com.engine.kq.wfset.util.KQSignUtil; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import weaver.conn.RecordSet; +import weaver.general.Util; + +/** + * 签到签退数据处理类 + */ +public class KQScheduleSignBiz { + + private KQLog kqLog = new KQLog(); + private String resourceid; + private String userType; + private String signDate; + private String signTime; + private String worksection; + /** + * 考勤数据所属日期 因为班次可能跨天 + */ + private String belongdate; + private String signtype; + private String signDateTimeSql; + /** + * 上班开始打卡时间 + */ + private String signSectionTime; + + /** + * 上班结束打卡时间 + */ + private String signSectionEndTime; + /** + * 下班开始打卡时间 + */ + private String signSectionBeginTime; + + /** + * 下班结束打卡时间 + */ + private String offSignSectionTime; + + private KQScheduleSignBiz(KQScheduleSignParamBuilder build){ + this.resourceid = build.resourceid; + this.userType = build.userType; + this.signDate = build.signDate; + this.signTime = build.signTime; + this.belongdate = build.belongdate; + this.signtype = build.signtype; + this.worksection = build.worksection; + this.signDateTimeSql = build.signDateTimeSql; + this.signSectionTime = build.signSectionTime; + this.signSectionEndTime = build.signSectionEndTime; + this.signSectionBeginTime = build.signSectionBeginTime; + this.offSignSectionTime = build.offSignSectionTime; + } + + /** + * 自由班制的签到签退数据 + * @return + */ + public List getFreeScheduleSignInfo() { + + RecordSet rs = new RecordSet(); + String signSql = "select * from hrmschedulesign where 1=1 and isInCom='1' "; + String sqlWhere = sqlParamWhere(); + if(sqlWhere.length() > 0){ + signSql += sqlWhere; + } + signSql += " order by signdate,signtime"; + List kqHrmScheduleSigns = new ArrayList<>(); + + try{ + rs.execute(signSql); + while (rs.next()){ + KQHrmScheduleSign kqHrmScheduleSign = getSignBean(rs); + + kqHrmScheduleSigns.add(kqHrmScheduleSign); + } + }catch (Exception e){ + e.printStackTrace(); + } + return kqHrmScheduleSigns; + } + /** + * 非自由班制的考勤数据 + * 针对设置了打卡开始范围,结束范围的数据,即可以出现,只签退没有签到的数据的处理 + * @return + */ + public Map getScheduleSignInfoWithCardRange(){ + + String signSql = ""; + Map signMap = new HashMap<>(); + RecordSet rs = new RecordSet(); + String dbtype = rs.getDBType(); + String baseSql = "select * from hrmschedulesign where 1=1 and isInCom='1' "; + String sqlWhere = sqlParamWhere(); + if(sqlWhere.length() > 0){ + baseSql += sqlWhere; + } + if(signSectionEndTime.length() == 0 && signSectionBeginTime.length() == 0){ + //如果没设置上班后,下班前打卡 + String signTimeSql = KQSignUtil.buildSignSql(signSectionTime,offSignSectionTime); + if(signTimeSql.length() > 0){ + baseSql += " and "+signTimeSql; + } + if(baseSql.length() > 0){ + signSql = baseSql; + signSql += " order by signdate,signtime"; + kqLog.info("signSql:"+signSql); + try{ + rs.execute(signSql); + while (rs.next()){ + getScheduleSignBean(rs,signMap); + } + }catch (Exception e){ + e.printStackTrace(); + } + } + }else { + String onSignTimeSql = KQSignUtil.buildSignSql(signSectionTime,signSectionEndTime); + String offSignTimeSql = KQSignUtil.buildSignSql(signSectionBeginTime,offSignSectionTime); + String onSql = ""; + String orderSql = ""; + if(onSignTimeSql.length() > 0){ + orderSql = " order by signdate asc, signtime asc "; + onSql += "select 'on' as belongtype,t.* from ("+baseSql+" and "+onSignTimeSql+") t"; + if("oracle".equalsIgnoreCase(dbtype)){ + onSql = "select * from ("+onSql+" "+orderSql+" ) a where rownum=1"; + }else if("mysql".equalsIgnoreCase(dbtype)){ + onSql = "select * from (select * from ("+onSql+" "+orderSql+" ) a limit 0,1) a "; + } + else if("postgresql".equalsIgnoreCase(dbtype)){ + onSql = "select * from (select * from ("+onSql+" "+orderSql+" ) a limit 1 offset 0) a "; + } + else if("sqlserver".equalsIgnoreCase(dbtype)){ + onSql = "select top 1 * from ("+onSql+" ) a "+" "+orderSql ; + } + } + String offSql = ""; + if(offSignTimeSql.length() > 0){ + orderSql = " order by signdate desc, signtime desc "; + offSql += "select 'off' as belongtype,t.* from ("+baseSql+" and "+offSignTimeSql+") t"; + if("oracle".equalsIgnoreCase(dbtype)){ + offSql = "select * from ("+offSql+" "+orderSql+" ) a where rownum=1"; + }else if("mysql".equalsIgnoreCase(dbtype)){ + offSql = "select * from (select * from ("+offSql+" "+orderSql+" ) a limit 0,1) a "; + } + else if("postgresql".equalsIgnoreCase(dbtype)){ + offSql = "select * from (select * from ("+offSql+" "+orderSql+" ) a limit 1 offset 0) a "; + } + else if("sqlserver".equalsIgnoreCase(dbtype)){ + offSql = "select top 1 * from ("+offSql+" ) a "+" "+orderSql ; + } + } + if(onSql.length() > 0 && offSql.length() > 0){ + signSql = "select * from ("+onSql+" UNION ALL "+offSql+") s "; + kqLog.info("signSql:"+signSql); + try{ + Map checkMap = new HashMap<>(); + rs.execute(signSql); + while (rs.next()){ + getScheduleSignCardRangeBean(rs,signMap,checkMap); + } + }catch (Exception e){ + e.printStackTrace(); + } + } + } + + return signMap; + } + + /** + * 如果签到和签退可以独立出来,用这个方法 + * @param rs + * @param signMap + * @param checkMap + */ + public void getScheduleSignCardRangeBean(RecordSet rs, Map signMap, + Map checkMap){ + String belongtype =Util.null2String(rs.getString("belongtype")); + KQHrmScheduleSign kqHrmScheduleSign = getSignBean(rs); + if("on".equalsIgnoreCase(belongtype)){ + if(!checkMap.containsKey("on")){ + signMap.put("signin",kqHrmScheduleSign); + } + }else{ + signMap.put("signout",kqHrmScheduleSign); + } + } + + /** + * 原始的获取最早时间作为签到,最晚时间作为签退的方法 + * @param rs + * @param signMap + */ + public void getScheduleSignBean(RecordSet rs,Map signMap){ + KQHrmScheduleSign kqHrmScheduleSign = getSignBean(rs); + if(signMap.isEmpty()){ + signMap.put("signin",kqHrmScheduleSign); + }else { + signMap.put("signout",kqHrmScheduleSign); + } + } + + public KQHrmScheduleSign getSignBean(RecordSet rs){ + + KQHrmScheduleSign kqHrmScheduleSign = new KQHrmScheduleSign(); + String id=Util.null2String(rs.getString("id")); + String userid=Util.null2String(rs.getString("userid")); + String usertype =Util.null2String(rs.getString("usertype")); + String signtype=Util.null2String(rs.getString("signtype")); + String signdate=Util.null2String(rs.getString("signdate")); + String signtime=Util.null2String(rs.getString("signtime")); + String clientaddress=Util.null2String(rs.getString("clientaddress")); + String signfrom=Util.null2String(rs.getString("signfrom")); + String longitude=Util.null2String(rs.getString("longitude")); + String latitude=Util.null2String(rs.getString("latitude")); + String addr=Util.null2String(rs.getString("addr")); + String isincom=Util.null2String(rs.getString("isincom")); + String isimport=Util.null2String(rs.getString("isimport")); + String importsql=Util.null2String(rs.getString("importsql")); + String belongdate=Util.null2String(rs.getString("belongdate")); + String serialid=Util.null2String(rs.getString("serialid")); + String worksections=Util.null2String(rs.getString("worksection")); + String signstatus=Util.null2String(rs.getString("signstatus")); + + kqHrmScheduleSign.setId(id); + kqHrmScheduleSign.setUserid(userid); + kqHrmScheduleSign.setUsertype(usertype); + kqHrmScheduleSign.setSigntype(signtype); + kqHrmScheduleSign.setSigndate(signdate); + kqHrmScheduleSign.setSigntime(signtime); + kqHrmScheduleSign.setClientaddress(clientaddress); + kqHrmScheduleSign.setSignfrom(signfrom); + kqHrmScheduleSign.setLongitude(longitude); + kqHrmScheduleSign.setLatitude(latitude); + kqHrmScheduleSign.setAddr(addr); + kqHrmScheduleSign.setIsincom(isincom); + kqHrmScheduleSign.setIsimport(isimport); + kqHrmScheduleSign.setImportsql(importsql); + kqHrmScheduleSign.setBelongdate(belongdate); + kqHrmScheduleSign.setSerialid(serialid); + kqHrmScheduleSign.setWorksections(worksections); + kqHrmScheduleSign.setSignstatus(signstatus); + + return kqHrmScheduleSign; + } + + /** + * 非自由班制的考勤数据 + * @return + */ + public Map getScheduleSignInfo(){ + + RecordSet rs = new RecordSet(); + String signSql = "select * from hrmschedulesign where 1=1 and isInCom='1' "; + String sqlWhere = sqlParamWhere(); + if(sqlWhere.length() > 0){ + signSql += sqlWhere; + } + signSql += " order by signdate,signtime"; + Map signMap = new HashMap<>(); + + try{ + kqLog.info("signSql:"+signSql); + rs.execute(signSql); + while (rs.next()){ + getScheduleSignBean(rs,signMap); + } + }catch (Exception e){ + e.printStackTrace(); + } + return signMap; + } + + /** + * 生成相应的查询条件 + * @return + */ + private String sqlParamWhere() { + String sqlWhere = ""; + if(resourceid.length() > 0){ + sqlWhere += " and userid in ( "+resourceid+" )"; + } + if(signDate.length() > 0){ + sqlWhere += " and signDate = '"+signDate+"' "; + } + if(signTime.length() > 0){ + sqlWhere += " and signTime = '"+signTime+"' "; + } + if(signDateTimeSql.length() > 0){ + sqlWhere += " and "+signDateTimeSql; + } + if(belongdate.length() > 0){ + sqlWhere += " and belongdate = '"+belongdate+"' "; + } + if(signtype.length() > 0){ + sqlWhere += " and signtype = '"+signtype+"' "; + } + //不需要userType,没啥用 +// if(userType.length() > 0){ +// sqlWhere += " and userType = '"+userType+"' "; +// } + if(worksection.length() > 0){ + sqlWhere += " and worksection = '"+worksection+"' "; + } + return sqlWhere; + } + + public static class KQScheduleSignParamBuilder{ + private String resourceid; + private String userType; + private String signDate; + private String signTime; + private String belongdate; + private String signtype; + private String worksection; + /** + * 自定义sql + */ + private String signDateTimeSql; + /** + * 上班开始打卡时间 + */ + private String signSectionTime; + + /** + * 上班结束打卡时间 + */ + private String signSectionEndTime; + /** + * 下班开始打卡时间 + */ + private String signSectionBeginTime; + + /** + * 下班结束打卡时间 + */ + private String offSignSectionTime; + + public KQScheduleSignParamBuilder() { + this.resourceid = resourceid; + //初始化的时候需要把其他参数先清空下 + this.userType = ""; + this.signDate = ""; + this.signTime = ""; + this.belongdate = ""; + this.signtype = ""; + this.worksection = ""; + this.signDateTimeSql = ""; + this.signSectionTime = ""; + this.signSectionEndTime = ""; + this.signSectionBeginTime = ""; + this.offSignSectionTime = ""; + } + + //成员方法返回其自身,所以可以链式调用 + public KQScheduleSignBiz.KQScheduleSignParamBuilder resourceidParam(final String resourceid) { + this.resourceid = resourceid; + return this; + } + + public KQScheduleSignBiz.KQScheduleSignParamBuilder userTypeParam(final String userType) { + this.userType = userType; + return this; + } + + public KQScheduleSignBiz.KQScheduleSignParamBuilder signDateParam(final String signDate) { + this.signDate = signDate; + return this; + } + + public KQScheduleSignBiz.KQScheduleSignParamBuilder signTimeParam(final String signTime) { + this.signTime = signTime; + return this; + } + + public KQScheduleSignBiz.KQScheduleSignParamBuilder belongDateParam(final String belongdate) { + this.belongdate = belongdate; + return this; + } + + public KQScheduleSignBiz.KQScheduleSignParamBuilder signtypeParam(final String signtype) { + this.signtype = signtype; + return this; + } + + public KQScheduleSignBiz.KQScheduleSignParamBuilder worksectionParam(final String worksection) { + this.worksection = worksection; + return this; + } + + public KQScheduleSignBiz.KQScheduleSignParamBuilder signDateTimeSqlParam(final String signDateTimeSql) { + this.signDateTimeSql = signDateTimeSql; + return this; + } + + public KQScheduleSignBiz.KQScheduleSignParamBuilder signSectionTimeParam(final String signSectionTime) { + this.signSectionTime = signSectionTime; + return this; + } + + public KQScheduleSignBiz.KQScheduleSignParamBuilder signSectionEndTimeParam(final String signSectionEndTime) { + this.signSectionEndTime = signSectionEndTime; + return this; + } + + public KQScheduleSignBiz.KQScheduleSignParamBuilder signSectionBeginTimeParam(final String signSectionBeginTime) { + this.signSectionBeginTime = signSectionBeginTime; + return this; + } + + public KQScheduleSignBiz.KQScheduleSignParamBuilder offSignSectionTimeParam(final String offSignSectionTime) { + this.offSignSectionTime = offSignSectionTime; + return this; + } + + //Builder的build方法,返回外部类的实例 + public KQScheduleSignBiz build() { + return new KQScheduleSignBiz(this); + } + + } + + +} diff --git a/src/com/engine/kq/biz/KQShiftRestTimeSectionComInfo.java b/src/com/engine/kq/biz/KQShiftRestTimeSectionComInfo.java new file mode 100644 index 0000000..4cab68f --- /dev/null +++ b/src/com/engine/kq/biz/KQShiftRestTimeSectionComInfo.java @@ -0,0 +1,242 @@ +package com.engine.kq.biz; + +import com.alibaba.fastjson.JSON; +import com.engine.kq.log.KQLog; +import weaver.cache.*; +import weaver.conn.RecordSet; +import weaver.general.Util; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 班次休息时段设置缓存类 + */ +public class KQShiftRestTimeSectionComInfo 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 serial; + + private KQLog kqLog = new KQLog(); + + @Override + protected boolean autoInitIfNotFound() { + return false; + } + + @Override + public CacheMap initCache() { + CacheMap localData = createCacheMap(); + RecordSet rs = new RecordSet(); + kqLog = new KQLog(); + + List restSectionList = new ArrayList<>(); + List sectionList = new ArrayList<>(); + Map sectionMap = new HashMap<>(); + + Map serialMaps = new HashMap<>();//分组用的map + try { + String getRestSections = "select * from kq_ShiftRestTimeSections where 1=1 "; + rs.executeQuery(getRestSections); + while(rs.next()){ + String id = Util.null2String(rs.getString("id")); + sectionMap = new HashMap<>(); + String serialid = Util.null2String(rs.getString("serialid")); + String resttype = Util.null2String(rs.getString("resttype")); + String across = Util.null2String(rs.getString("across")); + String times = Util.null2String(rs.getString("time")); + sectionMap.put("across", across); + sectionMap.put("times", times); + + if(serialMaps.get(serialid) != null){ + List tmpList = (List)serialMaps.get(serialid); + if("start".equalsIgnoreCase(resttype)){ + tmpList.set(0, sectionMap); + }else if("end".equalsIgnoreCase(resttype)){ + tmpList.set(1, sectionMap); + } + }else{ + restSectionList = new ArrayList<>(); + sectionList = new ArrayList<>(); + sectionList.add(""); + sectionList.add(""); + if("start".equalsIgnoreCase(resttype)){ + sectionList.set(0, sectionMap); + }else if("end".equalsIgnoreCase(resttype)){ + sectionList.set(1, sectionMap); + } + restSectionList.addAll(sectionList); + serialMaps.put(serialid, restSectionList); + + } + } + + for(Map.Entry me : serialMaps.entrySet()){ + String id = me.getKey(); + List valList = (List)me.getValue(); + CacheItem cacheItem = createCacheItem(); + cacheItem.set(PK_INDEX, id); + cacheItem.set(serial, valList); + modifyCacheItem(id, cacheItem); + localData.put(id, cacheItem); + } + }catch (Exception e){ + writeLog(e); + } + return localData; + } + + /** + * 根据班次id获取休息时段集合 + * @param serialid + * @return + */ + public List getRestSectionTimesList(String serialid){ + + String startSql = "select * from kq_ShiftRestTimeSections where (isdelete is null or isdelete <> '1') and resttype='start' and serialid = ? "; + String endSql = "select * from kq_ShiftRestTimeSections where (isdelete is null or isdelete <> '1') and resttype='end' and serialid = ? "; + List restList = new ArrayList<>(); + RecordSet rstemp=new RecordSet(); + rstemp.executeQuery(startSql, serialid); + while(rstemp.next()){ + String times = rstemp.getString("time"); + String[] timeArr = new String[2]; + timeArr[0] = times; + restList.add(timeArr); + } + + int i = 0; + rstemp=new RecordSet(); + rstemp.executeQuery(endSql, serialid); + while(rstemp.next()){ + String times = rstemp.getString("time"); + String[] timeArr = restList.get(i); + timeArr[1] = times; + i++; + } + + return restList; + } + /** + * 根据班次获取休息时段 + * @param serialid + * @return + */ + public List getRestSectionTimes(String serialid){ + //return (List) getObjValue(serial, serialid); + RecordSet rs = new RecordSet(); + kqLog = new KQLog(); + + List valList = new ArrayList<>(); + List restSectionList = new ArrayList<>(); + List sectionList = new ArrayList<>(); + Map sectionMap = new HashMap<>(); + + Map serialMaps = new HashMap<>();//分组用的map + Map groupSectionMaps = new HashMap<>();//分组用的map + try { + String getRestSections = "select * from kq_ShiftRestTimeSections where serialid=? order by orderId "; + rs.executeQuery(getRestSections,serialid); + while(rs.next()){ + String id = Util.null2String(rs.getString("id")); + sectionMap = new HashMap<>(); + String resttype = Util.null2String(rs.getString("resttype")); + String across = Util.null2String(rs.getString("across")); + String times = Util.null2String(rs.getString("time")); + String record = Util.null2String(rs.getString("record1")); + sectionMap.put("across", across); + sectionMap.put("times", times); + + if(serialMaps.get(serialid) != null){ + Map tmpgroupSectionMaps = (Map)serialMaps.get(serialid); + if(tmpgroupSectionMaps.get(record) != null){ + List tmpWorkSection = (List) tmpgroupSectionMaps.get(record); + List tmpSection = ((List)tmpWorkSection.get(tmpWorkSection.size()-1)); + if("start".equalsIgnoreCase(resttype)){ + tmpSection.set(0, sectionMap); + }else if("end".equalsIgnoreCase(resttype)){ + tmpSection.set(1, sectionMap); + } + }else{ + restSectionList = new ArrayList<>(); + sectionList = new ArrayList<>(); + sectionList.add(""); + sectionList.add(""); + if("start".equalsIgnoreCase(resttype)){ + sectionList.set(0, sectionMap); + }else if("end".equalsIgnoreCase(resttype)){ + sectionList.set(1, sectionMap); + } + restSectionList.add(sectionList); + tmpgroupSectionMaps.put(record, restSectionList); + } + }else{ + groupSectionMaps = new HashMap<>(); + restSectionList = new ArrayList<>(); + serialMaps.put(serialid, groupSectionMaps); + if(groupSectionMaps.get(record) != null){ + List tmpWorkSection = (List) groupSectionMaps.get(record); + List tmpSection = ((List)tmpWorkSection.get(tmpWorkSection.size()-1)); + if("start".equalsIgnoreCase(resttype)){ + tmpSection.set(0, sectionMap); + }else if("end".equalsIgnoreCase(resttype)){ + tmpSection.set(1, sectionMap); + } + }else{ + sectionList = new ArrayList<>(); + sectionList.add(""); + sectionList.add(""); + if("start".equalsIgnoreCase(resttype)){ + sectionList.set(0, sectionMap); + }else if("end".equalsIgnoreCase(resttype)){ + sectionList.set(1, sectionMap); + } + restSectionList.add(sectionList); + groupSectionMaps.put(record, restSectionList); + } + } + } + for(Map.Entry me : serialMaps.entrySet()){ + valList = new ArrayList<>(); + Map val = (Map)me.getValue(); + for(Map.Entry mee : val.entrySet()){ + valList.addAll((List)mee.getValue()); + } + } + + }catch (Exception e){ + writeLog(e); + } + return valList; + } + + /** + * 删除缓存信息 + */ + public void removeShiftRestTimeSectionCache() { + removeCache(); + } +} diff --git a/src/com/engine/kq/biz/KQShiftRuleInfoBiz.java b/src/com/engine/kq/biz/KQShiftRuleInfoBiz.java new file mode 100644 index 0000000..218b393 --- /dev/null +++ b/src/com/engine/kq/biz/KQShiftRuleInfoBiz.java @@ -0,0 +1,820 @@ +package com.engine.kq.biz; + +import com.alibaba.fastjson.JSON; +import com.engine.kq.bean.KQHrmScheduleSign; +import com.engine.kq.biz.chain.cominfo.HalfShiftComIndex; +import com.engine.kq.biz.chain.cominfo.ShiftInfoCominfoBean; +import com.engine.kq.biz.chain.duration.WorkHalfUnitSplitChain; +import com.engine.kq.biz.chain.shiftinfo.ShiftInfoBean; +import com.engine.kq.entity.TimeScopeEntity; +import com.engine.kq.entity.WorkTimeEntity; +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.Duration; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import weaver.common.DateUtil; +import weaver.general.BaseBean; +import weaver.general.Util; + +/** + * 考勤班次个性化设置 + */ +public class KQShiftRuleInfoBiz { + + public static void getShiftRuleInfo(ShiftInfoBean shiftInfoBean, String resourceId,Map shifRuleMap,List logList) { + getShiftRuleInfo(shiftInfoBean, resourceId, shifRuleMap, true,logList); + } + + public static void getShiftRuleInfo(ShiftInfoBean shiftInfoBean, String resourceId,Map shifRuleMap) { + getShiftRuleInfo(shiftInfoBean, resourceId, shifRuleMap, true); + } + + public static void getShiftRuleInfo(ShiftInfoBean shiftInfoBean, String resourceId,Map shifRuleMap,boolean need_lateoutlatein) { + getShiftRuleInfo(shiftInfoBean, resourceId, shifRuleMap, need_lateoutlatein, + Lists.newArrayList()); + } + /** + * 根据班次获取个性化设置 这个方法改逻辑的话 ,记得要把do4ShiftRule也一起改 + * @param shiftInfoBean + * @param resourceId + * @param need_lateoutlatein 是否需要处理晚走晚到 + */ + public static void getShiftRuleInfo(ShiftInfoBean shiftInfoBean, String resourceId,Map shifRuleMap,boolean need_lateoutlatein,List logList) { + DateTimeFormatter fullFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + DateTimeFormatter minFormatter = DateTimeFormatter.ofPattern("HH:mm"); + KQTimesArrayComInfo kqTimesArrayComInfo = new KQTimesArrayComInfo(); + List earlyinearlyout = null;//早到早走规则 + List lateinlateout = null;//晚到晚走规则 + List lateoutlatein = null;//晚走晚到规则 + if(shiftInfoBean == null){ + return ; + } + + String splitDate = shiftInfoBean.getSplitDate(); + String preDate = DateUtil.addDate(splitDate, -1);//上一天日期 + String nextDate = DateUtil.addDate(splitDate, 1);//下一天日期 + + KQWorkTime kqWorkTime = new KQWorkTime(); + kqWorkTime.setIsFormat(true); + WorkTimeEntity workTime = kqWorkTime.getWorkTime(resourceId, preDate); + Map preshiftRuleMap = workTime.getShiftRuleInfo(); + if (preshiftRuleMap != null && !preshiftRuleMap.isEmpty() && preshiftRuleMap.containsKey("ruleDetail")) { + Map preruleDetail = (Map) preshiftRuleMap.get("ruleDetail"); + if(preruleDetail != null && !preruleDetail.isEmpty()){ + lateoutlatein = (List) preruleDetail.get("lateoutlatein");//晚走晚到应该取前一天的个性化班次的设置,而不是当天 + } + } + + Map shiftRuleMap = shiftInfoBean.getShiftRuleMap(); + if (shiftRuleMap != null && !shiftRuleMap.isEmpty() && shiftRuleMap.containsKey("ruleDetail")) {//处理人性化设置其他规则 + //允许迟到分钟数 + boolean usepermitlateminutes = Util.null2String(shiftRuleMap.get("permitlatestatus")).equals("1"); + //和蔡志军讨论,优先满足弹性,即如果晚到了,开启了弹性,那么就先按照弹性来处理,不满足弹性的部分再按照允许迟到来处理 + usepermitlateminutes = false; + int permitlateminutes = Util.getIntValue(Util.null2String(shiftRuleMap.get("permitlateminutes")), 0); +// //允许早退分钟数 +// boolean usepermitleaveearlyminutes = Util.null2String(shiftRuleMap.get("permitleaveearlystatus")).equals("1"); +// int permitleaveearlyminutes = Util.getIntValue(Util.null2String(shiftRuleMap.get("permitleaveearlyminutes")), 0); + + Map ruleDetail = (Map) shiftRuleMap.get("ruleDetail"); + if(ruleDetail != null && !ruleDetail.isEmpty()){ + earlyinearlyout = (List) ruleDetail.get("earlyinearlyout"); + lateinlateout = (List) ruleDetail.get("lateinlateout"); + //上面已经搞了下面注释掉 +// lateoutlatein = (List) ruleDetail.get("lateoutlatein"); + +// KQWorkTime kqWorkTime = new KQWorkTime(); + //如果设置了个性化规则,需要先获取下打卡数据 + List lsSignTime = new ArrayList<>(); + List lsWorkTime = new ArrayList<>(); + List lsRestTime = new ArrayList<>(); + + lsSignTime = shiftInfoBean.getSignTime();//允许打卡时间 + lsWorkTime = shiftInfoBean.getWorkTime();//工作时间 + + //只有一次签到签退才有个性化的这些设置 + if(lsWorkTime != null && lsWorkTime.size() > 0){ + //早到早走后,引起下班时间变化后的时间 + LocalDateTime early_localEndDateTime = null; + //早到早走后,引起上班时间变化后的时间 + LocalDateTime early_localBeginDateTime = null; + //晚到晚走后,引起下班时间变化后的时间 + LocalDateTime late_localEndDateTime = null; + //晚到晚走后,引起上班时间变化后的时间 + LocalDateTime late_localBeginDateTime = null; + //晚走晚到后,引起上班时间变化后的时间 + LocalDateTime latein_localBeginDateTime = null; + + TimeScopeEntity signTimeScope = lsSignTime.get(0); + TimeScopeEntity workTimeScope = lsWorkTime.get(0); + + String signInDate = ""; + String signInTime = ""; + String signOutDate = ""; + String signOutTime = ""; + String workbeigintime = workTimeScope.getBeginTime(); + boolean beginTimeAcross = workTimeScope.getBeginTimeAcross(); + String workbegindate = splitDate; + if(beginTimeAcross){ + workbegindate = nextDate; + workbeigintime = kqTimesArrayComInfo.turn48to24Time(workbeigintime); + } + String workbegindatetime = workbegindate+" "+workbeigintime+":00"; + LocalDateTime localBeginDateTime = LocalDateTime.parse(workbegindatetime,fullFormatter); + + String workendtime = workTimeScope.getEndTime(); + boolean endTimeAcross = workTimeScope.getEndTimeAcross(); + String workenddate = splitDate; + if(endTimeAcross){ + workenddate = nextDate; + workendtime = kqTimesArrayComInfo.turn48to24Time(workendtime); + } + String workenddatetime = workenddate+" "+workendtime+":00"; + LocalDateTime localEndDateTime = LocalDateTime.parse(workenddatetime,fullFormatter); + + List lsCheckInfo = new KQFormatSignData().getSignInfo(resourceId,signTimeScope,workTimeScope,splitDate,preDate,nextDate,kqTimesArrayComInfo); + if(lsCheckInfo.isEmpty()){ + //如果当天没有打卡数据,判断下是否存在昨天有打卡数据,晚走晚到的情况 + if (lateoutlatein != null && lateoutlatein.size() > 0) { + }else{ + return ; + } + } + + if(lsCheckInfo.size() > 1){ + for(int i = 0 ; i < lsCheckInfo.size() ; i++){ + Map checkInfo = (Map) lsCheckInfo.get(i); + if (checkInfo.get("signType").equals("1")) { + //签到 + signInDate = Util.null2String(checkInfo.get("signDate")); + signInTime = Util.null2String(checkInfo.get("signTime")); + } + if (checkInfo.get("signType").equals("2")) { + //签退 + signOutDate = Util.null2String(checkInfo.get("signDate")); + signOutTime = Util.null2String(checkInfo.get("signTime")); + } + } + }else if(lsCheckInfo.size() == 1){ + Map checkInfo = (Map) lsCheckInfo.get(0); + if (checkInfo.get("signType").equals("1")) { + //签到 + signInDate = Util.null2String(checkInfo.get("signDate")); + signInTime = Util.null2String(checkInfo.get("signTime")); + } + if (checkInfo.get("signType").equals("2")) { + //签退 + signOutDate = Util.null2String(checkInfo.get("signDate")); + signOutTime = Util.null2String(checkInfo.get("signTime")); + } + } + + if (need_lateoutlatein && lateoutlatein != null && lateoutlatein.size() > 0) { + + String log_str = ""; + KQFormatShiftRule kqFormatShiftRule = new KQFormatShiftRule(); + int preDayLateOutMins = kqFormatShiftRule.getPreDayLateOutMins(resourceId, splitDate,logList); + if(!logList.isEmpty()){ + for(int i = 0 ; i < logList.size() ; i++){ + if(i == 0){ + log_str += ""+logList.get(i); + }else{ + log_str += ","+logList.get(i); + } + } + logList.clear(); + } + for (int i = 0; preDayLateOutMins > 0 && i < lateoutlatein.size(); i++) { + Map rule = (Map) lateoutlatein.get(i); + if (Util.null2String(rule.get("enable")).equals("1")) { + int advancetime = new Double((Util.getDoubleValue(Util.null2String(rule.get("advancetime"))))).intValue();//晚走时间 + int postponetime = new Double((Util.getDoubleValue(Util.null2String(rule.get("postponetime"))))).intValue();//允许晚到时间 + + boolean enablesame = Util.null2String(rule.get("enablesame")).equals("1"); + if(log_str.length() > 0){ + log_str += ","+(" "+"开启了晚走晚到,"+(enablesame?"相对时间,前一天晚走,第二天可以晚到,弹性限额"+postponetime+"分钟":"绝对时间"+",前一天晚走"+advancetime+"分钟,第二天上班可以晚到"+postponetime+"分钟")); + }else{ + log_str += ""+(" "+"开启了晚走晚到,"+(enablesame?"相对时间,前一天晚走,第二天可以晚到,弹性限额"+postponetime+"分钟":"绝对时间"+",前一天晚走"+advancetime+"分钟,第二天上班可以晚到"+postponetime+"分钟")); + } + if (enablesame) { + if(preDayLateOutMins >= advancetime){ + //如果昨日的晚走时长已经完全大于了设置的晚走时长,那么就可以晚到整个postponetime + latein_localBeginDateTime = localBeginDateTime.plusMinutes(postponetime); + }else{ + latein_localBeginDateTime = localBeginDateTime.plusMinutes(preDayLateOutMins); + } + break; + }else{ + if (preDayLateOutMins >= advancetime) { + //如果昨日的晚走时长已经完全大于了设置的晚走时长,那么就可以晚到整个postponetime + latein_localBeginDateTime = localBeginDateTime.plusMinutes(postponetime); + break; + }else{ + logList.clear(); + } + } + }else{ + logList.clear(); + } + } + if(latein_localBeginDateTime != null){ + shifRuleMap.put("shift_type", "lateoutlatein"); + String beginDate = latein_localBeginDateTime.format(dateFormatter); + String beginmin = latein_localBeginDateTime.format(minFormatter); + // 前一天的晚到影响了今天的早到或者晚到 + workbegindatetime = latein_localBeginDateTime.format(fullFormatter); + localBeginDateTime = LocalDateTime.parse(workbegindatetime,fullFormatter); + log_str += ","+("满足了晚走晚到,所以今天的上班时间变化了,变成了:"+workbegindatetime+"-"+workenddatetime); + + shifRuleMap.put("shift_begindate", beginDate); + if(beginDate.compareTo(splitDate) > 0){ + shifRuleMap.put("shift_beginworktime", kqTimesArrayComInfo.turn24to48Time(beginmin)); + }else{ + shifRuleMap.put("shift_beginworktime", beginmin); + } + }else{ + log_str = ""; + } + if(log_str.length() > 0){ + logList.add(log_str); + }else{ + logList.clear(); + } + } + String log_str = ""; + long signIn_before_mins = 0; + long signIn_after_mins = 0; + long signOut_before_mins = 0; + long signOut_after_mins = 0; + if(signInDate.length() > 0 && signInTime.length() > 0){ + //判断下签到和上班时间,是否存在早到或者晚到的情况的情况 + String fromDateTime = signInDate+" "+signInTime; + String toDateTime = workbegindatetime; + long signIn_mins = Duration.between(LocalDateTime.parse(fromDateTime, fullFormatter), LocalDateTime.parse(toDateTime, fullFormatter)).toMinutes(); + if(latein_localBeginDateTime != null){ + signIn_mins = Duration.between(LocalDateTime.parse(fromDateTime, fullFormatter), latein_localBeginDateTime).toMinutes(); + } + boolean need_plus_one_min = false; + new BaseBean().writeLog("fromDateTime="+fromDateTime+">>>toDateTime="+toDateTime); + if(signInTime.length() > 6){ + String signMinTime = signInTime.substring(0,5)+":00"; + if(signInTime.compareTo(signMinTime) > 0){ + //如果签到时间是带秒的且是迟到,那么签到时间多一秒和多一分钟是一样的 + need_plus_one_min = true; + String tmpfromDateTime = signInDate+" "+signMinTime; + if(need_plus_one_min){ + signIn_mins = Duration.between(LocalDateTime.parse(tmpfromDateTime, fullFormatter).plusMinutes(1), LocalDateTime.parse(toDateTime, fullFormatter)).toMinutes(); + if(latein_localBeginDateTime != null){ + signIn_mins = Duration.between(LocalDateTime.parse(tmpfromDateTime, fullFormatter).plusMinutes(1), latein_localBeginDateTime).toMinutes(); + } + } + } + } + if(signIn_mins > 0){ + log_str = (splitDate+" 上班时间是:"+toDateTime+",签到时间是:"+fromDateTime+",早到"+signIn_mins+"分钟"); + //确实是早到了 + signIn_before_mins = signIn_mins; + }else if(signIn_mins < 0){ + //这属于是晚到了 + signIn_after_mins = Math.abs(signIn_mins); + log_str = (splitDate+" "+"上班时间是:"+toDateTime+",签到时间是:"+fromDateTime+",晚到"+signIn_after_mins+"分钟"); + if (usepermitlateminutes) {//允许迟到分钟数 + signIn_after_mins = signIn_after_mins - permitlateminutes; + } + } + } + if(signOutDate.length() > 0 && signOutTime.length() > 0){ + //判断下签退和下班时间,是否存在晚走的情况 + String fromDateTime = workenddatetime; + String toDateTime = signOutDate+" "+signOutTime; + long signOut_mins = Duration.between(LocalDateTime.parse(fromDateTime, fullFormatter), LocalDateTime.parse(toDateTime, fullFormatter)).toMinutes(); + + if(signOut_mins > 0){ + //这属于是晚走了 + signOut_after_mins = signOut_mins; + }else if(signOut_mins < 0){ + //这属于是早退了 + signOut_before_mins = Math.abs(signOut_mins); + } + } + + if (earlyinearlyout != null && earlyinearlyout.size() > 0 && signIn_before_mins > 0) { + //必须有早到时间才能继续下面的判断 + for (int i = 0; i < earlyinearlyout.size(); i++) { + Map rule = (Map) earlyinearlyout.get(i); + if (Util.null2String(rule.get("enable")).equals("1")) { + int advancetime = new Double((Util.getDoubleValue(Util.null2String(rule.get("advancetime"))))).intValue();//早到时间 + int postponetime = new Double((Util.getDoubleValue(Util.null2String(rule.get("postponetime"))))).intValue();//允许早走时间 + boolean enablesame = Util.null2String(rule.get("enablesame")).equals("1"); + if(log_str.length() > 0){ + log_str += ","+(" "+"开启了早到早走,"+(enablesame?"相对时间,早到可以早走,弹性限额"+postponetime+"分钟":"绝对时间"+",上班早到"+advancetime+"分钟,下班可以早走"+postponetime+"分钟")); + }else{ + log_str += ""+(" "+"开启了早到早走,"+(enablesame?"相对时间,早到可以早走,弹性限额"+postponetime+"分钟":"绝对时间"+",上班早到"+advancetime+"分钟,下班可以早走"+postponetime+"分钟")); + } + if (enablesame) { + //使用相对时间 + if(signIn_before_mins >= advancetime){ + //如果打卡的早到时长已经完全大于了设置的早到时长,那么就可以早走整个postponetime + early_localEndDateTime = localEndDateTime.minusMinutes(postponetime); + early_localBeginDateTime = localBeginDateTime.minusMinutes(advancetime); + }else{ + early_localEndDateTime = localEndDateTime.minusMinutes(signIn_before_mins); + early_localBeginDateTime = localBeginDateTime.minusMinutes(signIn_before_mins); + } + break; + }else{ + if(signIn_before_mins >= advancetime){ + //如果打卡的早到时长已经完全大于了设置的早到时长,那么就可以早走整个postponetime + early_localEndDateTime = localEndDateTime.minusMinutes(postponetime); + early_localBeginDateTime = localBeginDateTime.minusMinutes(advancetime); + break; + } + } + } + } + + String new_beginDateTime = ""; + String new_endDateTime = ""; + if(early_localBeginDateTime != null){ + shifRuleMap.put("shift_type", "earlyinearlyout"); + String beginDate = early_localBeginDateTime.format(dateFormatter); + String beginmin = early_localBeginDateTime.format(minFormatter); + shifRuleMap.put("shift_begindate", beginDate); + if(beginDate.compareTo(splitDate) > 0){ + shifRuleMap.put("shift_beginworktime", kqTimesArrayComInfo.turn24to48Time(beginmin)); + }else{ + shifRuleMap.put("shift_beginworktime", beginmin); + } + new_beginDateTime = beginDate+" "+beginmin; + } + if(early_localEndDateTime != null){ + shifRuleMap.put("shift_type", "earlyinearlyout"); + String endDate = early_localEndDateTime.format(dateFormatter); + String endmin = early_localEndDateTime.format(minFormatter); + shifRuleMap.put("shift_enddate", endDate); + if(endDate.compareTo(splitDate) > 0){ + shifRuleMap.put("shift_endworktime", kqTimesArrayComInfo.turn24to48Time(endmin)); + }else{ + shifRuleMap.put("shift_endworktime", endmin); + } + new_endDateTime = endDate+" "+endmin; + } + if(new_beginDateTime.length() > 0 && new_endDateTime.length() > 0){ + log_str += ","+"满足了早到,所以"+splitDate+"的上班时间和下班时间变化了,上班时间变成了:"+new_beginDateTime+",下班时间变成了:"+new_endDateTime; + }else{ + log_str += ",不满足规则,所以"+splitDate+"的上班时间和下班时间未发生变化,上班时间还是:"+workbegindatetime+",下班时间还是:"+workenddatetime; + } + if(log_str.length() > 0){ + logList.add(log_str); + } + + } + + boolean isLateinlateout = false; + if (lateinlateout != null && lateinlateout.size() > 0) { + + if(signIn_after_mins > 0){ + isLateinlateout = true; + //必须有晚到时间才能继续下面的判断 + for (int i = 0; i < lateinlateout.size(); i++) { + Map rule = (Map) lateinlateout.get(i); + if (Util.null2String(rule.get("enable")).equals("1")) { + int advancetime = new Double((Util.getDoubleValue(Util.null2String(rule.get("advancetime"))))).intValue();//晚到时间 + int postponetime = new Double((Util.getDoubleValue(Util.null2String(rule.get("postponetime"))))).intValue();//需要晚走时间 + boolean enablesame = Util.null2String(rule.get("enablesame")).equals("1"); + if(log_str.length() > 0){ + log_str += ","+(" "+"开启了晚到晚走,"+(enablesame?"相对时间,晚到可以晚走,弹性限额"+postponetime+"分钟":"绝对时间"+",上班晚到"+advancetime+"分钟,下班需要晚走"+postponetime+"分钟")); + }else{ + log_str += ""+(" "+"开启了晚到晚走,"+(enablesame?"相对时间,晚到可以晚走,弹性限额"+postponetime+"分钟":"绝对时间"+",上班晚到"+advancetime+"分钟,下班需要晚走"+postponetime+"分钟")); + } + + if (enablesame) { + //使用相对时间 + if(signIn_after_mins <= advancetime){ + //如果打卡的晚到时长必须要小于等于设置的晚到时长,才算满足,晚到多久就可以晚走多久 + late_localEndDateTime = localEndDateTime.plusMinutes(signIn_after_mins); + late_localBeginDateTime = localBeginDateTime.plusMinutes(signIn_after_mins); + break; + }else{ + if(KQSettingsBiz.is_lateinlateout_outrule()){ + late_localEndDateTime = localEndDateTime.plusMinutes(advancetime); + late_localBeginDateTime = localBeginDateTime.plusMinutes(advancetime); + break; + } + } + }else{ + if (signIn_after_mins <= advancetime) { + //如果打卡的晚到时长已经完全小于了设置的晚到时长,那么需要晚走整个postponetime + late_localEndDateTime = localEndDateTime.plusMinutes(postponetime); + late_localBeginDateTime = localBeginDateTime.plusMinutes(advancetime); + break; + }else{ + if(KQSettingsBiz.is_lateinlateout_outrule()){ + late_localEndDateTime = localEndDateTime.plusMinutes(postponetime); + late_localBeginDateTime = localBeginDateTime.plusMinutes(advancetime); + break; + } + } + } + } + } + } + if(isLateinlateout){ + String new_beginDateTime = ""; + String new_endDateTime = ""; + if(late_localBeginDateTime != null){ + shifRuleMap.put("shift_type", "lateinlateout"); + String beginDate = late_localBeginDateTime.format(dateFormatter); + String beginmin = late_localBeginDateTime.format(minFormatter); + shifRuleMap.put("shift_begindate", beginDate); + if(beginDate.compareTo(splitDate) > 0){ + shifRuleMap.put("shift_beginworktime", kqTimesArrayComInfo.turn24to48Time(beginmin)); + }else{ + shifRuleMap.put("shift_beginworktime", beginmin); + } + new_beginDateTime = beginDate+" "+beginmin; + } + if(late_localEndDateTime != null){ + shifRuleMap.put("shift_type", "lateinlateout"); + String endDate = late_localEndDateTime.format(dateFormatter); + String endmin = late_localEndDateTime.format(minFormatter); + shifRuleMap.put("shift_enddate", endDate); + if(endDate.compareTo(splitDate) > 0){ + shifRuleMap.put("shift_endworktime", kqTimesArrayComInfo.turn24to48Time(endmin)); + }else{ + shifRuleMap.put("shift_endworktime", endmin); + } + new_endDateTime = endDate+" "+endmin; + } + if(new_beginDateTime.length() > 0 && new_endDateTime.length() > 0){ + log_str += ",满足了晚到,所以"+splitDate+"的上班时间和下班时间变化了,上班时间变成了:"+new_beginDateTime+",下班时间变成了:"+new_endDateTime; + }else{ + log_str += ",不满足规则,所以"+splitDate+"的上班时间和下班时间未发生变化,上班时间还是:"+workbegindatetime+",下班时间还是:"+workenddatetime; + } + if(log_str.length() > 0){ + logList.add(log_str); + } + } + } + } + } + } + } + + public void rest_workLongTimeIndex(ShiftInfoBean shiftInfoBean, + SplitBean splitBean, List real_workLongTimeIndex, + KQTimesArrayComInfo kqTimesArrayComInfo, + List real_allLongWorkTime){ + boolean is_flow_humanized = KQSettingsBiz.is_flow_humanized(); + if(!is_flow_humanized){ + return ; + } + //个性化设置只支持一次打卡的 + Map shifRuleMap = Maps.newHashMap(); + KQShiftRuleInfoBiz.getShiftRuleInfo(shiftInfoBean,splitBean.getResourceId(),shifRuleMap); + if(!shifRuleMap.isEmpty()){ + if(shifRuleMap.containsKey("shift_beginworktime")){ + String shift_beginworktime = Util.null2String(shifRuleMap.get("shift_beginworktime")); + if(shift_beginworktime.length() > 0){ + int[] workLongTimeIndex_arr = real_workLongTimeIndex.get(0); + workLongTimeIndex_arr[0] = kqTimesArrayComInfo.getArrayindexByTimes(shift_beginworktime); + if(real_allLongWorkTime != null){ + real_allLongWorkTime.set(0,shift_beginworktime); + } + } + } + if(shifRuleMap.containsKey("shift_endworktime")){ + String shift_endworktime = Util.null2String(shifRuleMap.get("shift_endworktime")); + if(shift_endworktime.length() > 0){ + int[] workLongTimeIndex_arr = real_workLongTimeIndex.get(0); + workLongTimeIndex_arr[1] = kqTimesArrayComInfo.getArrayindexByTimes(shift_endworktime); + if(real_allLongWorkTime != null){ + real_allLongWorkTime.set(1,shift_endworktime); + } + } + } + reset_halfIndex(shiftInfoBean,real_allLongWorkTime,kqTimesArrayComInfo); + } + + } + + public void reset_halfIndex(ShiftInfoBean shiftInfoBean, List real_allLongWorkTime, KQTimesArrayComInfo kqTimesArrayComInfo) { + try{ + List real_workAcrossTime = shiftInfoBean.getWorkAcrossTime(); + List shift_halfWorkIndex = shiftInfoBean.getHalfWorkIndex(); + List real_shift_halfWorkIndex = Lists.newArrayList(); + + List eachWorkMins = Lists.newArrayList(); + List tmp_eachWorkMins = Lists.newArrayList(); + List workLongTimeIndex = shiftInfoBean.getWorkLongTimeIndex(); + List restLongTimeIndex = shiftInfoBean.getRestLongTimeIndex(); + String allLongWorkBeginTime = real_allLongWorkTime.get(0); + String allLongWorkEndTime = real_allLongWorkTime.get(1); + + String[] real_workAcrossTimes = new String[2]; + real_workAcrossTimes[0] = allLongWorkBeginTime; + real_workAcrossTimes[1] = allLongWorkEndTime; + if(!workLongTimeIndex.isEmpty()){ + real_workAcrossTime.set(0,real_workAcrossTimes); + } + + int[] real_workLongTimeIndex = new int[2]; + real_workLongTimeIndex[0] = kqTimesArrayComInfo.getArrayindexByTimes(allLongWorkBeginTime); + real_workLongTimeIndex[1] = kqTimesArrayComInfo.getArrayindexByTimes(allLongWorkEndTime); + if(!workLongTimeIndex.isEmpty()){ + workLongTimeIndex.set(0, real_workLongTimeIndex); + } + + int allLongWorkBeginTime_Index = kqTimesArrayComInfo.getArrayindexByTimes(allLongWorkBeginTime); + int allLongWorkEndTime_Index = kqTimesArrayComInfo.getArrayindexByTimes(allLongWorkEndTime); + tmp_eachWorkMins.add(allLongWorkBeginTime_Index); + int real_workmins = allLongWorkEndTime_Index-allLongWorkBeginTime_Index; + for(int k = 0 ; k < restLongTimeIndex.size() ; k++){ + int[] rests = restLongTimeIndex.get(k); + if(rests != null && rests.length == 2){ + real_workmins = real_workmins - (rests[1]-rests[0]); + tmp_eachWorkMins.add(rests[0]); + tmp_eachWorkMins.add(rests[1]); + } + } + tmp_eachWorkMins.add(allLongWorkEndTime_Index); + for(int j = 0 ; j < tmp_eachWorkMins.size() ; ){ + int end_index = tmp_eachWorkMins.get(j+1); + int begin_index = tmp_eachWorkMins.get(j); + int tmp = end_index-begin_index; + if(tmp > 0){ + eachWorkMins.add(end_index-begin_index); + } + j = j + 2; + } + + Map workTimeMap = Maps.newHashMap(); + workTimeMap.put("halfcalrule", shiftInfoBean.getHalfcalrule()); + workTimeMap.put("halfcalpoint", shiftInfoBean.getHalfcalpoint()); + workTimeMap.put("halfcalpoint2cross", shiftInfoBean.getHalfcalpoint2cross()); + workTimeMap.put("workmins", real_workmins); + + HalfShiftComIndex halfShiftComIndex = new HalfShiftComIndex(""+weaver.systeminfo.SystemEnv.getHtmlLabelName(10005308,weaver.general.ThreadVarLanguage.getLang())+"",workTimeMap); + ShiftInfoCominfoBean shiftInfoCominfoBean = new ShiftInfoCominfoBean(); + shiftInfoCominfoBean.setAllLongWorkTime(real_allLongWorkTime); + shiftInfoCominfoBean.setRestLongTimeIndex(shiftInfoBean.getRestLongTimeIndex()); + shiftInfoCominfoBean.setWorkAcrossTime(real_workAcrossTime); + shiftInfoCominfoBean.setEachWorkMins(eachWorkMins); + shiftInfoCominfoBean.setHalfWorkIndex(real_shift_halfWorkIndex); + shiftInfoCominfoBean.setWorkLongTimeIndex(workLongTimeIndex); + halfShiftComIndex.handleHalfTime(shiftInfoCominfoBean); + if(!real_shift_halfWorkIndex.isEmpty()){ + shiftInfoBean.setHalfWorkIndex(real_shift_halfWorkIndex); + } + }catch (Exception e){ + } + } + + + /** + * 开启了个性化设置之后,对加班数据的影响 + * @param ruleDetail + * @param signInTimeBean + * @param signOutTimeBean + * @param allWorkTime + * @param splitDate + * @param nextday + * @param resourceid + */ + public static Map do4ShiftRule(Map ruleDetail, + KQHrmScheduleSign signInTimeBean, KQHrmScheduleSign signOutTimeBean, + List allWorkTime, String splitDate, String nextday, String resourceid) { + Map shifRuleMap = Maps.newHashMap(); + boolean is_flow_humanized = KQSettingsBiz.is_flow_humanized(); + if(!is_flow_humanized){ + return shifRuleMap; + } + DateTimeFormatter fullFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + DateTimeFormatter minFormatter = DateTimeFormatter.ofPattern("HH:mm"); + KQTimesArrayComInfo kqTimesArrayComInfo = new KQTimesArrayComInfo(); + + List earlyinearlyout = null;//早到早走规则 + List lateinlateout = null;//晚到晚走规则 + List lateoutlatein = null;//晚走晚到规则 + String begintime = allWorkTime.get(0); + String endtime = allWorkTime.get(allWorkTime.size()-1); + boolean isEndAcross = false; + if(begintime.compareTo(endtime) > 0){ + //结束时间跨天了 + isEndAcross = true; + } + //早到早走后,引起下班时间变化后的时间 + LocalDateTime early_localEndDateTime = null; + //早到早走后,引起上班时间变化后的时间 + LocalDateTime early_localBeginDateTime = null; + //晚到晚走后,引起下班时间变化后的时间 + LocalDateTime late_localEndDateTime = null; + //晚到晚走后,引起上班时间变化后的时间 + LocalDateTime late_localBeginDateTime = null; + //晚走晚到后,引起上班时间变化后的时间 + LocalDateTime latein_localBeginDateTime = null; + + earlyinearlyout = (List) ruleDetail.get("earlyinearlyout"); + lateinlateout = (List) ruleDetail.get("lateinlateout"); + lateoutlatein = (List) ruleDetail.get("lateoutlatein"); + + String workbegindatetime = splitDate+" "+begintime+":00"; + LocalDateTime localBeginDateTime = LocalDateTime.parse(workbegindatetime,fullFormatter); + String workenddatetime = (isEndAcross ? nextday : splitDate)+" "+endtime+":00"; + LocalDateTime localEndDateTime = LocalDateTime.parse(workenddatetime,fullFormatter); + + long signIn_before_mins = 0; + long signIn_after_mins = 0; + long signOut_before_mins = 0; + long signOut_after_mins = 0; + if(signInTimeBean != null){ + String signInDate = signInTimeBean.getSigndate(); + String signInTime = signInTimeBean.getSigntime(); + //判断下签到和上班时间,是否存在早到或者晚到的情况的情况 + String fromDateTime = signInDate+" "+signInTime; + String toDateTime = workbegindatetime; + long signIn_mins = Duration.between(LocalDateTime.parse(fromDateTime, fullFormatter), LocalDateTime.parse(toDateTime, fullFormatter)).toMinutes(); + + if(signIn_mins > 0){ + //确实是早到了 + signIn_before_mins = signIn_mins; + }else if(signIn_mins < 0){ + //这属于是晚到了 + signIn_after_mins = Math.abs(signIn_mins); + } + } + if(signOutTimeBean != null){ + String signOutDate = signOutTimeBean.getSigndate(); + String signOutTime = signOutTimeBean.getSigntime(); + //判断下签退和下班时间,是否存在晚走的情况 + String fromDateTime = workenddatetime; + String toDateTime = signOutDate+" "+signOutTime; + long signOut_mins = Duration.between(LocalDateTime.parse(fromDateTime, fullFormatter), LocalDateTime.parse(toDateTime, fullFormatter)).toMinutes(); + + if(signOut_mins > 0){ + //这属于是晚走了 + signOut_after_mins = signOut_mins; + }else if(signOut_mins < 0){ + //这属于是早退了 + signOut_before_mins = Math.abs(signOut_mins); + } + } + + if (earlyinearlyout != null && earlyinearlyout.size() > 0 && signIn_before_mins > 0) { + //必须有早到时间才能继续下面的判断 + for (int i = 0; i < earlyinearlyout.size(); i++) { + Map rule = (Map) earlyinearlyout.get(i); + if (Util.null2String(rule.get("enable")).equals("1")) { + int advancetime = new Double((Util.getDoubleValue(Util.null2String(rule.get("advancetime"))))).intValue();//早到时间 + int postponetime = new Double((Util.getDoubleValue(Util.null2String(rule.get("postponetime"))))).intValue();//允许早走时间 + if (Util.null2String(rule.get("enablesame")).equals("1")) { + //使用相对时间 + if(signIn_before_mins >= advancetime){ + //如果打卡的早到时长已经完全大于了设置的早到时长,那么就可以早走整个postponetime + early_localEndDateTime = localEndDateTime.minusMinutes(postponetime); + early_localBeginDateTime = localBeginDateTime.minusMinutes(advancetime); + }else{ + early_localEndDateTime = localEndDateTime.minusMinutes(signIn_before_mins); + early_localBeginDateTime = localBeginDateTime.minusMinutes(signIn_before_mins); + } + break; + }else{ + if(signIn_before_mins >= advancetime){ + //如果打卡的早到时长已经完全大于了设置的早到时长,那么就可以早走整个postponetime + early_localEndDateTime = localEndDateTime.minusMinutes(postponetime); + early_localBeginDateTime = localBeginDateTime.minusMinutes(advancetime); + break; + } + } + } + } + } + + if (lateinlateout != null && lateinlateout.size() > 0 && signIn_after_mins > 0) { + //必须有晚到时间才能继续下面的判断 + for (int i = 0; i < lateinlateout.size(); i++) { + Map rule = (Map) lateinlateout.get(i); + if (Util.null2String(rule.get("enable")).equals("1")) { + int advancetime = new Double((Util.getDoubleValue(Util.null2String(rule.get("advancetime"))))).intValue();//晚到时间 + int postponetime = new Double((Util.getDoubleValue(Util.null2String(rule.get("postponetime"))))).intValue();//需要晚走时间 + if (Util.null2String(rule.get("enablesame")).equals("1")) { + //使用相对时间 + if(signIn_after_mins <= advancetime){ + //如果打卡的晚到时长必须要小于等于设置的晚到时长,才算满足,晚到多久就可以晚走多久 + late_localEndDateTime = localEndDateTime.plusMinutes(signIn_after_mins); + late_localBeginDateTime = localBeginDateTime.plusMinutes(signIn_after_mins); + } + break; + }else{ + if (signIn_after_mins <= advancetime) { + //如果打卡的晚到时长已经完全小于了设置的晚到时长,那么需要晚走整个postponetime + late_localEndDateTime = localEndDateTime.plusMinutes(postponetime); + late_localBeginDateTime = localBeginDateTime.plusMinutes(advancetime); + break; + } + } + } + } + } + + + if (lateoutlatein != null && lateoutlatein.size() > 0) { + + LocalDateTime tmp_localBeginDateTime = localBeginDateTime; + if(early_localBeginDateTime != null){ + tmp_localBeginDateTime = early_localBeginDateTime; + } + if(late_localBeginDateTime != null){ + tmp_localBeginDateTime = late_localBeginDateTime; + } + KQFormatShiftRule kqFormatShiftRule = new KQFormatShiftRule(); + int preDayLateOutMins = kqFormatShiftRule.getPreDayLateOutMins(resourceid, splitDate); + for (int i = 0; preDayLateOutMins > 0 && i < lateoutlatein.size(); i++) { + Map rule = (Map) lateoutlatein.get(i); + if (Util.null2String(rule.get("enable")).equals("1")) { + int advancetime = new Double((Util.getDoubleValue(Util.null2String(rule.get("advancetime"))))).intValue();//晚走时间 + int postponetime = new Double((Util.getDoubleValue(Util.null2String(rule.get("postponetime"))))).intValue();//允许晚到时间 + + if (Util.null2String(rule.get("enablesame")).equals("1")) { + if(preDayLateOutMins >= advancetime){ + //如果昨日的晚走时长已经完全大于了设置的晚走时长,那么就可以晚到整个postponetime + latein_localBeginDateTime = tmp_localBeginDateTime.plusMinutes(postponetime); + }else{ + latein_localBeginDateTime = tmp_localBeginDateTime.plusMinutes(preDayLateOutMins); + } + break; + }else{ + if (preDayLateOutMins >= advancetime) { + //如果昨日的晚走时长已经完全大于了设置的晚走时长,那么就可以晚到整个postponetime + latein_localBeginDateTime = tmp_localBeginDateTime.plusMinutes(postponetime); + break; + } + } + } + } + } + + + if(early_localEndDateTime != null){ + shifRuleMap.put("shift_type", "earlyinearlyout"); + String endDate = early_localEndDateTime.format(dateFormatter); + String endmin = early_localEndDateTime.format(minFormatter); + if(endDate.compareTo(splitDate) > 0){ + shifRuleMap.put("shift_endworktime", kqTimesArrayComInfo.turn24to48Time(endmin)); + }else{ + shifRuleMap.put("shift_endworktime", endmin); + } + } + if(late_localEndDateTime != null){ + shifRuleMap.put("shift_type", "lateinlateout"); + String endDate = late_localEndDateTime.format(dateFormatter); + String endmin = late_localEndDateTime.format(minFormatter); + if(endDate.compareTo(splitDate) > 0){ + shifRuleMap.put("shift_endworktime", kqTimesArrayComInfo.turn24to48Time(endmin)); + }else{ + shifRuleMap.put("shift_endworktime", endmin); + } + } + if(early_localBeginDateTime != null){ + shifRuleMap.put("shift_type", "earlyinearlyout"); + String beginDate = early_localBeginDateTime.format(dateFormatter); + String beginmin = early_localBeginDateTime.format(minFormatter); + if(beginDate.compareTo(splitDate) > 0){ + shifRuleMap.put("shift_beginworktime", kqTimesArrayComInfo.turn24to48Time(beginmin)); + }else{ + shifRuleMap.put("shift_beginworktime", beginmin); + } + } + if(late_localBeginDateTime != null){ + shifRuleMap.put("shift_type", "lateinlateout"); + String beginDate = late_localBeginDateTime.format(dateFormatter); + String beginmin = late_localBeginDateTime.format(minFormatter); + if(beginDate.compareTo(splitDate) > 0){ + shifRuleMap.put("shift_beginworktime", kqTimesArrayComInfo.turn24to48Time(beginmin)); + }else{ + shifRuleMap.put("shift_beginworktime", beginmin); + } + } + if(latein_localBeginDateTime != null){ + shifRuleMap.put("shift_type", "lateoutlatein"); + String beginDate = latein_localBeginDateTime.format(dateFormatter); + String beginmin = latein_localBeginDateTime.format(minFormatter); + if(beginDate.compareTo(splitDate) > 0){ + shifRuleMap.put("shift_beginworktime", kqTimesArrayComInfo.turn24to48Time(beginmin)); + }else{ + shifRuleMap.put("shift_beginworktime", beginmin); + } + } + return shifRuleMap; + } + +} diff --git a/src/com/engine/kq/biz/KQWorkTime.java b/src/com/engine/kq/biz/KQWorkTime.java new file mode 100644 index 0000000..2b39b65 --- /dev/null +++ b/src/com/engine/kq/biz/KQWorkTime.java @@ -0,0 +1,402 @@ +package com.engine.kq.biz; + +import com.alibaba.fastjson.JSON; +import com.engine.kq.biz.chain.cominfo.ShiftInfoCominfoBean; +import com.engine.kq.cmd.shiftmanagement.toolkit.ShiftManagementToolKit; +import com.engine.kq.entity.KQGroupEntity; +import com.engine.kq.entity.TimeScopeEntity; +import com.engine.kq.entity.TimeSignScopeEntity; +import com.engine.kq.entity.WorkTimeEntity; +import com.engine.kq.log.KQLog; +import weaver.common.DateUtil; +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{ + isWorkDay = Util.getIntValue(Util.null2String(serialInfo.get(workdate)))>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); + 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); + 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"))); + } + }else{ + int serialid = Util.getIntValue(Util.null2String(serialInfo.get(workdate)), 0); + 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.setShiftRuleInfo(ShiftManagementToolKit.getShiftRuleInfo(""+serialid,true)); + workTimeEntity.setSignTime(formatTimeScope((List)dateWorkTimeMap.get("signTime"),false)); + workTimeEntity.setWorkTime(formatTimeScope((List)dateWorkTimeMap.get("workTime"),true)); + workTimeEntity.setRestTime(formatTimeScope((List)dateWorkTimeMap.get("restTime"),false)); + workTimeEntity.setWorkMins(Util.getIntValue(Util.null2String(dateWorkTimeMap.get("workMins")))); + workTimeEntity.setIsAcross(Util.null2String(dateWorkTimeMap.get("isAcross"))); + } + } + } + } catch (Exception e) { + writeLog(e); + } + return workTimeEntity; + } + + public List formatTimeScope(List timeScope, boolean needWorkMins){ + List timeScopes = new ArrayList<>(); + KQTimesArrayComInfo kqTimesArrayComInfo = new KQTimesArrayComInfo(); + TimeScopeEntity timeScopeEntity = null; + for(int i=0;timeScope!=null && i obj = (Map)timeScope.get(i); + String bengintime_end = Util.null2String(obj.get("bengintime_end")); + String bengintime_end_across = Util.null2String(obj.get("bengintime_end_across")); + String endtime_start = Util.null2String(obj.get("endtime_start")); + String endtime_start_across = Util.null2String(obj.get("endtime_start_across")); + String bengintime_pre_across = Util.null2String(obj.get("bengintime_pre_across")); + timeScopeEntity = new TimeScopeEntity(); + timeScopeEntity.setBeginTime(Util.null2String(obj.get("bengintime"))); + timeScopeEntity.setBeginTimeAcross(Util.null2String(obj.get("bengintime_across")).equals("1"));//标记是否跨天 + timeScopeEntity.setEndTime(Util.null2String(obj.get("endtime"))); + timeScopeEntity.setEndTimeAcross(Util.null2String(obj.get("endtime_across")).equals("1"));//标记是否跨天 + timeScopeEntity.setBeginTimePreAcross("1".equalsIgnoreCase(bengintime_pre_across)); + + if(needWorkMins) { + int workBeginIdx = kqTimesArrayComInfo.getArrayindexByTimes(timeScopeEntity.getBeginTime()); + int workEndIdx = kqTimesArrayComInfo.getArrayindexByTimes(timeScopeEntity.getEndTime()); + timeScopeEntity.setWorkMins(workEndIdx - workBeginIdx); + } + if((bengintime_end != null && bengintime_end.length() >0) || (endtime_start != null && endtime_start.length() > 0)){ + TimeSignScopeEntity timeSignScopeEntity = new TimeSignScopeEntity(); + timeSignScopeEntity.setBeginTimeEnd(bengintime_end); + timeSignScopeEntity.setBeginTimeEndAcross("1".equalsIgnoreCase(bengintime_end_across)); + timeSignScopeEntity.setEndTimeStart(endtime_start); + timeSignScopeEntity.setEndTimeStartAcross("1".equalsIgnoreCase(endtime_start_across)); + timeSignScopeEntity.setBeginTimePreAcross("1".equalsIgnoreCase(bengintime_pre_across)); + timeScopeEntity.setTimeSignScopeEntity(timeSignScopeEntity); + } + timeScopes.add(timeScopeEntity); + } + return timeScopes; + } + + /** + * 获取当天班次 + * @param userId + * @param workdate + * @return + */ + public String getSerialIds(String userId, String workdate) { + Map serialInfo = getSerialInfo( userId, workdate, false); + return serialInfo!=null?Util.null2String(serialInfo.get(workdate)):""; + } + + /** + * 获取班次信息 获取顺序 工作日调整、排班、固定班和周期班 + * @param userId + * @param workdate + * @param containYesterday + * @return + */ + public Map getSerialInfo(String userId, String workdate, boolean containYesterday) { + Map serialInfo = new HashMap<>(); + String preworkdate = ""; + try { + KQGroupMemberComInfo groupMemberComInfo = new KQGroupMemberComInfo(); + groupMemberComInfo.setIsFormat(this.isFormat); + KQFixedSchedulceComInfo kqFixedSchedulceComInfo = new KQFixedSchedulceComInfo(); + kqFixedSchedulceComInfo.setFormat(this.isFormat); + KQShiftScheduleComInfo kqShiftScheduleComInfo = new KQShiftScheduleComInfo(); + kqShiftScheduleComInfo.setFormat(this.isFormat); + KQGroupEntity kqGroupEntity = groupMemberComInfo.getUserKQGroupInfo(userId,workdate); + ResourceComInfo resourceComInfo = new ResourceComInfo(); + + preworkdate = DateUtil.addDate(workdate,-1); + if(containYesterday){ + Map pre_serialInfo = getSerialInfo(userId, preworkdate, false); + if(pre_serialInfo != null && !pre_serialInfo.isEmpty()){ + if(pre_serialInfo.containsKey(preworkdate)){ + serialInfo.put(preworkdate,pre_serialInfo.get(preworkdate));//获取前一天的班次 + } + } + } + + if(kqGroupEntity==null){//不在考勤组内 + 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 (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(),"2"); + 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..e2f43ed --- /dev/null +++ b/src/com/engine/kq/biz/chain/cominfo/ShiftInfoCominfoBean.java @@ -0,0 +1,508 @@ +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 = ""; + + public ShiftInfoCominfoBean() { + + this.preWorkTime = new ArrayList<>(); + this.workTime = new ArrayList<>(); + this.workAcrossTime = new ArrayList<>(); + this.preWorkTimeIndex = new ArrayList<>(); + this.workTimeIndex = new ArrayList<>(); + this.workAcrossTimeIndex = new ArrayList<>(); + this.workAcrossLongTime = new ArrayList<>(); + this.workPunchMins = new ArrayList<>(); + this.preRestTime = new ArrayList<>(); + this.restTime = new ArrayList<>(); + this.restAcrossTime = new ArrayList<>(); + this.preRestTimeIndex = new ArrayList<>(); + this.restTimeIndex = new ArrayList<>(); + this.restAcrossTimeIndex = new ArrayList<>(); + this.restAcrossLongTime = new ArrayList<>(); + this.halfWorkTime = new ArrayList<>(); + this.allWorkTime = new ArrayList<>(); + this.allAcrossWorkTime = new ArrayList<>(); + this.allRestTime = new ArrayList<>(); + this.allAcrossRestTime = new ArrayList<>(); + this.eachWorkMins = new ArrayList<>(); + this.workmins = 0; + this.serialid = ""; + this.isAcross = "0"; + this.halfcalrule = "0"; + this.halfWorkIndex = new ArrayList<>(); + + this.timelineList = new ArrayList<>(); + + this.workLongTimeIndex = new ArrayList<>(); + this.restLongTimeIndex = new ArrayList<>(); + this.allLongWorkTime = new ArrayList<>(); + this.signWorkTime = new ArrayList<>(); + this.allWorkTimeisAcross = new ArrayList<>(); + this.uuid = UUID.randomUUID().toString(); + this.halfcalpoint = "0"; + this.halfcalpoint2cross = "0"; + } + + public List getPreWorkTime() { + return preWorkTime; + } + + public void setPreWorkTime(List preWorkTime) { + this.preWorkTime = preWorkTime; + } + + public List getWorkTime() { + return workTime; + } + + public void setWorkTime(List workTime) { + this.workTime = workTime; + } + + public List getWorkAcrossTime() { + return workAcrossTime; + } + + public void setWorkAcrossTime(List workAcrossTime) { + this.workAcrossTime = workAcrossTime; + } + + public List> getWorkAcrossLongTime() { + return workAcrossLongTime; + } + + public void setWorkAcrossLongTime( + List> workAcrossLongTime) { + this.workAcrossLongTime = workAcrossLongTime; + } + + public List getWorkPunchMins() { + return workPunchMins; + } + + public void setWorkPunchMins(List workPunchMins) { + this.workPunchMins = workPunchMins; + } + + public List getHalfWorkTime() { + return halfWorkTime; + } + + public void setHalfWorkTime(List halfWorkTime) { + this.halfWorkTime = halfWorkTime; + } + + public int getWorkmins() { + return workmins; + } + + public void setWorkmins(int workmins) { + this.workmins = workmins; + } + + public String getSerialid() { + return serialid; + } + + public void setSerialid(String serialid) { + this.serialid = serialid; + } + + public List getAllWorkTime() { + return allWorkTime; + } + + public void setAllWorkTime(List allWorkTime) { + this.allWorkTime = allWorkTime; + } + + public List getAllAcrossWorkTime() { + return allAcrossWorkTime; + } + + public void setAllAcrossWorkTime(List allAcrossWorkTime) { + this.allAcrossWorkTime = allAcrossWorkTime; + } + + public List getRestTime() { + return restTime; + } + + public void setRestTime(List restTime) { + this.restTime = restTime; + } + + public String getIsAcross() { + return isAcross; + } + + public void setIsAcross(String isAcross) { + this.isAcross = isAcross; + } + + public List getPreRestTime() { + return preRestTime; + } + + public void setPreRestTime(List preRestTime) { + this.preRestTime = preRestTime; + } + + public List getRestAcrossTime() { + return restAcrossTime; + } + + public void setRestAcrossTime(List restAcrossTime) { + this.restAcrossTime = restAcrossTime; + } + + public List> getRestAcrossLongTime() { + return restAcrossLongTime; + } + + public void setRestAcrossLongTime( + List> restAcrossLongTime) { + this.restAcrossLongTime = restAcrossLongTime; + } + + public List getAllRestTime() { + return allRestTime; + } + + public void setAllRestTime(List allRestTime) { + this.allRestTime = allRestTime; + } + + public List getAllAcrossRestTime() { + return allAcrossRestTime; + } + + public void setAllAcrossRestTime(List allAcrossRestTime) { + this.allAcrossRestTime = allAcrossRestTime; + } + + public List getEachWorkMins() { + return eachWorkMins; + } + + public void setEachWorkMins(List eachWorkMins) { + this.eachWorkMins = eachWorkMins; + } + + public List getPreWorkTimeIndex() { + return preWorkTimeIndex; + } + + public void setPreWorkTimeIndex(List preWorkTimeIndex) { + this.preWorkTimeIndex = preWorkTimeIndex; + } + + public List getWorkTimeIndex() { + return workTimeIndex; + } + + public void setWorkTimeIndex(List workTimeIndex) { + this.workTimeIndex = workTimeIndex; + } + + public List getWorkAcrossTimeIndex() { + return workAcrossTimeIndex; + } + + public void setWorkAcrossTimeIndex(List workAcrossTimeIndex) { + this.workAcrossTimeIndex = workAcrossTimeIndex; + } + + public List getPreRestTimeIndex() { + return preRestTimeIndex; + } + + public void setPreRestTimeIndex(List preRestTimeIndex) { + this.preRestTimeIndex = preRestTimeIndex; + } + + public List getRestTimeIndex() { + return restTimeIndex; + } + + public void setRestTimeIndex(List restTimeIndex) { + this.restTimeIndex = restTimeIndex; + } + + public List getRestAcrossTimeIndex() { + return restAcrossTimeIndex; + } + + public void setRestAcrossTimeIndex(List restAcrossTimeIndex) { + this.restAcrossTimeIndex = restAcrossTimeIndex; + } + + public List getHalfWorkIndex() { + return halfWorkIndex; + } + + public void setHalfWorkIndex(List halfWorkIndex) { + this.halfWorkIndex = halfWorkIndex; + } + + public List getTimelineList() { + return timelineList; + } + + public void setTimelineList(List timelineList) { + this.timelineList = timelineList; + } + + public List getWorkLongTimeIndex() { + return workLongTimeIndex; + } + + public void setWorkLongTimeIndex(List workLongTimeIndex) { + this.workLongTimeIndex = workLongTimeIndex; + } + + public List getRestLongTimeIndex() { + return restLongTimeIndex; + } + + public void setRestLongTimeIndex(List restLongTimeIndex) { + this.restLongTimeIndex = restLongTimeIndex; + } + + public List getAllLongWorkTime() { + return allLongWorkTime; + } + + public void setAllLongWorkTime(List allLongWorkTime) { + this.allLongWorkTime = allLongWorkTime; + } + + public List> getSignWorkTime() { + return signWorkTime; + } + + public void setSignWorkTime( + List> signWorkTime) { + this.signWorkTime = signWorkTime; + } + + public List getAllWorkTimeisAcross() { + return allWorkTimeisAcross; + } + + public void setAllWorkTimeisAcross(List allWorkTimeisAcross) { + this.allWorkTimeisAcross = allWorkTimeisAcross; + } + + public String getHalfcalrule() { + return halfcalrule; + } + + public void setHalfcalrule(String halfcalrule) { + this.halfcalrule = halfcalrule; + } + + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public String getHalfcalpoint() { + return halfcalpoint; + } + + public void setHalfcalpoint(String halfcalpoint) { + this.halfcalpoint = halfcalpoint; + } + + public String getHalfcalpoint2cross() { + return halfcalpoint2cross; + } + + public void setHalfcalpoint2cross(String halfcalpoint2cross) { + this.halfcalpoint2cross = halfcalpoint2cross; + } +} + 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..2519c95 --- /dev/null +++ b/src/com/engine/kq/biz/chain/cominfo/WorkShiftComIndex.java @@ -0,0 +1,35 @@ +package com.engine.kq.biz.chain.cominfo; + +import com.engine.kq.biz.KQTimesArrayComInfo; +import java.util.List; +import java.util.Map; +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); + + setWorkDuration(workTimes, shiftInfoCominfoBean); + + } + +} diff --git a/src/com/engine/kq/cmd/attendanceButton/GetButtonBaseInfoCmd.java b/src/com/engine/kq/cmd/attendanceButton/GetButtonBaseInfoCmd.java new file mode 100644 index 0000000..4f5440e --- /dev/null +++ b/src/com/engine/kq/cmd/attendanceButton/GetButtonBaseInfoCmd.java @@ -0,0 +1,225 @@ +package com.engine.kq.cmd.attendanceButton; + +import com.engine.common.biz.AbstractCommonCommand; +import com.engine.common.entity.BizLogContext; +import com.engine.core.interceptor.CommandContext; +import com.engine.kq.biz.KQCardLogBiz; +import com.engine.kq.biz.KQGroupComInfo; +import com.engine.kq.biz.KQGroupMemberComInfo; +import com.engine.kq.biz.KQSettingsBiz; +import com.engine.kq.biz.KQWorkTime; +import com.engine.kq.entity.KQGroupEntity; +import com.engine.kq.entity.WorkTimeEntity; +import com.engine.kq.log.KQLog; +import com.google.common.collect.Maps; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.HashMap; +import java.util.Map; + +import com.engine.portal.biz.constants.ModuleConstants; +import com.engine.portal.biz.nonstandardfunction.SysModuleInfoBiz; +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.Util; +import weaver.hrm.User; +import weaver.hrm.resource.ResourceComInfo; +import weaver.systeminfo.SystemEnv; + +/** + * 获取考勤组的基本信息的 + */ +public class GetButtonBaseInfoCmd extends AbstractCommonCommand> { + public KQLog kqLog = new KQLog(); + private DateTimeFormatter fullFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + private DateTimeFormatter datetimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); + private DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm"); + private DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + private DateTimeFormatter fullTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss"); + private Map logMap = Maps.newHashMap(); + private Map workTimeEntityLogMap = Maps.newHashMap(); + + public GetButtonBaseInfoCmd(Map params, User user) { + this.user = user; + this.params = params; + } + + @Override + public Map execute(CommandContext commandContext) { + kqLog.info(user.getLastname()+":GetButtonBaseInfoCmd:params:"+params); + + logMap.put("lastname", user.getLastname()); + logMap.put("params", params); + Map retmap = new HashMap(); + RecordSet rs = new RecordSet(); + String sql = ""; + try{ + + KQGroupMemberComInfo kqGroupMemberComInfo = new KQGroupMemberComInfo(); + KQGroupComInfo kqGroupComInfo = new KQGroupComInfo(); + ResourceComInfo resourceComInfo = new ResourceComInfo(); + + String ismobile = Util.null2String(params.get("ismobile")); + + String lastname = user.getLastname(); + String messagerurl = resourceComInfo.getMessagerUrls(""+user.getUID()); + String shortname = ""; + + boolean USERICONLASTNAME = Util.null2String(new BaseBean().getPropValue("Others" , "USERICONLASTNAME")).equals("1"); + if(USERICONLASTNAME&&(messagerurl.indexOf("icon_w_wev8.jpg")>-1||messagerurl.indexOf("icon_m_wev8.jpg")>-1||messagerurl.indexOf("dummyContact.png")>-1)){ + shortname = User.getLastname(Util.null2String(Util.formatMultiLang(lastname, ""+user.getLanguage()))); + } + + String curDate = DateUtil.getCurrentDate(); + LocalDateTime now = LocalDateTime.now(); + String now_date = now.format(dateFormatter); + String now_time = now.format(fullTimeFormatter); + GetButtonsCmd getButtonsCmd = new GetButtonsCmd(params, user); + LocalDateTime now_zone = getButtonsCmd.getZoneOfClientDateTime(now_date,now_time,logMap); + if(now_zone != null){ + curDate = now_zone.format(dateFormatter); + } + KQWorkTime kqWorkTime = new KQWorkTime(); + WorkTimeEntity workTimeEntity = kqWorkTime.getWorkTime(user.getUID()+"", curDate); + String userinfo = "#userid#"+user.getUID()+"#getUserSubCompany1#"+user.getUserSubCompany1()+"#getUserSubCompany1#"+user.getUserDepartment() + +"#getJobtitle#"+user.getJobtitle(); + workTimeEntityLogMap.put("resourceid", userinfo); + workTimeEntityLogMap.put("splitDate", curDate); + workTimeEntityLogMap.put("workTimeEntity", workTimeEntity); + + String groupid = workTimeEntity.getGroupId(); + logMap.put("groupid", groupid); + String groupname = ""; + String locationshowaddress = Util.null2String(kqGroupComInfo.getLocationshowaddress(groupid));//是否记录统一地址 + String locationfacecheck = Util.null2String(kqGroupComInfo.getLocationfacecheck(groupid));//办公地点启用人脸识别拍照打卡 + String locationfacechecktype = Util.null2String(kqGroupComInfo.getLocationfacechecktype(groupid));//办公地点启用人脸识别拍照打卡方式 + String wififacecheck = Util.null2String(kqGroupComInfo.getWififacecheck(groupid));//wifi启用人脸识别拍照打卡 + String wififacechecktype = Util.null2String(kqGroupComInfo.getWififacechecktype(groupid));//wifi启用人脸识别拍照打卡方式 + logMap.put("locationshowaddress", locationshowaddress); + logMap.put("locationfacecheck", locationfacecheck); + logMap.put("locationfacechecktype", locationfacechecktype); + logMap.put("wififacecheck", wififacecheck); + logMap.put("wififacechecktype", wififacechecktype); + + boolean isAdmin = user.isAdmin(); + logMap.put("isAdmin", isAdmin); + if(isAdmin){ + retmap.put("showbutton", "0"); + retmap.put("status", "1"); + retmap.put("userid", user.getUID()); + KQCardLogBiz.logCardInfo(user.getUID()+"", logMap, workTimeEntityLogMap, "buttonBaseInfo"); + return retmap; + } +// * 1、PC和移动端均可打卡 +// * 2、仅PC可打卡 +// * 3、仅移动端可打卡 +// * 4、无需打卡 + String groupSignType = getSignType(); + logMap.put("groupSignType", groupSignType); + //无需打卡 + if("4".equalsIgnoreCase(groupSignType)){ + retmap.put("showbutton", "0"); + retmap.put("status", "1"); + retmap.put("userid", user.getUID()); + KQCardLogBiz.logCardInfo(user.getUID()+"", logMap, workTimeEntityLogMap, "buttonBaseInfo"); + return retmap; + } + if("2".equalsIgnoreCase(groupSignType)){ + if("1".equalsIgnoreCase(ismobile)){ + retmap.put("showbutton", "0"); + retmap.put("status", "1"); + retmap.put("userid", user.getUID()); + KQCardLogBiz.logCardInfo(user.getUID()+"", logMap, workTimeEntityLogMap, "buttonBaseInfo"); + return retmap; + } + } + if("3".equalsIgnoreCase(groupSignType)){ + if(!"1".equalsIgnoreCase(ismobile)){ + retmap.put("showbutton", "0"); + retmap.put("status", "1"); + retmap.put("userid", user.getUID()); + KQCardLogBiz.logCardInfo(user.getUID()+"", logMap, workTimeEntityLogMap, "buttonBaseInfo"); + return retmap; + } + } + + if(groupid.length() > 0){ + groupname = SystemEnv.getHtmlLabelName(10000801,weaver.general.Util.getIntValue(user.getLanguage()))+kqGroupComInfo.getGroupname(groupid); + }else{ + groupname = SystemEnv.getHtmlLabelName(10000799,weaver.general.Util.getIntValue(user.getLanguage())); + retmap.put("showbutton", "0"); + } + + retmap.put("hasCrmModule", SysModuleInfoBiz.checkModuleStatus(ModuleConstants.Crm)); + + retmap.put("userid", user.getUID()); + retmap.put("lastname", lastname); + retmap.put("shortname", shortname); + retmap.put("messagerurl", messagerurl); + retmap.put("groupname", groupname); + retmap.put("locationshowaddress", locationshowaddress); + retmap.put("locationfacecheck", locationfacecheck); + retmap.put("locationfacechecktype", locationfacechecktype); + retmap.put("wififacecheck", wififacecheck); + retmap.put("wififacechecktype", wififacechecktype); + retmap.put("date", curDate); + retmap.put("timemillis", System.currentTimeMillis()); + retmap.put("wificheck",Util.null2String(kqGroupComInfo.getWificheck(groupid)).equals("1")); + retmap.put("locationcheck",Util.null2String(kqGroupComInfo.getLocationcheck(groupid)).equals("1")); + retmap.put("locationcheckscope",Util.null2String(kqGroupComInfo.getLocationcheckscope(groupid))); + + String user_last_map = get_user_last_map(user.getUID()+""); + logMap.put("user_last_map", user_last_map); + if(user_last_map.length() > 0){ + retmap.put("user_last_map", user_last_map); + } + + retmap.put("isFirstLocation", KQSettingsBiz.isFirstLocation()?"1":"0"); + retmap.put("status", "1"); + }catch (Exception e) { + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(382661,user.getLanguage())); + writeLog(e); + } + kqLog.info(user.getLastname()+":GetButtonBaseInfoCmd:retmap:"+retmap); + logMap.put("result", retmap); + KQCardLogBiz.logCardInfo(user.getUID()+"", logMap, workTimeEntityLogMap, "buttonBaseInfo"); + return retmap; + } + + /** + * 获取当前用户选择的地图 + * @param userid + */ + public static String get_user_last_map(String userid) { + RecordSet rs = new RecordSet(); + String sql = "select * from user_last_map where userid = ? "; + rs.executeQuery(sql, userid); + if(rs.next()){ + return rs.getString("last_map"); + } + return ""; + } + + /** + * 获取考勤组的考勤方式 + * 1、PC和移动端均可打卡 + * 2、仅PC可打卡 + * 3、仅移动端可打卡 + */ + private String getSignType() { + KQGroupMemberComInfo kqGroupMemberComInfo = new KQGroupMemberComInfo(); + KQGroupEntity kqGroupEntity = kqGroupMemberComInfo.getUserKQGroupInfo(user.getUID()+""); + if(kqGroupEntity == null){ + return ""; + } + return kqGroupEntity.getSignintype(); + } + + @Override + public BizLogContext getLogContext() { + return null; + } + +} diff --git a/src/com/engine/kq/cmd/attendanceButton/GetButtonsCmd.java b/src/com/engine/kq/cmd/attendanceButton/GetButtonsCmd.java new file mode 100644 index 0000000..d4bec2f --- /dev/null +++ b/src/com/engine/kq/cmd/attendanceButton/GetButtonsCmd.java @@ -0,0 +1,1522 @@ +package com.engine.kq.cmd.attendanceButton; + +import com.alibaba.fastjson.JSON; +import com.engine.common.biz.AbstractCommonCommand; +import com.engine.common.entity.BizLogContext; +import com.engine.core.interceptor.CommandContext; +import com.engine.kq.bean.KQHrmScheduleSign; +import com.engine.kq.biz.KQCardLogBiz; +import com.engine.kq.biz.KQGroupComInfo; +import com.engine.kq.biz.KQGroupMemberComInfo; +import com.engine.kq.biz.KQReportBiz; +import com.engine.kq.biz.KQScheduleSignBiz; +import com.engine.kq.biz.KQTimesArrayComInfo; +import com.engine.kq.biz.KQWorkTime; +import com.engine.kq.entity.KQGroupEntity; +import com.engine.kq.entity.WorkTimeEntity; +import com.engine.kq.log.KQLog; +import com.engine.kq.util.KQDurationCalculatorUtil; +import com.google.common.collect.Maps; +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 weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.dateformat.DateTransformer; +import weaver.general.BaseBean; +import weaver.general.Util; +import weaver.hrm.User; +import weaver.hrm.resource.ResourceComInfo; +import weaver.systeminfo.SystemEnv; + +/** + * 获取签到签退按钮 + * 以及考勤流程数据 + * 以及上次签到时间 + */ +public class GetButtonsCmd extends AbstractCommonCommand> { + + private KQLog kqLog = new KQLog(); + private String curDate = DateUtil.getCurrentDate(); + private LocalDateTime now = LocalDateTime.now(); + private DateTimeFormatter fullFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + private DateTimeFormatter datetimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); + private DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm"); + private DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + private DateTimeFormatter fullTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss"); + private Map logMap = Maps.newHashMap(); + private Map workTimeEntityLogMap = Maps.newHashMap(); + + public GetButtonsCmd(Map params, User user) { + this.user = user; + this.params = params; + String now_date = now.format(dateFormatter); + String now_time = now.format(fullTimeFormatter); + LocalDateTime now_zone = getZoneOfClientDateTime(now_date,now_time, logMap); + if(now_zone != null){ + setNow(now_zone); + setCurDate(now_zone.format(dateFormatter)); + } + } + + /** + * 一个完整的timelines里map的样子 + * { + * across: "0" 是否是次日 + * active: "1" 是否是允许签到签退的范围 + * belongdate: "2018-12-27" 根据班次获取的所属日期 + * canSignTime: "2018-12-27 00:00:00" 允许签到签退的时间范围 + * date: "2018-12-27" 签到签退的日期 + * datetime: "2018-12-27 08:30:00" 签到签退日期+上下班时间 + * isYellow: "1" 当前时间是否已经是迟到或者早退 + * isacross: "0" 当前时间对应的班次是否是跨天班次 + * islastsign: "0" 是否是最后一次签退 + * min: "0" 允许打卡时段控制 + * needSign: "1" 是否可以签到签退,在active的基础上增加了hrmschedulesign签到签退数据的判断 + * pre: "0" 是否是昨日 + * serialid: "521" 班次id + * signsection: "2018-12-27 00:00:00#2018-12-27 14:00:00" 允许签到签退的范围 + * time: "08:30" 上班时间/下班时间 + * type: "on" 对应的是签到还是签退的状态 + * workdatesection: "2018-12-27 08:30:00#2018-12-27 11:30:00" 上下班日期时段 + * worksection: "08:30-11:30" 上下班时间 + * } + * @param commandContext + * @return + */ + @Override + public Map execute(CommandContext commandContext) { + logMap.put("lastname", user.getLastname()); + logMap.put("params", params); + kqLog.info(user.getLastname()+":GetButtonsCmd:params:"+params); + Map retmap = new HashMap(); + RecordSet rs = new RecordSet(); + String sql = ""; + try{ + curDate = getCurDate(); + //真正的考勤时间线 + List timelineList = new ArrayList<>(); + DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + + KQGroupMemberComInfo kqGroupMemberComInfo = new KQGroupMemberComInfo(); + KQGroupComInfo kqGroupComInfo = new KQGroupComInfo(); + ResourceComInfo resourceComInfo = new ResourceComInfo(); + KQReportBiz kqReportBiz = new KQReportBiz(); + + String lastname = user.getLastname(); + String messagerurl = resourceComInfo.getMessagerUrls(""+user.getUID()); + String shortname = ""; + + String ismobile = Util.null2String(params.get("ismobile")); + + boolean USERICONLASTNAME = Util.null2String(new BaseBean().getPropValue("Others" , "USERICONLASTNAME")).equals("1"); + if(USERICONLASTNAME&&(messagerurl.indexOf("icon_w_wev8.jpg")>-1||messagerurl.indexOf("icon_m_wev8.jpg")>-1||messagerurl.indexOf("dummyContact.png")>-1)){ + shortname = User.getLastname(Util.null2String(Util.formatMultiLang(lastname, ""+user.getLanguage()))); + } + + String groupname = ""; + KQWorkTime kqWorkTime = new KQWorkTime(); + WorkTimeEntity workTimeEntity = kqWorkTime.getWorkTime(user.getUID()+"", curDate); + String userinfo = "#userid#"+user.getUID()+"#getUserSubCompany1#"+user.getUserSubCompany1()+"#getUserSubCompany1#"+user.getUserDepartment() + +"#getJobtitle#"+user.getJobtitle(); + workTimeEntityLogMap.put("resourceid", userinfo); + workTimeEntityLogMap.put("splitDate", curDate); + workTimeEntityLogMap.put("workTimeEntity", workTimeEntity); + String groupid = workTimeEntity.getGroupId(); + logMap.put("groupid", groupid); + String outsidesign = ""; + KQGroupEntity kqGroupEntity = kqGroupMemberComInfo.getUserKQGroupInfo(user.getUID()+""); + String kqGroupEntityInfo = kqGroupEntity != null ? JSON.toJSONString(kqGroupEntity): ""; + logMap.put("kqGroupEntityInfo", kqGroupEntityInfo); + if (kqGroupEntity != null) { + outsidesign = kqGroupEntity.getOutsidesign(); + }else{ + groupname = SystemEnv.getHtmlLabelName(10000799,weaver.general.Util.getIntValue(user.getLanguage())); + retmap.put("showbutton", "0"); + retmap.put("status", "1"); + retmap.put("groupname", groupname); + KQCardLogBiz.logCardInfo(user.getUID()+"", logMap, workTimeEntityLogMap, "buttons"); + return retmap; + } + + boolean isAdmin = user.isAdmin(); + if(isAdmin){ + retmap.put("showbutton", "0"); + retmap.put("status", "1"); + KQCardLogBiz.logCardInfo(user.getUID()+"", logMap, workTimeEntityLogMap, "buttons"); + return retmap; + } +// * 1、PC和移动端均可打卡 +// * 2、仅PC可打卡 +// * 3、仅移动端可打卡 +// * 4、无需打卡 + String groupSignType = getSignType(); + //无需打卡 + if("4".equalsIgnoreCase(groupSignType)){ + retmap.put("showbutton", "0"); + retmap.put("status", "1"); + KQCardLogBiz.logCardInfo(user.getUID()+"", logMap, workTimeEntityLogMap, "buttons"); + return retmap; + } + if("2".equalsIgnoreCase(groupSignType)){ + if("1".equalsIgnoreCase(ismobile)){ + retmap.put("showbutton", "0"); + retmap.put("status", "1"); + KQCardLogBiz.logCardInfo(user.getUID()+"", logMap, workTimeEntityLogMap, "buttons"); + return retmap; + } + } + if("3".equalsIgnoreCase(groupSignType)){ + if(!"1".equalsIgnoreCase(ismobile)){ + retmap.put("showbutton", "0"); + retmap.put("status", "1"); + KQCardLogBiz.logCardInfo(user.getUID()+"", logMap, workTimeEntityLogMap, "buttons"); + return retmap; + } + } + + String yesterday = LocalDate.parse(curDate).minusDays(1).format(dateFormatter); + String nextday = LocalDate.parse(curDate).plusDays(1).format(dateFormatter); + List yesterdayLineButton = new ArrayList<>(); + List todayLineButton = new ArrayList<>(); + List restLineButton = new ArrayList<>(); + + //弹性工作制 + List freeLineButton = new ArrayList<>(); + + //先获取考勤工作时段的按钮 上下班时间 + Map todayLineMap = KQDurationCalculatorUtil.getWorkButton(user, curDate,true); + //明天的班次可能会存在上班开始时间在前一天的情况,这个也需要考虑 + Map nextLineMap = KQDurationCalculatorUtil.getWorkButton(user, nextday,true); + boolean isfree = "1".equalsIgnoreCase(Util.null2String(todayLineMap.get("isfree"))); + logMap.put("todayLineMap", todayLineMap); + logMap.put("nextLineMap", nextLineMap); + + if(isfree){ + do4FreeLine(user,freeLineButton,todayLineMap); + if(freeLineButton != null && !freeLineButton.isEmpty()){ + timelineList.addAll(freeLineButton); + retmap.put("lastname", lastname); + retmap.put("shortname", shortname); + retmap.put("messagerurl", messagerurl); + retmap.put("groupname", groupname+SystemEnv.getHtmlLabelName(10000800,weaver.general.Util.getIntValue(user.getLanguage()))); + retmap.put("outsidesign", outsidesign); + retmap.put("date", curDate); + retmap.put("timeline", timelineList); + retmap.put("status", "1"); + KQCardLogBiz.logCardInfo(user.getUID()+"", logMap, workTimeEntityLogMap, "buttons"); + return retmap; + } + } + //每次打开考勤按钮的时候,都只能有一个活动按钮 + List activeList = new ArrayList<>(); + + if(!todayLineMap.isEmpty()){ + if(todayLineMap.get("pre_timelineList") != null){ + do4YesterdayLine(todayLineMap,yesterdayLineButton,kqReportBiz,timelineList,yesterday,activeList); + } + if(todayLineMap.get("timelineList") != null){ + do4TodayLine(todayLineMap,todayLineButton,kqReportBiz,timelineList,activeList); + }else{ + //节假日或者休息日需要默认给客户拼接一个timelineList + retmap.put("isrest", "1"); + //kqLog.info("yesterdayLineButton:"+yesterdayLineButton); + if(yesterdayLineButton.isEmpty()){ + List yesterdayLine = (List)todayLineMap.get("pre_timelineList"); + //kqLog.info("yesterdayLine:"+yesterdayLine); + if(yesterdayLine != null){ + Map offTimelineMap = (Map)yesterdayLine.get(yesterdayLine.size()-1); + //kqLog.info("offTimelineMap:"+offTimelineMap); + //kqLog.info("signAcross:"+Util.null2String(offTimelineMap.get("signAcross")).equalsIgnoreCase("1")); + if(offTimelineMap.containsKey("signAcross") && Util.null2String(offTimelineMap.get("signAcross")).equalsIgnoreCase("1")){ + Map offTimelineMapTmp = reBuildYesTimeMap(offTimelineMap,yesterday,"off"); + //kqLog.info("offTimelineMapTmp:"+offTimelineMapTmp); + yesterdayLineButton.add(offTimelineMapTmp); + } + } + } + do4RestLine(""+user.getUID(),restLineButton,yesterdayLineButton,nextLineMap); + timelineList.addAll(restLineButton); + } + }else{ + //节假日或者休息日需要默认给客户拼接一个timelineList + retmap.put("isrest", "1"); + do4RestLine(""+user.getUID(),restLineButton, null,nextLineMap); + timelineList.addAll(restLineButton); + } + if(!nextLineMap.isEmpty()){ + List nextdayLineButton = new ArrayList<>(); + do4NextdayLine(nextLineMap,nextdayLineButton,kqReportBiz,timelineList,nextday,activeList); + } + + if(groupid.length() > 0){ + groupname = SystemEnv.getHtmlLabelName(10000801,weaver.general.Util.getIntValue(user.getLanguage()))+kqGroupComInfo.getGroupname(groupid); + }else{ + groupname = SystemEnv.getHtmlLabelName(10000799,weaver.general.Util.getIntValue(user.getLanguage())); + } + + retmap.put("lastname", lastname); + retmap.put("shortname", shortname); + retmap.put("messagerurl", messagerurl); + retmap.put("groupname", groupname); + retmap.put("outsidesign", outsidesign); + retmap.put("date", curDate); + retmap.put("timeline", timelineList); + retmap.put("status", "1"); + retmap.put("now", now.format(fullFormatter)); + + kqLog.info(user.getLastname()+":GetButtonsCmd:timelineList:"+timelineList); + }catch (Exception e) { + retmap.put("status", "-1"); + retmap.put("message", SystemEnv.getHtmlLabelName(382661,user.getLanguage())); + writeLog(e); + kqLog.info("考勤按钮报错",e); + } + logMap.put("retmap", retmap); + KQCardLogBiz.logCardInfo(user.getUID()+"", logMap, workTimeEntityLogMap, "buttons"); + return retmap; + } + + /** + * 当日的考勤按钮处理 + * @param todayLineMap + * @param todayLineButton + * @param kqReportBiz + * @param timelineList + * @param activeList + */ + private void do4TodayLine(Map todayLineMap, List todayLineButton, + KQReportBiz kqReportBiz, List timelineList, + List activeList) { + + List todayLine = (List)todayLineMap.get("timelineList"); + if(todayLine != null && !todayLine.isEmpty()){ + getWorkTimeButton(false, todayLine,todayLineButton, false); + //获取当天的考勤数据 +// List reports = kqReportBiz.getKqDateInfo(""+user.getUID(),curDate,curDate,true); + List reports = new ArrayList<>(); + getSignButton(user.getUID()+"",todayLineButton,reports); + timelineList.addAll(todayLineButton); + } + } + + /** + * 明日的跨天到今天的考勤按钮处理 + * 只有一种情况,那就是明日的班次设置的开始打卡时间在今天 + * 所以只有上班时间有这个情况要处理 + * @param nextLineMap + * @param nextdayLineButton + * @param kqReportBiz + * @param timelineList + * @param nextday + * @param activeList + */ + private void do4NextdayLine(Map nextLineMap, + List nextdayLineButton, KQReportBiz kqReportBiz, + List timelineList, String nextday, List activeList) { + + List nextdayLine = (List)nextLineMap.get("timelineList"); + if(nextdayLine != null && !nextdayLine.isEmpty()){ + Map onTimelineMap = (Map) nextdayLine.get(0); + if(onTimelineMap.containsKey("sign_preAcross")){ + boolean is_sign_preAcross = "1".equalsIgnoreCase(Util.null2String(onTimelineMap.get("sign_preAcross"))); + if(!is_sign_preAcross){ + return ; + } + } + getWorkTimeButton(false, nextdayLine,nextdayLineButton,true); + List reports = new ArrayList<>(); + getSignButton(user.getUID()+"",nextdayLineButton,reports); + timelineList.addAll(nextdayLineButton); + } + } + + /** + * 昨日跨天的考勤按钮处理 + * @param yesterdayLineMap + * @param yesterdayLineButton + * @param kqReportBiz + * @param timelineList + * @param yesterday + * @param activeList + */ + private void do4YesterdayLine(Map yesterdayLineMap, + List yesterdayLineButton, KQReportBiz kqReportBiz, + List timelineList, String yesterday, List activeList) { + + List yesterdayLine = (List)yesterdayLineMap.get("pre_timelineList"); + if(yesterdayLine != null && !yesterdayLine.isEmpty()){ + getWorkTimeButton(true, yesterdayLine,yesterdayLineButton, false); + //获取前一天的考勤数据 +// List reports = kqReportBiz.getKqDateInfo(""+user.getUID(),yesterday,yesterday,true); + List reports = new ArrayList<>(); + getSignButton(user.getUID()+"",yesterdayLineButton,reports); + timelineList.addAll(yesterdayLineButton); + } + } + + /** + * 针对自由工作制的人员单独处理 + * @param user + * @param freeLineButton + * @param todayLineMap + */ + private void do4FreeLine(User user, List freeLineButton, + Map todayLineMap) { + String resourceId = ""+user.getUID(); + if(todayLineMap != null && !todayLineMap.isEmpty()){ + LocalTime curTime = now.toLocalTime(); + + String signStart = Util.null2String(todayLineMap.get("signStart"));//签到开始时间 + String workMins = Util.null2String(todayLineMap.get("workMins"));//工作时长 + LocalTime signStartLocal = LocalTime.parse(signStart+":00", fullTimeFormatter); + boolean canSign = false; + if(curTime.isAfter(signStartLocal)){ + canSign = true; + } + + String signDateTimeSql = " signtime >= '"+signStart+":00"+"'"; + + KQScheduleSignBiz kqScheduleSignBiz = new KQScheduleSignBiz.KQScheduleSignParamBuilder().resourceidParam(resourceId) + .userTypeParam(user.getLogintype()).signDateParam(curDate).signDateTimeSqlParam(signDateTimeSql).build(); + List kqHrmScheduleSigns = kqScheduleSignBiz.getFreeScheduleSignInfo(); + if(kqHrmScheduleSigns != null && !kqHrmScheduleSigns.isEmpty()) { + int i = 0 ; + for(KQHrmScheduleSign sign : kqHrmScheduleSigns){ + String signtype = sign.getSigntype(); + String signtime = sign.getSigntime(); + String signdate = sign.getSigndate(); + String signStatus = sign.getSignstatus(); + String addr = sign.getAddr(); + + if(i%2 == 0){ + //签到 + freeLineButton.add(reBuildFreeButton("on", curDate, "0", "0",signtime,addr)); + }else{ +// 签退 + freeLineButton.add(reBuildFreeButton("off", curDate, "0", "0",signtime,addr)); + } + + i++; + } + //i是加1之后的结果 + if(i%2 == 0){ + //如果是成对存在的,那么需要再多出来俩,支持多次签到签退 + freeLineButton.add(reBuildFreeButton("on", curDate, "1", canSign?"1":"0","","")); + freeLineButton.add(reBuildFreeButton("off", curDate, "0", "0","","")); + }else{ + //如果不是成对存在,一定是签到多,签退少,当前处于需要签退的状态 + freeLineButton.add(reBuildFreeButton("off", curDate, "1", "1","","")); + } + + }else{ + //如果没有考勤数据,那么就是先签到再签退 + freeLineButton.add(reBuildFreeButton("on", curDate, "1", canSign?"1":"0","","")); + freeLineButton.add(reBuildFreeButton("off", curDate, "0", "0","","")); + } + } + + } + + private Map reBuildFreeButton(String type,String date,String active,String needSign,String signTime,String position){ + Map freetimelineMap = new HashMap<>(); + freetimelineMap.put("type", type); + freetimelineMap.put("belongdate", date); + freetimelineMap.put("date", date); + freetimelineMap.put("active", active); + freetimelineMap.put("needSign", needSign); + freetimelineMap.put("signTime", signTime); + freetimelineMap.put("position", position); + freetimelineMap.put("time", ""); + freetimelineMap.put("isfree", "1"); + + return freetimelineMap; + } + + /** + * 真对非工作时间的签到签退 + * @param resourceId + * @param restLineButton + * @param yesterdayLineButton + * @param nextLineMap + */ + private void do4RestLine(String resourceId, List restLineButton, + List yesterdayLineButton, + Map nextLineMap) { + boolean hasSignIn = false; + boolean hasSignOut = false; + boolean isActive = true; + Map timelineOnMap = new HashMap<>(); + timelineOnMap.put("type", "on"); + timelineOnMap.put("time", ""); + timelineOnMap.put("isfirstsign", "1"); + timelineOnMap.put("belongdate", curDate); + timelineOnMap.put("date", curDate); + Map timelineOffMap = new HashMap<>(); + timelineOffMap.put("type", "off"); + timelineOffMap.put("time", ""); + timelineOffMap.put("islastsign", "1"); + timelineOffMap.put("belongdate", curDate); + timelineOffMap.put("date", curDate); + String yesterday = LocalDate.parse(curDate).minusDays(1).format(dateFormatter); + String canSignTime = ""; + String next_canSignTime = ""; + String signDateTimeSql = ""; + //kqLog.info("do4RestLine::yesterdayLineButton"+yesterdayLineButton); + if(yesterdayLineButton != null && !yesterdayLineButton.isEmpty()){ + Map yesterdayMap = (Map)yesterdayLineButton.get(yesterdayLineButton.size()-1); + //kqLog.info("do4RestLine::yesterdayMap"+yesterdayMap); + if(yesterdayMap != null){ + canSignTime = Util.null2String(yesterdayMap.get("canSignTime")); + kqLog.info("do4RestLine::canSignTime"+canSignTime); + if(canSignTime != null && canSignTime.length() > 0){ + LocalTime localTime = LocalTime.parse(canSignTime, timeFormatter); + localTime = localTime.plusMinutes(1); + canSignTime = localTime.format(timeFormatter); + } + } + } + if(!nextLineMap.isEmpty()){ + List nextdayLine = (List)nextLineMap.get("timelineList"); + if(nextdayLine != null && !nextdayLine.isEmpty()){ + Map onTimelineMap = (Map) nextdayLine.get(0); + if(onTimelineMap.containsKey("sign_preAcross")){ + boolean is_sign_preAcross = "1".equalsIgnoreCase(Util.null2String(onTimelineMap.get("sign_preAcross"))); + if(is_sign_preAcross){ + int tMin = Util.getIntValue(Util.null2String(onTimelineMap.get("min"))); + String time = Util.null2String(onTimelineMap.get("time")); + String nextday = LocalDate.parse(curDate).plusDays(1).format(dateFormatter); + String next_date_canSignTime = nextday + " "+ time + ":00"; + if(tMin > 0) { + LocalDateTime tmpLocalDateTime = LocalDateTime.parse(next_date_canSignTime, fullFormatter).minusMinutes(tMin); + next_canSignTime = tmpLocalDateTime.format(timeFormatter); + } + } + } + } + + } + if(canSignTime.length() > 0){ + signDateTimeSql = " signtime >= '"+canSignTime+":00"+"'"; + timelineOnMap.put("signSectionTime",curDate+" "+canSignTime+":00"); + timelineOnMap.put("signSection",curDate+" "+canSignTime+":00"+"#"+curDate+" "+"23:59:59"); + timelineOnMap.put("canSignTime","00:00:00"); + timelineOffMap.put("signSectionTime",curDate+" "+"23:59:59"); + timelineOffMap.put("canSignTime","23:59:59"); + timelineOffMap.put("signSection",curDate+" "+canSignTime+":00"+"#"+curDate+" "+"23:59:59"); + if(next_canSignTime.length() > 0){ + signDateTimeSql += " and signtime <= '"+next_canSignTime+":59"+"'"; + String offSignSectionTime = curDate+" "+next_canSignTime+":59"; + LocalDateTime offLocalDateTime = LocalDateTime.parse(offSignSectionTime,fullFormatter); + if(now.isAfter(offLocalDateTime)){ + isActive = false; + } + timelineOffMap.put("signSectionTime",curDate+" "+next_canSignTime+":59"); + timelineOffMap.put("canSignTime",next_canSignTime+":59"); + timelineOffMap.put("signSection",curDate+" "+canSignTime+":00"+"#"+curDate+" "+next_canSignTime+":59"); + } + String onSignSectionTime = curDate+" "+canSignTime+":00"; + LocalDateTime onLocalDateTime = LocalDateTime.parse(onSignSectionTime,fullFormatter); + if(now.isBefore(onLocalDateTime)){ + isActive = false; + } + }else{ + timelineOnMap.put("signSectionTime",curDate+" "+"00:00:00"); + timelineOnMap.put("canSignTime","00:00:00"); + timelineOnMap.put("signSection",curDate+" "+"00:00:00"+":00"+"#"+curDate+" "+"23:59:59"); + timelineOffMap.put("signSectionTime",curDate+" "+"23:59:59"); + timelineOffMap.put("canSignTime","23:59:59"); + timelineOffMap.put("signSection",curDate+" "+"00:00:00"+":00"+"#"+curDate+" "+"23:59:59"); + if(next_canSignTime.length() > 0){ + String offSignSectionTime = curDate+" "+next_canSignTime+":59"; + LocalDateTime offLocalDateTime = LocalDateTime.parse(offSignSectionTime,fullFormatter); + if(now.isAfter(offLocalDateTime)){ + isActive = false; + } + signDateTimeSql += " signtime <= '"+next_canSignTime+":59"+"'"; + timelineOffMap.put("signSectionTime",curDate+" "+next_canSignTime+":59"); + timelineOffMap.put("canSignTime",next_canSignTime+":59"); + timelineOnMap.put("signSection",curDate+" "+"00:00:00"+":00"+"#"+curDate+" "+next_canSignTime+":59"); + timelineOffMap.put("signSection",curDate+" "+"00:00:00"+":00"+"#"+curDate+" "+next_canSignTime+":59"); + } + } + + KQScheduleSignBiz kqScheduleSignBiz = new KQScheduleSignBiz.KQScheduleSignParamBuilder().resourceidParam(resourceId) + .userTypeParam(user.getLogintype()).signDateParam(curDate).signDateTimeSqlParam(signDateTimeSql).build(); + Map signMap = kqScheduleSignBiz.getScheduleSignInfo(); + if(signMap != null && !signMap.isEmpty()) { + KQHrmScheduleSign signInTimeBean = signMap.get("signin"); + KQHrmScheduleSign signOutTimeBean = signMap.get("signout"); + if(signInTimeBean != null){ + String signtimeTmp = Util.null2String(signInTimeBean.getSigntime()); + timelineOnMap.put("signTime", signtimeTmp); + timelineOnMap.put("position", Util.null2String(signInTimeBean.getAddr())); + hasSignIn = true; + } + if(signOutTimeBean != null){ + String signtimeTmp = Util.null2String(signOutTimeBean.getSigntime()); + timelineOffMap.put("signTime", signtimeTmp); + timelineOffMap.put("position", Util.null2String(signOutTimeBean.getAddr())); + hasSignOut = true; + } + if(hasSignIn){ + //有签到 就记录下 + timelineOffMap.put("signInTime4Out", timelineOnMap.get("signTime")); + } + } + getActiveRestSign(isActive, hasSignIn, hasSignOut, timelineOnMap, timelineOffMap); + restLineButton.add(timelineOnMap); + restLineButton.add(timelineOffMap); + } + + /** + * 获取考勤组的考勤方式 + * 1、PC和移动端均可打卡 + * 2、仅PC可打卡 + * 3、仅移动端可打卡 + */ + private String getSignType() { + KQGroupMemberComInfo kqGroupMemberComInfo = new KQGroupMemberComInfo(); + KQGroupEntity kqGroupEntity = kqGroupMemberComInfo.getUserKQGroupInfo(user.getUID()+""); + if(kqGroupEntity == null){ + return ""; + } + return kqGroupEntity != null ? kqGroupEntity.getSignintype(): ""; + } + + /** + * 根据工作时段来获取对应工作时段下的签到签退数据 + * @param resourceId + * @param timelineList + * @param reports + */ + private void getSignButton(String resourceId,List timelineList,List reports) { + if(!timelineList.isEmpty()){ + //获取当前时间 + LocalDateTime now = getNow(); + + //因为工作时段是成对存在的,所以timelineList一定是两两一对的复数[0,1] [2,3] [4,5] + int count = timelineList.size(); + + int workCnt = 0; + for(int i = 0 ; i < count ; ){ + //成对出现的上下班时间 + int on_i = i; + int off_i = i+1; + Map timelineOnMap = (Map)timelineList.get(on_i); + Map timelineOffMap = (Map)timelineList.get(off_i); + if(timelineOnMap != null && !timelineOnMap.isEmpty() && timelineOffMap != null && !timelineOffMap.isEmpty()){ + String onTime = Util.null2String(timelineOnMap.get("time")); + String belongdate = Util.null2String(timelineOnMap.get("belongdate")); + //上班开始打卡时间 + String onSignSectionTime = Util.null2String(timelineOnMap.get("signSectionTime")); + //上班结束打卡时间 + String signSectionEndTime = Util.null2String(timelineOnMap.get("signSectionEndTime")); + String onDateTime = Util.null2String(timelineOnMap.get("datetime")); + String onIsacross = Util.null2String(timelineOnMap.get("isacross")); + + String offTime = Util.null2String(timelineOffMap.get("time")); + //下班开始打卡时间 + String signSectionBeginTime = Util.null2String(timelineOffMap.get("signSectionBeginTime")); + //下班结束打卡时间 + String offSignSectionTime = Util.null2String(timelineOffMap.get("signSectionTime")); + String offDateTime = Util.null2String(timelineOffMap.get("datetime")); + String offIsacross = Util.null2String(timelineOffMap.get("isacross")); + if(onSignSectionTime.length() == 0 || offSignSectionTime.length() == 0){ + kqLog.info(user.getLastname()+":"+curDate+":onSignSectionTime is null:"+onSignSectionTime+":offSignSectionTime is null:"+offSignSectionTime); + continue; + } + if(signSectionEndTime.length() == 0 || signSectionBeginTime.length() == 0){ + } + + LocalDateTime onLocalDateTime = LocalDateTime.parse(onSignSectionTime,fullFormatter); + LocalDateTime onLocalDateEndTime = null; + if(signSectionEndTime.length() > 0){ + onLocalDateEndTime = LocalDateTime.parse(signSectionEndTime,fullFormatter); + } + + LocalDateTime offLocalDateBeginTime = null; + if(signSectionBeginTime.length() > 0){ + offLocalDateBeginTime = LocalDateTime.parse(signSectionBeginTime,fullFormatter); + } + LocalDateTime offLocalDateTime = LocalDateTime.parse(offSignSectionTime,fullFormatter); + + LocalDateTime onworkDateTime = LocalDateTime.parse(onDateTime,fullFormatter); + LocalDateTime offworkDateTime = LocalDateTime.parse(offDateTime,fullFormatter); + + if("1".equalsIgnoreCase(onIsacross)){ + onTime = new KQTimesArrayComInfo().turn24to48Time(onTime); + timelineOffMap.put("belongtime", onTime); + } + if("1".equalsIgnoreCase(offIsacross)){ + offTime = new KQTimesArrayComInfo().turn24to48Time(offTime); + timelineOffMap.put("belongtime", offTime); + } + String worksection = onTime+"-"+offTime; + String signSection = onSignSectionTime+"#"+offSignSectionTime; + timelineOnMap.put("signSection", signSection); + timelineOnMap.put("signSectionEndTime", signSectionEndTime); + timelineOffMap.put("signSection", signSection); + timelineOffMap.put("signSectionBeginTime", signSectionBeginTime); + + if(i == (count-2)){ + //如果当前工作时段是最后一个工作时段 + timelineOnMap.put("islastsign", "1"); + timelineOffMap.put("islastsign", "1"); + }else{ + timelineOnMap.put("islastsign", "0"); + timelineOffMap.put("islastsign", "0"); + } + if(i == 0){ + timelineOnMap.put("isfirstsign", "1"); + }else{ + timelineOnMap.put("isfirstsign", "0"); + } + + boolean hasSignIn = false; + boolean hasSignOut = false; + //是否在这个整体的签到签退范围内 + boolean isActive = false; + //签到是否在允许的打卡范围内 + boolean isOnActive = false; + //签推是否在允许的打卡范围内 + boolean isOffActive = false; + if((now.isAfter(onLocalDateTime) && now.isBefore(offLocalDateTime))||(now.isEqual(onLocalDateTime))||(now.isEqual(offLocalDateTime))){ + isActive = true; + } + + if(now.isAfter(onworkDateTime)){ + timelineOnMap.put("isYellow", "1"); + }else{ + timelineOnMap.put("isYellow", "0"); + } + if(now.isBefore(offworkDateTime)){ + timelineOffMap.put("isYellow", "1"); + }else{ + timelineOffMap.put("isYellow", "0"); + } + if(onSignSectionTime.length() == 0 || offSignSectionTime.length() == 0){ + timelineOnMap.put("active", "0"); + timelineOffMap.put("active", "0"); + timelineOnMap.put("needSign", "0"); + timelineOffMap.put("needSign", "0"); + kqLog.info("考勤按钮报错:"+user.getLastname()+"::"+curDate+":onSignSectionTime:"+onSignSectionTime+":offSignSectionTime:"+offSignSectionTime); + return ; + } + //针对签到签退数据获取用的 + String sign_signSectionTime = ""; + String sign_signSectionEndTime = ""; + String sign_signSectionBeginTime = ""; + String sign_offSignSectionTime = ""; + if(signSectionEndTime.length() == 0 && signSectionBeginTime.length() == 0){ + //如果没设置上班后,下班前打卡 + sign_signSectionTime = onSignSectionTime; + sign_offSignSectionTime = offSignSectionTime; + }else{ + if(signSectionEndTime.length() > 0){ + if(signSectionBeginTime.length() > 0){ + //如果上班后,下班前打卡范围都做了控制 + if((now.isAfter(onLocalDateTime) && now.isBefore(onLocalDateEndTime)) ||(now.isEqual(onLocalDateTime))||(now.isEqual(onLocalDateEndTime))){ + isOnActive = true; + } + if((now.isAfter(offLocalDateBeginTime) && now.isBefore(offLocalDateTime)) ||(now.isEqual(offLocalDateBeginTime))||(now.isEqual(offLocalDateTime))){ + isOffActive = true; + } + String onSignSection = onLocalDateTime.format(fullFormatter)+"#"+onLocalDateEndTime.format(fullFormatter); + String offSignSection = offLocalDateBeginTime.format(fullFormatter)+"#"+offLocalDateTime.format(fullFormatter); + timelineOnMap.put("signSection", onSignSection); + timelineOffMap.put("signSection", offSignSection); + sign_signSectionTime = onSignSectionTime; + sign_signSectionEndTime = signSectionEndTime; + sign_signSectionBeginTime = signSectionBeginTime; + sign_offSignSectionTime = offSignSectionTime; + + }else{ + //如果只是上班后打卡范围做了控制 + if((now.isAfter(onLocalDateTime) && now.isBefore(onLocalDateEndTime)) ||(now.isEqual(onLocalDateTime))||(now.isEqual(onLocalDateEndTime))){ + isOnActive = true; + } + LocalDateTime tmp = LocalDateTime.parse(onLocalDateEndTime.plusMinutes(1).format(datetimeFormatter)+":00",fullFormatter); + String tmp_datetime = tmp.format(fullFormatter); + if((now.isAfter(tmp) && now.isBefore(offLocalDateTime)) ||(now.isEqual(tmp))||(now.isEqual(offLocalDateTime))){ + isOffActive = true; + } + String onSignSection = onLocalDateTime.format(fullFormatter)+"#"+onLocalDateEndTime.format(fullFormatter); + String offSignSection = tmp.format(fullFormatter)+"#"+offLocalDateTime.format(fullFormatter); + timelineOnMap.put("signSection", onSignSection); + timelineOffMap.put("signSection", offSignSection); + sign_signSectionTime = onSignSectionTime; + sign_signSectionEndTime = signSectionEndTime; + sign_signSectionBeginTime = tmp_datetime; + sign_offSignSectionTime = offSignSectionTime; + + } + }else if(signSectionBeginTime.length() > 0){ + //如果只是下班前打卡范围做了控制 + LocalDateTime tmp = LocalDateTime.parse(offLocalDateBeginTime.minusMinutes(1).format(datetimeFormatter)+":59",fullFormatter); + String tmp_datetime = tmp.format(fullFormatter); + if((now.isAfter(onLocalDateTime) && now.isBefore(tmp)) ||(now.isEqual(onLocalDateTime))||(now.isEqual(tmp))){ + isOnActive = true; + } + if((now.isAfter(offLocalDateBeginTime) && now.isBefore(offLocalDateTime)) ||(now.isEqual(offLocalDateBeginTime))||(now.isEqual(offLocalDateTime))){ + isOffActive = true; + } + String onSignSection = onLocalDateTime.format(fullFormatter)+"#"+tmp_datetime; + String offSignSection = offLocalDateBeginTime.format(fullFormatter)+"#"+offLocalDateTime.format(fullFormatter); + timelineOnMap.put("signSection", onSignSection); + timelineOffMap.put("signSection", offSignSection); + sign_signSectionTime = onSignSectionTime; + sign_signSectionEndTime = tmp_datetime; + sign_signSectionBeginTime = signSectionBeginTime; + sign_offSignSectionTime = offSignSectionTime; + } + + timelineOnMap.put("signSectionEndTime", sign_signSectionEndTime); + timelineOffMap.put("signSectionBeginTime", sign_signSectionBeginTime); + } + KQScheduleSignBiz kqScheduleSignBiz = new KQScheduleSignBiz.KQScheduleSignParamBuilder().resourceidParam(resourceId) + .userTypeParam(user.getLogintype()).signSectionTimeParam(sign_signSectionTime) + .signSectionEndTimeParam(sign_signSectionEndTime).signSectionBeginTimeParam(sign_signSectionBeginTime) + .offSignSectionTimeParam(sign_offSignSectionTime).build(); + + Map signMap = kqScheduleSignBiz.getScheduleSignInfoWithCardRange(); + if(signMap != null && !signMap.isEmpty()){ + KQHrmScheduleSign signInTimeBean = signMap.get("signin"); + KQHrmScheduleSign signOutTimeBean = signMap.get("signout"); + if(signInTimeBean != null){ + String signdate = Util.null2String(signInTimeBean.getSigndate()); + String signtimeTmp = Util.null2String(signInTimeBean.getSigntime()); + String signfrom = Util.null2String(signInTimeBean.getSignfrom()); + timelineOnMap.put("signfrom", signfrom); + timelineOnMap.put("signbelong", "today"); + timelineOnMap.put("signbelongspan", SystemEnv.getHtmlLabelName(15537, user.getLanguage())); + if(signdate.compareTo(curDate) < 0){ + timelineOnMap.put("signbelong", "yesterday"); + timelineOnMap.put("signbelongspan", SystemEnv.getHtmlLabelName(82640, user.getLanguage())); + } + timelineOnMap.put("signTime", signtimeTmp); + timelineOnMap.put("position", Util.null2String(signInTimeBean.getAddr())); + hasSignIn = true; + } + if(signOutTimeBean != null){ + String signdate = Util.null2String(signOutTimeBean.getSigndate()); + String signtimeTmp = Util.null2String(signOutTimeBean.getSigntime()); + String signfrom = Util.null2String(signOutTimeBean.getSignfrom()); + timelineOffMap.put("signfrom", signfrom); + timelineOffMap.put("signbelong", SystemEnv.getHtmlLabelName(15537, user.getLanguage())); + timelineOffMap.put("signbelongspan", SystemEnv.getHtmlLabelName(15537, user.getLanguage())); + if(signdate.compareTo(curDate) < 0){ + timelineOffMap.put("signbelong", SystemEnv.getHtmlLabelName(82640, user.getLanguage())); + timelineOffMap.put("signbelongspan", SystemEnv.getHtmlLabelName(82640, user.getLanguage())); + } + timelineOffMap.put("signTime", signtimeTmp); + timelineOffMap.put("position", Util.null2String(signOutTimeBean.getAddr())); + hasSignOut = true; + } + } + //根据考勤工作时段获取相应时段下的签到签退数据 + if(!reports.isEmpty()){ + updateStatusByReport(reports,belongdate, timelineOnMap, timelineOffMap,worksection); + } + if(signSectionEndTime.length() == 0 && signSectionBeginTime.length() == 0){ + getActiveRestSign(isActive, hasSignIn, hasSignOut, timelineOnMap, timelineOffMap); + }else{ + getActiveSign(isActive, hasSignIn, hasSignOut, timelineOnMap, timelineOffMap,isOnActive,isOffActive); + } + } + + i = i + 2; + workCnt++; + } + } + + } + + /** + * 根据考勤报表数据,更新打卡界面状态 + * @param reports + * @param belongdate + * @param timelineOnMap + * @param timelineOffMap + * @param worksection + */ + public void updateStatusByReport(List reports, String belongdate, + Map timelineOnMap, + Map timelineOffMap, String worksection) { + List checkInfoList = new ArrayList<>(); + for(int i = 0 ; i < reports.size() ; i++){ + Map reportData = (Map) reports.get(i); + if(reportData != null && !reportData.isEmpty()){ + String kqdate = Util.null2String(reportData.get("kqdate")); + if(belongdate.equalsIgnoreCase(kqdate)){ + checkInfoList = (List) reportData.get("checkInfo"); + if(checkInfoList != null && !checkInfoList.isEmpty()){ + for(int j = 0 ; j < checkInfoList.size() ; j++){ + Map kqData = (Map) checkInfoList.get(j); + String workbegintime = Util.null2String(kqData.get("workbegintime")); + String workendtime = Util.null2String(kqData.get("workendtime")); + if(worksection.equalsIgnoreCase((workbegintime+"-"+workendtime))){ + //如果有考勤数据,再根据考勤数据同步更新下 + setStatusByReport(kqData,timelineOnMap,timelineOffMap); + break; + } + } + } + } + } + } + + } + + /** + * 根据考勤报表数据返回签到签退按钮状态 + * @param reportData + * @param timelineOnMap + * @param timelineOffMap + */ + private void setStatusByReport(Map reportData, Map timelineOnMap, Map timelineOffMap) { + + String status = Util.null2String(reportData.get("status")); + if(status.contains(ButtonStatusEnum.ABSENT.getStatusCode())){ + //旷工 旷工大于一切 + timelineOnMap.put("status", ButtonStatusEnum.ABSENT.getStatusCode()); + timelineOffMap.put("status", ButtonStatusEnum.ABSENT.getStatusCode()); + return ; + } + if(status.contains(ButtonStatusEnum.NORMAL.getStatusCode())){ + timelineOnMap.put("status", ButtonStatusEnum.NORMAL.getStatusCode()); + timelineOffMap.put("status", ButtonStatusEnum.NORMAL.getStatusCode()); + return ; + } + + if(status.contains(ButtonStatusEnum.BELATE.getStatusCode())){ + //迟到 + timelineOnMap.put("status", ButtonStatusEnum.BELATE.getStatusCode()); + } + if(status.contains(ButtonStatusEnum.LEAVEERALY.getStatusCode())){ + //早退 + timelineOffMap.put("status", ButtonStatusEnum.LEAVEERALY.getStatusCode()); + } + if(status.contains(ButtonStatusEnum.NOSIGN.getStatusCode())){ + //漏签 + timelineOffMap.put("status", ButtonStatusEnum.NOSIGN.getStatusCode()); + } + } + + private void getActiveRestSign(boolean isActive, boolean hasSignIn, boolean hasSignOut, + Map timelineOnMap, Map timelineOffMap) { + + if(isActive){ + if(hasSignIn){ + if(hasSignOut){ + //签到了,签退了 + timelineOnMap.put("active", "0"); + timelineOffMap.put("active", "0"); + + timelineOnMap.put("needSign", "0"); + timelineOffMap.put("needSign", "0"); + timelineOffMap.put("reSign", "1"); + + }else{ + //签到了,未签退 + timelineOnMap.put("active", "0"); + timelineOffMap.put("active", "1"); + + timelineOnMap.put("needSign", "0"); + timelineOffMap.put("needSign", "1"); + } + }else{ + if(hasSignOut){ + //未签到,签退了 理论上是不可能的 + + }else{ + //未签到未签退 + timelineOnMap.put("active", "1"); + timelineOffMap.put("active", "0"); + + timelineOnMap.put("needSign", "1"); + timelineOffMap.put("needSign", "0"); + } + } + + }else{ + //如果都不在考勤范围内肯定不能签到签退 + timelineOnMap.put("active", "0"); + timelineOffMap.put("active", "0"); + + timelineOnMap.put("needSign", "0"); + timelineOffMap.put("needSign", "0"); + + } + } + /** + * 生成时间轴上 需要签到和活动考勤点的标识 + * @param isActive + * @param hasSignIn + * @param hasSignOut + * @param timelineOnMap + * @param timelineOffMap + * @param isOnActive + * @param isOffActive + */ + private void getActiveSign(boolean isActive, boolean hasSignIn, boolean hasSignOut, + Map timelineOnMap, Map timelineOffMap, + boolean isOnActive, boolean isOffActive) { + + if(isActive){ + if(hasSignIn){ + if(hasSignOut){ + //签到了,签退了 + timelineOnMap.put("active", "0"); + timelineOnMap.put("needSign", "0"); + + timelineOffMap.put("active", "0"); + timelineOffMap.put("needSign", "0"); + if(isOffActive){ + timelineOffMap.put("reSign", "1"); + } + }else{ + //签到了,未签退 + timelineOnMap.put("active", "0"); + timelineOnMap.put("needSign", "0"); + + if(isOffActive){ + timelineOffMap.put("needSign", "1"); + timelineOffMap.put("active", "1"); + }else{ + timelineOffMap.put("needSign", "0"); + timelineOffMap.put("active", "0"); + } + } + }else{ + if(hasSignOut){ + //未签到,签退了 + if(isOnActive){ + timelineOnMap.put("active", "1"); + timelineOnMap.put("needSign", "1"); + }else{ + timelineOnMap.put("active", "0"); + } + + timelineOffMap.put("active", "0"); + timelineOffMap.put("needSign", "0"); + + if(isOffActive){ + timelineOffMap.put("reSign", "1"); + } + }else{ + //未签到未签退 + if(isOnActive){ + timelineOnMap.put("active", "1"); + timelineOnMap.put("needSign", "1"); + }else{ + timelineOnMap.put("active", "0"); + } + if(isOffActive){ + timelineOffMap.put("needSign", "1"); + timelineOffMap.put("active", "1"); + }else{ + timelineOffMap.put("active", "0"); + } + + } + } + + }else{ + //如果都不在考勤范围内肯定不能签到签退 + timelineOnMap.put("active", "0"); + timelineOffMap.put("active", "0"); + + timelineOnMap.put("needSign", "0"); + timelineOffMap.put("needSign", "0"); + + } + } + + /** + * 先根据工作时段把考勤timeline基本信息加载一下 + * @param isYesterday + * @param timeLine + * @param timeLineButton + * @param isNextday 是否是明日的 + */ + private void getWorkTimeButton(boolean isYesterday, List timeLine, + List timeLineButton, boolean isNextday) { + boolean show_yes_button = show_yes_button(); + DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + String yesterday = LocalDate.parse(curDate).minusDays(1).format(dateFormatter); + String nextday = LocalDate.parse(curDate).plusDays(1).format(dateFormatter); + String next_nextday = LocalDate.parse(nextday).plusDays(1).format(dateFormatter); + + for(int i = 0 ; i < timeLine.size() ;){ + Map onTimelineMap = (Map)timeLine.get(i); + Map offTimelineMap = (Map)timeLine.get(i+1); + if(isYesterday){ + //如果允许打卡时间也跨天,那么也需要显示出来按钮 + if(Util.null2String(offTimelineMap.get("signAcross")).equalsIgnoreCase("1")){ + Map onTimelineMapTmp = reBuildYesTimeMap(onTimelineMap,yesterday,"on"); + Map offTimelineMapTmp = reBuildYesTimeMap(offTimelineMap,yesterday,"off"); + if(!show_yes_button && offTimelineMapTmp.containsKey("signSectionTime")){ + String signSectionTime = Util.null2s(Util.null2String(offTimelineMapTmp.get("signSectionTime")),""); + if(signSectionTime.length() > 0 && now.isAfter(LocalDateTime.parse(signSectionTime,fullFormatter))){ + i = i + 2; + continue; + } + } + timeLineButton.add(onTimelineMapTmp); + timeLineButton.add(offTimelineMapTmp); + } + }else if(isNextday){ + if(onTimelineMap.containsKey("sign_preAcross")){ + if("1".equalsIgnoreCase(Util.null2String(onTimelineMap.get("sign_preAcross")))){ + Map onTimelineMapTmp = reBuildNextTimeMap(onTimelineMap,nextday,next_nextday,"on"); + Map offTimelineMapTmp = reBuildNextTimeMap(offTimelineMap,nextday,next_nextday,"off"); + timeLineButton.add(onTimelineMapTmp); + timeLineButton.add(offTimelineMapTmp); + } + } + }else { + Map onTimelineMapTmp = reBuildTimeMap(onTimelineMap,nextday,"on"); + Map offTimelineMapTmp = reBuildTimeMap(offTimelineMap,nextday,"off"); + timeLineButton.add(onTimelineMapTmp); + timeLineButton.add(offTimelineMapTmp); + } + i = i + 2; + } + + } + + /** + * 是否显示昨日失效的考勤按钮 + * @return + */ + public boolean show_yes_button() { + boolean show_yes_button = true; + RecordSet rs = new RecordSet(); + String settingSql = "select * from KQ_SETTINGS where main_key='show_yes_button'"; + rs.executeQuery(settingSql); + if(rs.next()){ + String main_val = rs.getString("main_val"); + if(!"1".equalsIgnoreCase(main_val)){ + show_yes_button = false; + } + } + return show_yes_button; + } + + /** + * 针对前一天的工作时间 根据跨天判断重构一遍数据 + * @param timelineMap + * @param yesterday + * @param isOnOff + */ + private Map reBuildYesTimeMap(Map timelineMap, String yesterday, + String isOnOff) { + + Map lineMap = new HashMap<>(); + + String isacross = Util.null2String(timelineMap.get("isacross")); + String min = Util.null2String(timelineMap.get("min")); + String min_next = Util.null2String(timelineMap.get("min_next")); + String time = Util.null2String(timelineMap.get("time")); + String workmins = Util.null2String(timelineMap.get("workmins")); +// 打卡时段设置 一定是要开启的 + String isPunchOpen = "1"; + String signAcross = Util.null2String(timelineMap.get("signAcross")); + String signAcross_next = Util.null2String(timelineMap.get("signAcross_next")); + int tMin = Util.getIntValue(min,0); + int tMin_next = Util.getIntValue(min_next,-1); + + lineMap.put("type", timelineMap.get("type")); + lineMap.put("serialid", timelineMap.get("serialid")); + lineMap.put("isacross", isacross); + lineMap.put("time", time); + lineMap.put("belongtime", time); + lineMap.put("min", min); + lineMap.put("min_next", min_next); + lineMap.put("workmins", workmins); + lineMap.put("isPunchOpen", isPunchOpen); + lineMap.put("signAcross", signAcross); + lineMap.put("signAcross_next", signAcross_next); + + if("on".equalsIgnoreCase(isOnOff)){ + if("1".equalsIgnoreCase(isacross)){ + //上班时间,跨天 + lineMap.put("date", curDate);//打卡日期 + lineMap.put("belongdate", yesterday);//工作时段所属日期 + lineMap.put("pre", "0");//是否是昨日 + lineMap.put("across", "0");//是否是次日 + lineMap.put("datetime", curDate+" "+time+":00");//应打卡日期+时间 + + String canSignTime = curDate + " "+ time + ":00"; + if(tMin > 0) { + LocalDateTime tmpLocalDateTime = LocalDateTime.parse(canSignTime, fullFormatter).minusMinutes(tMin); + lineMap.put("signSectionTime",tmpLocalDateTime.format(fullFormatter)); + lineMap.put("canSignTime",tmpLocalDateTime.toLocalTime().format(timeFormatter)); + } + if(tMin_next > -1) { + canSignTime = curDate + " "+ time + ":59"; + LocalDateTime tmpLocalDateTime = LocalDateTime.parse(canSignTime, fullFormatter).plusMinutes(tMin_next); + lineMap.put("signSectionEndTime",tmpLocalDateTime.format(fullFormatter)); + lineMap.put("canSignEndTime",tmpLocalDateTime.toLocalTime().format(timeFormatter)); + } + }else{ + //上班时间,不跨天 + lineMap.put("date", yesterday); + lineMap.put("belongdate", yesterday); + lineMap.put("pre", "1"); + lineMap.put("across", "0"); + lineMap.put("datetime", yesterday+" "+time+":00");//应打卡日期+时间 + String canSignTime = yesterday + " "+ time + ":00"; + + if(tMin > 0) { + LocalDateTime tmpLocalDateTime = LocalDateTime.parse(canSignTime, fullFormatter).minusMinutes(tMin); + lineMap.put("signSectionTime",tmpLocalDateTime.format(fullFormatter)); + lineMap.put("canSignTime",tmpLocalDateTime.toLocalTime().format(timeFormatter)); + } + if(tMin_next > -1) { + canSignTime = yesterday + " "+ time + ":59"; + LocalDateTime tmpLocalDateTime = LocalDateTime.parse(canSignTime, fullFormatter).plusMinutes(tMin_next); + lineMap.put("signSectionEndTime",tmpLocalDateTime.format(fullFormatter)); + lineMap.put("canSignEndTime",tmpLocalDateTime.toLocalTime().format(timeFormatter)); + } + } + }else{ + if("1".equalsIgnoreCase(isacross)){ + //下班时间,跨天 + lineMap.put("date", curDate); + lineMap.put("belongdate", yesterday); + lineMap.put("pre", "0"); + lineMap.put("across", "0"); + lineMap.put("datetime", curDate+" "+time+":00");//应打卡日期+时间 + String canSignTime = curDate + " "+ time + ":59"; + if(tMin > 0) { + LocalDateTime tmpLocalDateTime = LocalDateTime.parse(canSignTime, fullFormatter).plusMinutes(tMin); + lineMap.put("signSectionTime",tmpLocalDateTime.format(fullFormatter)); + lineMap.put("canSignTime",tmpLocalDateTime.toLocalTime().format(timeFormatter)); + } + if(tMin_next > -1) { + canSignTime = curDate + " "+ time + ":00"; + LocalDateTime tmpLocalDateTime = LocalDateTime.parse(canSignTime, fullFormatter).minusMinutes(tMin_next); + lineMap.put("signSectionBeginTime",tmpLocalDateTime.format(fullFormatter)); + lineMap.put("canSignBeginTime",tmpLocalDateTime.toLocalTime().format(timeFormatter)); + } + }else{ + //下班时间,不跨天 + lineMap.put("date", yesterday); + lineMap.put("belongdate", yesterday); + lineMap.put("pre", "1"); + lineMap.put("across", "0"); + lineMap.put("datetime", yesterday+" "+time+":00");//应打卡日期+时间 + String canSignTime = yesterday + " "+ time + ":59"; + //如果开启了打卡时段设置 + if(tMin > 0){ + LocalDateTime tmpLocalDateTime = LocalDateTime.parse(canSignTime, fullFormatter).plusMinutes(tMin); + lineMap.put("signSectionTime",tmpLocalDateTime.format(fullFormatter)); + lineMap.put("canSignTime",tmpLocalDateTime.toLocalTime().format(timeFormatter)); + } + if(tMin_next > -1) { + canSignTime = yesterday + " "+ time + ":00"; + LocalDateTime tmpLocalDateTime = LocalDateTime.parse(canSignTime, fullFormatter).minusMinutes(tMin_next); + lineMap.put("signSectionBeginTime",tmpLocalDateTime.format(fullFormatter)); + lineMap.put("canSignBeginTime",tmpLocalDateTime.toLocalTime().format(timeFormatter)); + } + } + + } + return lineMap; + } + + /** + * 针对今天的工作时间 根据跨天判断重构一遍数据 + * @param timelineMap + * @param nextday + * @param isOnOff + */ + private Map reBuildTimeMap(Map timelineMap, String nextday, + String isOnOff) { + Map lineMap = new HashMap<>(); + + String isacross = Util.null2String(timelineMap.get("isacross")); + String min = Util.null2String(timelineMap.get("min")); + String time = Util.null2String(timelineMap.get("time")); + String min_next = Util.null2String(timelineMap.get("min_next")); + String workmins = Util.null2String(timelineMap.get("workmins")); +// 打卡时段设置 一定是要开启的 + String isPunchOpen = "1"; + String signAcross = Util.null2String(timelineMap.get("signAcross")); + String signAcross_next = Util.null2String(timelineMap.get("signAcross_next")); + int tMin = Util.getIntValue(min,0); + int tMin_next = Util.getIntValue(min_next,-1); + + lineMap.put("type", timelineMap.get("type")); + lineMap.put("serialid", timelineMap.get("serialid")); + lineMap.put("isacross", isacross); + lineMap.put("time", time); + lineMap.put("belongtime", time); + lineMap.put("min", min); + lineMap.put("min_next", min_next); + lineMap.put("workmins", workmins); + lineMap.put("isPunchOpen", isPunchOpen); + lineMap.put("signAcross", signAcross); + lineMap.put("signAcross_next", signAcross_next); + + if("on".equalsIgnoreCase(isOnOff)){ + if("1".equalsIgnoreCase(isacross)){ + //上班时间,跨天 + lineMap.put("date", nextday); + lineMap.put("belongdate", curDate); + lineMap.put("pre", "0"); + lineMap.put("across", "1"); + lineMap.put("datetime", nextday+" "+time+":00");//应打卡日期+时间 + String canSignTime = nextday + " "+ time + ":00"; + //如果开启了打卡时段设置 + if(tMin > 0){ + LocalDateTime tmpLocalDateTime = LocalDateTime.parse(canSignTime, fullFormatter).minusMinutes(tMin); + lineMap.put("signSectionTime",tmpLocalDateTime.format(fullFormatter)); + lineMap.put("canSignTime",tmpLocalDateTime.toLocalTime().format(timeFormatter)); + } + if(tMin_next > -1) { + canSignTime = nextday + " "+ time + ":59"; + LocalDateTime tmpLocalDateTime = LocalDateTime.parse(canSignTime, fullFormatter).plusMinutes(tMin_next); + lineMap.put("signSectionEndTime",tmpLocalDateTime.format(fullFormatter)); + lineMap.put("canSignEndTime",tmpLocalDateTime.toLocalTime().format(timeFormatter)); + } + }else{ + //上班时间,不跨天 + lineMap.put("date", curDate); + lineMap.put("belongdate", curDate); + lineMap.put("pre", "0"); + lineMap.put("across", "0"); + lineMap.put("datetime", curDate+" "+time+":00");//应打卡日期+时间 + String canSignTime = curDate + " "+ time + ":00"; + if(tMin > 0){ + LocalDateTime tmpLocalDateTime = LocalDateTime.parse(canSignTime, fullFormatter).minusMinutes(tMin); + lineMap.put("signSectionTime",tmpLocalDateTime.format(fullFormatter)); + lineMap.put("canSignTime",tmpLocalDateTime.toLocalTime().format(timeFormatter)); + } + if(tMin_next > -1) { + canSignTime = curDate + " "+ time + ":59"; + LocalDateTime tmpLocalDateTime = LocalDateTime.parse(canSignTime, fullFormatter).plusMinutes(tMin_next); + lineMap.put("signSectionEndTime",tmpLocalDateTime.format(fullFormatter)); + lineMap.put("canSignEndTime",tmpLocalDateTime.toLocalTime().format(timeFormatter)); + } + } + }else{ + if("1".equalsIgnoreCase(isacross)){ + //下班时间,跨天 + lineMap.put("date", nextday); + lineMap.put("belongdate", curDate); + lineMap.put("pre", "0"); + lineMap.put("across", "1"); + lineMap.put("datetime", nextday+" "+time+":00");//应打卡日期+时间 + String canSignTime = nextday + " "+ time + ":59"; + if(tMin > 0){ + LocalDateTime tmpLocalDateTime = LocalDateTime.parse(canSignTime, fullFormatter).plusMinutes(tMin); + lineMap.put("signSectionTime",tmpLocalDateTime.format(fullFormatter)); + lineMap.put("canSignTime",tmpLocalDateTime.toLocalTime().format(timeFormatter)); + } + if(tMin_next > -1) { + canSignTime = nextday + " "+ time + ":00"; + LocalDateTime tmpLocalDateTime = LocalDateTime.parse(canSignTime, fullFormatter).minusMinutes(tMin_next); + lineMap.put("signSectionBeginTime",tmpLocalDateTime.format(fullFormatter)); + lineMap.put("canSignBeginTime",tmpLocalDateTime.toLocalTime().format(timeFormatter)); + } + }else{ + //下班时间,不跨天 + lineMap.put("date", curDate); + lineMap.put("belongdate", curDate); + lineMap.put("pre", "0"); + lineMap.put("across", "0"); + lineMap.put("datetime", curDate+" "+time+":00");//应打卡日期+时间 + String canSignTime = curDate + " "+ time + ":59"; + if(tMin > 0){ + LocalDateTime tmpLocalDateTime = LocalDateTime.parse(canSignTime, fullFormatter).plusMinutes(tMin); + lineMap.put("signSectionTime",tmpLocalDateTime.format(fullFormatter)); + lineMap.put("canSignTime",tmpLocalDateTime.toLocalTime().format(timeFormatter)); + } + if(tMin_next > -1) { + canSignTime = curDate + " "+ time + ":00"; + LocalDateTime tmpLocalDateTime = LocalDateTime.parse(canSignTime, fullFormatter).minusMinutes(tMin_next); + lineMap.put("signSectionBeginTime",tmpLocalDateTime.format(fullFormatter)); + lineMap.put("canSignBeginTime",tmpLocalDateTime.toLocalTime().format(timeFormatter)); + } + } + + } + return lineMap; + } + + + /** + * 针对明日的工作时间 根据跨天判断重构一遍数据 + * @param timelineMap + * @param nextday + * @param next_nextday + * @param isOnOff + */ + private Map reBuildNextTimeMap(Map timelineMap, String nextday, String next_nextday, + String isOnOff) { + Map lineMap = new HashMap<>(); + + String isacross = Util.null2String(timelineMap.get("isacross")); + String min = Util.null2String(timelineMap.get("min")); + String time = Util.null2String(timelineMap.get("time")); + String min_next = Util.null2String(timelineMap.get("min_next")); + String workmins = Util.null2String(timelineMap.get("workmins")); +// 打卡时段设置 一定是要开启的 + String isPunchOpen = "1"; + String signAcross = Util.null2String(timelineMap.get("signAcross")); + String signAcross_next = Util.null2String(timelineMap.get("signAcross_next")); + int tMin = Util.getIntValue(min,0); + int tMin_next = Util.getIntValue(min_next,-1); + + lineMap.put("type", timelineMap.get("type")); + lineMap.put("serialid", timelineMap.get("serialid")); + lineMap.put("isacross", isacross); + lineMap.put("time", time); + lineMap.put("belongtime", time); + lineMap.put("min", min); + lineMap.put("min_next", min_next); + lineMap.put("workmins", workmins); + lineMap.put("isPunchOpen", isPunchOpen); + lineMap.put("signAcross", signAcross); + lineMap.put("signAcross_next", signAcross_next); + +// 因为当前是明日的班次,所以这个across就都搞成1,前端的话就显示次日 + if("on".equalsIgnoreCase(isOnOff)){ + if("1".equalsIgnoreCase(isacross)){ + //上班时间,跨天 + lineMap.put("date", next_nextday); + lineMap.put("belongdate", nextday); + lineMap.put("across", "1"); + lineMap.put("datetime", next_nextday+" "+time+":00");//应打卡日期+时间 + String canSignTime = next_nextday + " "+ time + ":00"; + //如果开启了打卡时段设置 + if(tMin > 0){ + LocalDateTime tmpLocalDateTime = LocalDateTime.parse(canSignTime, fullFormatter).minusMinutes(tMin); + lineMap.put("signSectionTime",tmpLocalDateTime.format(fullFormatter)); + lineMap.put("canSignTime",tmpLocalDateTime.toLocalTime().format(timeFormatter)); + } + if(tMin_next > -1) { + canSignTime = next_nextday + " "+ time + ":59"; + LocalDateTime tmpLocalDateTime = LocalDateTime.parse(canSignTime, fullFormatter).plusMinutes(tMin_next); + lineMap.put("signSectionEndTime",tmpLocalDateTime.format(fullFormatter)); + lineMap.put("canSignEndTime",tmpLocalDateTime.toLocalTime().format(timeFormatter)); + } + }else{ + //上班时间,不跨天 + lineMap.put("date", nextday); + lineMap.put("belongdate", nextday); + lineMap.put("pre", "0"); + lineMap.put("across", "1"); + lineMap.put("datetime", nextday+" "+time+":00");//应打卡日期+时间 + String canSignTime = nextday + " "+ time + ":00"; + if(tMin > 0){ + LocalDateTime tmpLocalDateTime = LocalDateTime.parse(canSignTime, fullFormatter).minusMinutes(tMin); + lineMap.put("signSectionTime",tmpLocalDateTime.format(fullFormatter)); + lineMap.put("canSignTime",tmpLocalDateTime.toLocalTime().format(timeFormatter)); + } + if(tMin_next > -1) { + canSignTime = nextday + " "+ time + ":59"; + LocalDateTime tmpLocalDateTime = LocalDateTime.parse(canSignTime, fullFormatter).plusMinutes(tMin_next); + lineMap.put("signSectionEndTime",tmpLocalDateTime.format(fullFormatter)); + lineMap.put("canSignEndTime",tmpLocalDateTime.toLocalTime().format(timeFormatter)); + } + } + }else{ + if("1".equalsIgnoreCase(isacross)){ + //下班时间,跨天 + lineMap.put("date", next_nextday); + lineMap.put("belongdate", nextday); + lineMap.put("pre", "0"); + lineMap.put("across", "1"); + lineMap.put("datetime", next_nextday+" "+time+":00");//应打卡日期+时间 + String canSignTime = next_nextday + " "+ time + ":59"; + if(tMin > 0){ + LocalDateTime tmpLocalDateTime = LocalDateTime.parse(canSignTime, fullFormatter).plusMinutes(tMin); + lineMap.put("signSectionTime",tmpLocalDateTime.format(fullFormatter)); + lineMap.put("canSignTime",tmpLocalDateTime.toLocalTime().format(timeFormatter)); + } + if(tMin_next > -1) { + canSignTime = next_nextday + " "+ time + ":00"; + LocalDateTime tmpLocalDateTime = LocalDateTime.parse(canSignTime, fullFormatter).minusMinutes(tMin_next); + lineMap.put("signSectionBeginTime",tmpLocalDateTime.format(fullFormatter)); + lineMap.put("canSignBeginTime",tmpLocalDateTime.toLocalTime().format(timeFormatter)); + } + }else{ + //下班时间,不跨天 + lineMap.put("date", nextday); + lineMap.put("belongdate", nextday); + lineMap.put("pre", "0"); + lineMap.put("across", "1"); + lineMap.put("datetime", nextday+" "+time+":00");//应打卡日期+时间 + String canSignTime = nextday + " "+ time + ":59"; + if(tMin > 0){ + LocalDateTime tmpLocalDateTime = LocalDateTime.parse(canSignTime, fullFormatter).plusMinutes(tMin); + lineMap.put("signSectionTime",tmpLocalDateTime.format(fullFormatter)); + lineMap.put("canSignTime",tmpLocalDateTime.toLocalTime().format(timeFormatter)); + } + if(tMin_next > -1) { + canSignTime = nextday + " "+ time + ":00"; + LocalDateTime tmpLocalDateTime = LocalDateTime.parse(canSignTime, fullFormatter).minusMinutes(tMin_next); + lineMap.put("signSectionBeginTime",tmpLocalDateTime.format(fullFormatter)); + lineMap.put("canSignBeginTime",tmpLocalDateTime.toLocalTime().format(timeFormatter)); + } + } + + } + return lineMap; + } + + public String getCurDate() { + return curDate; + } + + public void setCurDate(String curDate) { + this.curDate = curDate; + } + + public void setNow(LocalDateTime now){ + this.now = now; + } + + public LocalDateTime getNow() { + return now; + } + + public LocalDateTime getZoneOfClientDateTime(String now_date, String now_time, + Map logMap){ + LocalDateTime now_zone = null; + //处理多时区 + 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(); + DateTimeFormatter fullFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + String[] zone_localTime = dateTransformer.getLocaleDateAndTime(now_date,now_time); + kqLog.info((user != null ? user.getLastname() : "")+"::"+"now_date:"+now_date+":now_time:"+now_time+"::" + +(zone_localTime !=null ? JSON.toJSONString(zone_localTime): "")); + logMap.put("zone_localTime", (zone_localTime !=null ? JSON.toJSONString(zone_localTime): "")); + if(zone_localTime != null && zone_localTime.length == 2){ + now_date = zone_localTime[0]; + now_time = zone_localTime[1]; + } + String dateTime = now_date+" "+now_time; + now_zone = LocalDateTime.parse(dateTime,fullFormatter); + } + logMap.put("now_zone", now_zone); + return now_zone; + } + + @Override + public BizLogContext getLogContext() { + return null; + } + +} 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..efe8010 --- /dev/null +++ b/src/com/engine/kq/cmd/attendanceButton/PunchButtonCmd.java @@ -0,0 +1,608 @@ +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.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.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; + } + 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/leaverules/AddLeaveRulesCmd.java b/src/com/engine/kq/cmd/leaverules/AddLeaveRulesCmd.java new file mode 100644 index 0000000..c51f3d1 --- /dev/null +++ b/src/com/engine/kq/cmd/leaverules/AddLeaveRulesCmd.java @@ -0,0 +1,342 @@ +package com.engine.kq.cmd.leaverules; + +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.KQBalanceOfLeaveBiz; +import com.engine.kq.biz.KQLeaveRulesComInfo; +import com.engine.kq.biz.KQLeaveRulesDetailComInfo; +import com.engine.kq.util.KQTransMethod; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; +import weaver.hrm.company.SubCompanyComInfo; +import weaver.systeminfo.SystemEnv; + +import java.util.*; + +/** + * 假期规则--新建 + */ +public class AddLeaveRulesCmd extends AbstractCommonCommand> { + + private SimpleBizLogger logger; + + public AddLeaveRulesCmd(Map params, User user) { + this.user = user; + this.params = params; + this.logger = new SimpleBizLogger(); + + String ruleId = Util.null2String(params.get("typeId")); + String ruleName = Util.null2String(params.get("ruleName")); + BizLogContext bizLogContext = new BizLogContext(); + bizLogContext.setLogType(BizLogType.HRM_ENGINE);//模块类型 + bizLogContext.setBelongType(BizLogSmallType4Hrm.HRM_ENGINE_KQ_LEAVERULES);//所属大类型 + bizLogContext.setLogSmallType(BizLogSmallType4Hrm.HRM_ENGINE_KQ_LEAVERULES);//当前小类型 + bizLogContext.setParams(params);//当前request请求参数 + logger.setUser(user);//当前操作人 + String mainSql = "select * from kq_LeaveRulesDetail where ruleId=" + ruleId + " and ruleName like '%" + ruleName + "%'"; + logger.setMainSql(mainSql, "id");//主表sql + logger.setMainPrimarykey("id");//主日志表唯一key + logger.setMainTargetNameColumn("rulename"); + + SimpleBizLogger.SubLogInfo subLogInfo1 = logger.getNewSubLogInfo(); + String subSql1 = "select * from kq_EntryToLeave where leaveRulesId in (select id from kq_LeaveRulesDetail where ruleId=" + ruleId + " and ruleName like '%" + ruleName + "%')"; + subLogInfo1.setSubSql(subSql1, "id"); + logger.addSubLogInfo(subLogInfo1); + + SimpleBizLogger.SubLogInfo subLogInfo2 = logger.getNewSubLogInfo(); + String subSql2 = "select * from kq_WorkingAgeToLeave where leaveRulesId in (select id from kq_LeaveRulesDetail where ruleId=" + ruleId + " and ruleName like '%" + ruleName + "%')"; + subLogInfo2.setSubSql(subSql2, "id"); + logger.addSubLogInfo(subLogInfo2); + + SimpleBizLogger.SubLogInfo subLogInfo3 = logger.getNewSubLogInfo(); + String subSql3 = "select * from kq_MixModeToLegalLeave where leaveRulesId in (select id from kq_LeaveRulesDetail where ruleId=" + ruleId + " and ruleName like '%" + ruleName + "%')"; + subLogInfo3.setSubSql(subSql3, "id"); + logger.addSubLogInfo(subLogInfo3); + + SimpleBizLogger.SubLogInfo subLogInfo4 = logger.getNewSubLogInfo(); + String subSql4 = "select * from kq_MixModeToWelfareLeave where leaveRulesId in (select id from kq_LeaveRulesDetail where ruleId=" + ruleId + " and ruleName like '%" + ruleName + "%')"; + subLogInfo4.setSubSql(subSql4, "id"); + logger.addSubLogInfo(subLogInfo4); + + logger.before(bizLogContext); + } + + @Override + public BizLogContext getLogContext() { + return null; + } + + @Override + public List getLogContexts() { + return logger.getBizLogContexts(); + } + + @Override + public Map execute(CommandContext commandContext) { + Map resultMap = new HashMap(); + try { + boolean canAdd = HrmUserVarify.checkUserRight("KQLeaveRulesAdd:Add", user);//是否具有新建权限 + if (!canAdd) { + resultMap.put("status", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage()));//没有权限 + return resultMap; + } + + /*假期规则对应的假期类型的ID*/ + String ruleId = Util.null2String(params.get("typeId")); + + /*假期规则名称*/ + String ruleName = Util.null2String(params.get("ruleName")); + + /*应用范围:0-总部、1-分部*/ + int scopeType = Util.getIntValue((String) params.get("scopeType")); + + /*应用范围为分部时,选择的分部ID*/ + String scopeValue = Util.null2String(params.get("scopeValue")); + + /*余额发放方式:1-手动发放、2-按司龄自动发放、3-按工龄自动发放、4-每年自动发放固定天数、5-加班时长自动计入余额、6-按司龄+工龄自动发放*/ + int distributionMode = Util.getIntValue((String) params.get("distributionMode"), 1); + + /*每人发放小时(天)数(当余额发放方式为每年自动发放固定天数时有效)*/ + double annualAmount = Util.getDoubleValue((String) params.get("annualAmount"), 0); + + //法定年假规则:0-工龄、1-司龄、2-工龄+司龄 (当余额发放方式为按工龄+司龄自动发放时有效) + String legalKey = Util.null2s((String) params.get("legalKey"), "0"); + + //福利年假规则:0-工龄、1-工龄、2-工龄+司龄 (当余额发放方式为按工龄+司龄自动发放时有效) + String welfareKey = Util.null2s((String) params.get("welfareKey"), "1"); + + /*扣减优先级:1-法定年假、2-福利年假*/ + int priority = Util.getIntValue((String) params.get("priority"), 1); + + /*有效期规则:0-不限制、1-按自然月(1月1日-12月31日)、2-按入职日期起12个月、3-自定义次年失效日期、4-自定义有效天数*/ + int validityRule = Util.getIntValue((String) params.get("validityRule"), 1); + + /*有效期天数:(当有效期天数选择按天数失效的时候有效)*/ + int effectiveDays = Util.getIntValue((String) params.get("effectiveDays"), 30); + + //有效月数(当有效期规则选择自定义有效月数时) + int effectiveMonths = Util.getIntValue((String) params.get("effectiveMonths"), 1); + + /*失效日期--月(当有效期规则选择3-自定义次年失效日期时有效)*/ + String expirationMonth = Util.null2String(params.get("expirationMonth")); + + /*失效日期--日(当有效期规则选择3-自定义次年失效日期时有效)*/ + String expirationDay = Util.null2String(params.get("expirationDay")); + + /*允许延长有效期:0-不允许、1-允许*/ + int extensionEnable = Util.getIntValue((String) params.get("extensionEnable"), 0); + + /*允许超过有效期天数*/ + int extendedDays = Util.getIntValue((String) params.get("extendedDays"), 0); + + /*释放规则:0-不限制、1-按天释放、2-按月释放*/ + int releaseRule = Util.getIntValue((String) params.get("releaseRule"), 0); + + /*假期基数计算方式:0-精确计算、1-按最少的假期余额计算、2-按最多的假期余额计算*/ + int calcMethod = Util.getIntValue((String) params.get("calcMethod"), 0); + + /*是否折算:0-不折算、1-四舍五入、2-向上取整、3-向下取整、4-向上取0.5的倍数、5-向下取0.5的倍数*/ + int convertMode = Util.getIntValue("" + params.get("convertMode"), 1); + + /*次账号是否发放假期余额:0-不发放、1-发放*/ + int excludeSubAccount = Util.getIntValue("" + params.get("excludeSubAccount"), 1); + + /*转正之前是否发放假期余额:0-不发放、1-发放*/ + int beforeFormal = Util.getIntValue("" + params.get("excludeSubAccount"), 1); + + if (scopeType != 0 && scopeValue.equals("")) { + resultMap.put("status", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(388858, user.getLanguage()));//参数有误 + return resultMap; + } + /*两个不同的假期类型下不能同时存在 加班时长自动计入余额 的余额发放方式*/ + if (distributionMode == 5) { + releaseRule = 0; + String sql = "select * from kq_LeaveRules where (isDelete is null or isDelete<>1) and id<>? and id in (select ruleId from kq_LeaveRulesDetail where (isDelete is null or isDelete<>1) and distributionMode=5)"; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql, ruleId); + if (recordSet.next()) { + resultMap.put("status", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(505664, user.getLanguage()));//两个不同的假期类型下不能同时存在 加班时长自动计入余额 的余额发放方式 + return resultMap; + } + } else if (distributionMode == 6) { + /*同一假期类型下 按司龄+工龄自动发放 不能与其他余额发放方式共存*/ + String sql = "select * from kq_LeaveRulesDetail where (isDelete is null or isDelete<>1) and ruleId=? and distributionMode<>6"; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql, ruleId); + if (recordSet.next()) { + resultMap.put("status", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(505665, user.getLanguage()));//同一假期类型下 按司龄+工龄自动发放 不能与其他余额发放方式共存 + return resultMap; + } + } else { + /*同一个假期类型下其他余额发放方式不能与 按司龄+工龄自动发放 共存*/ + String sql = "select * from kq_LeaveRulesDetail where (isDelete is null or isDelete<>1) and ruleId=? and distributionMode=6"; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql, ruleId); + if (recordSet.next()) { + resultMap.put("status", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(505666, user.getLanguage()));//同一个假期类型下其他余额发放方式不能与 按司龄+工龄自动发放 共存 + return resultMap; + } + + //同一个假期类型下其他余额发放方式不能与 加班时长自动计入余额 共存 + sql = "select * from kq_LeaveRulesDetail where (isDelete is null or isDelete<>1) and ruleId=? and distributionMode=5"; + recordSet.executeQuery(sql, ruleId); + if (recordSet.next()) { + resultMap.put("status", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(510357, user.getLanguage()));//同一个假期类型下其他余额发放方式不能与 加班时长自动计入余额 共存 + return resultMap; + } + } + + String searchSql = "select * from kq_LeaveRulesDetail where (isDelete is null or isDelete<>1) and ruleId=?"; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(searchSql, ruleId); + while (recordSet.next()) { + int scopeTypeTemp = Util.getIntValue(recordSet.getString("scopeType"), 0); + String scopeValueTemp = recordSet.getString("scopeValue"); + + if (scopeType == 0 && scopeTypeTemp == 0) { + resultMap.put("status", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(505667, user.getLanguage()));//该假期类型下已经新建过总部的假期规则,请勿重复新建 + return resultMap; + } + if (scopeType == 1 && scopeTypeTemp == 1) { + List scopeValueTempList = Util.TokenizerString(scopeValueTemp, ","); + List scopeValueList = Util.TokenizerString(scopeValue, ","); + for (String temp : scopeValueList) + if (scopeValueTempList.contains(temp)) { + SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo(); + String subcomName = subCompanyComInfo.getSubCompanyname(temp); + + resultMap.put("status", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(505668, user.getLanguage()).replace("$", subcomName));//该假期类型下已经新建过分部的假期规则,请勿重复新建 + return resultMap; + } + } + } + boolean flag = false;//数据是否插入成功 + String sql = "insert into kq_LeaveRulesDetail(ruleId,ruleName,scopeType,scopeValue," + + "distributionMode,annualAmount,legalKey,welfareKey,priority,validityRule,effectiveDays,effectiveMonths,expirationMonth,expirationDay,extensionEnable,extendedDays,releaseRule,calcMethod,convertMode,excludeSubAccount,beforeFormal,isDelete) values(?,?,?,?, ?,?,?,?, ?,?,?,?, ?,?,?,?, ?,?,?,?, ?,0)"; + flag = recordSet.executeUpdate(sql, ruleId, ruleName, scopeType, scopeValue, + distributionMode, annualAmount, legalKey, welfareKey, priority, validityRule, effectiveDays, effectiveMonths, expirationMonth, expirationDay, extensionEnable, extendedDays, releaseRule, calcMethod, convertMode, excludeSubAccount, beforeFormal); + if (!flag) { + resultMap.put("sign", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败 + return resultMap; + } + + /*获取刚才插入的假期规则详情的ID*/ + int ruleDetailId = 0; + sql = "select max(id) maxId from kq_LeaveRulesDetail"; + recordSet.executeQuery(sql); + if (recordSet.next()) { + ruleDetailId = Util.getIntValue(recordSet.getString("maxId"), 0); + } + + if ((distributionMode == 2 || distributionMode == 7) && ruleDetailId != 0) { + int lowerLimit = 0;//司龄下限 + int upperLimit = 0;//司龄上限 + String data = Util.null2String(params.get("detailRule")); + JSONArray jsonArray = JSONArray.parseArray(data); + for (int i = 0; i < jsonArray.size(); i++) { + JSONObject jsonObject = jsonArray.getJSONObject(i); + int timePoint = jsonObject.getIntValue("timePoint"); + double amount = jsonObject.getDoubleValue("amount"); + + lowerLimit = i == 0 ? 0 : timePoint; + upperLimit = i == jsonArray.size() - 1 ? 9999 : jsonArray.getJSONObject(i + 1).getIntValue("timePoint"); + + sql = "insert into kq_EntryToLeave(leaveRulesId,lowerLimit,upperLimit,amount) values(?,?,?,?)"; + flag = recordSet.executeUpdate(sql, ruleDetailId, lowerLimit, upperLimit, amount); + if (!flag) { + resultMap.put("sign", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败 + return resultMap; + } + } + } + + if (distributionMode == 3 && ruleDetailId != 0) { + int lowerLimit = 0;//工龄下限 + int upperLimit = 0;//工龄上限 + String data = Util.null2String(params.get("detailRule")); + JSONArray jsonArray = JSONArray.parseArray(data); + for (int i = 0; i < jsonArray.size(); i++) { + JSONObject jsonObject = jsonArray.getJSONObject(i); + int timePoint = jsonObject.getIntValue("timePoint"); + double amount = jsonObject.getDoubleValue("amount"); + + lowerLimit = i == 0 ? 0 : timePoint; + upperLimit = i == jsonArray.size() - 1 ? 9999 : jsonArray.getJSONObject(i + 1).getIntValue("timePoint"); + + sql = "insert into kq_WorkingAgeToLeave(leaveRulesId,lowerLimit,upperLimit,amount) values(?,?,?,?)"; + flag = recordSet.executeUpdate(sql, ruleDetailId, lowerLimit, upperLimit, amount); + if (!flag) { + resultMap.put("sign", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败 + return resultMap; + } + } + } + + if (distributionMode == 6 && ruleDetailId != 0) { + String mixModeData = Util.null2String(params.get("legalRule")); + JSONArray jsonArray = JSONArray.parseArray(mixModeData); + for (int i = 0; i < jsonArray.size(); i++) { + JSONObject jsonObject = jsonArray.getJSONObject(i); + int workYear = jsonObject.getIntValue("workYear"); + int entryTime = jsonObject.getIntValue("entryTime"); + double legalAmount = jsonObject.getDoubleValue("legalAmount"); + + sql = "insert into kq_MixModeToLegalLeave(leaveRulesId,limit1,limit2,amount) values(?,?,?,?)"; + flag = recordSet.executeUpdate(sql, ruleDetailId, workYear, entryTime, legalAmount); + if (!flag) { + resultMap.put("sign", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败 + return resultMap; + } + } + + mixModeData = Util.null2String(params.get("welfareRule")); + jsonArray = JSONArray.parseArray(mixModeData); + for (int i = 0; i < jsonArray.size(); i++) { + JSONObject jsonObject = jsonArray.getJSONObject(i); + int workYear = jsonObject.getIntValue("workYear"); + int entryTime = jsonObject.getIntValue("entryTime"); + double welfareAmount = jsonObject.getDoubleValue("welfareAmount"); + + sql = "insert into kq_MixModeToWelfareLeave(leaveRulesId,limit1,limit2,amount) values(?,?,?,?)"; + flag = recordSet.executeUpdate(sql, ruleDetailId, workYear, entryTime, welfareAmount); + if (!flag) { + resultMap.put("sign", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败 + return resultMap; + } + } + } + + if (flag) { + resultMap.put("sign", "1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(83551, user.getLanguage()));//保存成功 + } + } catch (Exception e) { + writeLog(e); + } finally { + KQLeaveRulesDetailComInfo detailComInfo = new KQLeaveRulesDetailComInfo(); + detailComInfo.removeCache(); + } + return resultMap; + } +} diff --git a/src/com/engine/kq/cmd/leaverules/EditLeaveRulesCmd.java b/src/com/engine/kq/cmd/leaverules/EditLeaveRulesCmd.java new file mode 100644 index 0000000..0fc4fcd --- /dev/null +++ b/src/com/engine/kq/cmd/leaverules/EditLeaveRulesCmd.java @@ -0,0 +1,364 @@ +package com.engine.kq.cmd.leaverules; + +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.KQBalanceOfLeaveBiz; +import com.engine.kq.biz.KQLeaveRulesComInfo; +import com.engine.kq.biz.KQLeaveRulesDetailComInfo; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; +import weaver.hrm.company.SubCompanyComInfo; +import weaver.systeminfo.SystemEnv; + +import java.util.*; + +/** + * 假期规则--编辑 + */ +public class EditLeaveRulesCmd extends AbstractCommonCommand> { + + private SimpleBizLogger logger; + + public EditLeaveRulesCmd(Map params, User user) { + this.user = user; + this.params = params; + this.logger = new SimpleBizLogger(); + + int ruleDetailId = Util.getIntValue((String) params.get("ruleId")); + BizLogContext bizLogContext = new BizLogContext(); + bizLogContext.setLogType(BizLogType.HRM_ENGINE);//模块类型 + bizLogContext.setBelongType(BizLogSmallType4Hrm.HRM_ENGINE_KQ_LEAVERULES);//所属大类型 + bizLogContext.setLogSmallType(BizLogSmallType4Hrm.HRM_ENGINE_KQ_LEAVERULES);//当前小类型 + bizLogContext.setParams(params);//当前request请求参数 + logger.setUser(user);//当前操作人 + String mainSql = "select * from kq_LeaveRulesDetail where id=" + ruleDetailId; + logger.setMainSql(mainSql, "id");//主表sql + logger.setMainPrimarykey("id");//主日志表唯一key + logger.setMainTargetNameColumn("rulename"); + + SimpleBizLogger.SubLogInfo subLogInfo1 = logger.getNewSubLogInfo(); + String subSql1 = "select * from kq_EntryToLeave where leaveRulesId=" + ruleDetailId; + subLogInfo1.setSubSql(subSql1, "id"); + logger.addSubLogInfo(subLogInfo1); + + SimpleBizLogger.SubLogInfo subLogInfo2 = logger.getNewSubLogInfo(); + String subSql2 = "select * from kq_WorkingAgeToLeave where leaveRulesId=" + ruleDetailId; + subLogInfo2.setSubSql(subSql2, "id"); + logger.addSubLogInfo(subLogInfo2); + + SimpleBizLogger.SubLogInfo subLogInfo3 = logger.getNewSubLogInfo(); + String subSql3 = "select * from kq_MixModeToLegalLeave where leaveRulesId=" + ruleDetailId; + subLogInfo3.setSubSql(subSql3, "id"); + logger.addSubLogInfo(subLogInfo3); + + SimpleBizLogger.SubLogInfo subLogInfo4 = logger.getNewSubLogInfo(); + String subSql4 = "select * from kq_MixModeToLegalLeave where leaveRulesId=" + ruleDetailId; + subLogInfo4.setSubSql(subSql4, "id"); + logger.addSubLogInfo(subLogInfo4); + + logger.before(bizLogContext); + } + + @Override + public BizLogContext getLogContext() { + return null; + } + + @Override + public List getLogContexts() { + return logger.getBizLogContexts(); + } + + @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; + } + /*假期类型的ID*/ + int ruleId = Util.getIntValue((String) params.get("typeId")); + + /*假期规则详情的ID*/ + int ruleDetailId = Util.getIntValue((String) params.get("ruleId")); + + /*假期规则名称*/ + String ruleName = Util.null2String(params.get("ruleName")); + + /*应用范围:0-总部、1-分部*/ + int scopeType = Util.getIntValue((String) params.get("scopeType")); + + /*应用范围为分部时,选择的分部ID*/ + String scopeValue = Util.null2String(params.get("scopeValue")); + + /*余额发放方式:1-手动发放、2-按司龄自动发放、3-按工龄自动发放、4-每年自动发放固定天数、 5-加班时长自动计入余额*/ + int distributionMode = Util.getIntValue((String) params.get("distributionMode"), 1); + + /*每人发放小时(天)数(当余额发放方式为每年自动发放固定天数时有效)*/ + double annualAmount = Util.getDoubleValue((String) params.get("annualAmount"), 0); + + /*扣减优先级:1-法定年假、2-福利年假*/ + int priority = Util.getIntValue((String) params.get("priority"), 1); + + //法定年假规则:0-工龄、1-司龄、2-工龄+司龄 (当余额发放方式为按工龄+司龄自动发放时有效) + String legalKey = Util.null2s((String) params.get("legalKey"), "0"); + + //福利年假规则:0-工龄、1-工龄、2-工龄+司龄 (当余额发放方式为按工龄+司龄自动发放时有效) + String welfareKey = Util.null2s((String) params.get("welfareKey"), "1"); + + /*有效期规则:0-不限制、1-按自然月(1月1日-12月31日)、2-按入职日期起12个月、3-自定义次年失效日期、4-自定义有效天数*/ + int validityRule = Util.getIntValue((String) params.get("validityRule"), 1); + + /*有效期天数:(当有效期天数选择按天数失效的时候有效)*/ + int effectiveDays = Util.getIntValue((String) params.get("effectiveDays"), 30); + + //有效月数(当有效期规则选择自定义有效月数时) + int effectiveMonths = Util.getIntValue((String) params.get("effectiveMonths"), 1); + + /*失效日期--月(当有效期规则选择3-自定义次年失效日期时有效)*/ + String expirationMonth = Util.null2String(params.get("expirationMonth")); + + /*失效日期--日(当有效期规则选择3-自定义次年失效日期时有效)*/ + String expirationDay = Util.null2String(params.get("expirationDay")); + + /*允许延长有效期:0-不允许、1-允许*/ + int extensionEnable = Util.getIntValue((String) params.get("extensionEnable"), 0); + + /*允许超过有效期天数*/ + int extendedDays = Util.getIntValue((String) params.get("extendedDays"), 0); + + /*释放规则:0-不限制、1-按天释放、2-按月释放*/ + int releaseRule = Util.getIntValue((String) params.get("releaseRule"), 0); + + /*假期基数计算方式:0-精确计算、1-按最少的假期余额计算、2-按最多的假期余额计算*/ + int calcMethod = Util.getIntValue((String) params.get("calcMethod"), 0); + + /*是否折算:0-不折算、1-四舍五入、2-向上取整、3-向下取整、4-向上取0.5的倍数、5-向下取0.5的倍数*/ + int convertMode = Util.getIntValue("" + params.get("convertMode"), 1); + + /*次账号是否发放假期余额:0-不发放、1-发放*/ + int excludeSubAccount = Util.getIntValue("" + params.get("excludeSubAccount"), 1); + + /*转正之前是否发放假期余额:0-不发放、1-发放*/ + int beforeFormal = Util.getIntValue("" + params.get("beforeFormal"), 1); + + if (scopeType == 1 && scopeValue.equals("")) { + resultMap.put("status", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(388858, user.getLanguage()));//参数有误 + return resultMap; + } + if (distributionMode == 5) { + releaseRule = 0; + /*两个不同的假期类型下不能同时存在 加班时长自动计入余额 的余额发放方式*/ + String sql = "select * from kq_LeaveRules where (isDelete is null or isDelete<>1) and id<>? and id in (select ruleId from kq_LeaveRulesDetail where (isDelete is null or isDelete<>1) and distributionMode=5)"; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql, ruleId); + if (recordSet.next()) { + resultMap.put("status", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(505664, user.getLanguage()));//两个不同的假期类型下不能同时存在 加班时长自动计入余额 的余额发放方式 + return resultMap; + } + } else if (distributionMode == 6) { + /*同一假期类型下 按司龄+工龄自动发放 不能与其他余额发放方式共存*/ + String sql = "select * from kq_LeaveRulesDetail where (isDelete is null or isDelete<>1) and ruleId=? and distributionMode<>6"; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql, ruleId); + if (recordSet.next()) { + resultMap.put("status", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(505665, user.getLanguage()));//同一假期类型下 按司龄+工龄自动发放 不能与其他余额发放方式共存 + return resultMap; + } + } else { + /*同一个假期类型下其他余额发放方式不能与 按司龄+工龄自动发放 共存*/ + String sql = "select * from kq_LeaveRulesDetail where (isDelete is null or isDelete<>1) and ruleId=? and distributionMode=6"; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql, ruleId); + if (recordSet.next()) { + resultMap.put("status", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(505666, user.getLanguage()));//同一个假期类型下其他余额发放方式不能与 按司龄+工龄自动发放 共存 + return resultMap; + } + + //同一个假期类型下其他余额发放方式不能与 加班时长自动计入余额 共存 + sql = "select * from kq_LeaveRulesDetail where (isDelete is null or isDelete<>1) and ruleId=? and distributionMode=5"; + recordSet.executeQuery(sql, ruleId); + if (recordSet.next()) { + resultMap.put("status", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(510357, user.getLanguage()));//同一个假期类型下其他余额发放方式不能与 加班时长自动计入余额 共存 + return resultMap; + } + } + + String searchSql = "select * from kq_LeaveRulesDetail where (isDelete is null or isDelete<>1) and ruleId=? and id<>?"; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(searchSql, ruleId, ruleDetailId); + while (recordSet.next()) { + int scopeTypeTemp = Util.getIntValue(recordSet.getString("scopeType"), 0); + String scopeValueTemp = recordSet.getString("scopeValue"); + + if (scopeType == 0 && scopeTypeTemp == 0) { + resultMap.put("status", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(505667, user.getLanguage()));//该假期类型下已经新建过总部的假期规则,请勿重复新建 + return resultMap; + } + if (scopeType == 1 && scopeTypeTemp == 1) { + List scopeValueTempList = Util.TokenizerString(scopeValueTemp, ","); + List scopeValueList = Util.TokenizerString(scopeValue, ","); + for (String temp : scopeValueList) + if (scopeValueTempList.contains(temp)) { + SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo(); + String subcomName = subCompanyComInfo.getSubCompanyname(temp); + + resultMap.put("status", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(505668, user.getLanguage()).replace("$", subcomName));//该假期类型下已经新建过分部的假期规则,请勿重复新建 + return resultMap; + } + } + } + boolean flag = false;//数据是否更新成功 + String sql = "update kq_LeaveRulesDetail set ruleId=?,ruleName=?,scopeType=?,scopeValue=?," + + "distributionMode=?,annualAmount=?,legalKey=?,welfareKey=?,priority=?,validityRule=?,effectiveDays=?,effectiveMonths=?,expirationMonth=?,expirationDay=?,extensionEnable=?,extendedDays=?,releaseRule=?,calcMethod=?,convertMode=?,excludeSubAccount=?,beforeFormal=? where id=?"; + flag = recordSet.executeUpdate(sql, ruleId, ruleName, scopeType, scopeValue, + distributionMode, annualAmount, legalKey, welfareKey, priority, validityRule, effectiveDays, effectiveMonths, expirationMonth, expirationDay, extensionEnable, extendedDays, releaseRule, calcMethod, convertMode, excludeSubAccount, beforeFormal, ruleDetailId); + if (!flag) { + resultMap.put("sign", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败 + return resultMap; + } + + if ((distributionMode == 2 || distributionMode == 7) && ruleDetailId != 0) { + sql = "delete from kq_EntryToLeave where leaveRulesId=?"; + flag = recordSet.executeUpdate(sql, ruleDetailId); + if (!flag) { + resultMap.put("sign", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败 + return resultMap; + } + int lowerLimit = 0;//司龄下限 + int upperLimit = 0;//司龄上限 + String data = Util.null2String(params.get("detailRule")); + JSONArray jsonArray = JSONArray.parseArray(data); + for (int i = 0; i < jsonArray.size(); i++) { + JSONObject jsonObject = jsonArray.getJSONObject(i); + int timePoint = jsonObject.getIntValue("timePoint"); + double amount = jsonObject.getDoubleValue("amount"); + + lowerLimit = i == 0 ? 0 : timePoint; + upperLimit = i == jsonArray.size() - 1 ? 9999 : jsonArray.getJSONObject(i + 1).getIntValue("timePoint"); + + sql = "insert into kq_EntryToLeave(leaveRulesId,lowerLimit,upperLimit,amount) values(?,?,?,?)"; + flag = recordSet.executeUpdate(sql, ruleDetailId, lowerLimit, upperLimit, amount); + if (!flag) { + resultMap.put("sign", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败 + return resultMap; + } + } + } + + if (distributionMode == 3 && ruleDetailId != 0) { + sql = "delete from kq_WorkingAgeToLeave where leaveRulesId=?"; + flag = recordSet.executeUpdate(sql, ruleDetailId); + if (!flag) { + resultMap.put("sign", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败 + return resultMap; + } + int lowerLimit = 0;//工龄下限 + int upperLimit = 0;//工龄上限 + String data = Util.null2String(params.get("detailRule")); + JSONArray jsonArray = JSONArray.parseArray(data); + for (int i = 0; i < jsonArray.size(); i++) { + JSONObject jsonObject = jsonArray.getJSONObject(i); + int timePoint = jsonObject.getIntValue("timePoint"); + double amount = jsonObject.getDoubleValue("amount"); + + lowerLimit = i == 0 ? 0 : timePoint; + upperLimit = i == jsonArray.size() - 1 ? 9999 : jsonArray.getJSONObject(i + 1).getIntValue("timePoint"); + + sql = "insert into kq_WorkingAgeToLeave(leaveRulesId,lowerLimit,upperLimit,amount) values(?,?,?,?)"; + flag = recordSet.executeUpdate(sql, ruleDetailId, lowerLimit, upperLimit, amount); + if (!flag) { + resultMap.put("sign", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败 + return resultMap; + } + } + } + + if (distributionMode == 6 && ruleDetailId != 0) { + sql = "delete from kq_MixModeToLegalLeave where leaveRulesId=?"; + flag = recordSet.executeUpdate(sql, ruleDetailId); + if (!flag) { + resultMap.put("sign", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败 + return resultMap; + } + + sql = "delete from kq_MixModeToWelfareLeave where leaveRulesId=?"; + flag = recordSet.executeUpdate(sql, ruleDetailId); + if (!flag) { + resultMap.put("sign", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败 + return resultMap; + } + String mixModeData = Util.null2String(params.get("legalRule")); + JSONArray jsonArray = JSONArray.parseArray(mixModeData); + for (int i = 0; i < jsonArray.size(); i++) { + JSONObject jsonObject = jsonArray.getJSONObject(i); + int workYear = jsonObject.getIntValue("workYear"); + int entryTime = jsonObject.getIntValue("entryTime"); + double legalAmount = jsonObject.getDoubleValue("legalAmount"); + + sql = "insert into kq_MixModeToLegalLeave(leaveRulesId,limit1,limit2,amount) values(?,?,?,?)"; + flag = recordSet.executeUpdate(sql, ruleDetailId, workYear, entryTime, legalAmount); + if (!flag) { + resultMap.put("sign", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败 + return resultMap; + } + } + + mixModeData = Util.null2String(params.get("welfareRule")); + jsonArray = JSONArray.parseArray(mixModeData); + for (int i = 0; i < jsonArray.size(); i++) { + JSONObject jsonObject = jsonArray.getJSONObject(i); + int workYear = jsonObject.getIntValue("workYear"); + int entryTime = jsonObject.getIntValue("entryTime"); + double welfareAmount = jsonObject.getDoubleValue("welfareAmount"); + + sql = "insert into kq_MixModeToWelfareLeave(leaveRulesId,limit1,limit2,amount) values(?,?,?,?)"; + flag = recordSet.executeUpdate(sql, ruleDetailId, workYear, entryTime, welfareAmount); + if (!flag) { + resultMap.put("sign", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败 + return resultMap; + } + } + } + if (flag) { + resultMap.put("sign", "1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(83551, user.getLanguage()));//保存成功 + } + } catch (Exception e) { + writeLog(e); + resultMap.put("sign", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败 + } finally { + KQLeaveRulesDetailComInfo detailComInfo = new KQLeaveRulesDetailComInfo(); + detailComInfo.removeCache(); + } + 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..69f76b0 --- /dev/null +++ b/src/com/engine/kq/cmd/leaverules/GetLeaveRulesFormCmd.java @@ -0,0 +1,803 @@ +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)); + 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/leaverules/GetSearchListCmd.java b/src/com/engine/kq/cmd/leaverules/GetSearchListCmd.java new file mode 100644 index 0000000..e65922f --- /dev/null +++ b/src/com/engine/kq/cmd/leaverules/GetSearchListCmd.java @@ -0,0 +1,86 @@ +package com.engine.kq.cmd.leaverules; + +import com.cloudstore.dev.api.util.Util_TableMap; +import com.engine.common.biz.AbstractCommonCommand; +import com.engine.common.entity.BizLogContext; +import com.engine.core.interceptor.CommandContext; +import weaver.general.PageIdConst; +import weaver.general.Util; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; +import weaver.hrm.moduledetach.ManageDetachComInfo; +import weaver.systeminfo.SystemEnv; +import weaver.systeminfo.systemright.CheckSubCompanyRight; + +import java.util.HashMap; +import java.util.Map; + +/** + * 假期规则--查询结果列表 + */ +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(); + String ruleName = Util.null2String(params.get("ruleName"));//假期规则名称 + String typeId = Util.null2String(params.get("typeId"));//假期类型的ID + + boolean canEdit = HrmUserVarify.checkUserRight("KQLeaveRulesEdit:Edit", user);//是否具有编辑权限 + boolean canDelete = HrmUserVarify.checkUserRight("KQLeaveRulesDelete:Delete", user);//是否具有删除权限 + boolean canLog = HrmUserVarify.checkUserRight("KQLeaveRules:Log", user);//是否具有查看日志的权限 + + /*如果没有权限*/ + if (!canEdit) { + resultMap.put("status", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage())); + return resultMap; + } + + String backFields = " * "; + String sqlFrom = " from kq_LeaveRulesDetail "; + String sqlWhere = " where (isDelete is null or isDelete!=1) "; + String orderBy = " id "; + if (!ruleName.equals("")) { + sqlWhere += " and ruleName like '%" + ruleName + "%'"; + } + if(!typeId.equals("")){ + sqlWhere += " and ruleId="+typeId; + } + String pageUid = "b0c005a2-447f-0977-b692-6d8de7ead576"; + String operateString = ""; + operateString = ""; + operateString += " "; + operateString += " "; + operateString += " "; + operateString += " "; + operateString += ""; + String tableString = "" + + "" + + "" + + operateString + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + "
"; + String sessionKey = pageUid + "_" + Util.getEncrypt(Util.getRandom()); + Util_TableMap.setVal(sessionKey, tableString); + resultMap.put("sessionkey", sessionKey); + 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..e268788 --- /dev/null +++ b/src/com/engine/kq/cmd/myattendance/GetHrmKQMonthReportInfoCmd.java @@ -0,0 +1,991 @@ +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.KQSignUtil; +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.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) ; + } + + @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 (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(); + + //获取节假日 + 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("")) { + 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 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()); + } + } + } + + 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("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); + } + resultMap.put(kqDate,itemList); + } + } + } catch (Exception e) { + writeLog(e); + } + return resultMap; + } + + 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/overtimerules/AddOvertimeRulesCmd.java b/src/com/engine/kq/cmd/overtimerules/AddOvertimeRulesCmd.java new file mode 100644 index 0000000..30aa512 --- /dev/null +++ b/src/com/engine/kq/cmd/overtimerules/AddOvertimeRulesCmd.java @@ -0,0 +1,424 @@ +package com.engine.kq.cmd.overtimerules; + +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.KQOvertimeRulesBiz; +import com.engine.kq.log.KQLog; +import com.google.common.collect.Lists; +import java.util.Arrays; +import java.util.Calendar; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; +import weaver.systeminfo.SystemEnv; + +/** + * 加班规则--新建 + */ +public class AddOvertimeRulesCmd extends AbstractCommonCommand> { + + private SimpleBizLogger logger; + + public AddOvertimeRulesCmd(Map params, User user) { + this.user = user; + this.params = params; + this.logger = new SimpleBizLogger(); + + String name = Util.null2String(params.get("name")); + BizLogContext bizLogContext = new BizLogContext(); + bizLogContext.setLogType(BizLogType.HRM_ENGINE);//模块类型 + bizLogContext.setBelongType(BizLogSmallType4Hrm.HRM_ENGINE_KQ_OVERTIMERULES);//所属大类型 + bizLogContext.setLogSmallType(BizLogSmallType4Hrm.HRM_ENGINE_KQ_OVERTIMERULES);//当前小类型 + bizLogContext.setParams(params);//当前request请求参数 + logger.setUser(user);//当前操作人 + String mainSql = "select * from kq_overtimeRules where name like '%" + name + "%'"; + logger.setMainSql(mainSql, "id");//主表sql + logger.setMainPrimarykey("id");//主日志表唯一key + logger.setMainTargetNameColumn("name"); + + SimpleBizLogger.SubLogInfo subLogInfo = logger.getNewSubLogInfo(); + String subSql = "select * from kq_overtimeRulesDetail where ruleId in (select id from kq_overtimeRules where name like '%" + name + "%') order by id"; + subLogInfo.setSubSql(subSql, "id"); + logger.addSubLogInfo(subLogInfo); + logger.before(bizLogContext); + } + + @Override + public BizLogContext getLogContext() { + return null; + } + + @Override + public List getLogContexts() { + return logger.getBizLogContexts(); + } + + @Override + public Map execute(CommandContext commandContext) { + Map resultMap = new HashMap(); + try { + boolean canAdd = HrmUserVarify.checkUserRight("KQOvertimeRulesAdd:Add", user);//是否具有新建权限 + if (!canAdd) { + resultMap.put("status", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage())); + return resultMap; + } + + /*加班规则名称*/ + String name = Util.null2String(params.get("name")); + /*考勤组的ID*/ + String groupIds = Util.null2String(params.get("groupIds")); + + /*工作日是否允许加班:0-不允许、1-允许*/ + int overtimeEnable2 = Util.getIntValue((String) params.get("overtimeEnable2"), 1); + /*工作日的加班方式:1-需审批,以审批单为准、2-需审批,以打卡为准,但是不能超过审批时长、3-无需审批,根据打卡时间计算加班时长*/ + int computingMode2 = Util.getIntValue((String) params.get("computingMode2"), 1); + /*工作日下班多少分钟后开始计算加班*/ + int startTime2 = Util.getIntValue((String) params.get("startTime2"), 30); + /*工作日最小加班时长*/ + int minimumLen2 = Util.getIntValue((String) params.get("minimumLen2"), 30); + /*工作日是否允许加班转调休*/ + int paidLeaveEnable2 = Util.getIntValue((String) params.get("paidLeaveEnable2"), 0); + /*工作日加班转调休比例中的加班时长*/ + double lenOfOvertime2 = Util.getDoubleValue((String) params.get("lenOfOvertime2"), 30.0); + /*工作日加班转调休比例中的调休时长*/ + double lenOfLeave2 = Util.getDoubleValue((String) params.get("lenOfLeave2"), 30.0); + + /*休息日是否允许加班:0-不允许、1-允许*/ + int overtimeEnable3 = Util.getIntValue((String) params.get("overtimeEnable3"), 1); + /*休息日的加班方式:1-需审批,以审批单为准、2-需审批,以打卡为准,但是不能超过审批时长、3-无需审批,根据打卡时间计算加班时长*/ + int computingMode3 = Util.getIntValue((String) params.get("computingMode3"), 1); + /*休息日的最小加班时长*/ + int minimumLen3 = Util.getIntValue((String) params.get("minimumLen3"), 30); + /*休息日是否允许加班转调休*/ + int paidLeaveEnable3 = Util.getIntValue((String) params.get("paidLeaveEnable3"), 0); + /*休息日加班转调休比例中的加班时长*/ + double lenOfOvertime3 = Util.getDoubleValue((String) params.get("lenOfOvertime3"), 30.0); + /*休息日加班转调休比例中的调休时长*/ + double lenOfLeave3 = Util.getDoubleValue((String) params.get("lenOfLeave3"), 30.0); + /*休息日是否有休息时间*/ + int hasRestTime3 = Util.getIntValue((String) params.get("hasRestTime3"), 0); + + /*节假日是否允许加班:0-不允许、1-允许*/ + int overtimeEnable1 = Util.getIntValue((String) params.get("overtimeEnable1"), 1); + /*节假日的加班方式:1-需审批,以审批单为准、2-需审批,以打卡为准,但是不能超过审批时长、3-无需审批,根据打卡时间计算加班时长*/ + int computingMode1 = Util.getIntValue((String) params.get("computingMode1"), 1); + /*节假日的最小加班时长*/ + int minimumLen1 = Util.getIntValue((String) params.get("minimumLen1"), 30); + /*节假日是否允许加班转调休*/ + int paidLeaveEnable1 = Util.getIntValue((String) params.get("paidLeaveEnable1"), 0); + /*节假日加班转调休比例中的加班时长*/ + double lenOfOvertime1 = Util.getDoubleValue((String) params.get("lenOfOvertime1"), 30.0); + /*假节日加班转调休比例中的调休时长*/ + double lenOfLeave1 = Util.getDoubleValue((String) params.get("lenOfLeave1"), 30.0); + /*节假日是否有休息时间*/ + int hasRestTime1 = Util.getIntValue((String) params.get("hasRestTime1"), 0); + if(computingMode2 == 4 || computingMode1 == 4 || computingMode3 == 4 ){ + //如果是流程和打卡取交集的话,加班单位不能是下拉框半天或者整天 + int minimumUnit = KQOvertimeRulesBiz.getMinimumUnit(); + if(minimumUnit == 2 || minimumUnit == 4){ + resultMap.put("sign", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(529168, user.getLanguage())); + return resultMap; + } + } + KQLog kqLog = new KQLog(); + kqLog.info("AddOvertimeRulesCmd:params:"+params); + + /*获取今天的日期*/ + 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 tomorrowDate = DateUtil.addDate(currentDate, 1); + + //顺序显示,2是工作日,3是休息日,1是节假日 + int[] changetype = {2,3,1}; + + boolean flag = false;//是否保存成功 + + String sql = "insert into kq_OvertimeRules(name,groupIds,isDelete) values(?,?,0)"; + RecordSet recordSet = new RecordSet(); + RecordSet recordSet1 = new RecordSet(); + flag = recordSet.executeUpdate(sql, name, groupIds); + if (!flag) { + resultMap.put("sign", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败 + return resultMap; + } + + int ruleId = 0;//刚刚插入的数据的ID + sql = "select max(id) maxId from kq_OvertimeRules"; + recordSet.executeQuery(sql); + if (recordSet.next()) { + ruleId = recordSet.getInt("maxId"); + } + + List rulesdetailidList = Lists.newArrayList(); + + String[] fields = new String[]{"overtimeEnable","computingMode","startTime","minimumLen", + "paidLeaveEnable","lenOfOvertime","lenOfLeave","hasRestTime","before_startTime", + "has_cut_point","cut_point","paidLeaveEnableType","paidLeaveEnableDefaultType", + "paidLeaveEnableFlowType","restTimeType"}; + String str_fields = Arrays.asList(fields).stream().collect(Collectors.joining(",")); + String split_str = Arrays.asList(fields).stream().map(s -> {return "?";}).collect(Collectors.joining(",")); + for(int i = 0 ; i < changetype.length ; i++) { + int changetype_index = changetype[i]; + sql = "insert into kq_OvertimeRulesDetail(ruleId,dayType,"+str_fields+") " + + "values(?,?,"+split_str+")"; + String value_str = ""; + int size = 2+fields.length; + Object[] objects = new Object[size]; + objects[0] = ruleId; + objects[1] = changetype_index; + for(int j = 0 ; j < fields.length ;j++){ + String _key = fields[j]+changetype_index; + String _value = Util.null2String(params.get(_key)); + if("before_startTime".equalsIgnoreCase(fields[j])){ + _value = Util.null2s(Util.null2String(params.get(_key)),"0"); + } + if("startTime".equalsIgnoreCase(fields[j])){ + _value = Util.null2s(Util.null2String(params.get(_key)),"0"); + } + value_str += ","+_value; + objects[2+j] = _value; + } + if(value_str.length() > 0){ + flag = recordSet.executeUpdate(sql, objects); + if(flag){ + + int rulesdetailid = 0;//刚刚插入的明细数据的ID + sql = "select max(id) maxId from kq_OvertimeRulesDetail"; + recordSet.executeQuery(sql); + if (recordSet.next()) { + rulesdetailid = recordSet.getInt("maxId"); + } + rulesdetailidList.add(rulesdetailid+""); + + String hasRestTime_key = "hasRestTime"+changetype_index; + String hasRestTime_value = Util.null2String(params.get(hasRestTime_key)); + if("1".equalsIgnoreCase(hasRestTime_value)){ + List restIds = Lists.newArrayList(); + String restTimeType_key = "restTimeType"+changetype_index; + String restTimeType_value = Util.null2String(params.get(restTimeType_key)); + + String restTimeRule_key = "restTimeRule"+changetype_index; + String restTimeRule_value = Util.null2String(params.get(restTimeRule_key)); + if(restTimeRule_value.length() > 0){ + JSONArray jsonArray = JSONArray.parseArray(restTimeRule_value); + if("1".equalsIgnoreCase(restTimeType_value)){ + for(int k = 0 ; k < jsonArray.size() ; k++){ + JSONObject jsonObject = (JSONObject) jsonArray.get(k); + String startType = "0"; + String endType = "0"; + String startTime = Util.null2String(jsonObject.get("startTime")); + String endTime = Util.null2String(jsonObject.get("endTime")); + String restTimeSql = "insert into kq_OvertimeRestTime(ruleId,dayType,startType,startTime,endType,endTime) values(?,?,?,?,?,?)"; + flag = recordSet.executeUpdate(restTimeSql, ruleId, changetype_index, startType, startTime, endType, endTime); + if (flag) { + int restId = 0; + String restSql = "select max(id) maxId from kq_OvertimeRestTime"; + recordSet1.executeQuery(restSql); + if (recordSet1.next()) { + restId = recordSet1.getInt("maxId"); + restIds.add(""+restId); + } + resultMap.put("sign", "1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(83551, user.getLanguage()));//保存成功 + } else { + if(!rulesdetailidList.isEmpty()){ + delFail(rulesdetailidList,restIds,ruleId); + } + resultMap.put("sign", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败 + return resultMap; + } + } + }else if("2".equalsIgnoreCase(restTimeType_value)){ + for(int k = 0 ; k < jsonArray.size() ; k++){ + JSONObject jsonObject = (JSONObject) jsonArray.get(k); + String overtime = Util.null2String(jsonObject.get("overtime")); + String exclude = Util.null2String(jsonObject.get("exclude")); + String restTimeSql = "insert into kq_OvertimeRestlength(ruleId,dayType,overlength,cutlength,dsporder) values(?,?,?,?,?)"; + flag = recordSet.executeUpdate(restTimeSql, ruleId, changetype_index, overtime, exclude, k); + if (flag) { + int restId = 0; + String restSql = "select max(id) maxId from kq_OvertimeRestlength"; + recordSet1.executeQuery(restSql); + if (recordSet1.next()) { + restId = recordSet1.getInt("maxId"); + restIds.add(""+restId); + } + resultMap.put("sign", "1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(83551, user.getLanguage()));//保存成功 + } else { + if(!rulesdetailidList.isEmpty()){ + delFail(rulesdetailidList, restIds, ruleId); + } + resultMap.put("sign", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败 + return resultMap; + } + } + } + } + } + String paidLeaveEnableType_key = "paidLeaveEnableType"+changetype_index; + String paidLeaveEnableType_value = Util.null2String(params.get(paidLeaveEnableType_key)); + + String paidLeaveEnableTypeRule_key = "paidLeaveEnableTypeRule"+changetype_index; + String paidLeaveEnableTypeRule_value = Util.null2String(params.get(paidLeaveEnableTypeRule_key)); + if("1".equalsIgnoreCase(paidLeaveEnableType_value)){ + String paidLeaveEnableDefaultType_key = "paidLeaveEnableDefaultType"+changetype_index; + String paidLeaveEnableDefaultType_value = Util.null2String(params.get(paidLeaveEnableDefaultType_key)); + if("2".equalsIgnoreCase(paidLeaveEnableDefaultType_value)){ +// 按加班时长范围设置转调休时长 + JSONArray jsonArray = JSONArray.parseArray(paidLeaveEnableTypeRule_value); + for(int k = 0 ; k < jsonArray.size() ; k++){ + JSONObject jsonObject = (JSONObject) jsonArray.get(k); + String work = Util.null2String(jsonObject.get("work")); + String rest = Util.null2String(jsonObject.get("rest")); + String detailsql = "insert into kq_OvertimeBalanceLengthDetail(rulesdetailid,overtimelength,balancelength,dsporder) values(?,?,?,?)"; + flag = recordSet.executeUpdate(detailsql, rulesdetailid, work, rest, k); + if (flag) { + resultMap.put("sign", "1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(83551, user.getLanguage()));//保存成功 + } else { + if(!rulesdetailidList.isEmpty()){ + delFail(rulesdetailidList, null, ruleId); + } + resultMap.put("sign", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败 + return resultMap; + } + } + }else if("3".equalsIgnoreCase(paidLeaveEnableDefaultType_value)){ +// 按加班的时间段设置转调休时长 + JSONArray jsonArray = JSONArray.parseArray(paidLeaveEnableTypeRule_value); + for(int k = 0 ; k < jsonArray.size() ; k++){ + JSONObject jsonObject = (JSONObject) jsonArray.get(k); + String time = Util.null2String(jsonObject.get("time")); + String left = Util.null2String(jsonObject.get("left")); + String right = Util.null2String(jsonObject.get("right")); + String detailsql = "insert into kq_OvertimeBalanceTimeDetail(rulesdetailid,timepoint,lenOfOvertime,lenOfLeave,dsporder) values(?,?,?,?,?)"; + flag = recordSet.executeUpdate(detailsql, rulesdetailid, time, left, right,k); + if (flag) { + resultMap.put("sign", "1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(83551, user.getLanguage()));//保存成功 + } else { + if(!rulesdetailidList.isEmpty()){ + delFail(rulesdetailidList, null, ruleId); + } + resultMap.put("sign", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败 + return resultMap; + } + } + } + }else if("2".equalsIgnoreCase(paidLeaveEnableType_value)){ + String paidLeaveEnableFlowType_key = "paidLeaveEnableFlowType"+changetype_index; + String paidLeaveEnableFlowType_value = Util.null2String(params.get(paidLeaveEnableFlowType_key)); + if("2".equalsIgnoreCase(paidLeaveEnableFlowType_value)){ +// 按加班时长范围设置转调休时长 + JSONArray jsonArray = JSONArray.parseArray(paidLeaveEnableTypeRule_value); + for(int k = 0 ; k < jsonArray.size() ; k++){ + JSONObject jsonObject = (JSONObject) jsonArray.get(k); + String work = Util.null2String(jsonObject.get("work")); + String rest = Util.null2String(jsonObject.get("rest")); + String detailsql = "insert into kq_OvertimeBalanceLengthDetail(rulesdetailid,overtimelength,balancelength,dsporder) values(?,?,?,?)"; + flag = recordSet.executeUpdate(detailsql, rulesdetailid, work, rest, k); + if (flag) { + resultMap.put("sign", "1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(83551, user.getLanguage()));//保存成功 + } else { + if(!rulesdetailidList.isEmpty()){ + delFail(rulesdetailidList, null, ruleId); + } + resultMap.put("sign", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败 + return resultMap; + } + } + }else if("3".equalsIgnoreCase(paidLeaveEnableFlowType_value)){ +// 按加班的时间段设置转调休时长 + JSONArray jsonArray = JSONArray.parseArray(paidLeaveEnableTypeRule_value); + for(int k = 0 ; k < jsonArray.size() ; k++){ + JSONObject jsonObject = (JSONObject) jsonArray.get(k); + String time = Util.null2String(jsonObject.get("time")); + String left = Util.null2String(jsonObject.get("left")); + String right = Util.null2String(jsonObject.get("right")); + String detailsql = "insert into kq_OvertimeBalanceTimeDetail(rulesdetailid,timepoint,lenOfOvertime,lenOfLeave,dsporder) values(?,?,?,?,?)"; + flag = recordSet.executeUpdate(detailsql, rulesdetailid, time, left, right,k); + if (flag) { + resultMap.put("sign", "1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(83551, user.getLanguage()));//保存成功 + } else { + if(!rulesdetailidList.isEmpty()){ + delFail(rulesdetailidList, null, ruleId); + } + resultMap.put("sign", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败 + return resultMap; + } + } + } + } + }else{ + if(!rulesdetailidList.isEmpty()){ + delFail(rulesdetailidList, null, ruleId); + } + resultMap.put("sign", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败 + return resultMap; + } + } + } + + resultMap.put("sign", "1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(83551, user.getLanguage()));//保存成功 + + } catch (Exception e) { + resultMap.put("sign", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(382661, user.getLanguage())); + writeLog(e); + } + return resultMap; + } + + /** + * 保存失败时候把错误数据删除 + * @param rulesdetailidList + * @param restIds + * @param ruleId + */ + public void delFail(List rulesdetailidList, List restIds, int ruleId){ + RecordSet rs = new RecordSet(); + String delSql1 = "delete from kq_OvertimeRules where id = ? "; + rs.executeUpdate(delSql1, ruleId); + + for(String rulesdetailid : rulesdetailidList){ + String delSql = "delete from kq_overtimerulesdetail where id = ? "; + rs.executeUpdate(delSql,rulesdetailid); + } + if(restIds != null && !restIds.isEmpty()){ + for(String restId : restIds){ + String delSql = "delete from kq_overtimeresttime where id = ? "; + rs.executeUpdate(delSql,restId); + delSql = "delete from kq_overtimerestlength where id = ? "; + rs.executeUpdate(delSql,restId); + } + } + } +} diff --git a/src/com/engine/kq/cmd/overtimerules/DeleteOvertimeRulesCmd.java b/src/com/engine/kq/cmd/overtimerules/DeleteOvertimeRulesCmd.java new file mode 100644 index 0000000..879975b --- /dev/null +++ b/src/com/engine/kq/cmd/overtimerules/DeleteOvertimeRulesCmd.java @@ -0,0 +1,85 @@ +package com.engine.kq.cmd.overtimerules; + +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 weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; +import weaver.systeminfo.SystemEnv; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 加班规则--删除 + */ +public class DeleteOvertimeRulesCmd extends AbstractCommonCommand> { + + private SimpleBizLogger logger; + + public DeleteOvertimeRulesCmd(Map params, User user) { + this.user = user; + this.params = params; + this.logger = new SimpleBizLogger(); + + String ruleIds = Util.null2String(params.get("ruleIds"));//需要删除的加班规则ID + BizLogContext bizLogContext = new BizLogContext(); + bizLogContext.setLogType(BizLogType.HRM_ENGINE);//模块类型 + bizLogContext.setBelongType(BizLogSmallType4Hrm.HRM_ENGINE_KQ_OVERTIMERULES);//所属大类型 + bizLogContext.setLogSmallType(BizLogSmallType4Hrm.HRM_ENGINE_KQ_OVERTIMERULES);//当前小类型 + bizLogContext.setParams(params);//当前request请求参数 + logger.setUser(user);//当前操作人 + String mainSql = "select * from kq_overtimeRules where (isDelete is null or isDelete<>1) and id in ("+ruleIds+")"; + logger.setMainSql(mainSql, "id");//主表sql + logger.setMainPrimarykey("id");//主日志表唯一key + logger.setMainTargetNameColumn("name"); + logger.before(bizLogContext); + } + + @Override + public BizLogContext getLogContext() { + return null; + } + + @Override + public List getLogContexts() { + return logger.getBizLogContexts(); + } + + @Override + public Map execute(CommandContext commandContext) { + Map resultMap = new HashMap(); + String ruleIds = Util.null2String(params.get("ruleIds"));//需要删除的加班规则ID + if (ruleIds.equals("")) { + resultMap.put("status", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(388858, user.getLanguage())); + return resultMap; + } + + boolean canDelete = HrmUserVarify.checkUserRight("KQOvertimeRulesDelete:Delete", user);//是否具有删除的权限; + if (!canDelete) { + resultMap.put("status", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage())); + return resultMap; + } + + boolean flag = false; + String sql = "update kq_OvertimeRules set isDelete=1 where id in (" + ruleIds + ")"; + RecordSet recordSet = new RecordSet(); + flag = recordSet.executeUpdate(sql); + if (flag) { + resultMap.put("sign", "1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(20461, user.getLanguage()));//删除成功 + } else { + resultMap.put("sign", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(20462, user.getLanguage()));//删除失败 + } + return resultMap; + } +} diff --git a/src/com/engine/kq/cmd/overtimerules/EditOverTimeRulesCmd.java b/src/com/engine/kq/cmd/overtimerules/EditOverTimeRulesCmd.java new file mode 100644 index 0000000..bc6fd1a --- /dev/null +++ b/src/com/engine/kq/cmd/overtimerules/EditOverTimeRulesCmd.java @@ -0,0 +1,499 @@ +package com.engine.kq.cmd.overtimerules; + +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.KQOvertimeRulesBiz; +import com.engine.kq.log.KQLog; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import java.util.stream.Collectors; +import weaver.common.DateUtil; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; +import weaver.systeminfo.SystemEnv; + +import java.util.*; + +/** + * 加班规则--编辑 + */ +public class EditOverTimeRulesCmd extends AbstractCommonCommand> { + + private SimpleBizLogger logger; + + public EditOverTimeRulesCmd(Map params, User user) { + this.user = user; + this.params = params; + this.logger = new SimpleBizLogger(); + + int ruleId = Util.getIntValue((String) params.get("ruleId"), 0); + BizLogContext bizLogContext = new BizLogContext(); + bizLogContext.setLogType(BizLogType.HRM_ENGINE);//模块类型 + bizLogContext.setBelongType(BizLogSmallType4Hrm.HRM_ENGINE_KQ_OVERTIMERULES);//所属大类型 + bizLogContext.setLogSmallType(BizLogSmallType4Hrm.HRM_ENGINE_KQ_OVERTIMERULES);//当前小类型 + bizLogContext.setParams(params);//当前request请求参数 + logger.setUser(user);//当前操作人 + String mainSql = "select * from kq_overtimeRules where id="+ruleId; + logger.setMainSql(mainSql, "id");//主表sql + logger.setMainPrimarykey("id");//主日志表唯一key + logger.setMainTargetNameColumn("name"); + + SimpleBizLogger.SubLogInfo subLogInfo = logger.getNewSubLogInfo(); + String subSql = "select * from kq_overtimeRulesDetail where ruleId="+ruleId +" order by id"; + subLogInfo.setSubSql(subSql, "id"); + logger.addSubLogInfo(subLogInfo); + logger.before(bizLogContext); + } + + @Override + public BizLogContext getLogContext() { + return null; + } + + @Override + public List getLogContexts() { + return logger.getBizLogContexts(); + } + + @Override + public Map execute(CommandContext commandContext) { + Map resultMap = new HashMap(); + try { + /*加班规则的ID*/ + int ruleId = Util.getIntValue((String) params.get("ruleId"), 0); + if (ruleId == 0) { + resultMap.put("status", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(388858, user.getLanguage())); + return resultMap; + } + + boolean canEdit = HrmUserVarify.checkUserRight("KQOvertimeRulesEdit:Edit", user);//是否具有编辑的权限; + if (!canEdit) { + resultMap.put("status", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage())); + return resultMap; + } + + /*加班规则名称*/ + String name = Util.null2String(params.get("name")); + /*考勤组的ID*/ + String groupIds = Util.null2String(params.get("groupIds")); + + /*工作日是否允许加班:0-不允许、1-允许*/ + int overtimeEnable2 = Util.getIntValue((String) params.get("overtimeEnable2"), 1); + /*工作日的加班方式:1-需审批,以审批单为准、2-需审批,以打卡为准,但是不能超过审批时长、3-无需审批,根据打卡时间计算加班时长*/ + int computingMode2 = Util.getIntValue((String) params.get("computingMode2"), 1); + /*工作日下班多少分钟后开始计算加班*/ + int startTime2 = Util.getIntValue((String) params.get("startTime2"), 30); + /*工作日最小加班时长*/ + int minimumLen2 = Util.getIntValue((String) params.get("minimumLen2"), 30); + /*工作日是否允许加班转调休*/ + int paidLeaveEnable2 = Util.getIntValue((String) params.get("paidLeaveEnable2"), 0); + /*工作日加班转调休比例中的加班时长*/ + double lenOfOvertime2 = Util.getDoubleValue((String) params.get("lenOfOvertime2"), 30.0); + /*工作日加班转调休比例中的调休时长*/ + double lenOfLeave2 = Util.getDoubleValue((String) params.get("lenOfLeave2"), 30.0); + + /*休息日是否允许加班:0-不允许、1-允许*/ + int overtimeEnable3 = Util.getIntValue((String) params.get("overtimeEnable3"), 1); + /*休息日的加班方式:1-需审批,以审批单为准、2-需审批,以打卡为准,但是不能超过审批时长、3-无需审批,根据打卡时间计算加班时长*/ + int computingMode3 = Util.getIntValue((String) params.get("computingMode3"), 1); + /*休息日的最小加班时长*/ + int minimumLen3 = Util.getIntValue((String) params.get("minimumLen3"), 30); + /*休息日是否允许加班转调休*/ + int paidLeaveEnable3 = Util.getIntValue((String) params.get("paidLeaveEnable3"), 0); + /*休息日加班转调休比例中的加班时长*/ + double lenOfOvertime3 = Util.getDoubleValue((String) params.get("lenOfOvertime3"), 30.0); + /*休息日加班转调休比例中的调休时长*/ + double lenOfLeave3 = Util.getDoubleValue((String) params.get("lenOfLeave3"), 30.0); + /*休息日是否有休息时间*/ + int hasRestTime3 = Util.getIntValue((String) params.get("hasRestTime3"), 0); + + /*节假日是否允许加班:0-不允许、1-允许*/ + int overtimeEnable1 = Util.getIntValue((String) params.get("overtimeEnable1"), 1); + /*节假日的加班方式:1-需审批,以审批单为准、2-需审批,以打卡为准,但是不能超过审批时长、3-无需审批,根据打卡时间计算加班时长*/ + int computingMode1 = Util.getIntValue((String) params.get("computingMode1"), 1); + /*节假日的最小加班时长*/ + int minimumLen1 = Util.getIntValue((String) params.get("minimumLen1"), 30); + /*节假日是否允许加班转调休*/ + int paidLeaveEnable1 = Util.getIntValue((String) params.get("paidLeaveEnable1"), 0); + /*节假日加班转调休比例中的加班时长*/ + double lenOfOvertime1 = Util.getDoubleValue((String) params.get("lenOfOvertime1"), 30.0); + /*假节日加班转调休比例中的调休时长*/ + double lenOfLeave1 = Util.getDoubleValue((String) params.get("lenOfLeave1"), 30.0); + /*节假日是否有休息时间*/ + int hasRestTime1 = Util.getIntValue((String) params.get("hasRestTime1"), 0); + + if(computingMode2 == 4 || computingMode1 == 4 || computingMode3 == 4 ){ + //如果是流程和打卡取交集的话,加班单位不能是下拉框半天或者整天 + int minimumUnit = KQOvertimeRulesBiz.getMinimumUnit(); + if(minimumUnit == 2 || minimumUnit == 4){ + resultMap.put("sign", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(529168, user.getLanguage())); + return resultMap; + } + } + KQLog kqLog = new KQLog(); + kqLog.info("EditOverTimeRulesCmd:params:"+params); + + + /*获取今天的日期*/ + 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 tomorrowDate = DateUtil.addDate(currentDate, 1); + + //顺序显示,2是工作日,3是休息日,1是节假日 + int[] changetype = {2,3,1}; + + boolean flag = false;//是否保存成功 + + String sql = "update kq_OvertimeRules set name=?,groupIds=? where id=?"; + RecordSet recordSet = new RecordSet(); + RecordSet recordSet1 = new RecordSet(); + RecordSet recordSet2 = new RecordSet(); + flag = recordSet.executeUpdate(sql, name, groupIds, ruleId); + if (!flag) { + resultMap.put("sign", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败 + return resultMap; + } + Map detailMap = Maps.newHashMap(); + String detailSql = "select * from kq_OvertimeRulesDetail where ruleId=?"; + recordSet.executeQuery(detailSql,ruleId); + while (recordSet.next()){ + String daytype = recordSet.getString("daytype"); + String id = recordSet.getString("id"); + detailMap.put(daytype, id); + } + + String[] fields = new String[]{"overtimeEnable","computingMode","startTime","minimumLen", + "paidLeaveEnable","lenOfOvertime","lenOfLeave","hasRestTime","before_startTime", + "has_cut_point","cut_point","paidLeaveEnableType","paidLeaveEnableDefaultType", + "paidLeaveEnableFlowType","restTimeType"}; + String str_fields = Arrays.asList(fields).stream().collect(Collectors.joining(",")); + String split_str = Arrays.asList(fields).stream().map(s -> {return "?";}).collect(Collectors.joining(",")); + for(int i = 0 ; i < changetype.length ; i++) { + int changetype_index = changetype[i]; + String fieldName = ""; + for(int j = 0 ; j < fields.length ;j++){ + String _key = fields[j]+changetype_index; + String _value = Util.null2String(params.get(_key)); + if("before_startTime".equalsIgnoreCase(fields[j])){ + _value = Util.null2s(Util.null2String(params.get(_key)),"0"); + } + if("startTime".equalsIgnoreCase(fields[j])){ + _value = Util.null2s(Util.null2String(params.get(_key)),"0"); + } + fieldName += ","+fields[j]+"='"+_value+"'"; + } + if(fieldName.length() > 0){ + fieldName = fieldName.substring(1); + fieldName += ",ruleId="+ruleId+",dayType="+changetype_index; + String detailid = Util.null2s(detailMap.get((changetype_index+"")),"-1"); + + String updateSql = "update kq_OvertimeRulesDetail set "+fieldName+" where id = ? "; + flag = recordSet.executeUpdate(updateSql,detailid); + if(flag){ + + List restIds = Lists.newArrayList(); + List lengthDetailIds = Lists.newArrayList(); + List timeDetailIds = Lists.newArrayList(); + int rulesdetailid = Util.getIntValue(detailid); + + String hasRestTime_key = "hasRestTime"+changetype_index; + String hasRestTime_value = Util.null2String(params.get(hasRestTime_key)); + if("1".equalsIgnoreCase(hasRestTime_value)){ + String restTimeType_key = "restTimeType"+changetype_index; + String restTimeType_value = Util.null2String(params.get(restTimeType_key)); + + String restTimeRule_key = "restTimeRule"+changetype_index; + String restTimeRule_value = Util.null2String(params.get(restTimeRule_key)); + if(restTimeRule_value.length() > 0){ + JSONArray jsonArray = JSONArray.parseArray(restTimeRule_value); + if("1".equalsIgnoreCase(restTimeType_value)){ + String deleteSql = "delete from kq_OvertimeRestTime where dayType=? and ruleId = ?"; + flag = recordSet.executeUpdate(deleteSql, changetype_index,ruleId); + if (!flag) { + resultMap.put("sign", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败 + return resultMap; + } + for(int k = 0 ; k < jsonArray.size() ; k++){ + JSONObject jsonObject = (JSONObject) jsonArray.get(k); + String startType = "0"; + String endType = "0"; + String startTime = Util.null2String(jsonObject.get("startTime")); + String endTime = Util.null2String(jsonObject.get("endTime")); + String restTimeSql = "insert into kq_OvertimeRestTime(ruleId,dayType,startType,startTime,endType,endTime) values(?,?,?,?,?,?)"; + flag = recordSet.executeUpdate(restTimeSql, ruleId, changetype_index, startType, startTime, endType, endTime); + if (flag) { + int restDetailId = 0; + String getIdSql = "select max(id) maxId from kq_OvertimeRestTime"; + recordSet1.executeQuery(getIdSql); + if (recordSet1.next()) { + restDetailId = recordSet1.getInt("maxId"); + restIds.add(""+restDetailId); + } + resultMap.put("sign", "1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(83551, user.getLanguage()));//保存成功 + } else { + if(!restIds.isEmpty()){ + if(restIds != null && !restIds.isEmpty()){ + for(String detailId : restIds){ + String delSql = "delete from kq_OvertimeRestTime where id = ? "; + recordSet2.executeUpdate(delSql,detailId); + } + } + } + resultMap.put("sign", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败 + return resultMap; + } + } + }else if("2".equalsIgnoreCase(restTimeType_value)){ + String deleteSql = "delete from kq_OvertimeRestlength where dayType=? and ruleId = ?"; + flag = recordSet.executeUpdate(deleteSql, changetype_index,ruleId); + if (!flag) { + resultMap.put("sign", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败 + return resultMap; + } + for(int k = 0 ; k < jsonArray.size() ; k++){ + JSONObject jsonObject = (JSONObject) jsonArray.get(k); + String overtime = Util.null2String(jsonObject.get("overtime")); + String exclude = Util.null2String(jsonObject.get("exclude")); + String restTimeSql = "insert into kq_OvertimeRestlength(ruleId,dayType,overlength,cutlength,dsporder) values(?,?,?,?,?)"; + flag = recordSet.executeUpdate(restTimeSql, ruleId, changetype_index, overtime, exclude, k); + if (flag) { + int restDetailId = 0; + String getIdSql = "select max(id) maxId from kq_OvertimeRestlength"; + recordSet1.executeQuery(getIdSql); + if (recordSet1.next()) { + restDetailId = recordSet1.getInt("maxId"); + restIds.add(""+restDetailId); + } + resultMap.put("sign", "1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(83551, user.getLanguage()));//保存成功 + } else { + if(!restIds.isEmpty()){ + if(restIds != null && !restIds.isEmpty()){ + for(String detailId : restIds){ + String delSql = "delete from kq_OvertimeRestlength where id = ? "; + recordSet2.executeUpdate(delSql,detailId); + } + } + } + resultMap.put("sign", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败 + return resultMap; + } + } + } + } + } + String paidLeaveEnableType_key = "paidLeaveEnableType"+changetype_index; + String paidLeaveEnableType_value = Util.null2String(params.get(paidLeaveEnableType_key)); + + String paidLeaveEnableTypeRule_key = "paidLeaveEnableTypeRule"+changetype_index; + String paidLeaveEnableTypeRule_value = Util.null2String(params.get(paidLeaveEnableTypeRule_key)); + if("1".equalsIgnoreCase(paidLeaveEnableType_value)){ + String paidLeaveEnableDefaultType_key = "paidLeaveEnableDefaultType"+changetype_index; + String paidLeaveEnableDefaultType_value = Util.null2String(params.get(paidLeaveEnableDefaultType_key)); + if("2".equalsIgnoreCase(paidLeaveEnableDefaultType_value)){ + String deleteSql = "delete from kq_OvertimeBalanceLengthDetail where rulesdetailid = ?"; + flag = recordSet.executeUpdate(deleteSql, detailid); + if (!flag) { + resultMap.put("sign", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败 + return resultMap; + } +// 按加班时长范围设置转调休时长 + JSONArray jsonArray = JSONArray.parseArray(paidLeaveEnableTypeRule_value); + for(int k = 0 ; k < jsonArray.size() ; k++){ + JSONObject jsonObject = (JSONObject) jsonArray.get(k); + String work = Util.null2String(jsonObject.get("work")); + String rest = Util.null2String(jsonObject.get("rest")); + String detailsql = "insert into kq_OvertimeBalanceLengthDetail(rulesdetailid,overtimelength,balancelength,dsporder) values(?,?,?,?)"; + flag = recordSet.executeUpdate(detailsql, rulesdetailid, work, rest, k); + if (flag) { + int lengthDetailId = 0; + String getIdSql = "select max(id) maxId from kq_OvertimeBalanceLengthDetail"; + recordSet1.executeQuery(getIdSql); + if (recordSet1.next()) { + lengthDetailId = recordSet1.getInt("maxId"); + lengthDetailIds.add(""+lengthDetailId); + } + resultMap.put("sign", "1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(83551, user.getLanguage()));//保存成功 + } else { + if(!lengthDetailIds.isEmpty()){ + if(lengthDetailIds != null && !lengthDetailIds.isEmpty()){ + for(String detailId : lengthDetailIds){ + String delSql = "delete from kq_OvertimeBalanceLengthDetail where id = ? "; + recordSet2.executeUpdate(delSql,detailId); + } + } + } + resultMap.put("sign", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败 + return resultMap; + } + } + }else if("3".equalsIgnoreCase(paidLeaveEnableDefaultType_value)){ + String deleteSql = "delete from kq_OvertimeBalanceTimeDetail where rulesdetailid = ?"; + flag = recordSet.executeUpdate(deleteSql, detailid); + if (!flag) { + resultMap.put("sign", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败 + return resultMap; + } +// 按加班的时间段设置转调休时长 + JSONArray jsonArray = JSONArray.parseArray(paidLeaveEnableTypeRule_value); + for(int k = 0 ; k < jsonArray.size() ; k++){ + JSONObject jsonObject = (JSONObject) jsonArray.get(k); + String time = Util.null2String(jsonObject.get("time")); + String left = Util.null2String(jsonObject.get("left")); + String right = Util.null2String(jsonObject.get("right")); + String detailsql = "insert into kq_OvertimeBalanceTimeDetail(rulesdetailid,timepoint,lenOfOvertime,lenOfLeave,dsporder) values(?,?,?,?,?)"; + flag = recordSet.executeUpdate(detailsql, rulesdetailid, time, left, right,k); + if (flag) { + int timeDetailId = 0; + String getIdSql = "select max(id) maxId from kq_OvertimeBalanceTimeDetail"; + recordSet1.executeQuery(getIdSql); + if (recordSet1.next()) { + timeDetailId = recordSet1.getInt("maxId"); + timeDetailIds.add(""+timeDetailId); + } + resultMap.put("sign", "1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(83551, user.getLanguage()));//保存成功 + } else { + if(!timeDetailIds.isEmpty()){ + if(timeDetailIds != null && !timeDetailIds.isEmpty()){ + for(String detailId : timeDetailIds){ + String delSql = "delete from kq_OvertimeBalanceTimeDetail where id = ? "; + recordSet2.executeUpdate(delSql,detailId); + } + } + } + resultMap.put("sign", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败 + return resultMap; + } + } + } + }else if("2".equalsIgnoreCase(paidLeaveEnableType_value)){ + String paidLeaveEnableFlowType_key = "paidLeaveEnableFlowType"+changetype_index; + String paidLeaveEnableFlowType_value = Util.null2String(params.get(paidLeaveEnableFlowType_key)); + if("2".equalsIgnoreCase(paidLeaveEnableFlowType_value)){ + String deleteSql = "delete from kq_OvertimeBalanceLengthDetail where rulesdetailid = ?"; + flag = recordSet.executeUpdate(deleteSql, detailid); + if (!flag) { + resultMap.put("sign", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败 + return resultMap; + } +// 按加班时长范围设置转调休时长 + JSONArray jsonArray = JSONArray.parseArray(paidLeaveEnableTypeRule_value); + for(int k = 0 ; k < jsonArray.size() ; k++){ + JSONObject jsonObject = (JSONObject) jsonArray.get(k); + String work = Util.null2String(jsonObject.get("work")); + String rest = Util.null2String(jsonObject.get("rest")); + String detailsql = "insert into kq_OvertimeBalanceLengthDetail(rulesdetailid,overtimelength,balancelength,dsporder) values(?,?,?,?)"; + flag = recordSet.executeUpdate(detailsql, rulesdetailid, work, rest, k); + if (flag) { + int lengthDetailId = 0; + String getIdSql = "select max(id) maxId from kq_OvertimeBalanceLengthDetail"; + recordSet1.executeQuery(getIdSql); + if (recordSet1.next()) { + lengthDetailId = recordSet1.getInt("maxId"); + lengthDetailIds.add(""+lengthDetailId); + } + resultMap.put("sign", "1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(83551, user.getLanguage()));//保存成功 + } else { + if(!lengthDetailIds.isEmpty()){ + if(lengthDetailIds != null && !lengthDetailIds.isEmpty()){ + for(String detailId : lengthDetailIds){ + String delSql = "delete from kq_OvertimeBalanceLengthDetail where id = ? "; + recordSet2.executeUpdate(delSql,detailId); + } + } + } + resultMap.put("sign", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败 + return resultMap; + } + } + }else if("3".equalsIgnoreCase(paidLeaveEnableFlowType_value)){ + String deleteSql = "delete from kq_OvertimeBalanceTimeDetail where rulesdetailid = ?"; + flag = recordSet.executeUpdate(deleteSql, detailid); + if (!flag) { + resultMap.put("sign", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败 + return resultMap; + } +// 按加班的时间段设置转调休时长 + JSONArray jsonArray = JSONArray.parseArray(paidLeaveEnableTypeRule_value); + for(int k = 0 ; k < jsonArray.size() ; k++){ + JSONObject jsonObject = (JSONObject) jsonArray.get(k); + String time = Util.null2String(jsonObject.get("time")); + String left = Util.null2String(jsonObject.get("left")); + String right = Util.null2String(jsonObject.get("right")); + String detailsql = "insert into kq_OvertimeBalanceTimeDetail(rulesdetailid,timepoint,lenOfOvertime,lenOfLeave,dsporder) values(?,?,?,?,?)"; + flag = recordSet.executeUpdate(detailsql, rulesdetailid, time, left, right,k); + if (flag) { + int timeDetailId = 0; + String getIdSql = "select max(id) maxId from kq_OvertimeBalanceTimeDetail"; + recordSet1.executeQuery(getIdSql); + if (recordSet1.next()) { + timeDetailId = recordSet1.getInt("maxId"); + timeDetailIds.add(""+timeDetailId); + } + resultMap.put("sign", "1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(83551, user.getLanguage()));//保存成功 + } else { + if(!timeDetailIds.isEmpty()){ + if(timeDetailIds != null && !timeDetailIds.isEmpty()){ + for(String detailId : timeDetailIds){ + String delSql = "delete from kq_OvertimeBalanceTimeDetail where id = ? "; + recordSet2.executeUpdate(delSql,detailId); + } + } + } + resultMap.put("sign", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败 + return resultMap; + } + } + } + } + }else{ + resultMap.put("sign", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败 + return resultMap; + } + } + + } + resultMap.put("sign", "1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(83551, user.getLanguage()));//保存成功 + + } catch (Exception e) { + resultMap.put("sign", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(382661, user.getLanguage())); + writeLog(e); + } + return resultMap; + } + +} diff --git a/src/com/engine/kq/cmd/overtimerules/GetOvertimeRulesFormCmd.java b/src/com/engine/kq/cmd/overtimerules/GetOvertimeRulesFormCmd.java new file mode 100644 index 0000000..7a1642e --- /dev/null +++ b/src/com/engine/kq/cmd/overtimerules/GetOvertimeRulesFormCmd.java @@ -0,0 +1,697 @@ +package com.engine.kq.cmd.overtimerules; + +import com.api.browser.bean.SearchConditionItem; +import com.api.browser.bean.SearchConditionOption; +import com.engine.common.biz.AbstractCommonCommand; +import com.engine.common.entity.BizLogContext; +import com.engine.core.interceptor.CommandContext; +import com.api.hrm.bean.HrmFieldBean; +import com.api.hrm.util.HrmFieldSearchConditionComInfo; +import com.engine.kq.biz.KQGroupComInfo; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +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 GetOvertimeRulesFormCmd extends AbstractCommonCommand> { + + public GetOvertimeRulesFormCmd(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(); + String ruleId = Util.null2String(params.get("ruleId"));//加班规则的ID + boolean canAdd = HrmUserVarify.checkUserRight("KQOvertimeRulesAdd:Add", user);//是否具有新建权限 + boolean canEdit = HrmUserVarify.checkUserRight("KQOvertimeRulesEdit:Edit", user);//是否具有编辑的权限 + if (!canAdd && !canEdit) { + resultMap.put("status", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage())); + return resultMap; + } + boolean isEdit = false; + /*加班规则名称*/ + String name = ""; + /*考勤组的ID*/ + String groupIds = ""; + + /** + * 从这开始,下面的变量都是之前的写法,现在改成动态参数的,下面的这些参数就不用了 + */ + /*工作日是否允许加班:0-不允许、1-允许*/ + int overtimeEnable2 = 1; + /*工作日的加班方式:1-需审批,以加班流程为准、2-需审批,以打卡为准,但是不能超过加班流程时长、3-无需审批,根据打卡时间计算加班时长*/ + int computingMode2 = 1; + /*工作日下班多少分钟后开始计算加班*/ + int startTime2 = 30; + /*工作日上班前多少分钟后开始计算加班*/ + int before_startTime2 = 0; + /*工作日最小加班时长*/ + int minimumLen2 = 30; + /*工作日是否允许加班转调休*/ + int paidLeaveEnable2 = 0; + /*工作日加班转调休比例中的加班时长*/ + double lenOfOvertime2 = 1; + /*工作日加班转调休比例中的调休时长*/ + double lenOfLeave2 = 1; + + /*工作日加班补偿方式 1-默认加班补偿规则、2-根据员工在加班流程上选择的加班补偿类型进行补偿两种*/ + int paidLeaveEnableType2 = 0; + /*工作日默认加班补偿方式 里转调休的方式: 1-按加班时长比例转调休时长、2-按加班时长范围设置转调休时长、3-按加班的时间段设置转调休时长*/ + int paidLeaveEnableDefaultType2 = 1; + /*工作日 根据员工在加班流程上选择的加班补偿类型进行补偿 里转调休的方式: 1-按加班时长比例转调休时长、2-按加班时长范围设置转调休时长、3-按加班的时间段设置转调休时长*/ + int paidLeaveEnableFlowType2 = 1; + + // 按加班时长范围设置转调休时长: 加班时长 ≥* 分钟,转调休时长*分钟 + List> balanceLengthDetailLists2 = Lists.newArrayList(); + // 加班时间在19:00后,比例转调休时长 按照1:1 + List> balanceTimeDetailLists2 = Lists.newArrayList(); + /*工作日是否有休息时间*/ + int hasRestTime2 = 0; + /*排除休息时间两种方式 :1、设置休息时间 2、根据加班时长扣除 */ + int restType2=1; +// 工作日 是否开启 自定义跨天加班归属分界点 + int has_cut_point2 = 0; +// 开启 自定义跨天加班归属分界点 + String cut_point2 = "00:00"; + + + /*休息日是否允许加班:0-不允许、1-允许*/ + int overtimeEnable3 = 1; + /*休息日的加班方式:1-需审批,以加班流程为准、2-需审批,以打卡为准,但是不能超过加班流程时长、3-无需审批,根据打卡时间计算加班时长*/ + int computingMode3 = 1; + /*休息日的最小加班时长*/ + int minimumLen3 = 30; + /*休息日是否允许加班转调休*/ + int paidLeaveEnable3 = 0; + /*休息日加班转调休比例中的加班时长*/ + double lenOfOvertime3 = 1; + /*休息日加班转调休比例中的调休时长*/ + double lenOfLeave3 = 1; + /*休息日是否有休息时间*/ + int hasRestTime3 = 0; + + /*休息日加班补偿方式 1-默认加班补偿规则、2-根据员工在加班流程上选择的加班补偿类型进行补偿两种*/ + int paidLeaveEnableType3 = 0; + /*休息日默认加班补偿方式 里转调休的方式: 1-按加班时长比例转调休时长、2-按加班时长范围设置转调休时长、3-按加班的时间段设置转调休时长*/ + int paidLeaveEnableDefaultType3 = 1; + /*休息日 根据员工在加班流程上选择的加班补偿类型进行补偿 里转调休的方式: 1-按加班时长比例转调休时长、2-按加班时长范围设置转调休时长、3-按加班的时间段设置转调休时长*/ + int paidLeaveEnableFlowType3 = 1; + + // 按加班时长范围设置转调休时长: 加班时长 ≥* 分钟,转调休时长*分钟 + List> balanceLengthDetailLists3 = Lists.newArrayList(); + // 加班时间在19:00后,比例转调休时长 按照1:1 + List> balanceTimeDetailLists3 = Lists.newArrayList(); + /*排除休息时间两种方式 :1、设置休息时间 2、根据加班时长扣除 */ + int restType3=1; + + /*节假日是否允许加班:0-不允许、1-允许*/ + int overtimeEnable1 = 1; + /*节假日的加班方式:1-需审批,以加班流程为准、2-需审批,以打卡为准,但是不能超过加班流程时长、3-无需审批,根据打卡时间计算加班时长*/ + int computingMode1 = 1; + /*节假日的最小加班时长*/ + int minimumLen1 = 30; + /*节假日是否允许加班转调休*/ + int paidLeaveEnable1 = 0; + /*节假日加班转调休比例中的加班时长*/ + double lenOfOvertime1 = 1; + /*假节日加班转调休比例中的调休时长*/ + double lenOfLeave1 = 1; + /*节假日是否有休息时间*/ + int hasRestTime1 = 0; + + /*节假日加班补偿方式 1-默认加班补偿规则、2-根据员工在加班流程上选择的加班补偿类型进行补偿两种*/ + int paidLeaveEnableType1 = 0; + /*节假日默认加班补偿方式 里转调休的方式: 1-按加班时长比例转调休时长、2-按加班时长范围设置转调休时长、3-按加班的时间段设置转调休时长*/ + int paidLeaveEnableDefaultType1 = 1; + /*节假日 根据员工在加班流程上选择的加班补偿类型进行补偿 里转调休的方式: 1-按加班时长比例转调休时长、2-按加班时长范围设置转调休时长、3-按加班的时间段设置转调休时长*/ + int paidLeaveEnableFlowType1 = 1; + + // 按加班时长范围设置转调休时长: 加班时长 ≥* 分钟,转调休时长*分钟 + List> balanceLengthDetailLists1 = Lists.newArrayList(); + // 加班时间在19:00后,比例转调休时长 按照1:1 + List> balanceTimeDetailLists1 = Lists.newArrayList(); + /*排除节假时间两种方式 :1、设置休息时间 2、根据加班时长扣除 */ + int restType1=1; + /** + * 到这里结束,这块区间的变量就用不到了,就起到一个文字说明的意义 + */ + + //顺序显示,2是工作日,3是休息日,1是节假日 + int[] changetype = {2,3,1}; + + Map valueMap = Maps.newHashMap(); + if (!ruleId.equals("")) { + String sql = "select t1.name,t1.groupids,t2.* from kq_OvertimeRules t1 left join kq_OvertimeRulesDetail t2 on t1.id=t2.ruleId where (t1.isDelete is null or t1.isDelete!=1) and t1.id=" + ruleId; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql); + int dayType = 0;//1-工作日、2-休息日、3-节假日 + while (recordSet.next()) { + isEdit = true; + name = recordSet.getString("name"); + groupIds = recordSet.getString("groupIds"); + dayType = recordSet.getInt("dayType"); + int detailid = recordSet.getInt("id"); + int overtimeEnable = recordSet.getInt("overtimeEnable"); + int computingMode = recordSet.getInt("computingMode"); + int startTime = recordSet.getInt("startTime"); + int before_startTime = recordSet.getInt("before_startTime"); + int minimumLen = recordSet.getInt("minimumLen"); + int paidLeaveEnable = recordSet.getInt("paidLeaveEnable"); + double lenOfOvertime = recordSet.getDouble("lenOfOvertime"); + double lenOfLeave = recordSet.getDouble("lenOfLeave"); + int hasRestTime = recordSet.getInt("hasRestTime"); + int has_cut_point = recordSet.getInt("has_cut_point"); + String cut_point = recordSet.getString("cut_point"); + if("-1".equalsIgnoreCase(cut_point)){ + cut_point = "00:00"; + } + if(has_cut_point < 0){ + has_cut_point = 0; + } + if(has_cut_point == 0){ + cut_point = "00:00"; + } + if(before_startTime < 0){ + before_startTime = 0; + } + int paidLeaveEnableType = recordSet.getInt("paidLeaveEnableType"); + int paidLeaveEnableDefaultType = recordSet.getInt("paidLeaveEnableDefaultType"); + int paidLeaveEnableFlowType = recordSet.getInt("paidLeaveEnableFlowType"); + int restTimeType = recordSet.getInt("restTimeType"); + if(paidLeaveEnableType <= 0){ + paidLeaveEnableType = 1; + } + if(paidLeaveEnableDefaultType <= 0){ + paidLeaveEnableDefaultType = 1; + } + if(paidLeaveEnableFlowType <= 0){ + paidLeaveEnableFlowType = 1; + } + if(paidLeaveEnableDefaultType == 1 && paidLeaveEnable == 0){ + //如果是第一种生成调休方式,且没有开启关联调休,那么默认的加班转调休方式就是第一种 + paidLeaveEnableDefaultType = 1; + } + if(restTimeType <= 0){ + restTimeType = 1; + } + + valueMap.put("ID_"+dayType, detailid+""); + + valueMap.put("overtimeEnable"+dayType, overtimeEnable+""); + valueMap.put("computingMode"+dayType, computingMode+""); + valueMap.put("startTime"+dayType, startTime+""); + valueMap.put("before_startTime"+dayType, before_startTime+""); + valueMap.put("minimumLen"+dayType, minimumLen+""); + valueMap.put("paidLeaveEnable"+dayType, paidLeaveEnable+""); + valueMap.put("lenOfOvertime"+dayType, lenOfOvertime+""); + valueMap.put("lenOfLeave"+dayType, lenOfLeave+""); + valueMap.put("hasRestTime"+dayType, hasRestTime+""); + valueMap.put("restTimeType"+dayType, restTimeType+""); + valueMap.put("has_cut_point"+dayType, has_cut_point+""); + valueMap.put("cut_point"+dayType, cut_point+""); + valueMap.put("paidLeaveEnableType"+dayType, paidLeaveEnableType+""); + valueMap.put("paidLeaveEnableDefaultType"+dayType, paidLeaveEnableDefaultType+""); + valueMap.put("paidLeaveEnableFlowType"+dayType, paidLeaveEnableFlowType+""); + } + + for(int i = 0 ; i < changetype.length ; i++) { + int changetype_index = changetype[i]; + String hasRestTime_index = "hasRestTime"+changetype_index; + String paidLeaveEnable_index = "paidLeaveEnable"+changetype_index; + String paidLeaveEnableType_index = "paidLeaveEnableType"+changetype_index; + String paidLeaveEnableDefaultType_index = "paidLeaveEnableDefaultType"+changetype_index; + String paidLeaveEnableFlowType_index = "paidLeaveEnableFlowType"+changetype_index; + if(valueMap.containsKey(hasRestTime_index)){ + String hasRestTime = Util.null2String(valueMap.get(hasRestTime_index)); + if("1".equalsIgnoreCase(hasRestTime)){ + String restTimeType_index = "restTimeType"+changetype_index; + if(valueMap.containsKey(restTimeType_index)){ + String restTimeType = Util.null2String(valueMap.get(restTimeType_index)); + if("1".equalsIgnoreCase(restTimeType)){ +// 排除休息时间 + List restTimeList = new ArrayList(); + sql = "select * from kq_OvertimeRestTime where ruleId=? and dayType=? order by dayType,id"; + recordSet.executeQuery(sql, ruleId,changetype_index); + while (recordSet.next()) { + String startType = recordSet.getString("startType"); + String startTime = recordSet.getString("startTime"); + String endType = recordSet.getString("endType"); + String endTime = recordSet.getString("endTime"); + + Map restTimeMap = new HashMap(); + restTimeMap.put("startType", startType); + restTimeMap.put("startTime", startTime); + restTimeMap.put("endType", endType); + restTimeMap.put("endTime", endTime); + restTimeList.add(restTimeMap); + } + if(!restTimeList.isEmpty()){ + resultMap.put("restTimeRule"+changetype_index, restTimeList); + } + }else if("2".equalsIgnoreCase(restTimeType)){ +// 排除休息时长 + List restTimeList = new ArrayList(); + sql = "select * from kq_OvertimeRestlength where ruleId=? and dayType=? order by dayType,dsporder"; + recordSet.executeQuery(sql, ruleId,changetype_index); + while (recordSet.next()) { + String overlength = recordSet.getString("overlength"); + String cutlength = recordSet.getString("cutlength"); + + Map restTimeMap = new HashMap(); + restTimeMap.put("overtime", overlength); + restTimeMap.put("exclude", cutlength); + restTimeList.add(restTimeMap); + } + if(!restTimeList.isEmpty()){ + resultMap.put("restTimeRule"+changetype_index, restTimeList); + } + } + } + } + } + if(valueMap.containsKey(paidLeaveEnableType_index)){ + String ID_index = "ID_"+changetype_index; + if(valueMap.containsKey(ID_index)){ + String detailid = Util.null2String(valueMap.get(ID_index)); + String paidLeaveEnableType = Util.null2String(valueMap.get(paidLeaveEnableType_index)); + String paidLeaveEnableDefaultType = Util.null2String(valueMap.get(paidLeaveEnableDefaultType_index)); + String paidLeaveEnableFlowType = Util.null2String(valueMap.get(paidLeaveEnableFlowType_index)); + if("1".equalsIgnoreCase(paidLeaveEnableType)){ + if(valueMap.containsKey(paidLeaveEnable_index)) { + String paidLeaveEnable = Util.null2String(valueMap.get(paidLeaveEnable_index)); + if("1".equalsIgnoreCase(paidLeaveEnable)){ + if("2".equalsIgnoreCase(paidLeaveEnableDefaultType)){ + set_lengthDetailList(detailid,changetype_index,resultMap); + }else if("3".equalsIgnoreCase(paidLeaveEnableDefaultType)){ + set_TimeDetailList(detailid,changetype_index,resultMap); + } + } + } + }else if("2".equalsIgnoreCase(paidLeaveEnableType)){ + if("2".equalsIgnoreCase(paidLeaveEnableFlowType)){ + set_lengthDetailList(detailid,changetype_index,resultMap); + }else if("3".equalsIgnoreCase(paidLeaveEnableFlowType)){ + set_TimeDetailList(detailid,changetype_index,resultMap); + } + } + } + } + + } + } + + List> groupList = new ArrayList>(); + Map groupItem = new HashMap(); + List itemList = new ArrayList(); + HrmFieldSearchConditionComInfo hrmFieldSearchConditionComInfo = new HrmFieldSearchConditionComInfo(); + SearchConditionItem searchConditionItem = null; + HrmFieldBean hrmFieldBean = null; + + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname("name");//加班规则名称 + hrmFieldBean.setFieldlabel("388831"); + hrmFieldBean.setFieldhtmltype("1"); + hrmFieldBean.setType("1"); + hrmFieldBean.setViewAttr(3); + hrmFieldBean.setFieldvalue(name); + hrmFieldBean.setIsFormField(true); + searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + searchConditionItem.setRules("required|string"); + itemList.add(searchConditionItem); + + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname("groupIds");//应用范围--考勤组 + hrmFieldBean.setFieldlabel("19374"); + hrmFieldBean.setFieldhtmltype("3"); + hrmFieldBean.setType("mkqgroup"); + hrmFieldBean.setFieldvalue(groupIds); + hrmFieldBean.setIsFormField(true); + searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + KQGroupComInfo kqGroupComInfo = new KQGroupComInfo(); + List> replaceDatas = new ArrayList>(); + Map datas = new HashMap(); + String[] groupIdArr = groupIds.split(","); + for (String groupId : groupIdArr) { + datas = new HashMap(); + datas.put("id", groupId); + datas.put("name", kqGroupComInfo.getGroupname(groupId)); + replaceDatas.add(datas); + } + searchConditionItem.getBrowserConditionParam().setReplaceDatas(replaceDatas); + /*一个考勤组只能关联一个加班规则,所以新建或者编辑的时候需要对考勤组浏览按钮内的数据进行过滤*/ + Map dataMap = new HashMap(); + Map completeMap = new HashMap(); + String kqGroupIdStr = ""; + String sql = "select * from kq_OvertimeRules where (isDelete is null or isDelete !=1) "; + if (isEdit) { + sql += " and id !=" + ruleId; + } + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(sql); + while (recordSet.next()) { + String kqGroupIds = recordSet.getString("groupIds"); + if (kqGroupIds.equals("")) { + continue; + } + kqGroupIdStr += "," + kqGroupIds; + } + XssUtil xssUtil = new XssUtil(); + dataMap.put("sqlWhere", kqGroupIdStr.length() > 0 ? xssUtil.put(" kqType <>3 and id not in (" + kqGroupIdStr.substring(1) + ")") : xssUtil.put(" kqType <>3 ")); + completeMap.put("sqlWhere", kqGroupIdStr.length() > 0 ? xssUtil.put(" kqType <>3 and id not in (" + kqGroupIdStr.substring(1) + ")") : xssUtil.put(" kqType <>3 ")); + searchConditionItem.getBrowserConditionParam().setDataParams(dataMap); + searchConditionItem.getBrowserConditionParam().setCompleteParams(completeMap); + itemList.add(searchConditionItem); + + groupItem.put("title", SystemEnv.getHtmlLabelName(1361, user.getLanguage())); + groupItem.put("defaultshow", true); + groupItem.put("items", itemList); + groupList.add(groupItem); + + for(int i = 0 ; i < changetype.length ; i++){ + int changetype_index = changetype[i]; + groupItem = new HashMap(); + itemList = new ArrayList(); + String overtimeEnable_key = "overtimeEnable"+changetype_index; + String overtimeEnable_value = isEdit?Util.null2String(valueMap.get(overtimeEnable_key),"1"):"1"; + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname(overtimeEnable_key);//是否允许加班 + hrmFieldBean.setFieldlabel("388833"); + hrmFieldBean.setFieldhtmltype("4"); + hrmFieldBean.setType("1"); + hrmFieldBean.setFieldvalue(overtimeEnable_value); + hrmFieldBean.setIsFormField(true); + searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + Map otherParamsMap = new HashMap(); + otherParamsMap.put("display", "switch"); + searchConditionItem.setOtherParams(otherParamsMap); + itemList.add(searchConditionItem); + + String computingMode_key = "computingMode"+changetype_index; + String computingMode_value = isEdit?Util.null2String(valueMap.get(computingMode_key),"1"):"1"; + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname(computingMode_key);//加班方式 + hrmFieldBean.setFieldlabel("388834"); + hrmFieldBean.setFieldhtmltype("5"); + hrmFieldBean.setType("1"); + hrmFieldBean.setIsFormField(true); + searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + List statusOptions = new ArrayList(); + statusOptions.add(new SearchConditionOption("1", SystemEnv.getHtmlLabelName(500382, user.getLanguage()),"1".equalsIgnoreCase(computingMode_value))); + statusOptions.add(new SearchConditionOption("2", SystemEnv.getHtmlLabelName(500383, user.getLanguage()),"2".equalsIgnoreCase(computingMode_value))); + statusOptions.add(new SearchConditionOption("4", SystemEnv.getHtmlLabelName(524827, user.getLanguage()),"4".equalsIgnoreCase(computingMode_value))); + statusOptions.add(new SearchConditionOption("3", SystemEnv.getHtmlLabelName(390837, user.getLanguage()),"3".equalsIgnoreCase(computingMode_value))); + searchConditionItem.setOptions(statusOptions); + searchConditionItem.setDetailtype(3); + itemList.add(searchConditionItem); + + if(changetype_index == 2){ + String startTime_key = "startTime"+changetype_index; + String startTime_value = isEdit?Util.null2String(valueMap.get(startTime_key),"30"):"30"; + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname(startTime_key);//工作日下班多少分钟后开始计算加班 + hrmFieldBean.setFieldlabel("388842"); + hrmFieldBean.setFieldhtmltype("1"); + hrmFieldBean.setType("2"); + hrmFieldBean.setViewAttr(3); + hrmFieldBean.setFieldvalue(startTime_value); + hrmFieldBean.setIsFormField(true); + searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + searchConditionItem.setRules("required|integer"); + searchConditionItem.setMin("0"); + itemList.add(searchConditionItem); + + String before_startTime_key = "before_startTime"+changetype_index; + String before_startTime_value = isEdit?Util.null2String(valueMap.get(before_startTime_key),"0"):"0"; + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname(before_startTime_key);//工作日上班前多少分钟后开始计算加班 + hrmFieldBean.setFieldlabel("388842"); + hrmFieldBean.setFieldhtmltype("1"); + hrmFieldBean.setType("2"); + hrmFieldBean.setViewAttr(3); + hrmFieldBean.setFieldvalue(before_startTime_value); + hrmFieldBean.setIsFormField(true); + searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + searchConditionItem.setRules("required|integer"); + searchConditionItem.setMin("0"); + itemList.add(searchConditionItem); + } + + String minimumLen_key = "minimumLen"+changetype_index; + String minimumLen_value = isEdit?Util.null2String(valueMap.get(minimumLen_key),"30"):"30"; + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname(minimumLen_key);//最小加班时长 + hrmFieldBean.setFieldlabel("388843"); + hrmFieldBean.setFieldhtmltype("1"); + hrmFieldBean.setType("2"); + hrmFieldBean.setViewAttr(3); + hrmFieldBean.setFieldvalue(minimumLen_value); + hrmFieldBean.setIsFormField(true); + searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + searchConditionItem.setRules("required|integer"); + searchConditionItem.setMin("1"); + itemList.add(searchConditionItem); + + String paidLeaveEnableType_key = "paidLeaveEnableType"+changetype_index; + String paidLeaveEnableType_value = isEdit?Util.null2String(valueMap.get(paidLeaveEnableType_key),"1"):"1"; + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname(paidLeaveEnableType_key);//加班补偿方式 + hrmFieldBean.setFieldlabel("388838"); + hrmFieldBean.setFieldhtmltype("5"); + hrmFieldBean.setType("1"); + hrmFieldBean.setIsFormField(true); + searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + List paidLeaveEnableOptions = new ArrayList(); + paidLeaveEnableOptions.add(new SearchConditionOption("1", SystemEnv.getHtmlLabelName(524828, user.getLanguage()),"1".equalsIgnoreCase(paidLeaveEnableType_value))); + paidLeaveEnableOptions.add(new SearchConditionOption("2", SystemEnv.getHtmlLabelName(524833, user.getLanguage()),"2".equalsIgnoreCase(paidLeaveEnableType_value))); + searchConditionItem.setOptions(paidLeaveEnableOptions); + searchConditionItem.setDetailtype(3); + itemList.add(searchConditionItem); + + String paidLeaveEnableDefaultType_key = "paidLeaveEnableDefaultType"+changetype_index; + String paidLeaveEnableDefaultType_value = isEdit?Util.null2String(valueMap.get(paidLeaveEnableDefaultType_key),"1"):"1"; + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname(paidLeaveEnableDefaultType_key);//默认加班补偿方式 里转调休的方式 + hrmFieldBean.setFieldlabel("524828"); + hrmFieldBean.setFieldhtmltype("5"); + hrmFieldBean.setType("2"); + hrmFieldBean.setIsFormField(true); + searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + List paidLeaveDefaultTypeOptions = new ArrayList(); + paidLeaveDefaultTypeOptions.add(new SearchConditionOption("1", SystemEnv.getHtmlLabelName(524830, user.getLanguage()),"1".equalsIgnoreCase(paidLeaveEnableDefaultType_value))); + paidLeaveDefaultTypeOptions.add(new SearchConditionOption("2", SystemEnv.getHtmlLabelName(524831, user.getLanguage()),"2".equalsIgnoreCase(paidLeaveEnableDefaultType_value))); +// 这个方式只是临时屏蔽,后面可能还是会启用,不要占用这个key是3的 +// paidLeaveDefaultTypeOptions.add(new SearchConditionOption("3", SystemEnv.getHtmlLabelName(524832, user.getLanguage()),"3".equalsIgnoreCase(paidLeaveEnableDefaultType_value))); + searchConditionItem.setOptions(paidLeaveDefaultTypeOptions); + searchConditionItem.setDetailtype(1); + itemList.add(searchConditionItem); + + String paidLeaveEnableFlowType_key = "paidLeaveEnableFlowType"+changetype_index; + String paidLeaveEnableFlowType_value = isEdit?Util.null2String(valueMap.get(paidLeaveEnableFlowType_key),"1"):"1"; + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname(paidLeaveEnableFlowType_key);//根据员工在加班流程上选择的加班补偿类型进行补偿 + hrmFieldBean.setFieldlabel("524833"); + hrmFieldBean.setFieldhtmltype("5"); + hrmFieldBean.setType("2"); + hrmFieldBean.setIsFormField(true); + searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + List paidLeaveFlowTypeOptions = new ArrayList(); + paidLeaveFlowTypeOptions.add(new SearchConditionOption("1", SystemEnv.getHtmlLabelName(524830, user.getLanguage()),"1".equalsIgnoreCase(paidLeaveEnableFlowType_value))); + paidLeaveFlowTypeOptions.add(new SearchConditionOption("2", SystemEnv.getHtmlLabelName(524831, user.getLanguage()),"2".equalsIgnoreCase(paidLeaveEnableFlowType_value))); +// 这个方式只是临时屏蔽,后面可能还是会启用,不要占用这个key是3的 +// paidLeaveFlowTypeOptions.add(new SearchConditionOption("3", SystemEnv.getHtmlLabelName(524832, user.getLanguage()),"3".equalsIgnoreCase(paidLeaveEnableFlowType_value))); + searchConditionItem.setOptions(paidLeaveFlowTypeOptions); + searchConditionItem.setDetailtype(1); + itemList.add(searchConditionItem); + + String paidLeaveEnable_key = "paidLeaveEnable"+changetype_index; + String paidLeaveEnable_value = isEdit?Util.null2String(valueMap.get(paidLeaveEnable_key),"0"):"0"; + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname(paidLeaveEnable_key);//是否允许加班转调休 + hrmFieldBean.setFieldlabel("388838"); + hrmFieldBean.setFieldhtmltype("4"); + hrmFieldBean.setType("1"); + hrmFieldBean.setFieldvalue(paidLeaveEnable_value); + hrmFieldBean.setIsFormField(true); + searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + itemList.add(searchConditionItem); + + String lenOfOvertime_key = "lenOfOvertime"+changetype_index; + String lenOfOvertime_value = isEdit?Util.null2String(valueMap.get(lenOfOvertime_key),"1"):"1"; + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname(lenOfOvertime_key);//加班转调休比例中的加班时长 + hrmFieldBean.setFieldlabel("389222"); + hrmFieldBean.setFieldhtmltype("1"); + hrmFieldBean.setType("2"); + hrmFieldBean.setViewAttr(3); + hrmFieldBean.setFieldvalue(lenOfOvertime_value); + hrmFieldBean.setIsFormField(true); + searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + searchConditionItem.setRules("required|numeric"); + searchConditionItem.setStep("0.01"); + searchConditionItem.setPrecision(2); + itemList.add(searchConditionItem); + + String lenOfLeave_key = "lenOfLeave"+changetype_index; + String lenOfLeave_value = isEdit?Util.null2String(valueMap.get(lenOfLeave_key),"1"):"1"; + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname(lenOfLeave_key);//加班转调休比例中的调休时长 + hrmFieldBean.setFieldlabel("389223"); + hrmFieldBean.setFieldhtmltype("1"); + hrmFieldBean.setType("2"); + hrmFieldBean.setViewAttr(3); + hrmFieldBean.setFieldvalue(lenOfLeave_value); + hrmFieldBean.setIsFormField(true); + searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + searchConditionItem.setRules("required|numeric"); + searchConditionItem.setStep("0.01"); + searchConditionItem.setPrecision(2); + itemList.add(searchConditionItem); + + String hasRestTime_key = "hasRestTime"+changetype_index; + String hasRestTime_value = isEdit?Util.null2String(valueMap.get(hasRestTime_key),"0"):"0"; + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname(hasRestTime_key);//排除休息时间 + hrmFieldBean.setFieldlabel("388565"); + hrmFieldBean.setFieldhtmltype("4"); + hrmFieldBean.setType("1"); + hrmFieldBean.setFieldvalue(hasRestTime_value); + hrmFieldBean.setIsFormField(true); + searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + otherParamsMap = new HashMap(); + otherParamsMap.put("display", "switch"); + searchConditionItem.setOtherParams(otherParamsMap); + itemList.add(searchConditionItem); + + String restTimeType_key = "restTimeType"+changetype_index; + String restTimeType_value = isEdit?Util.null2String(valueMap.get(restTimeType_key),"1"):"1"; + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname(restTimeType_key);//排除休息时间类型 + hrmFieldBean.setFieldlabel("388565"); + hrmFieldBean.setFieldhtmltype("5"); + hrmFieldBean.setType("1"); + hrmFieldBean.setIsFormField(true); + searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + List restTimeTypeOptions = new ArrayList(); + restTimeTypeOptions.add(new SearchConditionOption("1", SystemEnv.getHtmlLabelName(525905, user.getLanguage()),"1".equalsIgnoreCase(restTimeType_value))); + restTimeTypeOptions.add(new SearchConditionOption("2", SystemEnv.getHtmlLabelName(524834, user.getLanguage()),"2".equalsIgnoreCase(restTimeType_value))); + searchConditionItem.setOptions(restTimeTypeOptions); + searchConditionItem.setDetailtype(3); + itemList.add(searchConditionItem); + + String has_cut_point_key = "has_cut_point"+changetype_index; + String has_cut_point_value = isEdit?Util.null2String(valueMap.get(has_cut_point_key),"0"):"0"; + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname(has_cut_point_key);// 是否开启 自定义跨天加班归属分界点 + hrmFieldBean.setFieldlabel("524835"); + hrmFieldBean.setFieldhtmltype("4"); + hrmFieldBean.setType("2"); + hrmFieldBean.setFieldvalue(has_cut_point_value); + hrmFieldBean.setIsFormField(true); + searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + itemList.add(searchConditionItem); + + String cut_point_key = "cut_point"+changetype_index; + String cut_point_value = isEdit?Util.null2String(valueMap.get(cut_point_key),"00:00"):"00:00"; + if("0".equalsIgnoreCase(has_cut_point_value)){ + cut_point_value = "00:00"; + } + hrmFieldBean = new HrmFieldBean(); + hrmFieldBean.setFieldname(cut_point_key);// 自定义跨天加班归属分界点 + hrmFieldBean.setFieldlabel("524835"); + hrmFieldBean.setFieldhtmltype("3"); + hrmFieldBean.setType("19"); + hrmFieldBean.setFieldvalue(cut_point_value); + hrmFieldBean.setIsFormField(true); + searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user); + itemList.add(searchConditionItem); + +// 2是工作日,3是休息日,1是节假日 + if(changetype_index == 2){ + groupItem.put("title", SystemEnv.getHtmlLabelName(388841, user.getLanguage()));//工作日加班 + }else if(changetype_index == 3){ + groupItem.put("title", SystemEnv.getHtmlLabelName(389730, user.getLanguage()));//休息日加班 + }else if(changetype_index == 1){ + groupItem.put("title", SystemEnv.getHtmlLabelName(1959, user.getLanguage()));//节假日加班 + } + groupItem.put("defaultshow", true); + groupItem.put("items", itemList); + groupList.add(groupItem); + } + resultMap.put("condition", groupList); + + /** + * 判断调休是否已设置 + */ + 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)"; + recordSet.executeQuery(sql); + boolean hasTXRules = recordSet.getCounts()>0; + resultMap.put("hasTXrules",hasTXRules); + return resultMap; + } + + private void set_TimeDetailList(String detailid, int changetype_index, Map resultMap) { + RecordSet recordSet = new RecordSet(); + List timeDetailList = new ArrayList(); + String sql = "select * from kq_OvertimeBalanceTimeDetail where rulesdetailid=? order by timepoint"; + recordSet.executeQuery(sql, detailid); + while (recordSet.next()) { + String timepoint = recordSet.getString("timepoint"); + String lenOfOvertime = recordSet.getString("lenOfOvertime"); + String lenOfLeave = recordSet.getString("lenOfLeave"); + String dsporder = recordSet.getString("dsporder"); + + Map timeDetailMap = new HashMap(); + timeDetailMap.put("time", timepoint); + timeDetailMap.put("left", lenOfOvertime); + timeDetailMap.put("right", lenOfLeave); + timeDetailMap.put("dsporder", dsporder); + timeDetailList.add(timeDetailMap); + } + if(!timeDetailList.isEmpty()){ + resultMap.put("paidLeaveEnableTypeRule"+changetype_index, timeDetailList); + } + } + + private void set_lengthDetailList(String detailid, int changetype_index, + Map resultMap){ + + RecordSet recordSet = new RecordSet(); + List lengthDetailList = new ArrayList(); + String sql = "select * from kq_OvertimeBalanceLengthDetail where rulesdetailid=? order by overtimelength"; + recordSet.executeQuery(sql, detailid); + while (recordSet.next()) { + String overtimelength = recordSet.getString("overtimelength"); + String balancelength = recordSet.getString("balancelength"); + String dsporder = recordSet.getString("dsporder"); + + Map lengthDetailMap = new HashMap(); + lengthDetailMap.put("work", overtimelength); + lengthDetailMap.put("rest", balancelength); + lengthDetailMap.put("dsporder", dsporder); + lengthDetailList.add(lengthDetailMap); + } + if(!lengthDetailList.isEmpty()){ + resultMap.put("paidLeaveEnableTypeRule"+changetype_index, lengthDetailList); + } + } +} diff --git a/src/com/engine/kq/cmd/overtimerules/GetSearchListCmd.java b/src/com/engine/kq/cmd/overtimerules/GetSearchListCmd.java new file mode 100644 index 0000000..8d272e4 --- /dev/null +++ b/src/com/engine/kq/cmd/overtimerules/GetSearchListCmd.java @@ -0,0 +1,67 @@ +package com.engine.kq.cmd.overtimerules; + +import com.cloudstore.dev.api.util.Util_TableMap; +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.PageIdConst; +import weaver.general.Util; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; +import weaver.systeminfo.SystemEnv; + +import java.util.HashMap; +import java.util.Map; + +/** + * 加班规则--获取加班规则列表 + */ +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(); + + boolean canEdit = HrmUserVarify.checkUserRight("KQOvertimeRulesEdit:Edit", user);//是否具有编辑的权限; + boolean canDelete = HrmUserVarify.checkUserRight("KQOvertimeRulesDelete:Delete", user);//是否具有删除的权限; + boolean canLog = HrmUserVarify.checkUserRight("KQOvertimeRules:Log", user);//是否具有查看日志的权限; + + String backFields = " id,name,groupIds "; + String sqlFrom = " from kq_OvertimeRules "; + String sqlWhere = " where 1=1 and (isDelete is null or isDelete!=1) "; + String orderBy = " id "; + String pageUid = "1b3ad739-67fa-8b1e-1c19-6d37c1a33469"; + String operateString = ""; + operateString = ""; + operateString += " "; + operateString += " "; + operateString += " "; + operateString += " "; + operateString += ""; + String tableString = "" + + "" + + " " + + operateString + + " " + + " " + + " " + + " " + + " " + + "
"; + String sessionKey = pageUid + "_" + Util.getEncrypt(Util.getRandom()); + Util_TableMap.setVal(sessionKey, tableString); + resultMap.put("sessionkey", sessionKey); + return resultMap; + } +} diff --git a/src/com/engine/kq/cmd/overtimerules/IsRepeatSettingCmd.java b/src/com/engine/kq/cmd/overtimerules/IsRepeatSettingCmd.java new file mode 100644 index 0000000..fb41d90 --- /dev/null +++ b/src/com/engine/kq/cmd/overtimerules/IsRepeatSettingCmd.java @@ -0,0 +1,70 @@ +package com.engine.kq.cmd.overtimerules; + +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 weaver.systeminfo.SystemEnv; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 加班规则--判断某考勤组是否重复设置了加班规则 + */ +public class IsRepeatSettingCmd extends AbstractCommonCommand> { + + public IsRepeatSettingCmd(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(); + + String ruleId = Util.null2String(params.get("ruleId"));//加班规则的ID + String groupIds = Util.null2String(params.get("groupIds"));//考勤组的ID + + List errMsgList = new ArrayList();//考勤组重复设置了加班规则的错误信息提示集合 + + RecordSet recordSet = new RecordSet(); + String[] groupIdArr = groupIds.split(","); + for (int i = 0; i < groupIdArr.length; i++) { + String groupId = groupIdArr[i]; + String groupName = "";//考勤组的名称 + String sql = "select * from kq_overtimeRules where (isDelete is null or isDelete!=1) "; + if (recordSet.getDBType().equalsIgnoreCase("sqlserver")) { + sql += " and ','+groupIds+',' like '%," + groupId + ",%'"; + } else if (recordSet.getDBType().equalsIgnoreCase("mysql")) { + sql += " and contract(',',groupIds,',') like '%," + groupId + ",%'"; + } else { + sql += " and ','||groupIds||',' like '%," + groupId + ",%'"; + } + if (!ruleId.equals("")) { + sql += " and ruleId not in (" + ruleId + ")"; + } + recordSet.executeQuery(sql); + if (recordSet.next()) { + errMsgList.add(groupName + SystemEnv.getHtmlLabelName(81869, user.getLanguage())); + } + } + + if(errMsgList.size()==0){ + resultMap.put("isRepeatSetting",false); + }else{ + resultMap.put("isRepeatSetting",true); + resultMap.put("message",errMsgList); + } + return resultMap; + } +} diff --git a/src/com/engine/kq/cmd/overtimerules/SaveOvertimeUnitCmd.java b/src/com/engine/kq/cmd/overtimerules/SaveOvertimeUnitCmd.java new file mode 100644 index 0000000..0d6ed68 --- /dev/null +++ b/src/com/engine/kq/cmd/overtimerules/SaveOvertimeUnitCmd.java @@ -0,0 +1,115 @@ +package com.engine.kq.cmd.overtimerules; + +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.KQAttFlowSetComInfo; +import weaver.conn.RecordSet; +import weaver.general.Util; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; +import weaver.systeminfo.SystemEnv; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 加班单位--保存 + */ +public class SaveOvertimeUnitCmd extends AbstractCommonCommand> { + + private SimpleBizLogger logger; + + public SaveOvertimeUnitCmd(Map params, User user) { + this.user = user; + this.params = params; + this.logger = new SimpleBizLogger(); + + BizLogContext bizLogContext = new BizLogContext(); + bizLogContext.setLogType(BizLogType.HRM_ENGINE);//模块类型 + bizLogContext.setBelongType(BizLogSmallType4Hrm.HRM_ENGINE_KQ_OVERTIMEUNIT);//所属大类型 + bizLogContext.setLogSmallType(BizLogSmallType4Hrm.HRM_ENGINE_KQ_OVERTIMEUNIT);//当前小类型 + bizLogContext.setParams(params);//当前request请求参数 + logger.setUser(user);//当前操作人 + String mainSql = "select * from kq_overtimeUnit"; + logger.setMainSql(mainSql, "id");//主表sql + logger.setMainPrimarykey("id");//主日志表唯一key + logger.setMainTargetNameMethod("com.engine.kq.util.KQTransMethod.getTargetName4OvertimeUnit",""+user.getLanguage()); + logger.before(bizLogContext); + } + + @Override + public BizLogContext getLogContext() { + return null; + } + + @Override + public List getLogContexts() { + return logger.getBizLogContexts(); + } + + @Override + public Map execute(CommandContext commandContext) { + Map resultMap = new HashMap(); + + /* 加班规则维护权限 */ + boolean canAdd = HrmUserVarify.checkUserRight("KQOvertimeRulesAdd:Add", user);//是否具有新建权限 + boolean canEdit = HrmUserVarify.checkUserRight("KQOvertimeRulesEdit:Edit", user);//是否具有编辑的权限; + if (!canAdd && !canEdit) { + resultMap.put("status", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage())); + return resultMap; + } + + //是否设置了【流程和打卡取交集的加班方式】 + boolean hasComputingmode4 = false; + RecordSet recordSet1 = new RecordSet(); + String checkSql = "select * from kq_overtimerulesdetail where computingmode = 4 and ruleid not in(select id from kq_overtimerules where isdelete =1) "; + recordSet1.executeQuery(checkSql); + if(recordSet1.next()){ + hasComputingmode4 = true; + } + + + int id = 1;////暂为备用字段,加班单位ID,固定为1 + int minimumUnit = Util.getIntValue((String) params.get("minimumUnit"), 1);//最小加班单位:1-按天加班、2-按半天加班、3-按小时加班、4-按整天加班 + int overtimeConversion = Util.getIntValue((String) params.get("overtimeConversion"), 1);//加班时长折算方式:1-四舍五入、2-向上取整、3-向下取整 + double hoursToday = Util.getDoubleValue((String) params.get("hoursToday"), -1.00);//日折算时长 + int timeselection = Util.getIntValue((String) params.get("timeselection"), 1);//半天单位 时间选择方式:1-下拉框选择 、2-具体时间 + if(hasComputingmode4){ + if(minimumUnit == 2 || minimumUnit == 4){ + resultMap.put("sign", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(529168, user.getLanguage())); + return resultMap; + } + } + + if(minimumUnit != 2){ + RecordSet rs = new RecordSet(); + //如果出差单位不再是半天了,需要删除原半天设置 + String del_2_sql = "delete from kq_timeselection where selectiontype=3 and minimumUnit=2"; + boolean is_2_del = rs.executeUpdate(del_2_sql); + } + + boolean flag = true; + String sql = "update kq_OvertimeUnit set minimumUnit=?,hoursToday=?,timeselection=?,overtimeConversion=? where id=?"; + RecordSet recordSet = new RecordSet(); + flag = recordSet.executeUpdate(sql, minimumUnit, hoursToday,timeselection,overtimeConversion, id); + if (flag) { + resultMap.put("sign", "1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(83551, user.getLanguage()));//保存成功 + } else { + resultMap.put("sign", "-1"); + resultMap.put("message", SystemEnv.getHtmlLabelName(84544, user.getLanguage()));//保存失败 + } + + KQAttFlowSetComInfo kqAttFlowSetComInfo = new KQAttFlowSetComInfo(); + kqAttFlowSetComInfo.removeKQAttFlowSetComInfoCache(); + + return resultMap; + } +} 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..f7dbe1b --- /dev/null +++ b/src/com/engine/kq/cmd/shiftmanagement/GetShiftManagementBaseFormCmd.java @@ -0,0 +1,431 @@ +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", + "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)){ + 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")); + String clockinnot = Util.null2String(rs.getString("clockinnot")); + sectionMap = new HashMap<>(); + sectionMaps = new HashMap<>(); + sectionMap.put("across", across); + sectionMap.put("times", times); + sectionMap.put("mins", mins); + sectionMap.put("mins_next", mins_next); + sectionMap.put("clockinnot", clockinnot); + 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); + } + } + + groupSectionMaps = new HashMap<>(); + sectionMaps = new HashMap<>(); + String getRestSections = "select * from kq_ShiftRestTimeSections where (isdelete is null or isdelete <> '1') and serialid = ? order by orderId "; + 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")); + String record = Util.null2String(rs.getString("record1")); + String orderId = Util.null2String(rs.getString("orderId")); + restSectionsMap = new HashMap<>(); + sectionMaps = new HashMap<>(); + restSectionsMap.put("resttype", resttype); + restSectionsMap.put("time", times); + restSectionsMap.put("across", across); + restSectionsMap.put("record", record); + restSectionsMap.put("orderId", orderId); + sectionMaps.put(resttype, restSectionsMap); + if(groupSectionMaps.get(record) != null){ + List tmpSections = (List) groupSectionMaps.get(record); + ((Map)tmpSections.get(tmpSections.size()-1)).putAll(sectionMaps); + }else{ + sectionMaps.put("record", record); + restSectionsList.add(sectionMaps); + groupSectionMaps.put(record, restSectionsList); + } + } + 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("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..f3d3a2d --- /dev/null +++ b/src/com/engine/kq/cmd/shiftmanagement/SaveShiftManagementBaseFormCmd.java @@ -0,0 +1,514 @@ +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.KQGroupBiz; +import com.engine.kq.biz.KQGroupComInfo; +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"))); + 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=? 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,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,record1,orderId) values(?,?,?,?,?,?)"; + int restCount = restTimeSections.size(); + rs = new RecordSet(); + for(int i = 0 ; i < restCount ; i++){ + JSONObject jsonRest = ((JSONObject)restTimeSections.get(i)); + if(jsonRest.containsKey("start") && jsonRest.containsKey("end")){ + String record=Util.null2String(jsonRest.get("record")); + String orderId=Util.null2String(jsonRest.get("orderId")); + + JSONObject start_jsonRest = (JSONObject) jsonRest.get("start"); + String time=Util.null2String(start_jsonRest.get("time")); + String resttype="start"; + String across=Util.null2String(start_jsonRest.get("accross")); + rst.executeUpdate(restSql, serialid,resttype,time,across,record,orderId); + + JSONObject end_jsonRest = (JSONObject) jsonRest.get("end"); + time=Util.null2String(end_jsonRest.get("time")); + resttype="end"; + across=Util.null2String(end_jsonRest.get("accross")); + rst.executeUpdate(restSql, serialid,resttype,time,across,record,orderId); + } + } + rs = new RecordSet(); + String workSql = "insert into kq_ShiftOnOffWorkSections(serialid,across,mins,times,onoffworktype,record,mins_next,clockinnot) 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")); + String clockinnot=Util.null2s(Util.null2String(inWork.get("clockinnot")),"0"); + rst.executeUpdate(workSql, serialid,across,mins,times,onOffWorkType,record,mins_next,clockinnot); + } + } + 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"))); + 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)" + + " 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); + + 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,record1,orderId) values(?,?,?,?,?,?)"; + int restCount = restTimeSections.size(); + rs = new RecordSet(); + for(int i = 0 ; i < restCount ; i++){ + JSONObject jsonRest = ((JSONObject)restTimeSections.get(i)); + if(jsonRest.containsKey("start") && jsonRest.containsKey("end")){ + String record=Util.null2String(jsonRest.get("record")); + String orderId=Util.null2String(jsonRest.get("orderId")); + JSONObject start_jsonRest = (JSONObject) jsonRest.get("start"); + String time=Util.null2String(start_jsonRest.get("time")); + String resttype="start"; + String across=Util.null2String(start_jsonRest.get("accross")); + rst.executeUpdate(restSql, serialid,resttype,time,across,record,orderId); + + JSONObject end_jsonRest = (JSONObject) jsonRest.get("end"); + time=Util.null2String(end_jsonRest.get("time")); + resttype="end"; + across=Util.null2String(end_jsonRest.get("accross")); + rst.executeUpdate(restSql, serialid,resttype,time,across,record,orderId); + } + } + rs = new RecordSet(); + String workSql = "insert into kq_ShiftOnOffWorkSections(serialid,across,mins,times,onoffworktype,record,mins_next,clockinnot) 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")); + String clockinnot = Util.null2s(Util.null2String(inWork.get("clockinnot")),"0"); + rst.executeUpdate(workSql, serialid,across,mins,times,onOffWorkType,record,mins_next,clockinnot); + } + } + 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", ""+ 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/entity/WorkTimeEntity.java b/src/com/engine/kq/entity/WorkTimeEntity.java new file mode 100644 index 0000000..4642f25 --- /dev/null +++ b/src/com/engine/kq/entity/WorkTimeEntity.java @@ -0,0 +1,127 @@ +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;//自由班制计算方式 + + 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; + } +} diff --git a/src/com/engine/kq/enums/OverTimeComputingModeEnum.java b/src/com/engine/kq/enums/OverTimeComputingModeEnum.java new file mode 100644 index 0000000..786d25d --- /dev/null +++ b/src/com/engine/kq/enums/OverTimeComputingModeEnum.java @@ -0,0 +1,66 @@ +package com.engine.kq.enums; + +/** + * 加班类型枚举类 + * 1-需审批,以审批单为准 + * 2-需审批,以打卡为准,但是不能超过审批时长 + * 3-无需审批,根据打卡时间计算加班时长 + */ +public enum OverTimeComputingModeEnum { + + /** + * 需审批,以审批单为准 + */ + FLOW("1","需审批,以加班流程为准","500382"), + /** + * 需审批,以打卡为准,但是不能超过审批时长 + */ + FLOW2CARD("2","需审批,以打卡为准,但不能超过加班流程时长","500383"), + /** + * 无需审批,根据打卡时间计算加班时长 + */ + FLOWINCARD("4","需审批,打卡和流程均统计,取两者的交集","524827"), + /** + * 无需审批,根据打卡时间计算加班时长 + */ + CARD("3","无需审批,根据打卡时间计算加班时长","390837"); + + private String computingMode; + private String title; + private String label; + + /** + * + * @param computingMode + */ + OverTimeComputingModeEnum(String computingMode,String title,String label) { + this.computingMode = computingMode; + this.title = title; + this.label = label; + } + + public String getComputingMode() { + return computingMode; + } + + public void setComputingMode(String computingMode) { + this.computingMode = computingMode; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + +} diff --git a/src/com/engine/kq/util/KQDurationCalculatorUtil.java b/src/com/engine/kq/util/KQDurationCalculatorUtil.java new file mode 100644 index 0000000..975769a --- /dev/null +++ b/src/com/engine/kq/util/KQDurationCalculatorUtil.java @@ -0,0 +1,608 @@ +package com.engine.kq.util; + +import com.engine.kq.biz.KQLeaveRulesBiz; +import com.engine.kq.biz.KQLeaveRulesComInfo; +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.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); + } + + /** + * 不记录日志的,流程的超时提醒日志太大 + * @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){ + 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"); + 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("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); + + //每一天的流程时长都在这里了,搞吧 + 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; + } + + durationMap.put("duration", KQDurationCalculatorUtil.getDurationRound(""+D_Duration)); + durationMap.put("min_duration", KQDurationCalculatorUtil.getDurationRound(""+Min_Duration)); + + }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..f930500 --- /dev/null +++ b/src/com/engine/kq/util/KQTransMethod.java @@ -0,0 +1,1367 @@ +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.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.time.LocalDate; +import java.time.Period; +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); + try { + 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")); + String legalOrWelfare = Util.null2String(otherParaArr[4]); + + /*获取当前日期*/ + String date = DateUtil.getCurrentDate(); + + canUseAmount = KQBalanceOfLeaveBiz.getCanUseAmount(resourceId, leaveRulesId, belongYear, baseAmount, legalOrWelfare, date); + } catch (Exception e) { + e.printStackTrace(); + } + return canUseAmount.setScale(2, RoundingMode.HALF_UP).toPlainString(); + } + + /** + * 获取剩余的假期余额(假期余额基数*释放比例+额外余额-已用余额) + * + * @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?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/wfset/action/KqSplitAction.java b/src/com/engine/kq/wfset/action/KqSplitAction.java new file mode 100644 index 0000000..8ab67a6 --- /dev/null +++ b/src/com/engine/kq/wfset/action/KqSplitAction.java @@ -0,0 +1,72 @@ +package com.engine.kq.wfset.action; + +import com.engine.kq.biz.KQFlowActiontBiz; +import com.engine.kq.log.KQLog; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.HashMap; +import java.util.Map; +import weaver.conn.RecordSet; +import weaver.general.BaseBean; +import weaver.general.Util; +import weaver.interfaces.workflow.action.Action; +import weaver.soa.workflow.request.RequestInfo; +import weaver.workflow.workflow.WorkflowComInfo; + +/** + * 考勤流程数据拆分action + */ +public class KqSplitAction extends BaseBean implements Action { + private KQLog kqLog = new KQLog(); + + @Override + public String execute(RequestInfo request) { + this.writeLog("KqSplitAction", "do action on request:" + request.getRequestid()); + String requestid = request.getRequestid(); + kqLog.info("do KqSplitAction on requestid:"+requestid); + int requestidInt = Util.getIntValue(requestid, 0); + + String workflowid = request.getWorkflowid(); + String formid = new WorkflowComInfo().getFormId(workflowid); + + try { + KQFlowActiontBiz kqFlowActiontBiz = new KQFlowActiontBiz(); + RecordSet rs = new RecordSet(); + String proc_set_sql = "select * from kq_att_proc_set where field001 = ? and field002 = ? "; + rs.executeQuery(proc_set_sql, workflowid,formid); + if(rs.next()){ + String proc_set_id = rs.getString("id"); + //得到这个考勤流程设置是否使用明细 + String usedetails = rs.getString("usedetail"); + + int kqtype = Util.getIntValue(rs.getString("field006")); + kqLog.info("do action on kqtype:" + kqtype+":requestidInt:"+requestidInt); + Map map = new HashMap(); + if(requestidInt > 0){ + map.put("requestId", "and t.requestId = " + requestidInt); + } + + Map result = kqFlowActiontBiz.handleKQFlowAction(proc_set_id, usedetails, requestidInt, kqtype, Util.getIntValue(workflowid), false,false,map); + + if(!result.isEmpty()){ + String error = Util.null2String(result.get("message")); + request.getRequestManager().setMessageid("666" + request.getRequestid() + "999"); + request.getRequestManager().setMessagecontent(error); + return Action.FAILURE_AND_CONTINUE; + } + } + } catch (Exception e) { + kqLog.info("流程数据报错:KqSplitAction:"); + StringWriter errorsWriter = new StringWriter(); + e.printStackTrace(new PrintWriter(errorsWriter)); + kqLog.info(errorsWriter.toString()); + request.getRequestManager().setMessageid("11111" + request.getRequestid() + "22222"); + request.getRequestManager().setMessagecontent("【考勤报表统计action】报错,请联系管理员!"); + return Action.FAILURE_AND_CONTINUE; + } + + return Action.SUCCESS; + + } + +}