#hansang-01# svn代码

main
shilei 8 months ago
parent 0cb1911a66
commit 6a4991b054

File diff suppressed because it is too large Load Diff

@ -0,0 +1,33 @@
package com.api.customization.qc2988837.Util;
import com.engine.kq.log.KQLog;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
public class KqCustomUtil {
/**
*
* @param resourceId
* @param workDate
* @return
*/
public boolean isExclude(String resourceId,String workDate){
KQLog kqLog = new KQLog();
RecordSet rs = new RecordSet();
boolean isExculde = false;
String tableName = new BaseBean().getPropValue("qc2988837","tableName");
String resourceField = new BaseBean().getPropValue("qc2988837","resourceField");
String fromDateField = new BaseBean().getPropValue("qc2988837","fromDateField");
String toDateField = new BaseBean().getPropValue("qc2988837","toDateField");
String sql = "select "+resourceField+","+fromDateField+","+toDateField+" from "+tableName+
" where FIND_IN_SET("+resourceId+","+resourceField+") > 0 and '"+workDate+"' between "+fromDateField+" and "+toDateField;
kqLog.info("该人员当天是否不计算考勤:" + sql);
rs.executeQuery(sql);
if (rs.next()){
isExculde = true;
}
return isExculde;
}
}

@ -0,0 +1,149 @@
package com.api.hrm.service;
import com.api.hrm.bean.TreeNode;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.hrm.appdetach.AppDetachComInfo;
import weaver.hrm.resource.ResourceComInfo;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HrmResourceTreeService extends BaseBean{
private AppDetachComInfo adci = null;
private User user = null;
private String alllevel = null;//是否显示所有下级
private String isNoAccount = null;// 是否显示无账号人员
public Map<String, Object> getHrmResourceTree(HttpServletRequest request, HttpServletResponse response) {
User user = HrmUserVarify.getUser(request, response);
TreeNode manager = new TreeNode();
Map<String,Object> apidatas = new HashMap<String,Object>();
Map<String, Object> resultDatas = new HashMap<String, Object>();
try{
adci = new AppDetachComInfo(user);
this.user = user;
String id = Util.null2String(request.getParameter("id"));
String rootid = Util.null2String(request.getParameter("rootid"));
if(id.length()>0){
rootid = "";
}
alllevel = Util.null2String(request.getParameter("alllevel"));//是否显示所有下级
isNoAccount = Util.null2String(request.getParameter("isNoAccount"));// 是否显示无账号人员
if(id.length()==0||rootid.length()>0){
String userid = ""+user.getUID();
String username = user.getLastname();
if(rootid.length()>0){
ResourceComInfo rci = new ResourceComInfo();
userid = rootid;
username = rci.getLastname(userid);
}
manager.setId(userid);
manager.setName(username);
manager.setType("1");
manager.setCanClick(true);
List<TreeNode> result = getChildTreeNode(manager).getSubs();
if(result!=null && result.size()>0){
manager.setIsParent(true);
}
resultDatas.put("rootManager", manager);
apidatas.put("datas", resultDatas);
}else{
manager.setId(id);
List<TreeNode> result = getChildTreeNode(manager).getSubs();
apidatas.put("datas", result);
}
}catch (Exception e) {
writeLog(e);
}
return apidatas;
}
private TreeNode getChildTreeNode(TreeNode manager){
List<TreeNode> childNode = null;
RecordSet rs = new RecordSet();
String sql = "";
String sqlwhere = "";
try{
childNode = new ArrayList<TreeNode>();
String id = manager.getId();
if(id.length()>0){
//二开修改 取线长下所有组员
sql = " select hr.id, lastname from hrmresource hr left join cus_fielddata c on hr.id=c.id and c.scope='HrmCustomFieldByInfoType' " +
" and c.scopeid=-1 left join hrmdepartmentdefined d on hr.departmentid=d.deptid where (field89="+id+" or managerid="+id+" or d.kqwy="+id+") ";
if(sqlwhere.length()>0)sqlwhere=" and " +sqlwhere;
sqlwhere+=" and hr.status in (0,1,2,3)";
if(!isNoAccount.equals("1")){
sqlwhere +=" and loginid is not null "+(rs.getDBType().equals("oracle")?"":" and loginid<>'' ");
}
if(adci.isUseAppDetach()){
String appdetawhere = adci.getScopeSqlByHrmResourceSearch(user.getUID()+"",true,"resource_hr");
String tempstr= (appdetawhere!=null&&!"".equals(appdetawhere)?(" and " + appdetawhere):"");
sqlwhere+=tempstr;
}
if(sqlwhere.length()>0)sql+=sqlwhere;
sql += " order by hr.dsporder ";
rs.executeSql(sql);
while(rs.next()){
TreeNode orgBean = new TreeNode();
if(id.equals(rs.getString("id")))continue;
orgBean.setId(rs.getString("id"));
orgBean.setName(rs.getString("lastname"));
orgBean.setType("1");
orgBean.setCanClick(true);
orgBean.setIsParent(hasChild(rs.getString("id")));
childNode.add(orgBean);
}
}
manager.setSubs(childNode);
}catch (Exception e) {
writeLog(e);
}
return manager;
}
private boolean hasChild(String id){
RecordSet rs = new RecordSet();
String sql = "";
String sqlwhere = "";
boolean isParent = false;
try{
if(id.length()>0){
//sql = "select count(1) from hrmresource hr where managerid = "+id;
sql = " select count(1) from hrmresource hr left join cus_fielddata c on hr.id=c.id and c.scope='HrmCustomFieldByInfoType' " +
" and c.scopeid=-1 left join hrmdepartmentdefined d on hr.departmentid=d.deptid where (field89="+id+" or managerid="+id+" or d.kqwy="+id+")";
if(sqlwhere.length()>0)sqlwhere=" and " +sqlwhere;
sqlwhere+=" and hr.status in (0,1,2,3)";
if(!isNoAccount.equals("1")){
sqlwhere +=" and loginid is not null "+(rs.getDBType().equals("oracle")?"":" and loginid<>'' ");
}
if(adci.isUseAppDetach()){
String appdetawhere = adci.getScopeSqlByHrmResourceSearch(user.getUID()+"",true,"resource_hr");
String tempstr= (appdetawhere!=null&&!"".equals(appdetawhere)?(" and " + appdetawhere):"");
sqlwhere+=tempstr;
}
if(sqlwhere.length()>0)sql+=sqlwhere;
//sql += " order by hr.dsporder ";
rs.executeSql(sql);
if(rs.next()){
if(rs.getInt(1)>0){
isParent = true;
}
}
}
}catch (Exception e) {
writeLog(e);
}
return isParent;
}
}

@ -0,0 +1,10 @@
package com.api.hs;
import com.engine.hsCheck.web.QkCheckAction;
import javax.ws.rs.Path;
@Path("/hshrm")
public class HsCheckApi extends QkCheckAction {
}

@ -0,0 +1,13 @@
package com.api.leshanvc.web;
import javax.ws.rs.Path;
/**
* @Author ml
* @Date 2023/3/1 11:34
* @Description This is description of class
* @Since version-1.0
*/
@Path("/leshavc/formmode")
public class EntryCommitFormModeController extends com.engine.leshanvc.web.EntryCommitFormModeController {
}

@ -0,0 +1,13 @@
package com.api.leshanvc.web;
import javax.ws.rs.Path;
/**
* @Author weaver_cl
* @Description:
* @Date 2023/2/21
* @Version V1.0
**/
@Path("/leshavc/entry/workflow")
public class EntryWorkflowSaveEventAction extends com.engine.leshanvc.web.EntryWorkflowSaveEventAction {
}

@ -0,0 +1,13 @@
package com.api.leshanvc.web;
import javax.ws.rs.Path;
/**
* @Author weaver_cl
* @Description:
* @Date 2023/3/3
* @Version V1.0
**/
@Path("/leshavc/kq/workflow")
public class KqWorkflowRangeLimitAction extends com.engine.leshanvc.web.KqWorkflowRangeLimitAction {
}

@ -0,0 +1,12 @@
package com.api.leshanvc.web;
import javax.ws.rs.Path;
/**
* @author:dxfeng
* @createTime: 2023/04/19
* @version: 1.0
*/
@Path("/leshavc/leaver/workflow")
public class LeaverWorkflowAction extends com.engine.leshanvc.web.LeaverWorkflowAction {
}

@ -0,0 +1,13 @@
package com.api.leshanvc.web;
import javax.ws.rs.Path;
/**
* @Author ml
* @Date 2023/3/16 9:19
* @Description This is description of class
* @Since version-1.0
*/
@Path("/leshavc/lz/workflow")
public class LzWorkflowManageAction extends com.engine.leshanvc.web.LzWorkflowManageAction {
}

@ -0,0 +1,12 @@
package com.api.leshanvc.web;
import javax.ws.rs.Path;
/**
* @author:dxfeng
* @createTime: 2023/04/20
* @version: 1.0
*/
@Path("/leshavc/resource")
public class ResourceCardAction extends com.engine.leshanvc.web.ResourceCardAction{
}

@ -0,0 +1,7 @@
package com.api.leshanvc.web;
import javax.ws.rs.Path;
@Path("/leshavc/common/formmode")
public class SyncXcDataAction extends com.engine.leshanvc.web.SyncXcDataAction {
}

@ -0,0 +1,13 @@
package com.api.leshanvc.web;
import javax.ws.rs.Path;
/**
* @Author weaver_cl
* @Description:
* @Date 2023/3/8
* @Version V1.0
**/
@Path("/leshavc/common/workflow")
public class WorkflowCheckAction extends com.engine.leshanvc.web.WorkflowCheckAction {
}

File diff suppressed because it is too large Load Diff

@ -0,0 +1,40 @@
package com.customization.leshanvc;
import com.engine.core.cfg.annotation.CommandDynamicProxy;
import com.engine.core.interceptor.AbstractCommandProxy;
import com.engine.core.interceptor.Command;
import com.engine.kq.biz.KQExitRulesBiz;
import com.engine.kq.cmd.attendanceEvent.GetOutWorkDurationCmd;
import org.apache.commons.lang.StringUtils;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.leshanvc.workflow.util.ConvertDurationUtil;
import java.util.Map;
/**
* @author:dxfeng
* @createTime: 2023/02/17
* @version: 1.0
*/
@CommandDynamicProxy(target = GetOutWorkDurationCmd.class, desc = "公出流程时间计算按照半小时为最小单位")
public class HsGetOutWorkDurationCmd extends AbstractCommandProxy<Map<String, Object>> {
@Override
public Map<String, Object> execute(Command<Map<String, Object>> targetCommand) {
String minimumUnit = KQExitRulesBiz.getMinimumUnit();
Map<String, Object> resultMap = nextExecute(targetCommand);
// 半小时
if ("3".equals(minimumUnit)) {
String duration = Util.null2String(resultMap.get("duration"));
if (StringUtils.isNotBlank(duration)) {
try {
resultMap.put("duration", ConvertDurationUtil.handelHalfHour(duration));
} catch (NumberFormatException e) {
new BaseBean().writeLog(e);
}
}
}
return resultMap;
}
}

@ -0,0 +1,30 @@
package com.customization.leshanvc;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.core.cfg.annotation.CommandDynamicProxy;
import com.engine.core.interceptor.AbstractCommandProxy;
import com.engine.core.interceptor.Command;
import com.engine.kq.cmd.attendanceEvent.GetOutWorkDurationCmd;
import com.engine.kq.cmd.travelrules.GetTravelRulesFormCmd;
import java.util.List;
import java.util.Map;
/**
* @author:dxfeng
* @createTime: 2023/02/17
* @version: 1.0
*/
@CommandDynamicProxy(target = GetTravelRulesFormCmd.class, desc = "公出流程时间计算按照半小时为最小单位")
public class HsGetTravelRulesFormCmd extends AbstractCommandProxy<Map<String, Object>> {
@Override
public Map<String, Object> execute(Command<Map<String, Object>> targetCommand) {
GetTravelRulesFormCmd getTravelRulesFormCmd = (GetTravelRulesFormCmd) targetCommand;
Map<String, Object> result = nextExecute(targetCommand);
List<String> minimumUnit = (List<String>) result.get("exit_minimumUnit");
minimumUnit.set(2, minimumUnit.get(2).replace("1分钟", "半小时"));
return result;
}
}

@ -0,0 +1,855 @@
package com.engine.cube.cmd.app;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.api.formmode.cache.ModeFormFieldEncryptComInfo;
import com.cloudstore.dev.api.util.Util_TableMap;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.common.entity.EncryptFieldEntity;
import com.engine.core.interceptor.CommandContext;
import com.engine.cube.biz.CardFormHelper;
import com.engine.cube.biz.DetachHelper;
import com.engine.encrypt.biz.EncryptFieldConfigComInfo;
import com.engine.cube.util.AddSeclevelUtil;
import com.weaver.formmodel.util.StringHelper;
import weaver.conn.RecordSet;
import weaver.conn.constant.DBConstant;
import weaver.formmode.cache.StringCacheMap;
import weaver.formmode.excel.ExcelCacheUtil;
import weaver.formmode.excel.ExpExcelUtil;
import weaver.formmode.excel.ImpExcelServer;
import weaver.formmode.service.AppInfoService;
import weaver.formmode.service.FormInfoService;
import weaver.formmode.service.ModelInfoService;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.systeminfo.SystemEnv;
import java.util.*;
public class GetBatchImportInfo extends AbstractCommonCommand<Map<String, Object>> {
private static String hostaddr = "";
public GetBatchImportInfo(Map<String, Object> params, User user) {
this.params = params;
this.user = user;
}
@Override
public BizLogContext getLogContext() {
return null;
}
@Override
public Map<String, Object> execute(CommandContext commandContext) {
Map<String, Object> result = new HashMap<String,Object>();
String modeid = Util.null2String(this.params.get("modeid"));
boolean BatchImportRight = false;
ModeRightInfo modeRightInfo = new ModeRightInfo();
modeRightInfo.setModeId(Util.getIntValue(modeid));
modeRightInfo.setUser(user);
modeRightInfo.setType(4);
BatchImportRight = modeRightInfo.checkUserRight(4);
if (!BatchImportRight) {
BatchImportRight = HrmUserVarify.checkUserRight("ModeSetting:All", user);
}
if(!BatchImportRight){
result.put("status", false);
result.put("errorCode","no-right");
result.put("error",SystemEnv.getHtmlLabelName(2011,user.getLanguage()));//没有权限
result.put("noRight", true);
return result;
}
String operation = Util.null2String(this.params.get("operation"));
String customId = Util.null2String(this.params.get("customid"));
String isSinglePage = Util.null2String(this.params.get("isSinglePage"));//单页模式用于前端用户导入
int sourcetype = 0;
if(!"1".equals(isSinglePage)){
sourcetype = 1;
}
int modelId = Util.getIntValue(modeid);
int appId = Util.getIntValue(Util.null2String(this.params.get("appid")));//当前所选应用id
ModelInfoService modelInfoService = new ModelInfoService();
AppInfoService appInfoService = new AppInfoService();
Map<String, Object> data = new HashMap<String, Object>();
if(modelId>0){
data = modelInfoService.getModelInfoById(modelId);
}
if(modelId>0&&data.size()==0){
throw new RuntimeException("no data was found");
}
int modetype = Util.getIntValue(Util.null2String(data.get("modetype")),0);
int formid = Util.getIntValue(Util.null2String(data.get("formid")),0);
String modename = Util.null2String(data.get("modename"));
if(modelId==0){
modetype = appId;
}
int tempId = modetype;
if(tempId==0){
tempId = appId;
}
String maintablename ="";
RecordSet recordSet = new RecordSet();
recordSet.executeQuery("select tablename from workflow_bill where id = ?",formid);
if(recordSet.next()){
maintablename = recordSet.getString("tablename");
}
String userRightStr = "ModeSetting:All";
Map<String, Object> appInfo = appInfoService.getAppInfoById(tempId);
boolean isUseFmManageDetach=DetachHelper.modeDetachIsOpen();
int subCompanyId = Util.getIntValue(Util.null2String(data.get("subCompanyId")),-1);
if(subCompanyId==-1){
subCompanyId = Util.getIntValue(Util.null2String(appInfo.get("subcompanyid")),-1);
}
int operatelevel = DetachHelper.getUserDeatchOperateLevel(user, subCompanyId, userRightStr);
//判断模块是否开启分级保护
AddSeclevelUtil addSeclevelUtil = new AddSeclevelUtil();
boolean isOpenClassprotect = false;
Map<String, Object> params = new HashMap<>();
params.put("modeid", modeid);
isOpenClassprotect = addSeclevelUtil.modeOpenClassProtect(params);
String fmdetachable = isUseFmManageDetach?"1":"0";
if(operation.equals("getImpStatus")){
JSONObject impStatus = new JSONObject();
String tempkey = Util.null2String(this.params.get("tempkey"));
String key = user.getUID()+"_"+modeid+"_"+tempkey;
Object obj = ExpExcelUtil.getObject("modeimp_"+key);
Map cacheMap = null;
if(obj!=null){
cacheMap = (Map) obj;
}
int step = 0;
if(cacheMap!=null&&cacheMap.containsKey("msg")){
int s = 1;
String msg = Util.null2String(cacheMap.get("msg"));
String status = Util.null2String(cacheMap.get("status"));
step = Util.getIntValue(Util.null2String(cacheMap.get("step")));
String impaddr = Util.null2String(cacheMap.get("impaddr"));
String starttimeStr = Util.null2String(cacheMap.get("starttime"));
String endtimeStr = Util.null2String(cacheMap.get("endtime"));
String searchid = Util.null2String(cacheMap.get("searchid"));
String errorflag = Util.null2String(cacheMap.get("errorflag"));
if(!"".equals(starttimeStr)&&!"".equals(endtimeStr)){
long starttime = Long.parseLong(starttimeStr);
long endtime= Long.parseLong(endtimeStr);
if(starttime>endtime){//还未结束
ImpExcelServer.putMessage("status", key, "0");
if(step==6){
step = 0;
msg = "";
s = 0;
ImpExcelServer.putMessage("step", key, "0");
}
}
}
String errmsg = "";
String time = "";
if(status.equals("-1")){
errmsg = Util.null2String(cacheMap.get("errmsg"));
time = Util.null2String(cacheMap.get("time"));
if(!StringHelper.isEmpty(errmsg)){
errmsg = errmsg.replace("\\n","<br />");
}
}
impStatus.put("s",s);
impStatus.put("msg",msg);
impStatus.put("status",status);
impStatus.put("errmsg",errmsg);
impStatus.put("time",time);
impStatus.put("step",step);
impStatus.put("impaddr", impaddr);
impStatus.put("searchid", searchid);
impStatus.put("errorflag", errorflag);
impStatus.put("modeid", modeid);
}else{
impStatus.put("s",0);
impStatus.put("size",cacheMap==null?0:cacheMap.size());
}
hostaddr = ExcelCacheUtil.getHostaddr();
result.put("hostaddr", hostaddr);
result.put("impStatus", impStatus);
// try {
// if(step>3){//主表数据执行后就删除临时表,序列删除,触发器删除
// RecordSet rs = new RecordSet();
// rs.execute("delete from M_"+modeid+"_"+user.getUID());
// rs.writeLog("GetBatchImportInfo-step="+step);
// String dbType = rs.getDBType();
//// if(DBConstant.DB_TYPE_ORACLE.equals(dbType)){
//// rs.execute("DROP SEQUENCE M_"+modeid+"_"+user.getUID()+"_id");
//// rs.execute("DROP TRIGGER M_"+modeid+"_"+user.getUID()+"_Trigger");
//// }
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
return result;
}else if(operation.equals("stopImport")){
String tempkey = Util.null2String(this.params.get("tempkey"));
String key = user.getUID()+"_"+modeid+"_"+tempkey+"_cancel";
StringCacheMap.put(key, key);
hostaddr = ExcelCacheUtil.getHostaddr();
result.put("hostaddr", hostaddr);
return result;
}else if(operation.equals("getBatchImportLogList")){
String startdate = Util.null2String(this.params.get("startdate"));
String enddate = Util.null2String(this.params.get("enddate"));
String operator = Util.null2String(this.params.get("operator"));
String operatetype = Util.null2String(this.params.get("operatetype"));
String SqlWhere = " where a.modeid='"+modeid+"' " ;
if(!startdate.isEmpty()){
SqlWhere += " and optdatetime >= '"+startdate+" 00:00:00'";
}
if(!enddate.isEmpty()){
SqlWhere += " and optdatetime <= '"+enddate+" 23:59:59 '";
}
if(!operator.isEmpty()){
SqlWhere += " and operator = '"+operator+"'";
}
if(!operatetype.isEmpty()){
SqlWhere += " and operatetype = '"+operatetype+"'";
}
String perpage = "10";
String backFields = " a.id,a.id optid,a.modeid,a.operatetype,a.ipaddress,a.operator,a.optdatetime,a.addrow,a.updaterow,a.delrow,a.failurerow,a.adddetailrow,a.deldetailrow,a.backupremark,a.backindex";
String sqlFrom = " from mode_batchimp_log a ";
String pageUid = "modeList_12345678";
String orderby = " a.optdatetime desc ";
String tableString=""+
"<table pagesize=\""+perpage+"\" tabletype=\"none\" pageId=\""+pageUid+"\" pageUid=\""+ pageUid+ "\" >"+
"<sql backfields=\""+backFields+"\" sqlform=\""+sqlFrom+"\" sqlorderby=\""+orderby+"\" sqlprimarykey=\"a.id\" sqlsortway=\"desc\" sqldistinct=\"true\" sqlwhere=\""+Util.toHtmlForSplitPage(SqlWhere)+"\"/>"+
"<head>"+
//操作人
"<col width=\"15%\" text=\""+SystemEnv.getHtmlLabelName(17482,user.getLanguage())+"\" column=\"operator\" orderkey=\"operator\" otherpara=\"operator+"+user.getLanguage()+"\" transmethod=\"weaver.formmode.service.LogService.getLogNameByBatch\" />"+
//操作类型
"<col width=\"12%\" text=\""+SystemEnv.getHtmlLabelName(15503,user.getLanguage())+"\" column=\"operatetype\" orderkey=\"operatetype\" otherpara=\"operatetype+"+user.getLanguage()+"\" transmethod=\"weaver.formmode.service.LogService.getLogNameByBatch\" />"+
"<col width=\"12%\" text=\"IP\" column=\"ipaddress\" />"+
//操作日期
"<col width=\"20%\" text=\""+SystemEnv.getHtmlLabelName(21663,user.getLanguage())+"\" column=\"optdatetime\" />"+
//增加
"<col width=\"8%\" text=\""+SystemEnv.getHtmlLabelName(456,user.getLanguage())+"\" column=\"addrow\" />"+
//删除
"<col width=\"8%\" text=\""+SystemEnv.getHtmlLabelName(17744,user.getLanguage())+"\" column=\"updaterow\" />"+
//更新
"<col width=\"8%\" text=\""+SystemEnv.getHtmlLabelName(125426,user.getLanguage())+"\" column=\"delrow\" />"+
//失败
"<col width=\"8%\" text=\""+SystemEnv.getHtmlLabelName(388508,user.getLanguage())+"\" column=\"failurerow\" />"+
//增加明细
"<col width=\"12%\" text=\""+SystemEnv.getHtmlLabelName(129856,user.getLanguage())+"\" column=\"adddetailrow\" />"+
//删除明细
"<col width=\"12%\" text=\""+SystemEnv.getHtmlLabelName(129857,user.getLanguage())+"\" column=\"deldetailrow\" />"+
"<col width=\"0%\" hide=\"true\" text=\"backindex\" column=\"backindex\" />";
if (operatelevel>=2) {//如果拥有完全控制权限
//下载导入的文件
tableString+="<col width=\"12%\" text=\""+SystemEnv.getHtmlLabelName(539084,user.getLanguage())+"\" column=\"optid\" otherpara=\""+user.getLanguage()+"\" transmethod=\"weaver.formmode.service.LogService.getBatchImportOperate\"/>";
//备注
tableString+="<col width=\"30%\" text=\""+SystemEnv.getHtmlLabelName(454,user.getLanguage())+"\" column=\"backupremark\" />";
}
tableString+=
"</head>"+
"</table>";
Map<String, Object> apidatas = new HashMap<String, Object>();
String sessionkey = pageUid + "_" + Util.getEncrypt(Util.getRandom());
Util_TableMap.setVal(sessionkey, tableString);
apidatas.put("sessionkey", sessionkey);
return apidatas;
}
if("getTemplate".equals(operation)){
JSONArray templateFields = new JSONArray();
FormInfoService formInfoService = new FormInfoService();
formInfoService.setUser(user);
net.sf.json.JSONObject resultObj = formInfoService.getAllFieldByImport(Util.getIntValue(modeid),formid);
String maintable1 = resultObj.getString("maintable");
net.sf.json.JSONArray tables = resultObj.getJSONArray("tables");
for(int i=0;i<tables.size();i++){
String table = tables.getString(i);
String tablename = table.replace(maintable1, "");
String tablenamelabel = "";
if("".equals(tablename)){
tablename = SystemEnv.getHtmlLabelName(21778,user.getLanguage())+"("+maintable1+")";
tablenamelabel = SystemEnv.getHtmlLabelName(21778,user.getLanguage());
}else{
tablename = table.replace(maintable1+"_dt", "");
tablenamelabel = SystemEnv.getHtmlLabelName(17463,user.getLanguage())+tablename;
}
JSONObject tableObj = new JSONObject();
tableObj.put("index", i);
templateFields.add(tableObj);
JSONArray fieldArray = new JSONArray();
tableObj.put("tablenamelabel", tablenamelabel);
tableObj.put("tablename", table);
tableObj.put("fieldArray", fieldArray);
net.sf.json.JSONArray tabledata = resultObj.getJSONArray(table);
for (int j = 0; j < tabledata.size(); j++) {
net.sf.json.JSONObject JSONObject = tabledata.getJSONObject(j);
String fieldid = JSONObject.getString("fieldid");
String fieldname = JSONObject.getString("fieldname");
// if(isOpenClassprotect){
// if("seclevel".equals(fieldname.toLowerCase())){
// continue;
// }
// }
String fieldlabelname = JSONObject.getString("fieldlabelname");
String ischeck = JSONObject.getString("ischeck");
String dsporder = JSONObject.getString("dsporder");
JSONObject fieldObj = new JSONObject();
fieldArray.add(fieldObj);
fieldObj.put("key", fieldid);
fieldObj.put("fieldid", fieldid);
fieldObj.put("fieldname", fieldname);
fieldObj.put("fieldlabelname", fieldlabelname);
fieldObj.put("ischeck", ischeck);
fieldObj.put("dsporder", dsporder);
}
}
result.put("templateFields", templateFields);
result.put("fmdetachable", fmdetachable);
result.put("operatelevel", operatelevel);
return result;
}else if("getFieldTrans".equals(operation)){//字段设置
JSONArray templateFields = this.getFieldTrans(modeid,formid);
result.put("templateFields", templateFields);
result.put("fmdetachable", fmdetachable);
result.put("operatelevel", operatelevel);
return result;
}else if("getBatchImportValidate".equals(operation)){
JSONObject batchImportValidate = new JSONObject();
RecordSet rs = new RecordSet();
RecordSet rs2 = new RecordSet();
RecordSet RecordSet = new RecordSet();
int validateid = Util.getIntValue(Util.null2String(this.params.get("validateid")));
String note = "";
if (validateid>0) {
String sql = "select note from mode_excelField where id="+validateid;
RecordSet.execute(sql);
if (RecordSet.next()) {
note = RecordSet.getString("note");
}
}
batchImportValidate.put("note", note);
String sqlwhere = " and modeid="+StringHelper.empty2Null(modeid)+" and formid="+formid+" and ( fieldid in ('-1000','-1001','-1002') or exists (select 1 from workflow_billfield b where b.billid="+formid+" and b.id=a.fieldid) )";
String sql2 = "select a.fieldid from mode_import_template a where 1=1 "+sqlwhere+" order by a.dsporder,a.fieldid ";
rs2.execute(sql2);//设置的字段
int count = rs2.getCounts();
sqlwhere = "";
if(count>0){
sqlwhere = " and exists (select 1 from mode_import_template c where c.fieldid=a.id and c.modeid="+StringHelper.empty2Null(modeid)+" and c.formid="+formid+" )";
}
//----------------选择框字段--------------------
String sql = "";
if(count>0){
sql = "select * from (select a.id,a.viewtype,a.detailtable,b.indexdesc,a.fieldname from workflow_billfield a, htmllabelindex b "
+ " where a.billid="+formid+" and fieldhtmltype=5 and type<>2 and b.id=a.fieldlabel "+sqlwhere+") t";
}else{
sql="select * from (select a.id,a.viewtype,a.detailtable,b.indexdesc ,c.needExcel,a.fieldname from workflow_billfield a, htmllabelindex b, ModeFormFieldExtend c where c.needExcel = 1 and a.billid=c.formId "
+"and a.id=c.fieldId and a.billid="+formid+" and fieldhtmltype=5 and type<>2 and b.id=a.fieldlabel "
+ " union "
+ " select a.id,a.viewtype,a.detailtable,c.indexdesc,1 as needExcel, a.fieldname from workflow_billfield a ,HtmlLabelindex c where "
+"a.billid="+formid+" and c.id=a.fieldlabel and fieldhtmltype=5 and type<>2 and not exists (select 1 from ModeFormFieldExtend b where b.formid=a.billid and b.formid="+formid+" and b.fieldId=a.id)"
+ ") t";
}
sql += " ORDER BY viewtype,detailtable,id ";
JSONArray selectFields = new JSONArray();
batchImportValidate.put("selectFields", selectFields);
rs.execute(sql);
while(rs.next()){
JSONObject temp = new JSONObject();
String fieldid = rs.getString("id");
String fieldlabel = rs.getString("indexdesc");
String detailtable = rs.getString("detailtable");
String fieldname = rs.getString("fieldname");
if(isOpenClassprotect){
if("seclevel".equals(fieldname.toLowerCase())){
continue;
}
}
if(!detailtable.equals("")){
fieldlabel = fieldlabel + "("+ SystemEnv.getHtmlLabelName(126218, user.getLanguage())+CardFormHelper.getNumOfDetailTableName(detailtable)+")";
}
if(StringHelper.isEmpty(detailtable)){
detailtable = "maintable";
}
temp.put("key",fieldid);
temp.put("showname",fieldlabel);
temp.put("detailtable",detailtable);
selectFields.add(temp);
}
//选择项目
JSONObject selectOption = new JSONObject();
batchImportValidate.put("selectOption", selectOption);
sql = "select a.fieldid,a.selectvalue,a.selectname from workflow_SelectItem a,workflow_billfield b "
+ " where a.fieldid=b.id AND b.fieldhtmltype=5 AND b.billid="+formid+" ORDER BY b.viewtype,a.fieldid,a.listorder";
rs.execute(sql);
while(rs.next()){
String fieldid = rs.getString("fieldid");
String selectvalue = rs.getString("selectvalue");
String selectname = rs.getString("selectname");
JSONArray options = null;
if(selectOption.containsKey(fieldid)){
options = selectOption.getJSONArray(fieldid);
}else{
options = new JSONArray();
selectOption.put(fieldid, options);
}
JSONObject obj = new JSONObject();
obj.put("key", selectvalue);
obj.put("showname", selectname);
options.add(obj);
}
//-------已经设置的列表------------
JSONArray validateFieldDetail = new JSONArray();
batchImportValidate.put("validateFieldDetail", validateFieldDetail);
if(validateid>0){
sql = "select * from mode_excelFieldDetail where mainid="+validateid;
if(count==0){
sql+=" and (selectids in(select a.id from workflow_billfield a, htmllabelindex b, ModeFormFieldExtend c where c.needExcel = 1 and a.billid=c.formId "
+"and a.id=c.fieldId and a.billid="+formid+" and fieldhtmltype=5 and b.id=a.fieldlabel union select a.id from workflow_billfield a ,HtmlLabelindex c where "
+"a.billid="+formid+" and c.id=a.fieldlabel and fieldhtmltype=5 and not exists (select 1 from ModeFormFieldExtend b where b.formid=a.billid and b.formid="+formid+" and b.fieldId=a.id) )"
+ " or (selectids is null or selectids='')) ";
}
sql += " order by id ";
RecordSet.execute(sql);
while(RecordSet.next()){
String id = RecordSet.getString("id");
String fieldid = RecordSet.getString("fieldid");
String selectid = Util.null2String(RecordSet.getString("selectids"));
String selectvalue = Util.null2String(RecordSet.getString("selectvalue"));
JSONObject obj = new JSONObject();
obj.put("key", id);
obj.put("selectid", selectid);
obj.put("selectvalue", selectvalue);
obj.put("fieldid", fieldid);
validateFieldDetail.add(obj);
}
}
//如果没有数据默认添加一行
if(validateFieldDetail.size()==0){
JSONObject obj = new JSONObject();
obj.put("key", "new_"+new Date().getTime());
obj.put("selectid", "");
obj.put("selectvalue", "");
obj.put("fieldid", "");
validateFieldDetail.add(obj);
}
//----------------每个表的字段-----------------------
JSONObject tableFields = new JSONObject();
batchImportValidate.put("tableFields", tableFields);
List<String[]>list=new ArrayList<String[]>();
String selectid = "";
String fieldsql = "";
if(count==0){
fieldsql = "select b.id,b.detailtable,c.indexdesc from htmllabelindex c,workflow_billfield b left join ModeFormFieldExtend a "
+ " on b.id=a.fieldId where (needExcel !=0 or needExcel is null) and c.id=b.fieldlabel and b.billid="+formid;
}else{
fieldsql = "select b.*,c.indexdesc from htmllabelindex c,workflow_billfield b join mode_import_template a "
+ " on b.id=a.fieldId and modeid='"+modeid+"' and formid='"+formid+"' where c.id=b.fieldlabel and b.billid="+formid;
}
rs.executeQuery(fieldsql);
List tableList = new ArrayList();
while(rs.next()){
////QC 364486 表单建模,设置为多语言,批量导入,导入必填字段,选择必填字段,乱码
String indexdesc =Util.formatMultiLang(Util.null2String(rs.getString("indexdesc")), user.getLanguage()+"");
String fieldid = Util.null2String(rs.getString("id"));
String detailtable = Util.null2String(rs.getString("detailtable"));
if(!detailtable.equals("")){
indexdesc += "("+ SystemEnv.getHtmlLabelName(126218, user.getLanguage()) +CardFormHelper.getNumOfDetailTableName(detailtable)+")";
}
if(StringHelper.isEmpty(detailtable)){
detailtable = "maintable";
}
JSONArray fieldids = null;
if(tableFields.containsKey(detailtable)){
fieldids = tableFields.getJSONArray(detailtable);
}else{
fieldids = new JSONArray();
tableFields.put(detailtable,fieldids);
tableList.add(detailtable);
}
JSONObject obj = new JSONObject();
obj.put("key", fieldid);
obj.put("showname", indexdesc);
fieldids.add(obj);
}
batchImportValidate.put("tableList",tableList);
result.put("batchImportValidate", batchImportValidate);
result.put("fmdetachable", fmdetachable);
result.put("operatelevel", operatelevel);
return result;
}else if(operation.equals("checkImp")){
JSONObject jsonObj = ExpExcelUtil.checkCanImpExcel(user,modeid);
result.putAll(jsonObj);
result.put("fmdetachable", fmdetachable);
result.put("operatelevel", operatelevel);
return result;
}else{
//-----获取基本信息
RecordSet rs = new RecordSet();
String needfav = "";
String needhelp = "";
int rightLevel = -1;//无权限
ModeRightInfo ModeRightInfo = new ModeRightInfo();
int type = 4;//批量导入权限
boolean isRight = false;
boolean isALLRight = false;
if (type == 4) {//监控权限判断
ModeRightInfo.setModeId(modelId);
ModeRightInfo.setType(type);
ModeRightInfo.setUser(user);
isRight = ModeRightInfo.checkUserRight(type);
if (!isRight) {
isALLRight = HrmUserVarify.checkUserRight(userRightStr, user);
if (!isALLRight) {
result.put("isRight", false);
result.put("rightLevel", -1);
result.put("fmdetachable", fmdetachable);
result.put("operatelevel", operatelevel);
JSONObject batchImportInfo = new JSONObject();
batchImportInfo.put("modename", modename);
batchImportInfo.put("isRight", isRight);
batchImportInfo.put("formid", formid);
batchImportInfo.put("modeid", modeid);
result.put("batchImportInfo", batchImportInfo);
return result;
}
}
}
List<Integer> importTypes = ModeRightInfo.checkUserImportType();
/*if (importTypes.size() == 0) {
if (isALLRight) {
importTypes.add(0);
}
}*/
JSONArray importTypeOption = new JSONArray();
//根据后台设置的导入类型 这里做一个限制
if ( importTypes.contains(1) || user.getUID()==1 ||isALLRight) {
JSONObject obj = new JSONObject();
obj.put("key", "1");
obj.put("showname", SystemEnv.getHtmlLabelName(31259, user.getLanguage()));
importTypeOption.add(obj);
}
if (importTypes.contains(3) || user.getUID()==1 || isALLRight) {
JSONObject obj = new JSONObject();
obj.put("key", "3");
obj.put("showname", SystemEnv.getHtmlLabelName(17744, user.getLanguage()));
importTypeOption.add(obj);
}
if ( importTypes.contains(2)) {
JSONObject obj = new JSONObject();
obj.put("key", "2");
obj.put("showname", SystemEnv.getHtmlLabelName(517042, user.getLanguage()));
importTypeOption.add(obj);
}
//--------------
String sql = "";
String interfacepath = "";
String fieldtranspath = "";
String importorder = "";
String isuse = "";
String validateid = "";
String keyfield = "";
int fieldDetailCount = 0;
String templateTitle = "";
String fieldtransTitle = "";
int isHaveTemplate = 0;
boolean isHaveFieldtrans=false;//是否存在导入转换接口
if (modelId>0) {
String templateSql = "select 1 from mode_import_template a where modeid=" + modeid + " and formid=" + formid + " and (exists(select 1 from workflow_billfield b where b.billid=" + formid + " and b.id=a.fieldid) or a.fieldid in(-1000,-1001,-1002)) ";
rs.execute(templateSql);
if (rs.getCounts() > 0) {
isHaveTemplate = 1;
}
}
//获取接口路径等信息
sql = "select * from mode_DataBatchImport where modeid=" + modeid;
rs.execute(sql);
if (rs.next()) {
interfacepath = rs.getString("interfacepath");
keyfield = rs.getString("keyfield");
fieldtranspath = rs.getString("fieldtranspath");
importorder = rs.getString("importorder");
isuse = rs.getString("isuse");
validateid = Util.null2String(rs.getString("validateid"));
if (!validateid.equals("")) {
sql = "select COUNT(a.id) as num from mode_excelFieldDetail a,mode_excelField b where a.mainid=b.id and b.modeid=" + modeid;
rs.execute(sql);
if (rs.next()) {
fieldDetailCount = rs.getInt("num");
}
}
}
if (sourcetype == 1 && operatelevel > 0) {
if(isHaveTemplate==1){//编辑模板
templateTitle = SystemEnv.getHtmlLabelName(28052, user.getLanguage());
}else{//设置模板
templateTitle = SystemEnv.getHtmlLabelName(503155, user.getLanguage());
}
if(isHaveFieldtrans){//编辑字段
fieldtransTitle = SystemEnv.getHtmlLabelName(15449, user.getLanguage());
}else{//设置字段
fieldtransTitle = SystemEnv.getHtmlLabelName(504193, user.getLanguage());
}
}
JSONArray keyFieldOption = new JSONArray();
JSONObject obj = new JSONObject();
obj.put("key", "");
obj.put("showname", "");
keyFieldOption.add(obj);
if (importTypes.size() == 0 || importTypes.contains(3) || importTypes.contains(0)|| user.getUID()==1 || isALLRight) {
String sql1 = "";
if(isHaveTemplate==1){
sql1 = " select 1 from mode_import_template c where c.fieldid=-1000 and c.modeid="+modeid+" and c.formid="+formid+" ";
}else{
sql1 = "select 1 from ModeFormFieldExtend where fieldid=-1000 and needExcel=1 and formid="+formid+" ";
}
rs.execute(sql1);
if(rs.getCounts()>0){//显示数据id时才显示此选项
obj = new JSONObject();
obj.put("key", "dataid");
obj.put("showname", SystemEnv.getHtmlLabelName(81287, user.getLanguage()));
keyFieldOption.add(obj);
}
}
String sqlwhere = "";
if(isHaveTemplate==1){
sqlwhere = " and exists (select 1 from mode_import_template c where c.fieldid=a.id and c.modeid="+modeid+" and c.formid="+formid+" )";
sql = "select a.id,a.fieldname,a.fieldlabel from workflow_billfield a where "
+ "billid="+formid +" and (fieldhtmltype<>2 and fieldhtmltype<>6 and fieldhtmltype<> 7) "
+sqlwhere+ " and viewtype=0 order by dsporder,id";
}else{
sql = "select a.id,a.fieldname,b.needExcel,a.fieldlabel from workflow_billfield a, ModeFormFieldExtend b where b.formid=a.billid and "
+"b.formid="+formid+" and b.needExcel=1 and (fieldhtmltype<>2 and fieldhtmltype<>6 and fieldhtmltype<> 7) and viewtype=0 union "
+"select a.id,a.fieldname,1 as needExcel,a.fieldlabel from workflow_billfield a where a.billid="+formid+" "
+"and (fieldhtmltype<>2 and fieldhtmltype<>6 and fieldhtmltype<> 7) and a.viewtype=0 and not exists (select 1 from ModeFormFieldExtend b where b.formid=a.billid and b.formid="+formid+" and b.fieldId=a.id) ";
}
rs.execute(sql);
ModeFormFieldEncryptComInfo modeFormFieldEncryptComInfo=new ModeFormFieldEncryptComInfo();
while (rs.next()) {
String fieldid=rs.getString("id");
String fieldname = rs.getString("fieldname");
if(isOpenClassprotect){
if("seclevel".equals(fieldname.toLowerCase())){
continue;
}
}
String labelname = SystemEnv.getHtmlLabelName(Util.getIntValue(rs.getString("fieldlabel")), user.getLanguage());
EncryptFieldEntity encryptFieldEntity = new EncryptFieldConfigComInfo().getFieldEncryptConfig(maintablename, fieldname);
String isencrypt = modeFormFieldEncryptComInfo.getIsencrypt(fieldid);
if(encryptFieldEntity != null && ("1".equals(encryptFieldEntity.getDesensitization()) || "1".equals(encryptFieldEntity.getIsEncrypt()))) {
isencrypt = "1";//前端不能选择加密字段
}
obj = new JSONObject();
obj.put("key", fieldname);
obj.put("showname", labelname);
obj.put("isencrypt", isencrypt );
keyFieldOption.add(obj);
}
if( (operatelevel < 1 && !isRight)){
rightLevel = 0;//只读权限
}else if(operatelevel>=0){
rightLevel = operatelevel;
}
JSONObject batchImportInfo = new JSONObject();
batchImportInfo.put("importTypeOption", importTypeOption);
batchImportInfo.put("modename", modename);
batchImportInfo.put("templateTitle", templateTitle);
batchImportInfo.put("fieldtransTitle", fieldtransTitle);
batchImportInfo.put("isHaveFieldtrans", isHaveFieldtrans);
batchImportInfo.put("fieldtranspath", fieldtranspath);
batchImportInfo.put("isRight", isRight);
batchImportInfo.put("importorder", importorder);
batchImportInfo.put("interfacepath", interfacepath);
batchImportInfo.put("isuse", isuse);
batchImportInfo.put("validateid", validateid);
batchImportInfo.put("fieldDetailCount", fieldDetailCount);
batchImportInfo.put("keyFieldOption", keyFieldOption);
batchImportInfo.put("excelid", "");
batchImportInfo.put("formid", formid);
batchImportInfo.put("isHaveTemplate", isHaveTemplate);
batchImportInfo.put("modeid", modeid);
RecordSet appRs= new RecordSet();
appRs.executeQuery("select * from HrmOrganizationShowSet");
String applyToModel = ""; //是否全路径
while (appRs.next()){
applyToModel = Util.null2String(appRs.getString("applyToModel"));
}
String windowTitle = "";
if(null != customId&& !customId.equals("")){
RecordSet titileRs = new RecordSet();
titileRs.executeQuery("select customname from mode_customsearch where id = ?",customId);
if(titileRs.next()){
windowTitle = Util.null2String(titileRs.getString("customname"));
}
}
JSONArray arr = new JSONArray();
if (!"".equals(keyfield)) {
String [] keyfields = keyfield.split("\\|");
for (int i = 0; i < keyfields.length; i++) {
arr.add( keyfields[i]);
}
}
batchImportInfo.put("keyfield", arr);
//qc656609获取应用图标信息
String geticonsql = "select icon,iconcolor,iconbg from modetreefield where id=(select modetype from modeinfo where id="+modeid+")";
JSONObject iconInfo = new JSONObject();
String icon = "";//图标
String iconcolor = "";//图标颜色
String iconbg = "";//图标背景颜色
rs.execute(geticonsql);
if(rs.next()){
icon = rs.getString("icon");
iconcolor = rs.getString("iconcolor");
iconbg = rs.getString("iconbg");
}
iconInfo.put("icon", icon);
iconInfo.put("iconcolor", iconcolor);
iconInfo.put("iconbg", iconbg);
result.put("windowTitle", windowTitle);
result.put("applyToModel", applyToModel);
result.put("rightLevel", rightLevel);
result.put("isRight", isRight);
result.put("batchImportInfo", batchImportInfo);
result.put("modeid", modeid);
result.put("operatelevel", operatelevel);
result.put("fmdetachable", fmdetachable);
result.put("iconInfo", iconInfo);
return result;
}
}
/**
*
* @param modeid
* @param formid
* @return
*/
private JSONArray getFieldTrans(String modeid, int formid) {
JSONArray array = new JSONArray();
RecordSet rs = new RecordSet();
String sql = "select fieldid from mode_import_fieldtrans a where modeid=? and formid=? and (exists(select 1 from workflow_billfield b where b.billid=? and b.id=a.fieldid) or a.fieldid in(-1000,-1001,-1002)) ";
rs.executeQuery(sql, modeid,formid,formid);
List<String> fieldTrans = new ArrayList<String>();
while (rs.next()) {
String fieldid=Util.null2String(rs.getString("fieldid"));
fieldTrans.add(fieldid);
}
List<String> tables = new ArrayList<String>();
String maintablename="";
sql="select * from (select 'main' tabletype,tablename,0 as orderid from workflow_bill where id=? union select 'detail' tabletype,tablename,orderid from Workflow_billdetailtable where billid=? ) t order by orderid";
rs.executeQuery(sql, formid,formid);
while (rs.next()) {
String tablename=Util.null2String(rs.getString("tablename"));
String tabletype=Util.null2String(rs.getString("tabletype"));
if ("main".equals(tabletype)) {
maintablename=tablename;
}
tables.add(tablename);
}
sql="select fieldid,w.fieldname,info.labelname fieldlabelname,w.detailtable,w.viewtype from mode_import_template t left join workflow_billfield w on w.id=t.fieldid left join htmllabelinfo info on info.indexid=w.fieldlabel and info.languageid=? where t.modeid=? and t.formid=? order by t.fieldid";
rs.executeQuery(sql, user.getLanguage(),modeid,formid);
if (rs.getCounts()<=0) {//如果没有设置字段,则以表达中的导入字段为准
sql=" select fieldid ,'' fieldname,'' fieldlabelname,'' detailtable,0 viewtype from modeformfieldextend where formid=? and needexcel=1 and fieldid in (-1000,-1001,-1002) ";
sql+=" union all select w.id fieldid,w.fieldname,info.labelname fieldlabelname,w.detailtable,w.viewtype from workflow_billfield w left join htmllabelinfo info on info.indexid=w.fieldlabel and info.languageid=? where billid=? and w.fieldhtmltype not in (6,7) and id not in (select fieldid from modeformfieldextend where needexcel=0 and formid=?)";
rs.executeQuery(sql,formid, user.getLanguage(),formid,formid);
}
Map<String, JSONArray> infomap = new HashMap<String, JSONArray>();
while (rs.next()) {
String fieldid = Util.null2String(rs.getString("fieldid"));
String fieldname = Util.null2String(rs.getString("fieldname"));
String fieldlabelname = Util.null2String(rs.getString("fieldlabelname"));
String detailtable = Util.null2String(rs.getString("detailtable"));
String viewtype = Util.null2String(rs.getString("viewtype"));
String temptablename=maintablename;
if ("1".equals(viewtype)) {//明细表
temptablename=detailtable;
}
if ("-1000".equals(fieldid)) {//数据id
fieldname="id";
fieldlabelname=SystemEnv.getHtmlLabelName(81287,user.getLanguage());
}else if ("-1001".equals(fieldid)) {
fieldname="modedatacreater";
fieldlabelname=SystemEnv.getHtmlLabelName(382643,user.getLanguage());
}else if ("-1002".equals(fieldid)) {
fieldname="modedatacreatedate";
fieldlabelname=SystemEnv.getHtmlLabelName(126848,user.getLanguage());
}
JSONArray tablemap;
if (infomap.containsKey(temptablename)) {
tablemap=infomap.get(temptablename);
}else {
tablemap=new JSONArray();
infomap.put(temptablename, tablemap);
}
JSONObject obj = new JSONObject();
obj.put("fieldid", fieldid);
obj.put("key", fieldid);
obj.put("fieldlabelname", fieldlabelname);
obj.put("fieldname", fieldname);
obj.put("ischeck", fieldTrans.contains(fieldid)?"1":"0");
tablemap.add(obj);
}
for (int i = 0; i < tables.size(); i++) {
String tablename = tables.get(i);
JSONObject tableObj = new JSONObject();
String tablenamelabel = "";
if(i==0){//主表
tablenamelabel = SystemEnv.getHtmlLabelName(21778,user.getLanguage());
}else{
String index = tablename.replace(maintablename+"_dt", "");
tablenamelabel = SystemEnv.getHtmlLabelName(17463,user.getLanguage())+index;
}
tableObj.put("index", i);
tableObj.put("tablename", tablename);
tableObj.put("tablenamelabel", tablenamelabel);
JSONArray fieldArray = infomap.get(tablename);
if (fieldArray==null) {
fieldArray=new JSONArray();
}
tableObj.put("fieldArray", fieldArray);
array.add(tableObj);
}
return array;
}
}

@ -0,0 +1,663 @@
package com.engine.cube.cmd.card;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.cube.biz.CardHelper;
import com.engine.cube.biz.DataHelper;
import com.engine.cube.entity.CardEntity;
import com.weaver.formmodel.util.DateHelper;
import com.weaver.formmodel.util.StringHelper;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.report.schedulediff.HrmScheduleDiffUtil;
import weaver.hrm.resource.ResourceComInfo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LayoutFieldAttrExcute extends AbstractCommonCommand<Map<String, Object>> {
private final DataHelper dataHelper;
private CardEntity card;
public LayoutFieldAttrExcute(Map<String, Object> stringObjectMap, User user) {
this.params = stringObjectMap;
this.user = user;
this.dataHelper = new DataHelper(user);
}
@Override
public BizLogContext getLogContext() {
return null;
}
@Override
public Map<String, Object> execute(CommandContext commandContext) {
Map<String, Object> result = new HashMap<String, Object>();
JSONObject datas = new JSONObject();
this.card = CardHelper.initBaseCardEntity(params);
String triggerStr = Util.null2String(this.params.get("trigger"));
JSONObject trigger = JSONObject.parseObject(triggerStr);
if(trigger == null || trigger.isEmpty()) {
return result;
}
RecordSet rs = new RecordSet();
rs.executeQuery(" select fieldid, attrcontent, caltype, othertype, transtype, datasource" +
" from modefieldattr where layoutid = ? and caltype <> '5' ", card.getLayoutId());
while(rs.next()) {
String attrcontent = Util.null2String(rs.getString(2)).trim();
//attrcontent = attrcontent.replaceAll("\\$currentdate\\$", "\\$date\\$"+ DateHelper.getCurrentDate()+"\\$date\\$");
attrcontent = attrcontent.replaceAll("\\$currentdept\\$", user.getUserDepartment()+"");
attrcontent = attrcontent.replaceAll("\\$currentuser\\$", user.getUID()+"");
attrcontent = attrcontent.replaceAll("\\$billid\\$", Util.null2String(this.card.getBillId()));
attrcontent = attrcontent.replaceAll("\\$dataid\\$", Util.null2String(this.card.getBillId()));
attrcontent = attrcontent.replaceAll("\\$modeid\\$", Util.null2String(this.card.getModeId()));
attrcontent = attrcontent.replaceAll("\\$formid\\$", Util.null2String(this.card.getFormId()));
Pattern pat = Pattern.compile("\\$([-]?\\d+)\\$");
Matcher mat = pat.matcher(attrcontent);
List<String> fields = new ArrayList<String>();
boolean hasFind = false;
JSONArray triggerDatas = null;
while(mat.find()){
String field = mat.group();
field = field.replaceAll("\\$", "");
String fieldStr = "field"+field;
if(trigger.containsKey(fieldStr)) {
hasFind = true;
if(triggerDatas==null){
triggerDatas = trigger.getJSONArray(fieldStr);
}else{
triggerDatas.addAll(trigger.getJSONArray(fieldStr));
}
}
}
if(hasFind && triggerDatas != null && !triggerDatas.isEmpty()) {
String caltype = Util.null2String(rs.getString(3));
String fieldid = "field"+Util.null2String(rs.getString(1)).toLowerCase();
String datasource = Util.null2String(rs.getString("datasource"));
if(datasource.isEmpty()) {
datasource = null;
}
JSONArray tempArr = new JSONArray();
if(datas.containsKey(caltype)){
tempArr = (JSONArray) datas.get(caltype);
}
int othretype = Util.getIntValue(rs.getString(4));
if("1".equals(caltype)||"0".equals(caltype)) {
tempArr.addAll(this.doFieldSql(fieldid, attrcontent, triggerDatas, datasource));
} else if("2".equals(caltype)) {
tempArr.addAll(this.doFieldMath(fieldid, attrcontent, triggerDatas));
} else if("3".equals(caltype)) {
tempArr.addAll(this.doDateTimeCal(fieldid, attrcontent, triggerDatas, othretype ));
} else {
tempArr.addAll(this.doOtherAttr(fieldid, attrcontent, triggerDatas));
}
datas.put(caltype, tempArr);
}
}
result.put("datas", datas);
return result;
}
private JSONArray doOtherAttr(String fieldid, String attrcontent, JSONArray triggerDatas){
JSONArray result = new JSONArray();
int size = triggerDatas.size();
for(int i = 0; i<size; i++) {
String attrcontentTmp = attrcontent;
JSONObject data = new JSONObject();
JSONObject triggerData = triggerDatas.getJSONObject(i);
if (triggerData != null && !triggerData.isEmpty()) {
Pattern pat = Pattern.compile("\\$([-]?\\d+)\\$");
Matcher mat1 = pat.matcher(attrcontent);
while (mat1.find()) {
try {
String field = mat1.group();
String fid = field.replaceAll("\\$", "");
attrcontentTmp = attrcontentTmp.replaceAll("\\$"+fid+"\\$",Util.null2String(triggerData.getString("field"+fid)));
} catch (Exception e) {
e.printStackTrace();
}
}
dataHelper.addValue(data, fieldid, attrcontentTmp);
dataHelper.dealData(data, new String[]{fieldid});
}
if (triggerData.containsKey("index")) {
data.put("index", triggerData.get("index"));
}
result.add(data);
}
return result;
}
private JSONArray doFieldSql(String fieldid, String attrcontent, JSONArray triggerDatas, String datasource) {
JSONArray result = new JSONArray();
attrcontent = attrcontent.replaceAll("\\$currentdate\\$", DateHelper.getCurrentDate());
String execSql = attrcontent;
int index = execSql.indexOf("doFieldSQL(\"");
if (index < 0 || execSql.toUpperCase().indexOf("INSERT") > -1 || execSql.toUpperCase().indexOf("UPDATE") > -1
|| execSql.toUpperCase().indexOf("DROP") > -1 || execSql.toUpperCase().indexOf("TRUNCATE") > -1
|| execSql.toUpperCase().indexOf("DELETE") > -1 || execSql.toUpperCase().indexOf("EXEC") > -1
|| execSql.toUpperCase().indexOf("CALL") > -1 ){
return result;
}
execSql = execSql.substring(index + 12);
index = execSql.lastIndexOf("\")");
if (index > -1) {
execSql = execSql.substring(0, index);
execSql = execSql.trim();
}
Pattern pat = Pattern.compile("\\$([-]?\\d+)\\$");
Matcher mat = pat.matcher(attrcontent);
List<String> paramNames = new ArrayList<String>();
List<String> fieldArr = new ArrayList<String>();
while(mat.find()){
try{
String field = mat.group();
String fid = field.replaceAll("\\$", "");
paramNames.add("field"+fid);
fieldArr.add(field);
//execSql = Util.replaceString(execSql, field, " ? ");
//execSql = execSql.replaceAll( "\\$"+fid+"\\$", " ? ");
}catch(Exception e){
e.printStackTrace();
}
}
RecordSet rs = new RecordSet();
int size = triggerDatas.size();
for(int i = 0; i<size; i++) {
String tempexecSql=execSql;
JSONObject data = new JSONObject();
JSONObject triggerData = triggerDatas.getJSONObject(i);
if(triggerData != null && !triggerData.isEmpty()) {
int size2 = paramNames.size();
for(int j = 0; j<size2; j++) {
String field = fieldArr.get(j);
try {
System.out.println(triggerData.getString(paramNames.get(j)));
tempexecSql = tempexecSql.replace(field, triggerData.getString(paramNames.get(j)));
}catch(Exception e){
}
}
/* tempexecSql = " select zs from uf_glzd_cp where id = '1' and dxwb = '1' ";*/
if(datasource==null||StringHelper.isEmpty(datasource)){
rs.executeSql(tempexecSql);
}else{
rs.executeSql(tempexecSql, datasource);
}
String[] cols = rs.getColumnName();
while(rs.next()) {
if(cols.length > 1){
dataHelper.addValue(data, fieldid, rs.getString(2));
} else {
dataHelper.addValue(data, fieldid, rs.getString(1));
}
}
dataHelper.dealData(data, new String[]{fieldid});
}
//if(data.isEmpty()) {
// data.put(fieldid, "");
//}
if(triggerData.containsKey("index")) {
data.put("index", triggerData.get("index"));
}
result.add(data);
}
return result;
}
private JSONArray doDateTimeCal(String fieldid, String attrcontent, JSONArray triggerDatas, int othertype) {
JSONArray result = new JSONArray();
int size = triggerDatas.size();
for(int i=0;i<size; i++) {
JSONObject triggerData = triggerDatas.getJSONObject(i);
if(triggerData != null && !triggerData.isEmpty()) {
JSONObject data = this.doDateTimeCal(fieldid, attrcontent,triggerData, othertype);
dataHelper.dealData(data, new String[]{fieldid});
if(triggerData.containsKey("index")) {
data.put("index", triggerData.get("index"));
}
result.add(data);
}
}
return result;
}
private JSONObject doDateTimeCal(String fieldid, String attrcontent, JSONObject triggerData, int othertype){
String datecontent_tmp = attrcontent;
String retDateContent = "";
int index = datecontent_tmp.indexOf("$");
String fieldType = dataHelper.getFieldType(fieldid);
while (index > -1) {
int index0 = datecontent_tmp.indexOf("$", index + 1);
String field1 = datecontent_tmp.substring(index + 1, index0);
String mark_t = datecontent_tmp.substring(0, index).trim();
if ("+".equals(mark_t)) {
retDateContent += ("+");
} else if ("-".equals(mark_t)) {
retDateContent += ("-");
}
if (("datetime").equals(field1)) {
retDateContent += "$datetime$";
} else if ("currentdate".equals(field1)) {
retDateContent += "$date$"+ DateHelper.getCurrentDate()+"$date$";
} else if ("currentdatetime".equals(field1)) {
retDateContent += "$currentdatetime$"+ DateHelper.getCurDateTime()+"$currentdatetime$";
} else {
String fieldtypeStr = "";
String htmltype = dataHelper.getFieldHtmlType("field"+field1);
String detailtype = dataHelper.getFieldType("field"+field1);
boolean isdate = "3".equals(htmltype)&&"2".equals(detailtype);
boolean istime = "3".equals(htmltype)&&"19".equals(detailtype);
boolean isinput = !isdate&&!istime;
if (isinput == true) {
fieldtypeStr = "$input$";
} else if (isdate == true) {
fieldtypeStr = "$date$";
} else if (istime == true) {
fieldtypeStr = "$time$";
}
retDateContent += (fieldtypeStr + triggerData.getString("field"+field1) + fieldtypeStr) ;
}
datecontent_tmp = datecontent_tmp.substring(index0 + 1);
index = datecontent_tmp.indexOf("$");
}
// 最后结尾如果有数据,要特殊处理
String[] tailStr = datecontent_tmp.split("");
Pattern pa = Pattern.compile("\\d{1}");
if (tailStr != null) {
int ishead = -1;
for (int j = 0; j < tailStr.length; j++) {
String s = tailStr[j].trim();
Matcher matcher = pa.matcher(s);
if ("+".equals(s)) {
if (ishead == 0) {
retDateContent += "$input$";
}
retDateContent += ("+");
ishead = 1;
} else if ("-".equals(s)) {
if (ishead == 0) {
retDateContent += "$input$";
}
retDateContent += ("-");
ishead = 1;
} else if (matcher.find()) {
if (ishead == 1) {
retDateContent += ("$input$" + s);
ishead = 0;
} else {
retDateContent += s;
}
}
}
if (ishead == 0) {
retDateContent += "$input$\"";
}
}
String datecontent = retDateContent;
String key = "";
String fromdate = "";
String fromtime = "";
String todate = "";
String totime = "";
String tempCalStr = "";
int inputDate = -1;
int setDataCx = 0;//赋值次数
String tempDateTime = "";
double tempDouble = 0;
boolean isDateTimeCal = false;
int index0 = datecontent.indexOf("$");
while(index0 > -1){
String calStr = "";
int index1 = datecontent.indexOf("$", index0+1);
String espStr = datecontent.substring(index0+1, index1);//数据类型标识。date日期、time时间、input数字
datecontent = datecontent.substring(index1+1);
if("datetime".equals(espStr)){
//datecontent = datecontent.substring(index1+espStr.length()+1);
isDateTimeCal = true;
}else{
int index2 = datecontent.indexOf("$"+espStr+"$");//找这个标签的下一次出现的地方
String data0 = datecontent.substring(0, index2);//标识中的值
if("date".equalsIgnoreCase(espStr)){
if("".equals(fromdate)){
fromdate = data0;
setDataCx += 1;
}else{
todate = data0;
if(isDateTimeCal == false){
setDataCx += 2;
}
}
}else if("time".equalsIgnoreCase(espStr)){
if("".equals(fromtime)){
fromtime = data0;
}else{
totime = data0;
if(isDateTimeCal == true){
setDataCx += 2;
}
}
}else if("currentdatetime".equalsIgnoreCase(espStr)){
String[] split = data0.split(" ");
if (split.length==2) {
if("".equals(fromdate)){
fromdate = split[0];
fromtime=split[1];
setDataCx += 1;
}else{
todate = split[0];
totime=split[1];
if(isDateTimeCal == true){
setDataCx += 2;
}
}
}
}else if("input".equalsIgnoreCase(espStr)){
inputDate = Util.getIntValue(data0, 0);
setDataCx += 5;
}
try{
if(setDataCx==3 || setDataCx==6 || setDataCx==5){//3日期[合并时间]与日期[合并时间]计算6日期[合并]时间与数字计算5做过日期计算又做与数字的计算
if(setDataCx == 3){
tempDouble = Util.getDoubleValue(getDateTimeCal(fromdate, fromtime, todate, totime, isDateTimeCal, othertype, tempCalStr));
key = ""+tempDouble;
/*if(tempDouble<0){
key = null;
}*/
inputDate = Util.getIntValue(key);
fromdate = "";
fromtime = "";
todate = "";
todate = "";
}else if(setDataCx == 6){
tempDateTime = getDateTimeInputCal(fromdate, fromtime, inputDate, isDateTimeCal, othertype, tempCalStr);
key = tempDateTime;
}else if(setDataCx == 5){
if("+".equalsIgnoreCase(tempCalStr)){
tempDouble = tempDouble + inputDate;
}else{
tempDouble = tempDouble - inputDate;
}
key = ""+tempDouble;
}
setDataCx = 0;
}
}catch(Exception e){
e.printStackTrace();
setDataCx = 0;
}
int index3 = datecontent.indexOf("$", index2+espStr.length()+2);//
if(index3 > -1){
calStr = datecontent.substring(index2+espStr.length()+2, index3);
if(!"".equals(calStr.trim())){
tempCalStr = calStr;
}
}
datecontent = datecontent.substring(index2+espStr.length()+2);
}
index0 = datecontent.indexOf("$");
}
JSONObject result = new JSONObject();
result.put(fieldid, key);
return result;
}
/**
* [][]
* isDateTimeCal
* othertype0使1
* tempCalStr
*/
public String getDateTimeInputCal(String fromdate, String fromtime, int inputData, boolean isDateTimeCal, int othertype, String tempCalStr){
String retStr = "";
if("".equals(fromdate)){
return retStr;
}
try{
if(inputData==0 && isDateTimeCal==true){
retStr = fromdate + " " + fromtime;
return retStr;
}
if("-".equals(tempCalStr)){
inputData = inputData * (-1);
tempCalStr = "+";
}
if((inputData==1 || inputData==0) && isDateTimeCal==false){
retStr = fromdate;
return retStr;
}
if(inputData >= 0){
inputData = inputData - 1;
}else{
inputData = inputData;
}
if("".equals(fromtime)){
isDateTimeCal = false;
}
if(othertype == 0){
if(isDateTimeCal == false){
retStr = TimeUtil.dateAdd(fromdate, inputData);
}else{
retStr = TimeUtil.timeAdd(fromdate+" "+((fromtime + ":00").substring(0, 8)), inputData*24*3600);
}
}else{
//如果考虑排除工作日,时间暂时无法参与计算
int addtype = 0;
if("-".equals(tempCalStr)){
addtype = 0;
}else{
addtype = 1;
}
if(inputData<0){
inputData = inputData * (-1);
if(addtype == 1){
addtype = 0;
}else{
addtype = 1;
//inputData = inputData * (-1);
}
}
retStr = getNextWorkDate(fromdate, inputData, user, addtype);//无法获取人员信息,当前操作者未必就是正确的分部,所以用总部的
if(isDateTimeCal == true){
retStr = retStr + " " + fromtime;
}
}
}catch(Exception e){
new BaseBean().writeLog(e);
}
return retStr;
}
/**
*
* addtype1days0days
*/
public String getNextWorkDate(String fromdate, int days, User user, int addtype){
String retStr = "";
try{
//writeLog("fromdate = " + fromdate);
//writeLog("days = " + days);
//writeLog("addtype = " + addtype);
HrmScheduleDiffUtil hrmScheduleDiffUtil = new HrmScheduleDiffUtil();
hrmScheduleDiffUtil.setUser(user);
String nextDate_t = fromdate;
int day0 = 1;
if(addtype == 1){
day0 = 1;
}else{
day0 = -1;
}
int index = 0;
for(int cx=0; cx<days; ){
//writeLog("cx = " + cx);
nextDate_t = TimeUtil.dateAdd(nextDate_t, day0);
boolean isworkday = hrmScheduleDiffUtil.getIsWorkday(nextDate_t);
index++;
if(index>100&&index>2*days){
index=-1;
break;
}
if(isworkday == true){
retStr = nextDate_t;
cx++;
}
}
if(index==-1){
retStr = fromdate;
}
}catch(Exception e){
new BaseBean().writeLog(e);
}
//writeLog("retStr = " + retStr);
return retStr;
}
/**
** []floatString
* isDateTimeCal
* othertype0使1
* tempCalStr
*/
private String getDateTimeCal(String fromdate, String fromtime, String todate, String totime, boolean isDateTimeCal, int othertype, String tempCalStr){
String retStr = "";
if("".equals(fromdate) || "".equals(todate)){
return retStr;
}
try{
if("-".equals(tempCalStr)){
if("".equals(fromtime) || "".equals(totime)){
isDateTimeCal = false;
}else{
fromtime = (fromtime + ":00").substring(0, 8);
totime = (totime + ":00").substring(0, 8);
}
if(othertype == 0){
if(isDateTimeCal == true){
//做减法,要把数据倒过来
if(TimeUtil.timeInterval(todate+" "+totime, fromdate +" "+ fromtime) >= (long)0){
retStr = ""+(Util.getDoubleValue((""+TimeUtil.timeInterval(todate+" "+totime, fromdate +" "+ fromtime)))/3600/24);
}else{
retStr = ""+(Util.getDoubleValue((""+TimeUtil.timeInterval(todate+" "+totime, fromdate +" "+ fromtime)))/3600/24);
}
}else{
if(TimeUtil.dateInterval(todate, fromdate) >= (long)0){
retStr = ""+(TimeUtil.dateInterval(todate, fromdate) + 1);
}else{
retStr = ""+(TimeUtil.dateInterval(todate, fromdate));
}
}
}else{
HrmScheduleDiffUtil hrmScheduleDiffUtil = new HrmScheduleDiffUtil();
hrmScheduleDiffUtil.setUser(user);
ResourceComInfo resourceComInfo = new ResourceComInfo();
DepartmentComInfo departmentComInfo = new DepartmentComInfo();
int departmentId = Util.getIntValue(resourceComInfo.getDepartmentID(""+user.getUID()));
int subCompanyId = Util.getIntValue(departmentComInfo.getSubcompanyid1(""+departmentId));
//做减法,要把数据倒过来
long firstCal = 0;
if(isDateTimeCal == true){
firstCal = TimeUtil.timeInterval(todate+" "+totime, fromdate+" "+fromtime);//前小后大返回大于0的数
}else{
firstCal = TimeUtil.dateInterval(todate, fromdate);
}
//下面的那个方法必须前面参数的日期在后面参数的日期之前比如2012-02-01---2012-03-01得到的值大于0
if(totime.length() == 8){
totime = totime.substring(0, 5);
}
if(fromtime.length() == 8){
fromtime = fromtime.substring(0, 5);
}
if(firstCal >= (long)0){
String a = hrmScheduleDiffUtil.getTotalWorkingDays(todate, totime, fromdate, fromtime, subCompanyId);
if(!"".equals(a)){
a = ""+(Util.getFloatValue(a));
}else{
a = ""+0;
}
retStr = a;
}else{
String b = hrmScheduleDiffUtil.getTotalWorkingDays(fromdate, fromtime, todate, totime, subCompanyId);
if(!"".equals(totime)){
b = ""+(Util.getFloatValue(b));
}else{
b = ""+(Util.getFloatValue(b) - 1);
}
retStr = "-" + b;
}
}
}else{
}
if(!"".equals(retStr) && retStr.indexOf(".")>-1){
//处理一分钟的特殊情况
if(retStr.equals("6.944444444444445E-4")){
retStr = "0.001388888888888889";
}
retStr = retStr + "00000";
retStr = retStr.substring(0, retStr.indexOf(".")+5);
}
}catch(Exception e){
new BaseBean().writeLog(e);
}
return retStr;
}
private JSONArray doFieldMath(String fieldid, String attrcontent, JSONArray triggerDatas){
JSONArray result = new JSONArray();
Pattern pat = Pattern.compile("\\$([-]?\\d+)\\$");
int index = attrcontent.indexOf("doFieldMath(\"");
String attrcontentTemp=null;
if (index > -1) {
attrcontentTemp = attrcontent.substring(index + 13);
index = attrcontentTemp.lastIndexOf("\")");
if (index > -1) {
attrcontentTemp = attrcontentTemp.substring(0, index);
}
int size = triggerDatas.size();
for(int i = 0; i<size; i++) {
JSONObject data = triggerDatas.getJSONObject(i);
JSONObject rtData = new JSONObject();
if(data == null || data.isEmpty()) {
continue;
}
String calc = attrcontentTemp;
Matcher mat = pat.matcher(calc);
while(mat.find()) {
String field = mat.group();
String fieldidStr = field.replaceAll("\\$", "");
double value=0.0;
if(null!=data.getString("field"+fieldidStr)){
value = Util.getDoubleValue(data.getString("field"+fieldidStr).replaceAll(",",""), 0);
}
calc = calc.replaceAll("\\$"+fieldidStr+"\\$", "("+value+")" );
}
rtData.put(fieldid, calc);
if(data.containsKey("index")) {
rtData.put("index", data.get("index"));
}
result.add(rtData);
}
}
return result;
}
}

@ -0,0 +1,131 @@
package com.engine.hansang.action;
import com.time.util.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestInfo;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
*
* <p>
*
* 1稿
* 2
*
* 153
*
* @author wangj
* @version 1.00
* @Date 2023/9/4
*/
public class UpdateMarriageLeaveBalance implements Action {
@Override
public String execute(RequestInfo requestInfo) {
Map mainnInfo = new HashMap(1000);
Property[] property = requestInfo.getMainTableInfo().getProperty();
for (int i = 0; i < property.length; i++) {
mainnInfo.put(property[i].getName().toLowerCase(), Util.null2String(property[i].getValue()));
}
//自助信息类型
String zzxxlx = Util.null2String(mainnInfo.get("zzxxlx"));
//婚姻状况
String hyzk = Util.null2String(mainnInfo.get("hyzk"));
try {
//已婚
if ("1".equals(zzxxlx) && "1".equals(hyzk)) {
int days = 0;
//是否初婚
String sfch = Util.null2String(mainnInfo.get("sfch"));
//登记日期
String djrq = Util.null2String(mainnInfo.get("djrq"));
//申请人
String sqr = Util.null2String(mainnInfo.get("sqr"));
//入职日期
String rzrq = getRzrq(sqr);
//判断结婚登记日期在入职期间的
boolean flag = compareDateLessEquation(rzrq, djrq);
if (flag) {
if ("1".equals(sfch)) {
//再婚3天
days = 3;
} else {
//0 或 空默认初婚 15天
days = 15;
}
if (days > 0) {
updateLeaveBalance(sqr, days);
}
}
}
} catch (Exception e) {
requestInfo.getRequestManager().setMessagecontent("接口异常:"+e.getMessage());
return Action.FAILURE_AND_CONTINUE;
}
return Action.SUCCESS;
}
/**
* @Description:
* @Param:
* @return:
* @Author: wangj
*/
private boolean compareDateLessEquation(String start, String end) {
boolean flag = false;
if ("".equals(start) || "".equals(end)) {
return false;
}
Date sdate = DateUtil.parseDate(start, "yyyy-MM-dd");
Date edate = DateUtil.parseDate(end, "yyyy-MM-dd");
if (sdate.getTime() < edate.getTime()) {
flag = true;
}
return flag;
}
private String getRzrq(String id) {
String date = "";
RecordSet rs = new RecordSet();
String sql = "select workcode,lastname,companystartdate from hrmresource where id = ?";
rs.executeQuery(sql, id);
while (rs.next()) {
date = Util.null2String(rs.getString("companystartdate"));
}
return date;
}
private void updateLeaveBalance(String sqr, int days) {
String sql = "select count(1) as sl from kq_balanceofleave where leaveRulesId = 32 and resourceid = ?";
RecordSet rs = new RecordSet();
int count = 0;
rs.executeQuery(sql,sqr);
while (rs.next()){
count = Util.getIntValue(rs.getString("sl"));
}
String year = DateUtil.getCurrentTime("yyyy");
if(count > 0){
sql = "update kq_balanceofleave set leaveRulesId = ?, resourceId = ?, belongYear = ?, baseAmount = ?, extraAmount = ?, usedAmount = ?, baseAmount2 = ?, extraAmount2 = ?, usedAmount2 = ?, status = ?,tiaoxiuamount = ?,isDelete = ? where resourceid = ? and leaveRulesId = ?";
rs.executeUpdate(sql,"32",sqr,year,days,"0","0","0","0","0","0","0","0",sqr,"32");
}else{
sql = "insert into kq_balanceofleave (leaveRulesId, resourceId, belongYear, baseAmount, extraAmount, usedAmount, baseAmount2, extraAmount2, usedAmount2, status,tiaoxiuamount) values (?,?,?,?,?,?,?,?,?,?,?)";
rs.executeUpdate(sql,"32",sqr,year,days,"0","0","0","0","0","0","0");
}
}
}

@ -0,0 +1,268 @@
package com.engine.hansang.job;
import c.u.d.c.gh;
import com.alibaba.fastjson.JSONObject;
import com.engine.kq.util.KQDurationCalculatorUtil;
import com.time.util.DateUtil;
import org.apache.tools.ant.types.selectors.modifiedselector.Cache;
import org.htmlparser.tags.TableRow;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.schedule.BaseCronJob;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.*;
/**
* 80%
*
* @author wangj
* @version 1.00
* @Date 2023/9/7
*/
public class CountOvertimeWorkersJob extends BaseCronJob {
private static DecimalFormat df = new DecimalFormat("0.00");
@Override
public void execute() {
Map<String, String> jbmap = new HashMap<>(1000);
String date = DateUtil.getCurrentTime("yyyy-MM");
String start = date + "-01";
String end = getLastDayByMonth();
Map<String, Object> flowData = getFlowOverTimeDataNew(start, end);
RecordSet rs = new RecordSet();
//1、查询当月的加班时长限制
String sql = "select bm,gw,zjj,dyljjbcexs from uf_jbfjsp where dyljjbcexs is not null";
rs.execute(sql);
while (rs.next()) {
String bm = Util.null2String(rs.getString("bm"));
String gw = Util.null2String(rs.getString("gw"));
String zjj = Util.null2String(rs.getString("zjj"));
String dyljjbcexs = Util.null2String(rs.getString("dyljjbcexs"));
String str = bm + "-" + gw + "-" + zjj;
jbmap.put(str, dyljjbcexs);
}
String formmodeid = "";
rs.execute("select k.id from modeinfo k inner join workflow_bill l on formid = l.id where l.tablename = 'uf_gwjbsxtz'");
if (rs.next()) {
formmodeid = Util.null2String(rs.getString("id"));
}
rs.execute("delete from uf_gwjbsxtz where yf = '" + date + "'");
//2、获取全部人员信息,查询人员的加班时长总计(当月)
sql = "select a.id,a.workcode,a.lastname,a.departmentid,a.jobtitle,a.managerid,b.field35 as zjj,b.field102 as xnfz,b.field36 as xzsx,c.field118 as cbzxmc from hrmresource a left join cus_fielddata b on a.id = b.id left join cus_fielddata c on a.id = c.id where b.scope = 'HrmCustomFieldByInfoType' and b.scopeid = '-1' and c.scope = 'HrmCustomFieldByInfoType' and c.scopeid = '3'";
rs.execute(sql);
while (rs.next()) {
String id = Util.null2String(rs.getString("id"));
String workcode = Util.null2String(rs.getString("workcode"));
String lastname = Util.null2String(rs.getString("lastname"));
String departmentid = Util.null2String(rs.getString("departmentid"));
String jobtitle = Util.null2String(rs.getString("jobtitle"));
String managerid = Util.null2String(rs.getString("managerid"));
String zjj = Util.null2String(rs.getString("zjj"));
String xnfz = Util.null2String(rs.getString("xnfz"));
String xzsx = Util.null2String(rs.getString("xzsx"));
String cbzxmc = Util.null2String(rs.getString("cbzxmc"));
Map<String, String> deptm = getDepartmentManager(departmentid);
String bmjl = Util.null2String(deptm.get("bmjl"));
String bmzj = Util.null2String(deptm.get("bmzj"));
String bmzg = Util.null2String(deptm.get("bmzg"));
String limithour = Util.null2String(jbmap.get(departmentid + "-" + jobtitle + "-" + zjj));
if ("".equals(limithour)) {
continue;
}
//获取人员当月的加班总计(小时)
String overHours = getOverTimeByUserId(id, flowData);
BigDecimal a = new BigDecimal(overHours);
BigDecimal b = new BigDecimal(limithour);
BigDecimal c = a.divide(b, 2, RoundingMode.HALF_UP);
String bl = c.toString();
//更新数据到岗位加班上限台账建模表
insertData(workcode, id, departmentid, jobtitle, xzsx, cbzxmc, xnfz, managerid, limithour, overHours, date, formmodeid, bl, bmjl, bmzj, bmzg);
}
}
private Map<String, String> getDepartmentManager(String deptid) {
Map<String, String> map = new HashMap<>(100);
String bmjl = "0";
String bmzj = "0";
String bmzg = "0";
String sql = "select bmjl,bmzj,bmzg from hrmdepartmentdefined where deptid = ?";
RecordSet rs = new RecordSet();
rs.executeQuery(sql, deptid);
while (rs.next()) {
bmjl = Util.null2String(rs.getString("bmjl"));
bmzj = Util.null2String(rs.getString("bmzj"));
bmzg = Util.null2String(rs.getString("bmzg"));
}
map.put("bmjl", bmjl);
map.put("bmzj", bmzj);
map.put("bmzg", bmzg);
return map;
}
private void insertData(String gh, String xm, String bm, String gw, String xzzx, String cbzx, String xnfz, String zjld, String dyjbsx, String dyljjbsc, String yf, String formmodeid, String bl, String bmjl, String bmzj, String bmzg) {
RecordSetTrans rst = new RecordSetTrans();
String modedatacreater = "1";
String modedatacreatertype = "0";
String createdate = DateUtil.getCurrentTime("yyyy-MM-dd");
String createtime = DateUtil.getCurrentTime("HH:mm:ss");
String modeuuid = UUID.randomUUID().toString();
rst.setAutoCommit(false);
try {
String sql = " insert into uf_gwjbsxtz(gh,xm,bm,gw,xzzx,cbzx,xnfz,zjld,dyjbsx,dyljjbsc,yf,bl,bmjl,bmzj,bmzg,formmodeid,modedatacreater,modedatacreatertype,modeuuid,modedatacreatedate,modedatacreatetime) " +
"values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
rst.executeUpdate(sql, gh, xm, bm, gw, xzzx, cbzx, xnfz, zjld, dyjbsx, dyljjbsc, yf, bl, bmjl, bmzj, bmzg, formmodeid, modedatacreater, modedatacreatertype, modeuuid, createdate, createtime);
} catch (Exception e) {
e.getMessage();
}
rst.commit();
int dataId = getDataIdByUUID(modeuuid);
ModeRightInfo modeRightInfo = new ModeRightInfo();
modeRightInfo.editModeDataShare(1, Integer.parseInt(formmodeid), dataId);
}
/**
* uuidid
*
* @param uuid modeUuid
* @return dataId
*/
public static int getDataIdByUUID(String uuid) {
RecordSet rs = new RecordSet();
int dataid = -1;
String sql = "select id uf_gwjbsxtz where modeuuid = ?";
if (rs.executeQuery(sql, uuid) && rs.next()) {
dataid = Util.getIntValue(rs.getString(1));
}
return dataid;
}
/**
*
*
* @return
*/
public Map<String, Object> getFlowOverTimeDataNew(String start, String end) {
Map<String, Object> datas = new HashMap<>();
;
RecordSet rs = new RecordSet();
String sql = "select resourceid,changeType, sum(cast(duration_min as decimal(18,4))) as val,paidLeaveEnable from hrmresource a, kq_flow_overtime b where a.id = b.resourceid and belongdate >='" + start + "' and belongdate <='" + end + "' group by resourceid,changeType,paidLeaveEnable";
rs.execute(sql);
try {
while (rs.next()) {
String resourceid = rs.getString("resourceid");
String paidLeaveEnable = rs.getString("paidLeaveEnable");
int changeType = rs.getInt("changeType");//1-节假日、2-工作日、3-休息日
double value = rs.getDouble("val") < 0 ? 0 : rs.getDouble("val");
value = Util.getDoubleValue(KQDurationCalculatorUtil.getDurationRound(value / (60.0) + ""));
String flowType = "";
if (changeType == 1) {
flowType = "holidayOvertime";
} else if (changeType == 2) {
flowType = "workingDayOvertime";
} else if (changeType == 3) {
flowType = "restDayOvertime";
}
if ("1".equalsIgnoreCase(paidLeaveEnable)) {
//1表示关联调休
flowType += "_4leave";
} else {
//0表示不关联调休
flowType += "_nonleave";
}
String key = resourceid + "|" + flowType;
//df.format 默认是不四舍五入的 0.125这样的就会直接变成0.12了
df.setMaximumFractionDigits(5);
if (datas.containsKey(key)) {
double tmpVal = Util.getDoubleValue(Util.null2String(datas.get(key)), 0.0);
tmpVal += value;
datas.put(key, df.format(tmpVal));
} else {
datas.put(key, df.format(value));
}
}
} catch (Exception e) {
new BaseBean().writeLog(e);
}
return datas;
}
/**
*
*
* @param id
* @param flowData
* @return
*/
private String getOverTimeByUserId(String id, Map<String, Object> flowData) {
String fieldValue = "";
double workingDayOvertime_4leave = Util.getDoubleValue(Util.null2String(flowData.get(id + "|workingDayOvertime_4leave")));
workingDayOvertime_4leave = workingDayOvertime_4leave < 0 ? 0 : workingDayOvertime_4leave;
double restDayOvertime_4leave = Util.getDoubleValue(Util.null2String(flowData.get(id + "|restDayOvertime_4leave")));
restDayOvertime_4leave = restDayOvertime_4leave < 0 ? 0 : restDayOvertime_4leave;
double holidayOvertime_4leave = Util.getDoubleValue(Util.null2String(flowData.get(id + "|holidayOvertime_4leave")));
holidayOvertime_4leave = holidayOvertime_4leave < 0 ? 0 : holidayOvertime_4leave;
double workingDayOvertime_nonleave = Util.getDoubleValue(Util.null2String(flowData.get(id + "|workingDayOvertime_nonleave")));
workingDayOvertime_nonleave = workingDayOvertime_nonleave < 0 ? 0 : workingDayOvertime_nonleave;
double restDayOvertime_nonleave = Util.getDoubleValue(Util.null2String(flowData.get(id + "|restDayOvertime_nonleave")));
restDayOvertime_nonleave = restDayOvertime_nonleave < 0 ? 0 : restDayOvertime_nonleave;
double holidayOvertime_nonleave = Util.getDoubleValue(Util.null2String(flowData.get(id + "|holidayOvertime_nonleave")));
holidayOvertime_nonleave = holidayOvertime_nonleave < 0 ? 0 : holidayOvertime_nonleave;
fieldValue = KQDurationCalculatorUtil.getDurationRound(String.valueOf(workingDayOvertime_4leave + restDayOvertime_4leave + holidayOvertime_4leave +
workingDayOvertime_nonleave + restDayOvertime_nonleave + holidayOvertime_nonleave));
if ("".equals(fieldValue)) {
fieldValue = "0.00";
}
return fieldValue;
}
/**
*
*
* @return
*/
private String getLastDayByMonth() {
// 指定日期
Date date = new Date();
// 获取指定日期所在月份的最后一天
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
Date lastDayOfMonth = calendar.getTime();
String dates = DateUtil.formatDate(lastDayOfMonth, "yyyy-MM-dd");
return dates;
}
}

@ -0,0 +1,78 @@
package com.engine.hansang.job;
import com.time.util.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.interfaces.schedule.BaseCronJob;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* lastname
*
*
* 1lastname-
* 2lastname-Rfield82
*
* @author wangj
* @version 1.00
* @Date 2023/9/4
*/
public class UpdateHrmLastNameJob extends BaseCronJob {
@Override
public void execute() {
String date = DateUtil.getCurrentTime("yyyy-MM-dd");
RecordSet rs = new RecordSet();
String sql = "select a.id,workcode,lastname,field82 as lzrq from hrmresource a left join cus_fielddata b on a.id = b.id where b.scope = 'HrmCustomFieldByInfoType' and scopeid = 3";
rs.execute(sql);
while (rs.next()){
String newLastname = "";
String id = Util.null2String(rs.getString("id"));
String workcode = Util.null2String(rs.getString("workcode"));
String lastname = Util.null2String(rs.getString("lastname"));
String lzrq = Util.null2String(rs.getString("lzrq"));
if(lastname.contains("-")){
String[] lastnameArr = lastname.split("-");
lastname = lastnameArr[lastnameArr.length-1];
lastname = lastname.replaceAll("\\(R\\)","");
}
newLastname = workcode+"-"+lastname;
if(!"".equals(lzrq)){
//当前日期>=离职日期的吧
boolean flag = compareDate(lzrq,date);
if(flag){
newLastname = newLastname+"(R)";
}
}
updateLastName(id,newLastname);
}
}
private void updateLastName(String id,String lastname){
RecordSet rs = new RecordSet();
String sql = "update hrmresource set lastname = ? where id = ?";
rs.executeUpdate(sql,lastname,id);
}
//比较时间大小
public static boolean compareDate(String start, String end) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date1 = simpleDateFormat.parse(start);
Date date2 = simpleDateFormat.parse(end);
if (date1.getTime() <= date2.getTime()) {
return true;
}
} catch (ParseException e) {
throw new RuntimeException(e);
}
return false;
}
}

@ -0,0 +1,61 @@
package com.engine.hrm.cmd.codeseting;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.hrm.entity.RuleCodeType;
import com.engine.hrm.util.CodeRuleManager;
import com.engine.integration.util.StringUtils;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.resource.ResourceComInfo;
import java.util.HashMap;
import java.util.Map;
public class RegenerateCodeCmd extends AbstractCommonCommand<Map<String, Object>> {
public RegenerateCodeCmd(Map<String, Object> params, User user) {
this.params = params;
this.user = user;
}
@Override
public BizLogContext getLogContext() {
return null;
}
@Override
public Map<String, Object> execute(CommandContext commandContext) {
Map<String, Object> apidata = new HashMap<>();
try {
DepartmentComInfo departmentComInfo = new DepartmentComInfo();
ResourceComInfo resourceComInfo = new ResourceComInfo();
String serialtype = Util.null2String(params.get("serialtype"));
String subcompanyid = Util.null2String(params.get("subcompanyid"));
String deptid = Util.null2String(params.get("departmentid"));
String jobtitlesid = Util.null2String(params.get("jobtitlesid"));
String userid = Util.null2String(params.get("userid"));
switch (RuleCodeType.getByValue(serialtype)) {
case DEPARTMENT:
if (StringUtils.isEmpty(subcompanyid)) subcompanyid = departmentComInfo.getSubcompanyid1(deptid);
break;
case USER:
if (StringUtils.isEmpty(subcompanyid)) subcompanyid = resourceComInfo.getSubCompanyID(userid);
if (StringUtils.isEmpty(deptid)) deptid = resourceComInfo.getDepartmentID(userid);
if (StringUtils.isEmpty(jobtitlesid)) jobtitlesid = resourceComInfo.getJobTitle(userid);
break;
}
String code = CodeRuleManager.getCodeRuleManager().generateRuleCode(Enum.valueOf(RuleCodeType.class, serialtype), subcompanyid, deptid, jobtitlesid, null);
apidata.put("code", code);
} catch (Exception e) {
writeLog(e);
apidata.put("api_status", false);
apidata.put("api_errormsg", e.getMessage());
}
return apidata;
}
}

@ -0,0 +1,231 @@
package com.engine.hsCheck.cmd;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import java.util.HashMap;
import java.util.Map;
public class CheckCmd extends AbstractCommonCommand<Map<String, Object>> {
public CheckCmd(Map<String, Object> params) {
this.params = params;
}
@Override
public BizLogContext getLogContext() {
return null;
}
@Override
public Map<String, Object> execute(CommandContext commandContext) {
RecordSet rs = new RecordSet();
BaseBean bb = new BaseBean();
Map<String, Object> apimap = new HashMap<String, Object>();
try {
String workflowId = Util.null2String(params.get("workflowId"));
String resourceId = Util.null2String(params.get("resourceId"));
String fromDate = Util.null2String(params.get("fromDate"));
String fromTime = Util.null2String(params.get("fromTime"));
String toDate = Util.null2String(params.get("toDate"));
String toTime = Util.null2String(params.get("toTime"));
String st = fromDate + " " + fromTime;
String ed = toDate + " " + toTime;
int _tmpRq = 0;
String msg = "";
if ("105".equals(workflowId)) {
rs.execute("select wr.requestid,wr.requestname from formtable_main_20_dt1 a,formtable_main_20 b ,workflow_requestbase wr " +
"where b.requestId =wr.REQUESTID and b.id=a.mainid and a.resourceId=" + resourceId + " and wr.CURRENTNODETYPE >0 and " +
" ((CONCAT(fromDate ,' ',fromTime) < '" + st + "' and '" + st + "' < CONCAT(toDate ,' ',toTime) ) or (CONCAT(fromDate ,' ',fromTime) < '" + ed + "' and '"+ed+"' < CONCAT(toDate ,' ',toTime)) or (CONCAT(fromDate ,' ',fromTime) > '" + st + "' and '"+ed+"' > CONCAT(toDate ,' ',toTime)) )" +
" " +
" ");
bb.writeLog("select wr.requestid,wr.requestname from formtable_main_20_dt1 a,formtable_main_20 b ,workflow_requestbase wr " +
"where b.requestId =wr.REQUESTID and b.id=a.mainid and a.resourceId=" + resourceId + " and wr.CURRENTNODETYPE >0 and " +
" ((CONCAT(fromDate ,' ',fromTime) < '" + st + "' and '" + st + "' < CONCAT(toDate ,' ',toTime) ) or (CONCAT(fromDate ,' ',fromTime) < '" + ed + "' and '"+ed+"' < CONCAT(toDate ,' ',toTime)) or (CONCAT(fromDate ,' ',fromTime) > '" + st + "' and '"+ed+"' > CONCAT(toDate ,' ',toTime)))" +
" " +
" ");
rs.next();
String reqid = rs.getString("requestid");
_tmpRq = Util.getIntValue(reqid);
msg = Util.null2String(rs.getString("requestname"));
if(StringUtils.isNotBlank(reqid)){
boolean checkBack = checkLeaveBack(reqid,st,ed);
if(!checkBack){
_tmpRq = 0;
}
}
}else if("50".equals(workflowId)){
rs.execute("select wr.requestid,wr.requestname from formtable_main_74 b ,workflow_requestbase wr " +
"where b.requestId =wr.REQUESTID and b.resourceId=" + resourceId + " and wr.CURRENTNODETYPE >0 and " +
" ((CONCAT(fromDate ,' ',fromTime) < '" + st + "' and '" + st + "' < CONCAT(toDate ,' ',toTime) ) or (CONCAT(fromDate ,' ',fromTime) < '" + ed + "' and '"+ed+"' < CONCAT(toDate ,' ',toTime)) or (CONCAT(fromDate ,' ',fromTime) > '" + st + "' and '"+ed+"' > CONCAT(toDate ,' ',toTime)) )" +
" " +
" ");
bb.writeLog("select wr.requestid,wr.requestname from formtable_main_74 b ,workflow_requestbase wr " +
"where b.requestId =wr.REQUESTID and b.resourceId=" + resourceId + " and wr.CURRENTNODETYPE >0 and " +
" ((CONCAT(fromDate ,' ',fromTime) < '" + st + "' and '" + st + "' < CONCAT(toDate ,' ',toTime) ) or (CONCAT(fromDate ,' ',fromTime) < '" + ed + "' and '"+ed+"' < CONCAT(toDate ,' ',toTime)) or (CONCAT(fromDate ,' ',fromTime) > '" + st + "' and '"+ed+"' > CONCAT(toDate ,' ',toTime)) )" +
" " +
" ");
rs.next();
String reqid = rs.getString("requestid");
_tmpRq = Util.getIntValue(reqid);
msg = Util.null2String(rs.getString("requestname"));
if(StringUtils.isNotBlank(reqid)){
boolean checkBack = checkLeaveBack(reqid,st,ed);
if(!checkBack){
_tmpRq = 0;
}
}
}else if("75".equals(workflowId)) {
rs.execute("select wr.requestid,wr.requestname from formtable_main_76_dt1 a,formtable_main_76 b ,workflow_requestbase wr " +
"where b.requestId =wr.REQUESTID and b.id=a.mainid and a.jbry=" + resourceId + " and wr.CURRENTNODETYPE >0 and " +
" ((CONCAT(ksrq ,' ',kssj) < '" + st + "' and '" + st + "' < CONCAT(jsrq ,' ',jssj) ) or (CONCAT(ksrq ,' ',kssj) < '" + ed + "' and '"+ed+"' < CONCAT(jsrq ,' ',jssj)) or (CONCAT(ksrq ,' ',kssj) > '" + st + "' and '"+ed+"' > CONCAT(jsrq ,' ',jssj)))" +
" " +
" ");
bb.writeLog("select wr.requestid,wr.requestname from formtable_main_76_dt1 a,formtable_main_76 b ,workflow_requestbase wr " +
"where b.requestId =wr.REQUESTID and b.id=a.mainid and a.jbry=" + resourceId + " and wr.CURRENTNODETYPE >0 and " +
" ((CONCAT(ksrq ,' ',kssj) < '" + st + "' and '" + st + "' < CONCAT(jsrq ,' ',jssj) ) or (CONCAT(ksrq ,' ',kssj) < '" + ed + "' and '"+ed+"' < CONCAT(jsrq ,' ',jssj)) or (CONCAT(ksrq ,' ',kssj) > '" + st + "' and '"+ed+"' > CONCAT(jsrq ,' ',jssj)))" +
" " +
" ");
rs.next();
_tmpRq = Util.getIntValue(rs.getString("requestid"));
msg = Util.null2String(rs.getString("requestname"));
}else if("76".equals(workflowId)||"88".equals(workflowId)){
rs.execute("select wr.requestid,wr.requestname from formtable_main_75 b ,workflow_requestbase wr " +
"where b.requestId =wr.REQUESTID and b.resourceId=" + resourceId + " and wr.CURRENTNODETYPE >0 and " +
" ((CONCAT(fromDate ,' ',fromTime) < '" + st + "' and '" + st + "' < CONCAT(toDate ,' ',toTime) ) or (CONCAT(fromDate ,' ',fromTime) < '" + ed + "' and '"+ed+"' < CONCAT(toDate ,' ',toTime)) or (CONCAT(fromDate ,' ',fromTime) > '" + st + "' and '"+ed+"' > CONCAT(toDate ,' ',toTime)))" +
" " +
" ");
bb.writeLog("select wr.requestid,wr.requestname from formtable_main_75 b ,workflow_requestbase wr " +
"where b.requestId =wr.REQUESTID and b.resourceId=" + resourceId + " and wr.CURRENTNODETYPE >0 and " +
" ((CONCAT(fromDate ,' ',fromTime) < '" + st + "' and '" + st + "' < CONCAT(toDate ,' ',toTime) ) or (CONCAT(fromDate ,' ',fromTime) < '" + ed + "' and '"+ed+"' < CONCAT(toDate ,' ',toTime)) or (CONCAT(fromDate ,' ',fromTime) > '" + st + "' and '"+ed+"' > CONCAT(toDate ,' ',toTime)))" +
" " +
" ");
rs.next();
_tmpRq = Util.getIntValue(rs.getString("requestid"));
msg = Util.null2String(rs.getString("requestname"));
}else if("77".equals(workflowId)){
rs.execute("select wr.requestid,wr.requestname from formtable_main_77 b ,workflow_requestbase wr " +
"where b.requestId =wr.REQUESTID and b.resourceId=" + resourceId + " and wr.CURRENTNODETYPE >0 and " +
" ((CONCAT(fromDate ,' ',fromTime) < '" + st + "' and '" + st + "' < CONCAT(toDate ,' ',toTime) ) or (CONCAT(fromDate ,' ',fromTime) < '" + ed + "' and '"+ed+"' < CONCAT(toDate ,' ',toTime)) or (CONCAT(fromDate ,' ',fromTime) > '" + st + "' and '"+ed+"' > CONCAT(toDate ,' ',toTime)))" +
" " +
" ");
bb.writeLog("select wr.requestid,wr.requestname from formtable_main_77 b ,workflow_requestbase wr " +
"where b.requestId =wr.REQUESTID and b.resourceId=" + resourceId + " and wr.CURRENTNODETYPE >0 and " +
" ((CONCAT(fromDate ,' ',fromTime) < '" + st + "' and '" + st + "' < CONCAT(toDate ,' ',toTime) ) or (CONCAT(fromDate ,' ',fromTime) < '" + ed + "' and '"+ed+"' < CONCAT(toDate ,' ',toTime)) or (CONCAT(fromDate ,' ',fromTime) > '" + st + "' and '"+ed+"' > CONCAT(toDate ,' ',toTime)))" +
" " +
" ");
rs.next();
_tmpRq = Util.getIntValue(rs.getString("requestid"));
msg = Util.null2String(rs.getString("requestname"));
}else if("51".equals(workflowId)){
rs.execute("select wr.requestid,wr.requestname from formtable_main_77 b ,workflow_requestbase wr " +
"where b.requestId =wr.REQUESTID and b.resourceId=" + resourceId + " and wr.CURRENTNODETYPE >0 and " +
" ((CONCAT(fromDate ,' ',fromTime) < '" + st + "' and '" + st + "' < CONCAT(toDate ,' ',toTime) ) or (CONCAT(fromDate ,' ',fromTime) < '" + ed + "' and '"+ed+"' < CONCAT(toDate ,' ',toTime)) or (CONCAT(fromDate ,' ',fromTime) > '" + st + "' and '"+ed+"' > CONCAT(toDate ,' ',toTime)))" +
" " +
" ");
bb.writeLog("select wr.requestid,wr.requestname from formtable_main_77 b ,workflow_requestbase wr " +
"where b.requestId =wr.REQUESTID and b.resourceId=" + resourceId + " and wr.CURRENTNODETYPE >0 and " +
" ((CONCAT(fromDate ,' ',fromTime) < '" + st + "' and '" + st + "' < CONCAT(toDate ,' ',toTime) ) or (CONCAT(fromDate ,' ',fromTime) < '" + ed + "' and '"+ed+"' < CONCAT(toDate ,' ',toTime)) or (CONCAT(fromDate ,' ',fromTime) > '" + st + "' and '"+ed+"' > CONCAT(toDate ,' ',toTime)))" +
" " +
" ");
rs.next();
_tmpRq = Util.getIntValue(rs.getString("requestid"));
msg = Util.null2String(rs.getString("requestname"));
}else if("78".equals(workflowId)){
rs.execute("select wr.requestid,wr.requestname from formtable_main_78 b ,workflow_requestbase wr " +
"where b.requestId =wr.REQUESTID and b.resourceId=" + resourceId + " and wr.CURRENTNODETYPE >0 and " +
" ((CONCAT(fromDate ,' ',fromTime) < '" + st + "' and '" + st + "' < CONCAT(toDate ,' ',toTime) ) or (CONCAT(fromDate ,' ',fromTime) < '" + ed + "' and '"+ed+"' < CONCAT(toDate ,' ',toTime)) or (CONCAT(fromDate ,' ',fromTime) > '" + st + "' and '"+ed+"' > CONCAT(toDate ,' ',toTime)))" +
" " +
" ");
bb.writeLog("select wr.requestid,wr.requestname from formtable_main_78 b ,workflow_requestbase wr " +
"where b.requestId =wr.REQUESTID and b.resourceId=" + resourceId + " and wr.CURRENTNODETYPE >0 and " +
" ((CONCAT(fromDate ,' ',fromTime) < '" + st + "' and '" + st + "' < CONCAT(toDate ,' ',toTime) ) or (CONCAT(fromDate ,' ',fromTime) < '" + ed + "' and '"+ed+"' < CONCAT(toDate ,' ',toTime)) or (CONCAT(fromDate ,' ',fromTime) > '" + st + "' and '"+ed+"' > CONCAT(toDate ,' ',toTime)))" +
" " +
" ");
rs.next();
_tmpRq = Util.getIntValue(rs.getString("requestid"));
msg = Util.null2String(rs.getString("requestname"));
}else if("55".equals(workflowId)){
rs.execute("select wr.requestid,wr.requestname from formtable_main_78 b ,workflow_requestbase wr " +
"where b.requestId =wr.REQUESTID and b.resourceId=" + resourceId + " and wr.CURRENTNODETYPE >0 and " +
" ((CONCAT(fromDate ,' ',fromTime) < '" + st + "' and '" + st + "' < CONCAT(toDate ,' ',toTime) ) or (CONCAT(fromDate ,' ',fromTime) < '" + ed + "' and '"+ed+"' < CONCAT(toDate ,' ',toTime)) or (CONCAT(fromDate ,' ',fromTime) > '" + st + "' and '"+ed+"' > CONCAT(toDate ,' ',toTime)))" +
" " +
" ");
bb.writeLog("select wr.requestid,wr.requestname from formtable_main_78 b ,workflow_requestbase wr " +
"where b.requestId =wr.REQUESTID and b.resourceId=" + resourceId + " and wr.CURRENTNODETYPE >0 and " +
" ((CONCAT(fromDate ,' ',fromTime) < '" + st + "' and '" + st + "' < CONCAT(toDate ,' ',toTime) ) or (CONCAT(fromDate ,' ',fromTime) < '" + ed + "' and '"+ed+"' < CONCAT(toDate ,' ',toTime)) or (CONCAT(fromDate ,' ',fromTime) > '" + st + "' and '"+ed+"' > CONCAT(toDate ,' ',toTime)))" +
" " +
" ");
rs.next();
_tmpRq = Util.getIntValue(rs.getString("requestid"));
msg = Util.null2String(rs.getString("requestname"));
}else if("80".equals(workflowId)){
rs.execute("select wr.requestid,wr.requestname from formtable_main_80 b ,workflow_requestbase wr " +
"where b.requestId =wr.REQUESTID and b.resourceId=" + resourceId + " and wr.CURRENTNODETYPE >0 and " +
" ((CONCAT(fromDate ,' ',fromTime) < '" + st + "' and '" + st + "' < CONCAT(toDate ,' ',toTime) ) or (CONCAT(fromDate ,' ',fromTime) < '" + ed + "' and '"+ed+"' < CONCAT(toDate ,' ',toTime)) or (CONCAT(fromDate ,' ',fromTime) > '" + st + "' and '"+ed+"' > CONCAT(toDate ,' ',toTime)))" +
" " +
" ");
bb.writeLog("select wr.requestid,wr.requestname from formtable_main_80 b ,workflow_requestbase wr " +
"where b.requestId =wr.REQUESTID and b.resourceId=" + resourceId + " and wr.CURRENTNODETYPE >0 and " +
" ((CONCAT(fromDate ,' ',fromTime) < '" + st + "' and '" + st + "' < CONCAT(toDate ,' ',toTime) ) or (CONCAT(fromDate ,' ',fromTime) < '" + ed + "' and '"+ed+"' < CONCAT(toDate ,' ',toTime)) or (CONCAT(fromDate ,' ',fromTime) > '" + st + "' and '"+ed+"' > CONCAT(toDate ,' ',toTime)))" +
" " +
" ");
rs.next();
_tmpRq = Util.getIntValue(rs.getString("requestid"));
msg = Util.null2String(rs.getString("requestname"));
}else if("52".equals(workflowId)){
rs.execute("select wr.requestid,wr.requestname from formtable_main_80 b ,workflow_requestbase wr " +
"where b.requestId =wr.REQUESTID and b.resourceId=" + resourceId + " and wr.CURRENTNODETYPE >0 and " +
" ((CONCAT(fromDate ,' ',fromTime) < '" + st + "' and '" + st + "' < CONCAT(toDate ,' ',toTime) ) or (CONCAT(fromDate ,' ',fromTime) < '" + ed + "' and '"+ed+"' < CONCAT(toDate ,' ',toTime)) or (CONCAT(fromDate ,' ',fromTime) > '" + st + "' and '"+ed+"' > CONCAT(toDate ,' ',toTime)))" +
" " +
" ");
bb.writeLog("select wr.requestid,wr.requestname from formtable_main_80 b ,workflow_requestbase wr " +
"where b.requestId =wr.REQUESTID and b.resourceId=" + resourceId + " and wr.CURRENTNODETYPE >0 and " +
" ((CONCAT(fromDate ,' ',fromTime) < '" + st + "' and '" + st + "' < CONCAT(toDate ,' ',toTime) ) or (CONCAT(fromDate ,' ',fromTime) < '" + ed + "' and '"+ed+"' < CONCAT(toDate ,' ',toTime)) or (CONCAT(fromDate ,' ',fromTime) > '" + st + "' and '"+ed+"' > CONCAT(toDate ,' ',toTime)))" +
" " +
" ");
rs.next();
_tmpRq = Util.getIntValue(rs.getString("requestid"));
msg = Util.null2String(rs.getString("requestname"));
}
if (_tmpRq > 0) {
apimap.put("status",1);
apimap.put("hsmsg","时间与流程"+msg+"存在重复,请重新提交!");
}else{
apimap.put("status",0);
apimap.put("hsmsg","");
}
}catch (Exception e){
apimap.put("status",1);
apimap.put("hsmsg",e.toString());
}
return apimap;
}
/**
*
* @param requestId
* @return
*/
public static Boolean checkLeaveBack(String requestId,String startDate,String endDate){
RecordSet rs = new RecordSet();
Boolean back = false;
String sql = "select workflowid from kq_flow_split_leave where leavebackrequestid is null and belongdate >= '"+startDate+"' and belongdate <= '"+endDate+"' and requestid = "+requestId;
rs.executeQuery(sql);
if(rs.getCounts()>0){
//该请假流程存在未退假的日期
back = true;
}
return back;
}
}

@ -0,0 +1,19 @@
package com.engine.hsCheck.service;
import java.util.Map;
/**
* TODO
*
* @Description
* @Author matrix
* @Date 2023/9/12 23:57
**/
public interface CheckService {
Map<String,Object> check(Map<String, Object> paramMap);
Map<String,Object> kqFormatByMode(Map<String, Object> paramMap);
}

@ -0,0 +1,578 @@
package com.engine.hsCheck.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.common.util.ServiceUtil;
import com.engine.core.impl.Service;
import com.engine.hsCheck.cmd.CheckCmd;
import com.engine.hsCheck.service.CheckService;
import com.engine.kq.biz.KQReportBiz;
import com.engine.kq.service.KQReportService;
import com.engine.kq.service.impl.KQReportServiceImpl;
import org.apache.commons.lang3.StringUtils;
import weaver.common.DateUtil;
import weaver.conn.BatchRecordSet;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.systeminfo.SystemEnv;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* TODO
*
* @Description
* @Author matrix
* @Date 2023/9/12 23:57
**/
public class CheckServiceImpl extends Service implements CheckService {
static String dateFormat = "yyyy-MM-dd";
static SimpleDateFormat format = new SimpleDateFormat(dateFormat);
@Override
public Map<String, Object> check(Map<String, Object> params) {
return commandExecutor.execute(new CheckCmd(params));
}
private KQReportService getService(User user) {
return (KQReportService) ServiceUtil.getService(KQReportServiceImpl.class, user);
}
/**
*
* @param params
* @return
*/
@Override
public Map<String, Object> kqFormatByMode(Map<String, Object> params) {
Map<String,Object> resutl = new HashMap<String,Object>();
BaseBean bb = new BaseBean();
bb.writeLog("kqFormatByMode ==>");
try{
String userId = Util.null2String(params.get("userId"));
String deptId = Util.null2String(params.get("deptId"));
String fromDateOri = Util.null2String(params.get("fromDate"));
String toDateOri = Util.null2String(params.get("toDate"));
Map<String, Object> paramsMain = new HashMap<String, Object>();
Map<String, Object> paramsNew = new HashMap<String, Object>();
paramsNew.put("pageIndex",0);
paramsNew.put("typeselect","3");
paramsNew.put("viewScope","2");
if(StringUtils.isNotBlank(userId)){
paramsNew.put("resourceId",userId);
}
if(StringUtils.isNotBlank(deptId)){
paramsNew.put("departmentId",deptId);
}
if(StringUtils.isNotBlank(fromDateOri)){
paramsNew.put("fromDate",fromDateOri);
}
if(StringUtils.isNotBlank(toDateOri)){
paramsNew.put("toDate",toDateOri);
}
paramsNew.put("status","9");
paramsNew.put("isNoAccount","1");
paramsNew.put("attendanceSerial","");
User userLcc = new User(1);
paramsMain.put("data",JSONObject.toJSONString(paramsNew));
Map<String, Object> apidatasF = new HashMap<String, Object>();
apidatasF = getService(userLcc).formatReport(paramsMain, userLcc);
bb.writeLog("apidatasF:"+JSONObject.toJSONString(apidatasF));
//格式化结束重新获取考勤汇总表数据
String fromDate = fromDateOri.substring(0,7)+"-01";
String toDateRl = fromDateOri.substring(0,7)+"-31";
String toDateSet = fromDateOri.substring(0,7);
String toDate = getLastDayOfMonth(toDateSet);
Map<String, Object> apidatas = new HashMap<String, Object>();
Map<String, Object> paramsN = new HashMap<String, Object>();
paramsN.put("reportType","month");
Map<String, Object> paramsData = new HashMap<String, Object>();
paramsData.put("pageIndex",0);
paramsData.put("typeselect","6");
paramsData.put("viewScope","0");
paramsData.put("status","9");
paramsData.put("isNoAccount","1");
paramsData.put("attendanceSerial","");
if(StringUtils.isNotBlank(userId)){
paramsData.put("resourceId",userId);
}
if(StringUtils.isNotBlank(deptId)){
paramsData.put("departmentId",deptId);
}
paramsData.put("fromDate",fromDate);
paramsData.put("toDate",toDate);
paramsN.put("data",JSONObject.toJSONString(paramsData));
apidatas = getService(userLcc).getKQReport(paramsN, userLcc);
// bb.writeLog("apidatas:"+JSONObject.toJSONString(apidatas));
JSONArray jsonArray = JSON.parseArray(Util.null2String(JSONObject.toJSONString(apidatas.get("datas"))));
bb.writeLog("jsonArray:"+JSONObject.toJSONString(jsonArray));
for (Iterator<Object> iterator = jsonArray.iterator(); iterator.hasNext(); ) {
List<List<Object>> lsParams = new ArrayList<>();
List<List<Object>> lsDelParams = new ArrayList<>();
JSONObject next = (JSONObject) iterator.next();
//人员id
String resourceId = next.getString("resourceId");
//编号
String workcode = next.getString("workcode");
//岗位
String jobtitleId = next.getString("jobtitleId");
//部门编码
String deptcode = next.getString("deptcode");
//上级部门
String supdept = next.getString("supdept");
//部门
String departmentId = next.getString("departmentId");
//新增属性
String ofr08name = next.getString("ofr08name");
//直\间接
String ofr07name = next.getString("ofr07name");
//应出勤天数
String workdays = next.getString("workdays");
//应工作时长
String workmins = next.getString("workmins");
//实际出勤天数
String attendancedays = next.getString("attendancedays");
//实际工作时长
String attendanceMins = next.getString("attendanceMins");
//迟到次数
String beLate = next.getString("beLate");
//迟到时长
String beLateMins = next.getString("beLateMins");
//严重迟到
String graveBeLate = next.getString("graveBeLate");
//严重迟到时长
String graveBeLateMins = next.getString("graveBeLateMins");
//早退
String leaveEearly = next.getString("leaveEearly");
//早退时长
String leaveEarlyMins = next.getString("leaveEarlyMins");
//严重早退
String graveLeaveEarly = next.getString("graveLeaveEarly");
//严重早退时长
String graveLeaveEarlyMins = next.getString("graveLeaveEarlyMins");
//缺勤
String absenteeism = next.getString("absenteeism");
//缺勤时长
String absenteeismMins = next.getString("absenteeismMins");
//漏签
String forgotCheck = next.getString("forgotCheck");
//午餐次数
String wucancishu = next.getString("wucancishu");
//晚餐次数
String jiabancishu = next.getString("jiabancishu");
//午餐次数含夜班
String jiabancishuYb = next.getString("jiabancishuYb");
//晚餐次数含夜班
String wucancishuYb = next.getString("wucancishuYb");
//夜班次数
String ybcs = next.getString("ybcs");
//法定年假
String fdnj = next.getString("leaveType_-6");
//带薪病假
String dxbj = next.getString("leaveType_4");
//调休平时加班
String txpsjb = next.getString("leaveType_5");
//产假
String cj = next.getString("leaveType_8");
//陪产假
String pcj = next.getString("leaveType_9");
//福利年假
String flnj = next.getString("leaveType_13");
//小产假
String xcj = next.getString("leaveType_14");
//产检假
String cjj = next.getString("leaveType_15");
//调休周末加班
String txzmjb = next.getString("leaveType_16");
//产假刨妇产顺延
String cjpfc = next.getString("leaveType_17");
//产假多胞胎顺延
String cjdbtsy = next.getString("leaveType_18");
//三八节福利假
String sbjflj = next.getString("leaveType_19");
//特殊公出
String tsgc = next.getString("leaveType_20");
//放工假
String fgj = next.getString("leaveType_21");
//工伤假
String gsj = next.getString("leaveType_22");
//事假
String sj = next.getString("leaveType_26");
//病假
String bj = next.getString("leaveType_27");
//婚假
String hj = next.getString("leaveType_32");
//哺乳假
String brj = next.getString("leaveType_34");
//丧假
String sangj = next.getString("leaveType_35");
//育儿假
String yrj = next.getString("leaveType_36");
//独生子女护理假
String dsznhlj = next.getString("leaveType_37");
//工作日加班不关联调休
String gzrjbno = next.getString("workingDayOvertime_nonleave");
//工作日加班关联调休
String gzrjb = next.getString("workingDayOvertime_4leave");
//休息日加班不关联调休
String xxrjbno = next.getString("restDayOvertime_nonleave");
//休息日加班关联调休
String xxrjb = next.getString("restDayOvertime_4leave");
//节假日加班不关联调休
String jjrjbno = next.getString("holidayOvertime_nonleave");
//节假日加班关联调休
String jjrjb = next.getString("holidayOvertime_4leave");
//加班汇总
String jbhz = next.getString("overtimeTotal");
//出差
String cc = next.getString("businessLeave");
//公出
String gc = next.getString("officialBusiness");
bb.writeLog("userId:"+resourceId+"workdays:"+workdays);
KQReportBiz kqReportBiz = new KQReportBiz();
Map<String, Object> detialDatas = kqReportBiz.getDetialDatasOnlyTime(resourceId, fromDate, toDateRl, userLcc);
Map<String, Object> detialOvtimeDatas = kqReportBiz.getDetialOvtimeData(resourceId, fromDate, toDateRl);
List<Object> data = new ArrayList<>();
String today = DateUtil.getCurrentDate();
bb.writeLog("detialDatas:"+JSONObject.toJSONString(detialDatas)+"detialOvtimeDatas:"+JSONObject.toJSONString(detialOvtimeDatas));
List<String> all = new ArrayList<>();
all.add(fromDate);
List<String> back = days(fromDate,toDateRl);
all.addAll(back);
all.add(toDateRl);
for(String date:all){
if (DateUtil.compDate(today, date) > 0) {
data.add("");
} else {
if (detialDatas.get(resourceId + "|" + date) != null) {
double atttime = Util.getDoubleValue((String) detialDatas.get(resourceId + "|" + date),0);
bb.writeLog("date:"+date+"atttime:"+atttime);
if(detialOvtimeDatas.get(resourceId + "|" + date) !=null ){
atttime += (double) detialOvtimeDatas.get(resourceId + "|" + date);
bb.writeLog("atttimeNew:"+atttime);
}
data.add(atttime);
} else {
data.add(SystemEnv.getHtmlLabelName(26593, userLcc.getLanguage()));
}
}
}
bb.writeLog("dataText:"+JSONObject.toJSONString(data));
List<Object> par = new ArrayList<>();
List<Object> parDel = new ArrayList<>();
par.add(resourceId);
par.add(workcode);
par.add(jobtitleId);
par.add(deptcode);
par.add(supdept);
par.add(departmentId);
par.add(ofr08name);
par.add(ofr07name);
par.add(workdays);
par.add(workmins);
par.add(attendancedays);
par.add(attendanceMins);
par.add(beLate);
par.add(beLateMins);
par.add(graveBeLate);
par.add(graveBeLateMins);
par.add(leaveEearly);
par.add(leaveEarlyMins);
par.add(graveLeaveEarly);
par.add(graveLeaveEarlyMins);
par.add(absenteeism);
par.add(absenteeismMins);
par.add(forgotCheck);
par.add(wucancishu);
par.add(jiabancishu);
par.add(jiabancishuYb);
par.add(wucancishuYb);
par.add(ybcs);
par.add(fdnj);
par.add(dxbj);
par.add(txpsjb);
par.add(cj);
par.add(pcj);
par.add(flnj);
par.add(xcj);
par.add(cjj);
par.add(txzmjb);
par.add(cjpfc);
par.add(cjdbtsy);
par.add(sbjflj);
par.add(tsgc);
par.add(fgj);
par.add(gsj);
par.add(sj);
par.add(bj);
par.add(hj);
par.add(brj);
par.add(sangj);
par.add(yrj);
par.add(dsznhlj);
par.add(gzrjbno);
par.add(xxrjbno);
par.add(jjrjbno);
par.add(gzrjb);
par.add(xxrjb);
par.add(jjrjb);
par.add(jbhz);
par.add(cc);
par.add(gc);
//年月
String ny = fromDate.substring(0,7);
par.add(ny);
//入职日期
String rzrq = findRzrq(resourceId);
//转正日期
String zzrq = getField18(resourceId);
//离职日期
String lzrq = getField82(resourceId);
par.add(rzrq);
par.add(zzrq);
par.add(lzrq);
//人员状态
String ryzt = getStatus(resourceId);
par.add(ryzt);
//考勤月
String kqy = ny+"-01";
par.add(kqy);
//日历
for (int i = 0; i < all.size(); i++) {
par.add(data.get(i));
}
parDel.add(resourceId);
parDel.add(ny);
lsDelParams.add(parDel);
BatchRecordSet bRs = new BatchRecordSet();
bb.writeLog("开始同步数据");
bb.writeLog("lsDelParams:"+JSON.toJSONString(lsDelParams));
String sql = "";
//删除本次同步数据
sql = " delete from uf_kqhzbx where xm = ? and ny = ?";
bRs.executeBatchSql(sql, lsDelParams);
int modeid = getFormModeIdByCubeName("uf_kqhzbx");
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdfTime = new SimpleDateFormat("HH:mm:ss");
String modedatacreatedate = sdfDate.format(new java.util.Date());
String modedatacreatetime = sdfTime.format(new Date());
par.add(modeid);
par.add(resourceId);
par.add("0");
par.add(modedatacreatedate);
par.add(modedatacreatetime);
lsParams.add(par);
sql = " insert into uf_kqhzbx (xm, bh, gw, bmbm, sjbm, bm, xzzx, zjj, ycqtst, ygzscxs, " +
"sjcqtst,sjgzscxs,cdc,cdscxs,yzcdc,yzcdscxs,ztc,ztscxs,yzztc,yzztscxs," +
"qqc,qqscxs,lqc,wuccsc,wanccsc,wuccshybc,wanccshybc,ybcsc,fdnjxs,flnjxs," +
"sjxs,dxbjt,bjt,hjt,sjt,xcjt,cjjt,pcjt,dxpsjbxs,dxzmjbxs," +
"brjxs,cjt,cjpfcsyt,cjdbtsyt,sbjfljt,tsgct,fgjxs,gsjt,yejt,dsznhljt," +
"bgldxgzrjbxs,bgldxxxrjbxs,bgldxjjrjbxs,gldxgzrjbxs,gldxxxrjbxs,gldxjjrjbxs,jbzjxs,cct,gcxs," +
"ny,rzrq,zzrq,lzrq,ryzt,kqy,h1,h2,h3,h4,h5,h6," +
"h7,h8,h9,h10,h11,h12,h13,h14,h15,h16," +
"h17,h18,h19,h20,h21,h22,h23,h24,h25,h26," +
"h27,h28,h29,h30,h31,FORMMODEID,MODEDATACREATER,MODEDATACREATERTYPE,MODEDATACREATEDATE,MODEDATACREATETIME) "
+ " values(?,?,?,?,?,?,?,?,?,?," +
"?,?,?,?,?,?,?,?,?,?," +
"?,?,?,?,?,?,?,?,?,?," +
"?,?,?,?,?,?,?,?,?,?," +
"?,?,?,?,?,?,?,?,?,?," +
"?,?,?,?,?,?,?,?,?," +
"?,?,?,?,?,?,?,?,?,?,?,?," +
"?,?,?,?,?,?,?,?,?,?," +
"?,?,?,?,?,?,?,?,?,?," +
"?,?,?,?,?,?,?,?,?,?)";
bRs.executeBatchSql(sql,lsParams);
String idNew = "";
RecordSet findNew = new RecordSet();
String sqlFindnew ="select Id from uf_kqhzbx where xm = "+resourceId+" and ny = '"+ny+"' order by" +
" modedatacreatedate desc,modedatacreatetime desc";
findNew.execute(sqlFindnew);
bb.writeLog("findSqlNew:"+sqlFindnew);
if (findNew.next()){
idNew = weaver.general.Util.null2String(findNew.getString("id"));
}
bb.writeLog("idNew:"+idNew);
// 权限重构
int dataId = Integer.valueOf(idNew);
ModeRightInfo modeRightInfo = new ModeRightInfo();
modeRightInfo.editModeDataShare(Integer.valueOf(resourceId), modeid, dataId);
}
resutl.put("code","200");
resutl.put("msg","格式化成功");
}catch (Exception e) {
bb.writeLog("kqFormatByMode Exception: "+e);
resutl.put("code","500");
resutl.put("msg","接口异常:"+e.getMessage());
return resutl;
}
return resutl;
}
/**
*
* @param userid
* @return
*/
private static String getStatus(String userid){
RecordSet rs = new RecordSet();
String sql = "select status from hrmresource where id = "+userid;
rs.executeQuery(sql);
String status = "";
if (rs.next()){
status = Util.null2String(rs.getString("status"));
}
return status;
}
/**
* formModeId
*
* @param cubeName
* @return int formModeId
*/
private static int getFormModeIdByCubeName(String cubeName) {
RecordSet rs = new RecordSet();
rs.executeQuery("select t1.id from modeinfo t1\n" +
" left join workflow_bill t2\n" +
" on t1.formid=t2.id\n" +
" where t2.tablename='" + cubeName + "'");
rs.next();
return rs.getInt("id");
}
/**
*
*
* @return
*/
public static String findRzrq(String jbr) {
RecordSet rs = new RecordSet();
String sql = "select id,companystartdate from hrmresource where id ="+jbr;
rs.executeQuery(sql);
String companystartdate = "";
if (rs.next()) {
companystartdate = Util.null2String(rs.getString("companystartdate"));
}
return companystartdate;
}
/**
*
* @param userid
* @return
*/
private static String getField18(String userid){
RecordSet rs = new RecordSet();
String sql = "select field18 from cus_fielddata where id = "+userid+" and scope = 'HrmCustomFieldByInfoType' and scopeid = 3";
rs.executeQuery(sql);
String field18 = "";
if (rs.next()){
field18 = Util.null2String(rs.getString("field18"));
}
return field18;
}
/**
*
* @param userid
* @return
*/
private static String getField82(String userid){
RecordSet rs = new RecordSet();
String sql = "select field82 from cus_fielddata where id = "+userid+" and scope = 'HrmCustomFieldByInfoType' and scopeid = 3";
rs.executeQuery(sql);
String field82 = "";
if (rs.next()){
field82 = Util.null2String(rs.getString("field82"));
}
return field82;
}
/**
*
* @param date1
* @param date2
* @return
*/
public static ArrayList days(String date1, String date2) {
ArrayList L = new ArrayList();
if (date1.equals(date2)) {
System.out.println("两个日期相等!");
return L;
}
String tmp;
if (date1.compareTo(date2) > 0) { // 确保 date1的日期不晚于date2
tmp = date1;
date1 = date2;
date2 = tmp;
}
tmp = format.format(str2Date(date1).getTime() + 3600 * 24 * 1000);
int num = 0;
while (tmp.compareTo(date2) < 0) {
L.add(tmp);
num++;
tmp = format.format(str2Date(tmp).getTime() + 3600 * 24 * 1000);
}
if (num == 0)
System.out.println("两个日期相邻!");
return L;
}
private static Date str2Date(String str) {
if (str == null)
return null;
try {
return format.parse(str);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
/**
*
* @param yearMonth
* @return
*/
public static String getLastDayOfMonth(String yearMonth){
int year = Integer.parseInt(yearMonth.split("-")[0]);//年
int month = Integer.parseInt(yearMonth.split("-")[1]); //月
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month); //设置当前月的上一个月
int lastDay = cal.getMinimum(Calendar.DATE); //获取月份中的最小值,即第一天// 设置日历中月份的最大天数
cal.set(Calendar.DAY_OF_MONTH, lastDay-1); //上月的第一天减去1就是当月的最后一天// 格式化日期
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.format(cal.getTime());
}
}

@ -0,0 +1,101 @@
package com.engine.hsCheck.web;
import com.alibaba.fastjson.JSONObject;
import com.engine.common.util.ParamUtil;
import com.engine.common.util.ServiceUtil;
import com.engine.hsCheck.service.CheckService;
import com.engine.hsCheck.service.impl.CheckServiceImpl;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.HashMap;
import java.util.Map;
public class QkCheckAction {
public CheckService getService(){
return (CheckService) ServiceUtil.getService(CheckServiceImpl.class);
}
@POST
@Path("/check")
@Produces(MediaType.TEXT_PLAIN)
public String doGetPurchaseReq1(@Context HttpServletRequest request, @Context HttpServletResponse response){
Map<String, Object> apidatas = new HashMap<String, Object>();
BaseBean bb = new BaseBean();
try {
apidatas.putAll(getService().check(ParamUtil.request2Map(request)));
} catch (Exception e) {
e.printStackTrace();
// apidatas.put("api_status", false);
// apidatas.put("api_errormsg", "catch exception : " + e.getMessage());
}
return JSONObject.toJSONString(apidatas);
}
/**
*
* @param request
* @param response
* @return
*/
@GET
@Path("/kqFormatByMode")
@Produces({MediaType.TEXT_PLAIN})
public String kqFormatByMode(@Context HttpServletRequest request, @Context HttpServletResponse response) {
Map<String, Object> apidatas = new HashMap<String, Object>();
try{
apidatas.putAll(getService().kqFormatByMode(ParamUtil.request2Map(request)));
}catch (Exception e) {
e.printStackTrace();
apidatas.put("code","500");
apidatas.put("msg","fail");
}
return JSONObject.toJSONString(apidatas);
}
/**
*
* @param request
* @param response
* @return
*/
@GET
@Path("/getPersonInfo")
@Produces({MediaType.TEXT_PLAIN})
public String getPersonInfo(@Context HttpServletRequest request, @Context HttpServletResponse response) {
Map<String, Object> apidatas = new HashMap<String, Object>();
try{
RecordSet rs = new RecordSet();
Map<String, Object> params = ParamUtil.request2Map(request);
String userid = Util.null2String(params.get("userid"));
String xb = "";
String zt = "";
String sql = "select sex,status from HrmResource where id = ?";
rs.executeQuery(sql,userid);
if(rs.next()){
xb = Util.null2String(rs.getString("sex"));
zt = Util.null2String(rs.getString("status"));
}
apidatas.put("code","200");
apidatas.put("xb",xb);
apidatas.put("zt",zt);
}catch (Exception e) {
e.printStackTrace();
apidatas.put("code","500");
apidatas.put("msg","fail");
}
return JSONObject.toJSONString(apidatas);
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

@ -0,0 +1,19 @@
package com.engine.kq.biz;
import com.engine.kq.log.KQLog;
import weaver.interfaces.schedule.BaseCronJob;
public class KQClearFormatPoolJob extends BaseCronJob {
private KQLog kqLog = new KQLog();
@Override
public void execute() {
kqLog.info("begin do KQClearFormatPoolJob invoke ...");
try {
KQFormatBiz kqFormatBiz = new KQFormatBiz();
kqFormatBiz.clearFormatPool();
kqLog.info("end do KQClearFormatPoolJob invoke ...");
} catch (Exception e) {
kqLog.info(e);
}
}
}

@ -0,0 +1,913 @@
package com.engine.kq.biz;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.engine.kq.biz.chain.duration.WorkDayUnitSplitChain;
import com.engine.kq.biz.chain.duration.WorkDurationChain;
import com.engine.kq.biz.chain.duration.WorkHalfUnitSplitChain;
import com.engine.kq.biz.chain.duration.WorkHourUnitSplitChain;
import com.engine.kq.biz.chain.duration.WorkWholeUnitSplitChain;
import com.engine.kq.biz.chain.shiftinfo.ShiftInfoBean;
import com.engine.kq.entity.TimeScopeEntity;
import com.engine.kq.entity.WorkTimeEntity;
import com.engine.kq.enums.DurationTypeEnum;
import com.engine.kq.enums.KqSplitFlowTypeEnum;
import com.engine.kq.log.KQLog;
import com.engine.kq.wfset.attendance.manager.HrmAttProcSetManager;
import com.engine.kq.wfset.bean.SplitBean;
import com.engine.kq.wfset.util.KQFlowCardUtil;
import com.engine.kq.wfset.util.KQFlowEvectionUtil;
import com.engine.kq.wfset.util.KQFlowLeaveBackUtil;
import com.engine.kq.wfset.util.KQFlowLeaveUtil;
import com.engine.kq.wfset.util.KQFlowOtherUtil;
import com.engine.kq.wfset.util.KQFlowOutUtil;
import com.engine.kq.wfset.util.KQFlowOvertimeUtil;
import com.engine.kq.wfset.util.KQFlowProcessChangeUtil;
import com.engine.kq.wfset.util.KQFlowShiftUtil;
import com.engine.kq.wfset.util.KQFlowUtil;
import com.engine.kq.wfset.util.SplitActionUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.resource.ResourceComInfo;
/**
* action
*/
public class KQFlowActiontBiz {
public KQLog kqLog = new KQLog();
/**
*
* @param requestId
*/
public void handleDel(int requestId) {
RecordSet rs = new RecordSet();
try {
String updateFreezeSql = "update KQ_ATT_VACATION set status=2 where requestId=? ";
boolean isUpdate = rs.executeUpdate(updateFreezeSql,requestId);
}catch (Exception e){
e.printStackTrace();
rs.writeLog("handleDrawBack:删除action报错:"+e.getMessage());
}
}
/**
*
* @param requestId
* @param workflowId
*/
public void handleDrawBack(int requestId, int workflowId) {
kqLog.writeLog("handleDrawBack:进入 强制收回:requestId:"+requestId+":workflowId:"+workflowId);
RecordSet rs = new RecordSet();
try {
String updateFreezeSql = "update KQ_ATT_VACATION set status=2 where requestId=? and workflowId = ? ";
boolean isUpdate = rs.executeUpdate(updateFreezeSql,requestId,workflowId);
kqLog.writeLog("handleDrawBack:强制收回isUpdate:"+isUpdate+":updateFreezeSql:"+updateFreezeSql+":requestId:"+requestId+":workflowId:"+workflowId);
}catch (Exception e){
e.printStackTrace();
kqLog.writeLog("handleDrawBack:强制收回action报错:"+e.getMessage());
}
}
/**
*
* @param requestId
* @param workflowId
*/
public void handleforceOver(int requestId, int workflowId) {
RecordSet rs = new RecordSet();
try {
if(!KQSettingsBiz.isforceflow_attend()){
return ;
}
String proc_set_sql = "select * from kq_att_proc_set where field001 = ? ";
rs.executeQuery(proc_set_sql, workflowId);
if(rs.next()) {
String proc_set_id = rs.getString("id");
//得到这个考勤流程设置是否使用明细
String usedetails = rs.getString("usedetail");
int kqtype = Util.getIntValue(rs.getString("field006"));
kqLog.info("handleforceOver:proc_set_id:"+proc_set_id+":kqtype:"+kqtype+":requestId:"+requestId);
Map<String, String> map = new HashMap<String, String>();
if(requestId > 0){
map.put("requestId", "and t.requestId = " + requestId);
}
Map<String,String> result = handleKQFlowAction(proc_set_id,usedetails,requestId,kqtype,workflowId,true,false,map);
if(!result.isEmpty()){
kqLog.info("handleforceOver:强制归档action失败:requestId"+requestId+":workflowId:"+workflowId+":proc_set_id:"+proc_set_id);
}
}
}catch (Exception e){
e.printStackTrace();
kqLog.info("handleforceOver:强制归档action报错:"+e.getMessage());
}
}
public Map<String,String> handleKQFlowAction(String proc_set_id, String usedetails, int requestId, int kqtype,
int workflowId,boolean isForce,boolean isUpgrade,Map<String, String> map) throws Exception{
Map<String,String> result = new HashMap<>();
ResourceComInfo rci = new ResourceComInfo();
List<SplitBean> splitBeans = new ArrayList<SplitBean>();
DateTimeFormatter datetimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
//生成处理的sql
Map<String, String> sqlMap = handleSql(proc_set_id, usedetails, requestId,kqtype,map);
if(sqlMap != null && !sqlMap.isEmpty()){
KqSplitFlowTypeEnum flowTypeEnum = null;
if(kqtype == KqSplitFlowTypeEnum.LEAVE.getFlowtype()){
KQFlowLeaveUtil kqFlowLeaveUtil = new KQFlowLeaveUtil();
result=kqFlowLeaveUtil.handleKQLeaveAction(sqlMap,splitBeans,datetimeFormatter,workflowId,requestId,rci);
flowTypeEnum = KqSplitFlowTypeEnum.LEAVE;
}else if(kqtype == KqSplitFlowTypeEnum.EVECTION.getFlowtype()){
KQFlowEvectionUtil kqFlowEvectionUtil = new KQFlowEvectionUtil();
result=kqFlowEvectionUtil.handleKQEvectionAction(sqlMap,splitBeans,datetimeFormatter,workflowId,requestId,rci);
flowTypeEnum = KqSplitFlowTypeEnum.EVECTION;
}else if(kqtype == KqSplitFlowTypeEnum.OUT.getFlowtype()){
KQFlowOutUtil kqFlowOutUtil = new KQFlowOutUtil();
result=kqFlowOutUtil.handleKQOutAction(sqlMap,splitBeans,datetimeFormatter,workflowId,requestId,rci);
flowTypeEnum = KqSplitFlowTypeEnum.OUT;
}else if(kqtype == KqSplitFlowTypeEnum.OVERTIME.getFlowtype()){
KQFlowOvertimeUtil kqFlowOvertimeUtil = new KQFlowOvertimeUtil();
result=kqFlowOvertimeUtil.handleKQOvertimeAction(sqlMap,splitBeans,datetimeFormatter,workflowId,requestId,rci,"");
flowTypeEnum = KqSplitFlowTypeEnum.OVERTIME;
}else if(kqtype == KqSplitFlowTypeEnum.SHIFT.getFlowtype()){
KQFlowShiftUtil kqFlowShiftUtil = new KQFlowShiftUtil();
kqFlowShiftUtil.handleKQShiftAction(sqlMap,splitBeans,datetimeFormatter,workflowId,requestId,rci);
flowTypeEnum = KqSplitFlowTypeEnum.SHIFT;
}else if(kqtype == KqSplitFlowTypeEnum.OTHER.getFlowtype()){
KQFlowOtherUtil kqFlowOtherUtil = new KQFlowOtherUtil();
result=kqFlowOtherUtil.handleKQOtherAction(sqlMap,splitBeans,datetimeFormatter,workflowId,requestId,rci);
flowTypeEnum = KqSplitFlowTypeEnum.OTHER;
}else if(kqtype == KqSplitFlowTypeEnum.CARD.getFlowtype()){
KQFlowCardUtil kqFlowCardUtil = new KQFlowCardUtil();
result=kqFlowCardUtil.handleKQCardAction(sqlMap,splitBeans,datetimeFormatter,workflowId,requestId,rci);
flowTypeEnum = KqSplitFlowTypeEnum.CARD;
}else if(kqtype == KqSplitFlowTypeEnum.LEAVEBACK.getFlowtype()){
KQFlowLeaveBackUtil kqFlowLeaveBackUtil = new KQFlowLeaveBackUtil();
result=kqFlowLeaveBackUtil.handleKQLeaveBackAction(sqlMap,splitBeans,datetimeFormatter,workflowId,requestId,rci);
flowTypeEnum = KqSplitFlowTypeEnum.LEAVEBACK;
}else if(kqtype == KqSplitFlowTypeEnum.PROCESSCHANGE.getFlowtype()){
KQFlowProcessChangeUtil kqFlowProcessChangeUtil = new KQFlowProcessChangeUtil();
result=kqFlowProcessChangeUtil.handleKQProcessChangeAction(sqlMap,splitBeans,datetimeFormatter,workflowId,requestId,rci);
flowTypeEnum = KqSplitFlowTypeEnum.PROCESSCHANGE;
}else{
new BaseBean().writeLog("考勤流程没有找到对应类型:proc_set_id:"+proc_set_id+":requestId:"+requestId+":kqtype:"+kqtype);
}
if(!result.isEmpty()){
if(!isUpgrade){
return result;
}
}
if(!splitBeans.isEmpty() && flowTypeEnum != null){
if(flowTypeEnum == KqSplitFlowTypeEnum.LEAVEBACK){
KQFlowLeaveBackUtil kqFlowLeaveBackUtil = new KQFlowLeaveBackUtil();
//销假流程需要再拆分下
kqFlowLeaveBackUtil.handleSplitFLowActionData4LeaveBack(splitBeans,result,isUpgrade,requestId);
clear_flow_deduct_card(splitBeans,KqSplitFlowTypeEnum.LEAVEBACK.getFlowtype()+"",requestId);
}else if(flowTypeEnum == KqSplitFlowTypeEnum.PROCESSCHANGE){
KQFlowProcessChangeUtil kqFlowProcessChangeUtil = new KQFlowProcessChangeUtil();
kqFlowProcessChangeUtil.handleSplitFLowActionData4ProcessChange(splitBeans,result,isUpgrade,requestId);
}else if(flowTypeEnum != KqSplitFlowTypeEnum.CARD && flowTypeEnum != KqSplitFlowTypeEnum.SHIFT){
KQFlowUtil kqFlowUtil = new KQFlowUtil();
kqFlowUtil.handleSplitFLowActionData(splitBeans,flowTypeEnum,rci,result,isForce,requestId,workflowId,isUpgrade);
//流程抵扣打卡
handle_flow_deduct_card(workflowId,splitBeans,requestId);
}
}
}
return result;
}
/**
*
* @param workflowId
* @param splitBeans
* @param requestId
*/
public void handle_flow_deduct_card(int workflowId,
List<SplitBean> splitBeans, int requestId) {
KQAttProcSetComInfo kqAttProcSetComInfo = new KQAttProcSetComInfo();
String flow_deduct_card = Util.null2String(kqAttProcSetComInfo.getFlow_deduct_card(""+workflowId));
String kqType = Util.null2String(kqAttProcSetComInfo.getkqType(""+workflowId));
kqLog.info("handle_flow_deduct_card:flow_deduct_card:"+ flow_deduct_card+":workflowId:"+workflowId+":requestId:"+requestId);
if("1".equalsIgnoreCase(flow_deduct_card)){
do_flow_deduct_card(splitBeans,kqType,requestId);
}else{
// 这里扩展个操作如果没有开启就先把对应的requestid删除掉
if(requestId > 0){
RecordSet rs = new RecordSet();
String sql1 = "select * from kq_flow_deduct_card where requestid = ? ";
rs.executeQuery(sql1,requestId);
List<String> formateList = new ArrayList<>();
while (rs.next()){
String resourceid = rs.getString("resourceid");
String belongdate = rs.getString("belongdate");
String key = resourceid+"_"+belongdate;
formateList.add(key);
}
String sql = "delete from kq_flow_deduct_card where requestid = ? ";
rs.executeUpdate(sql, requestId);
kqLog.info("clear_flow_deduct_card:formateList:"+formateList);
for(String format: formateList){
kqLog.info("clear_flow_deduct_card:format:"+ JSON.toJSONString(format));
String[] formats = format.split("_");
new KQFormatData().formatKqDate(formats[0],formats[1]);
}
}
}
}
/**
*
* @param splitBeans
* @param kqType
* @param requestId
*/
public void clear_flow_deduct_card(List<SplitBean> splitBeans, String kqType, int requestId) {
RecordSet rs = new RecordSet();
RecordSet rs1 = new RecordSet();
List<String> clear_ids = new ArrayList<>();
List<String> formateList = new ArrayList<>();
List updateParamList = new ArrayList();
List updateList = new ArrayList();
KQTimesArrayComInfo kqTimesArrayComInfo = new KQTimesArrayComInfo();
for(SplitBean bean : splitBeans){
String leavebackrequestid = bean.getLeavebackrequestid();
String resourceId = bean.getResourceId();
String belongDate = bean.getBelongDate();
String fromdate = bean.getFromDate();
String fromtime = bean.getFromTime();
String todate = bean.getToDate();
String totime = bean.getToTime();
String key = resourceId+"_"+belongDate;
formateList.add(key);
int fromtimeIdx = kqTimesArrayComInfo.getArrayindexByTimes(fromtime);
int totimeIdx = kqTimesArrayComInfo.getArrayindexByTimes(totime);
String deduct_sql = "select * from kq_flow_deduct_card where requestid = '"+leavebackrequestid+"' and resourceId='"+resourceId+"' and belongDate='"+belongDate+"'";
rs.executeQuery(deduct_sql);
while(rs.next()){
String deduct_id = rs.getString("id");
String signtype = rs.getString("signtype");
String deduct_fromtime = rs.getString("fromtime");
String deduct_totime = rs.getString("totime");
int deduct_fromtimeIdx = kqTimesArrayComInfo.getArrayindexByTimes(deduct_fromtime);
int deduct_totimeIdx = kqTimesArrayComInfo.getArrayindexByTimes(deduct_totime);
updateList = new ArrayList();
if("1".equalsIgnoreCase(signtype)){
if(fromtimeIdx == deduct_fromtimeIdx && !clear_ids.contains(deduct_id)){
clear_ids.add(deduct_id);
updateList.add(deduct_id);
updateParamList.add(updateList);
}
}else if("2".equalsIgnoreCase(signtype)){
if(totimeIdx == deduct_totimeIdx && !clear_ids.contains(deduct_id)){
clear_ids.add(deduct_id);
updateList.add(deduct_id);
updateParamList.add(updateList);
}
}
}
}
kqLog.info("clear_flow_deduct_card:clear_ids:"+ clear_ids.size());
// if(!clear_ids.isEmpty()){
// for(String id : clear_ids){
// String sql = "update kq_flow_deduct_card set isclear=1 where id = "+id;
// rs1.executeUpdate(sql);
// }
/*更新抵扣打卡数据 start*/
boolean isSuccess = true;
String updateSql = "update kq_flow_deduct_card set isclear=1 where id=?";
if (updateParamList.size() > 0) {
isSuccess = rs1.executeBatchSql(updateSql, updateParamList);
kqLog.info("clear_flow_deduct_card:formateList:"+formateList);
for(String format: formateList){
kqLog.info("clear_flow_deduct_card:format:"+ JSON.toJSONString(format));
String[] formats = format.split("_");
new KQFormatData().formatKqDate(formats[0],formats[1]);
}
}
/*更新抵扣打卡数据 end*/
// }
}
/**
*
* @param splitBeans
* @param kqType
* @param requestId
*/
public void do_flow_deduct_card(List<SplitBean> splitBeans, String kqType, int requestId) {
RecordSet rs = new RecordSet();
RecordSet rs1 = new RecordSet();
String batchSql = "insert into kq_flow_deduct_card(requestid,resourceid,belongDate,fromdate,fromtime,todate,totime,workBeginTime,workEndTime,signtype,flowtype,serialnumber)"+
" values(?,?,?,?,?,?,?,?,?,?,?,?) ";
List<List> params = new ArrayList<List>();
List<String> formateList = new ArrayList<>();
kqLog.info("handle_flow_deduct_card:splitBeans:"+ JSON.toJSONString(splitBeans));
for(SplitBean bean : splitBeans){
do_flow_deduct_in_table(bean,formateList,params,kqType,requestId, "");
if(Util.getIntValue(kqType) == KqSplitFlowTypeEnum.EVECTION.getFlowtype()){
String companion = Util.null2s(bean.getCompanion(), "");
if(companion.length() > 0){
String[] companions = companion.split(",");
if(companions != null && companions.length > 0 ) {
for (int i = 0; i < companions.length; i++) {
String compan_resid = companions[i];
if(bean.getResourceId().equalsIgnoreCase(compan_resid)){
//陪同人是自己的不要存到中间表里
continue;
}
do_flow_deduct_in_table(bean,formateList,params,kqType,requestId,compan_resid);
}
}
}
}
}
if(!params.isEmpty()) {
//先根据requestid删除中间表里的数据再做啥插入操作
String delSql = "delete from kq_flow_deduct_card where requestid = " + requestId;
rs.executeUpdate(delSql);
boolean isOk = rs1.executeBatchSql(batchSql, params);
if(!isOk){
kqLog.info("do_flow_deduct_card:requestId:"+requestId+":kq_flow_deduct_card error"+params);
return ;
}
kqLog.info("do_flow_deduct_card:formateList:"+formateList);
for(String format: formateList){
kqLog.info("do_flow_deduct_card:format:"+ JSON.toJSONString(format));
String[] formats = format.split("_");
new KQFormatData().formatKqDate(formats[0],formats[1]);
}
}else{
if(!splitBeans.isEmpty()){
//有流程数据,但是签到签退都不包含的情况,支持多次归档,所以需要先删除再插入
String delSql = "delete from kq_flow_deduct_card where requestid = " + requestId;
rs.executeUpdate(delSql);
}
}
}
/**
*
* @param bean
* @param formateList
* @param params
* @param kqType
* @param requestId
* @param compan_resid
*/
public void do_flow_deduct_in_table(SplitBean bean, List<String> formateList,
List<List> params, String kqType, int requestId, String compan_resid) {
KQWorkTime kqWorkTime = new KQWorkTime();
KQTimesArrayComInfo kqTimesArrayComInfo = new KQTimesArrayComInfo();
String resourceId = bean.getResourceId();
if(compan_resid.length() > 0 && Util.getIntValue(kqType) == KqSplitFlowTypeEnum.EVECTION.getFlowtype()){
resourceId = compan_resid;
}
String belongDate = bean.getBelongDate();
String fromdate = bean.getFromDate();
String fromtime = bean.getFromTime();
String todate = bean.getToDate();
String totime = bean.getToTime();
boolean oneSign = false;
WorkTimeEntity workTime = kqWorkTime.getWorkTime(resourceId, belongDate);
String key = resourceId+"_"+belongDate;
formateList.add(key);
List<TimeScopeEntity> lsWorkTime = new ArrayList<>();
List<TimeScopeEntity> lsSignTime = new ArrayList<>();
if (workTime != null) {
lsWorkTime = workTime.getWorkTime();//工作时间
lsSignTime = workTime.getSignTime();//允许打卡时间
oneSign = lsWorkTime!=null&&lsWorkTime.size()==1;
for (int i = 0; lsWorkTime != null && i < lsWorkTime.size(); i++) {
TimeScopeEntity workTimeScope = lsWorkTime.get(i);
String workBeginTime = Util.null2String(workTimeScope.getBeginTime());
int workBeginIdx = kqTimesArrayComInfo.getArrayindexByTimes(workBeginTime);
boolean workBenginTimeAcross = workTimeScope.getBeginTimeAcross();
String workEndTime = Util.null2String(workTimeScope.getEndTime());
int workEndIdx = kqTimesArrayComInfo.getArrayindexByTimes(workEndTime);
boolean workEndTimeAcross = workTimeScope.getEndTimeAcross();
int[] dayMins = new int[2880];//一天所有分钟数
int beginIdx = kqTimesArrayComInfo.getArrayindexByTimes(Util.null2String(fromtime));
int endIdx = kqTimesArrayComInfo.getArrayindexByTimes(Util.null2String(totime));
if(beginIdx > endIdx){
continue;
}
if(oneSign){
boolean is_flow_humanized = KQSettingsBiz.is_flow_humanized();
if(is_flow_humanized){
//个性化设置只支持一天一次上下班
ShiftInfoBean shiftInfoBean = new ShiftInfoBean();
Map<String, String> shifRuleMap = Maps.newHashMap();
shiftInfoBean.setSplitDate(belongDate);
shiftInfoBean.setShiftRuleMap(workTime.getShiftRuleInfo());
shiftInfoBean.setSignTime(lsSignTime);
shiftInfoBean.setWorkTime(lsWorkTime);
KQShiftRuleInfoBiz.getShiftRuleInfo(shiftInfoBean, resourceId, shifRuleMap);
if(!shifRuleMap.isEmpty()){
if(shifRuleMap.containsKey("shift_beginworktime")){
String shift_beginworktime = Util.null2String(shifRuleMap.get("shift_beginworktime"));
if(shift_beginworktime.length() > 0){
workBeginTime = Util.null2String(shift_beginworktime);
workBeginIdx = kqTimesArrayComInfo.getArrayindexByTimes(workBeginTime);
}
}
if(shifRuleMap.containsKey("shift_endworktime")){
String shift_endworktime = Util.null2String(shifRuleMap.get("shift_endworktime"));
if(shift_endworktime.length() > 0){
workEndTime = Util.null2String(shift_endworktime);
workEndIdx = kqTimesArrayComInfo.getArrayindexByTimes(workEndTime);
}
}
}
}
}
if(Util.getIntValue(kqType) == KqSplitFlowTypeEnum.EVECTION.getFlowtype()){
Arrays.fill(dayMins, beginIdx, endIdx, 7);//出差抵扣时段标识 7
}else if(Util.getIntValue(kqType) == KqSplitFlowTypeEnum.OUT.getFlowtype()){
Arrays.fill(dayMins, beginIdx, endIdx, 8);//公出抵扣时段标识 8
}else if(Util.getIntValue(kqType) == KqSplitFlowTypeEnum.LEAVE.getFlowtype()){
if (endIdx > beginIdx) {
Arrays.fill(dayMins, beginIdx, endIdx, 5);//流程抵扣时段标识 5
}
}else{
if (endIdx > beginIdx) {
Arrays.fill(dayMins, beginIdx, endIdx, 99);//异常流程抵扣时段标识99
}
}
int cnt_7 = kqTimesArrayComInfo.getCnt(dayMins, workBeginIdx, workEndIdx, 7);
int cnt_8 = kqTimesArrayComInfo.getCnt(dayMins, workBeginIdx, workEndIdx, 8);
int cnt_5 = kqTimesArrayComInfo.getCnt(dayMins, workBeginIdx, workEndIdx, 5);
int cnt_99 = kqTimesArrayComInfo.getCnt(dayMins, workBeginIdx, workEndIdx, 99);
//流程时长大于0的才去做流程抵扣的处理
if(cnt_7 > 0 || cnt_8 > 0 || cnt_5 > 0 || cnt_99 > 0){
//如果流程时长大于0 结束时间因为是下标需要补1分钟
if(Util.getIntValue(kqType) == KqSplitFlowTypeEnum.EVECTION.getFlowtype()){
Arrays.fill(dayMins, endIdx, endIdx+1, 7);//出差抵扣时段标识 7
}else if(Util.getIntValue(kqType) == KqSplitFlowTypeEnum.OUT.getFlowtype()){
Arrays.fill(dayMins, endIdx, endIdx+1, 8);//公出抵扣时段标识 8
}else if(Util.getIntValue(kqType) == KqSplitFlowTypeEnum.LEAVE.getFlowtype()){
Arrays.fill(dayMins, endIdx, endIdx+1, 5);//流程抵扣时段标识 5
}else{
Arrays.fill(dayMins, endIdx, endIdx+1, 99);//异常流程抵扣时段标识99
}
if(dayMins[workBeginIdx]>=5){//签到时间点有流程
List<Object> beanParams = new ArrayList<Object>();
beanParams.add(requestId);
beanParams.add(resourceId);
beanParams.add(belongDate);
beanParams.add(fromdate);
beanParams.add(fromtime);
beanParams.add(todate);
beanParams.add(totime);
beanParams.add(workBeginTime);
beanParams.add(workEndTime);
beanParams.add("1");
beanParams.add(kqType);
beanParams.add(i);
params.add(beanParams);
}
if(dayMins[workEndIdx]>=5){//签退时间点有流程
List<Object> beanParams = new ArrayList<Object>();
beanParams.add(requestId);
beanParams.add(resourceId);
beanParams.add(belongDate);
beanParams.add(fromdate);
beanParams.add(fromtime);
beanParams.add(todate);
beanParams.add(totime);
beanParams.add(workBeginTime);
beanParams.add(workEndTime);
beanParams.add("2");
beanParams.add(kqType);
beanParams.add(i);
params.add(beanParams);
}
}else{
kqLog.info("handle_flow_deduct_card::i:"+i+":workBeginIdx:"+ workBeginIdx+":workEndIdx:"+ workEndIdx
+":cnt_7:"+cnt_7+":cnt_8:"+cnt_8+":cnt_5:"+cnt_5+":cnt_99:"+cnt_99);
}
}
}else{
kqLog.info("handle_flow_deduct_card:workTime is null :resourceId:"+ resourceId+":belongDate:"+belongDate);
}
}
/**
* splitBeans
* @param sqlMap
* @param splitBeans
* @param datetimeFormatter
* @param workflowId
* @param requestId
* @param rci
* @param durationTypeEnum
* @return
* @throws Exception
*/
public Map<String,String> handleAction(Map<String, String> sqlMap,
List<SplitBean> splitBeans, DateTimeFormatter datetimeFormatter, int workflowId,
int requestId, ResourceComInfo rci,DurationTypeEnum durationTypeEnum) throws Exception{
RecordSet rs1 = new RecordSet();
KQFlowUtil kqFlowUtil = new KQFlowUtil();
Map<String,String> result = new HashMap<>();
if(!sqlMap.isEmpty()){
for(Map.Entry<String,String> me : sqlMap.entrySet()){
String key = me.getKey();
String value = me.getValue();
rs1.execute(value);
while (rs1.next()) {
SplitBean splitBean = new SplitBean();
boolean isFillRight = kqFlowUtil.fillSplitBean(splitBean, rs1, ""+requestId, rci, ""+workflowId, durationTypeEnum,key,result,datetimeFormatter,
"");
if(!isFillRight){
new BaseBean().writeLog("升级失败:"+requestId+";;result>>>"+JSONObject.toJSONString(result));
continue ;
}
if(result.containsKey("isProcessDrawBack")){
result.clear();
splitBeans.add(splitBean);
}else{
doWorkSplitChain(splitBean, splitBeans);
}
if(durationTypeEnum == DurationTypeEnum.EVECTION){
String companion = Util.null2s(splitBean.getCompanion(), "");
if(companion.length() > 0){
List<String> companionList = Util.splitString2List(companion,",");
for(int i = 0 ; i < companionList.size() ; i++){
String be_companion = Util.null2String(companionList.get(i));
if(be_companion.length() > 0 && Util.getIntValue(be_companion) > 0){
SplitBean compSplitBean = new SplitBean();
boolean compFillRight = kqFlowUtil.fillSplitBean(compSplitBean, rs1, ""+requestId,
rci, ""+workflowId, durationTypeEnum,key,result,datetimeFormatter, "");
if(!compFillRight){
return result;
}
if(splitBean.getResourceId().equalsIgnoreCase(be_companion)){
//陪同人是自己的不要存到中间表里
continue;
}
compSplitBean.setResourceId(be_companion);
compSplitBean.setSubcompanyid(Util.null2s(rci.getSubCompanyID(be_companion),"0"));
compSplitBean.setDepartmentid(Util.null2s(rci.getDepartmentID(be_companion),"0"));
compSplitBean.setJobtitle(Util.null2s(rci.getJobTitle(be_companion),"0"));
compSplitBean.setIscompanion("1");
compSplitBean.setCompanion("");
if(result.containsKey("isProcessDrawBack")){
result.clear();
splitBeans.add(compSplitBean);
}else{
doWorkSplitChain(compSplitBean, splitBeans);
}
}
}
}
}
}
}
}
return result;
}
/**
* sql
* @param proc_set_id
* @param usedetails
* @param requestidInt
* @return
*/
public Map<String,String> handleSql(String proc_set_id,String usedetails,int requestidInt,int kqtype,Map<String, String> map) {
HrmAttProcSetManager hrmAttProcSetManager= new HrmAttProcSetManager();
Map<String,String> sqlMap = new HashMap<>();
sqlMap = hrmAttProcSetManager.getSQLByField006Map(kqtype, map, false, true, proc_set_id,usedetails);
return sqlMap;
}
/**
*
* @param splitBean
* @param splitBeans
* @throws Exception
*/
public void doWorkSplitChain(SplitBean splitBean,List<SplitBean> splitBeans) throws Exception{
WorkDurationChain hourUnitSplitChain = new WorkHourUnitSplitChain(splitBeans);
WorkDurationChain dayUnitSplitChain = new WorkDayUnitSplitChain(splitBeans);
WorkDurationChain halfUnitSplitChain = new WorkHalfUnitSplitChain(splitBeans);
WorkDurationChain wholeUnitSplitChain = new WorkWholeUnitSplitChain(splitBeans);
//设置执行链
hourUnitSplitChain.setDurationChain(dayUnitSplitChain);
dayUnitSplitChain.setDurationChain(halfUnitSplitChain);
halfUnitSplitChain.setDurationChain(wholeUnitSplitChain);
//把初始数据设置进去
hourUnitSplitChain.handleDuration(splitBean);
}
/**
*
* 1
* 2
* 3
* @param temprequestid
* @param workflowid
*/
public void delTest(int temprequestid, String workflowid,String from) {
RecordSet rs = new RecordSet();
RecordSet rs1 = new RecordSet();
RecordSet rs2 = new RecordSet();
RecordSet rs3 = new RecordSet();
try {
kqLog.info("KQFlowActiontBiz delTest:workflowid:"+workflowid+":from:"+from);
if(Util.null2s(workflowid,"").length() == 0){
return ;
}
String getkqType = "select * from kq_att_proc_set where field001=? ";
rs.executeQuery(getkqType,workflowid);
if(rs.next()){
boolean isCard = false;
boolean isOvertime = false;
boolean isLeave = false;
String tablename = "";
int kqtype= Util.getIntValue(rs.getString("field006"),-1);
if(kqtype == KqSplitFlowTypeEnum.LEAVE.getFlowtype()){
tablename = KqSplitFlowTypeEnum.LEAVE.getTablename();
isLeave = true;
}else if(kqtype == KqSplitFlowTypeEnum.EVECTION.getFlowtype()){
tablename = KqSplitFlowTypeEnum.EVECTION.getTablename();
}else if(kqtype == KqSplitFlowTypeEnum.OUT.getFlowtype()){
tablename = KqSplitFlowTypeEnum.OUT.getTablename();
}else if(kqtype == KqSplitFlowTypeEnum.OVERTIME.getFlowtype()){
tablename = KqSplitFlowTypeEnum.OVERTIME.getTablename();
isOvertime = true;
}else if(kqtype == KqSplitFlowTypeEnum.SHIFT.getFlowtype()){
tablename = KqSplitFlowTypeEnum.SHIFT.getTablename();
}else if(kqtype == KqSplitFlowTypeEnum.OTHER.getFlowtype()){
tablename = KqSplitFlowTypeEnum.OTHER.getTablename();
}else if(kqtype == KqSplitFlowTypeEnum.CARD.getFlowtype()){
tablename = KqSplitFlowTypeEnum.CARD.getTablename();
isCard = true;
}else if(kqtype == KqSplitFlowTypeEnum.LEAVEBACK.getFlowtype()){
tablename = KqSplitFlowTypeEnum.LEAVEBACK.getTablename();
}else{
new BaseBean().writeLog("删除测试流程异常,未找到考勤流程类型:workflowid:"+workflowid);
}
if(tablename.length() > 0){
KQFormatBiz kqFormatBiz = new KQFormatBiz();
List<String> formateList = new ArrayList<>();
if(isCard){
String signfrom_param = "|requestid|"+temprequestid;
String selTableSql = "select * from hrmschedulesign where signfrom like ? ";
rs2.executeQuery(selTableSql,"%"+signfrom_param+"%");
while (rs2.next()){
String userid = rs2.getString("userid");
String signdate = rs2.getString("signdate");
String key = userid+"_"+signdate;
formateList.add(key);
}
kqLog.info("KQFlowActiontBiz isCard delTest:formateList:"+formateList);
String delTableSql = "delete from hrmschedulesign where signfrom like ? ";
boolean isUpdate = rs3.executeUpdate(delTableSql,"%"+signfrom_param+"%");
kqLog.info("KQFlowActiontBiz isCard delTest:delTableSql:"+delTableSql+":temprequestid:"+temprequestid+":isUpdate:"+isUpdate);
if(isUpdate){
for(String formateStr : formateList){
String[] formateStrs = formateStr.split("_");
new KQFormatData().formatKqDate(formateStrs[0],formateStrs[1]);
}
}
}else if(isOvertime){
SplitActionUtil.clearSameRequestTX(temprequestid+"");
String delTableSql = "delete from "+tablename+" where requestId= ? ";
boolean isUpdate = rs2.executeUpdate(delTableSql,temprequestid);
kqLog.info("KQFlowActiontBiz delTest:delTableSql:"+delTableSql+":temprequestid:"+temprequestid+":isUpdate:"+isUpdate);
}else{
List<SplitBean> backsplitBeans = new ArrayList<>();
String sql = "select * from "+tablename+" where requestId= ? ";
rs2.executeQuery(sql, temprequestid);
kqLog.info("KQFlowActiontBiz delTest:sql:"+sql+":requestId:"+temprequestid+":counts:"+rs2.getCounts());
while (rs2.next()){
String resourceid = rs2.getString("resourceid");
String belongdate = rs2.getString("belongdate");
String key = resourceid+"_"+belongdate;
formateList.add(key);
if(isLeave) {
SplitBean splitBean = new SplitBean();
String requestid = rs2.getString("requestid");
String newLeaveType = rs2.getString("newleavetype");
String duration = rs2.getString("duration");
String durationrule = rs2.getString("durationrule");
String fromdatedb = rs2.getString("fromdatedb");
splitBean.setRequestId(requestid);
splitBean.setResourceId(resourceid);
splitBean.setNewLeaveType(newLeaveType);
splitBean.setDuration(duration);
splitBean.setDurationrule(durationrule);
splitBean.setFromdatedb(fromdatedb);
backsplitBeans.add(splitBean);
}
}
kqLog.info("KQFlowActiontBiz delTest:isLeave:"+isLeave+":backsplitBeans:"+JSON.toJSONString(backsplitBeans));
String delTableSql = "delete from "+tablename+" where requestId= ? ";
boolean isUpdate = rs2.executeUpdate(delTableSql,temprequestid);
kqLog.info("KQFlowActiontBiz delTest:delTableSql:"+delTableSql+":temprequestid:"+temprequestid+":isUpdate:"+isUpdate);
//如果有流程抵扣,删除对应流程抵扣的数据
String delSql = "delete from kq_flow_deduct_card where requestid = ? ";
isUpdate = rs3.executeUpdate(delSql,temprequestid);
kqLog.info("KQFlowActiontBiz delTest:delSql:"+delSql+":temprequestid:"+temprequestid+":isUpdate:"+isUpdate);
kqLog.info("KQFlowActiontBiz delTest:formateList:"+formateList);
for(String formateStr : formateList){
String[] formateStrs = formateStr.split("_");
new KQFormatData().formatKqDate(formateStrs[0],formateStrs[1]);
}
if(isLeave) {
for (SplitBean splitBean : backsplitBeans) {
String requestid = splitBean.getRequestId();
String resourceId = splitBean.getResourceId();
String newLeaveType = splitBean.getNewLeaveType();
String duration = splitBean.getDuration();
String durationrule = splitBean.getDurationrule();
String fromdatedb = splitBean.getFromdatedb();
boolean isLeaveFlowOver = isLeaveFlowOver(requestid);
kqLog.info("isLeaveFlowOver:"+isLeaveFlowOver);
if (isLeaveFlowOver) {
kqLog.info("流程退回后主动返还假期:delTest:resourceId:" + resourceId + ":duration:" + duration + ":newLeaveType:" + newLeaveType + ":durationrule:" + durationrule + ":requestid:" + requestid + ":fromdatedb:" + fromdatedb);
KQBalanceOfLeaveBiz.reduceUsedAmount(resourceId, fromdatedb, newLeaveType, duration, "", requestid);
}
}
String updateFreezeSql = "update KQ_ATT_VACATION set status=2 where requestId=? ";
isUpdate = rs1.executeUpdate(updateFreezeSql,temprequestid);
kqLog.info("KQFlowActiontBiz delTest:updateFreezeSql:"+updateFreezeSql+":temprequestid:"+temprequestid+":isUpdate:"+isUpdate);
}
}
}
}
}catch (Exception e){
e.printStackTrace();
rs.writeLog("KQFlowActiontBiz delTest:temprequestid:"+temprequestid+":workflowid:"+workflowid+":报错:"+e.getMessage());
}
}
/**
*
* @param requestId
* @return
*/
private boolean isLeaveFlowOver(String requestId) {
RecordSet rs = new RecordSet();
String sql = "select * from kq_UsageHistory where wfRequestId=?";
rs.executeQuery(sql, requestId);
boolean isOver = false;
if(rs.next()) {
isOver = true;
}
return isOver;
}
/**
* splitBeans
* @param sqlMap
* @param splitBeans
* @param datetimeFormatter
* @param workflowId
* @param requestId
* @param rci
* @return
* @throws Exception
*/
public Map<String,String> handleKQLeaveAction(Map<String, String> sqlMap,
List<SplitBean> splitBeans, DateTimeFormatter datetimeFormatter, int workflowId,
int requestId, ResourceComInfo rci) throws Exception{
KQFlowLeaveUtil kqFlowLeaveUtil = new KQFlowLeaveUtil();
return kqFlowLeaveUtil.handleKQLeaveAction(sqlMap,splitBeans,datetimeFormatter,workflowId,requestId,rci);
}
/**
* splitBeans
* @param sqlMap
* @param splitBeans
* @param datetimeFormatter
* @param workflowId
* @param requestId
* @param rci
* @return
* @throws Exception
*/
public Map<String,String> handleKQEvectionAction(Map<String, String> sqlMap,
List<SplitBean> splitBeans, DateTimeFormatter datetimeFormatter, int workflowId,
int requestId, ResourceComInfo rci) throws Exception{
KQFlowEvectionUtil kqFlowEvectionUtil = new KQFlowEvectionUtil();
return kqFlowEvectionUtil.handleKQEvectionAction(sqlMap,splitBeans,datetimeFormatter,workflowId,requestId,rci);
}
/**
* splitBeans
* @param sqlMap
* @param splitBeans
* @param datetimeFormatter
* @param workflowId
* @param requestId
* @param rci
* @return
* @throws Exception
*/
public Map<String,String> handleKQOutAction(Map<String, String> sqlMap,
List<SplitBean> splitBeans, DateTimeFormatter datetimeFormatter, int workflowId,
int requestId, ResourceComInfo rci) throws Exception{
KQFlowOutUtil kqFlowOutUtil = new KQFlowOutUtil();
return kqFlowOutUtil.handleKQOutAction(sqlMap,splitBeans,datetimeFormatter,workflowId,requestId,rci);
}
/**
* splitBeans
* @param sqlMap
* @param splitBeans
* @param datetimeFormatter
* @param workflowId
* @param requestId
* @param rci
* @return
* @throws Exception
*/
public Map<String,String> handleKQOvertimeAction(Map<String, String> sqlMap,
List<SplitBean> splitBeans, DateTimeFormatter datetimeFormatter, int workflowId,
int requestId, ResourceComInfo rci) throws Exception{
KQFlowOvertimeUtil kqFlowOvertimeUtil = new KQFlowOvertimeUtil();
return kqFlowOvertimeUtil.handleKQOvertimeAction(sqlMap,splitBeans,datetimeFormatter,workflowId,requestId,rci,"");
}
/**
*
* @param sqlMap
* @param splitBeans
* @param datetimeFormatter
* @param workflowId
* @param requestId
* @param rci
* @return
* @throws Exception
*/
public void handleKQShiftAction(Map<String, String> sqlMap,
List<SplitBean> splitBeans, DateTimeFormatter datetimeFormatter, int workflowId,
int requestId, ResourceComInfo rci) throws Exception{
KQFlowShiftUtil kqFlowShiftUtil = new KQFlowShiftUtil();
kqFlowShiftUtil.handleKQShiftAction(sqlMap,splitBeans,datetimeFormatter,workflowId,requestId,rci);
}
/**
* 退
* @param sqlMap
* @param splitBeans
* @param datetimeFormatter
* @param workflowId
* @param requestId
* @param rci
* @return
* @throws Exception
*/
public Map<String,String> handleKQCardAction(Map<String, String> sqlMap,
List<SplitBean> splitBeans, DateTimeFormatter datetimeFormatter, int workflowId,
int requestId, ResourceComInfo rci) throws Exception{
KQFlowCardUtil kqFlowCardUtil = new KQFlowCardUtil();
return kqFlowCardUtil.handleKQCardAction(sqlMap,splitBeans,datetimeFormatter,workflowId,requestId,rci);
}
/**
* splitBeansbacksplitBeans
* @param sqlMap
* @param splitBeans
* @param datetimeFormatter
* @param workflowId
* @param requestId
* @param rci
* @return
* @throws Exception
*/
public Map<String,String> handleKQLeaveBackAction(Map<String, String> sqlMap,
List<SplitBean> splitBeans, DateTimeFormatter datetimeFormatter, int workflowId,
int requestId, ResourceComInfo rci) throws Exception{
KQFlowLeaveBackUtil kqFlowLeaveBackUtil = new KQFlowLeaveBackUtil();
return kqFlowLeaveBackUtil.handleKQLeaveBackAction(sqlMap,splitBeans,datetimeFormatter,workflowId,requestId,rci);
}
}

@ -0,0 +1,301 @@
package com.engine.kq.biz;
import com.alibaba.fastjson.JSON;
import com.engine.kq.entity.TimeScopeEntity;
import com.engine.kq.entity.WorkTimeEntity;
import com.engine.kq.log.KQLog;
import java.io.PrintWriter;
import java.io.StringWriter;
import weaver.common.DateUtil;
import weaver.conn.BatchRecordSet;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.systeminfo.SystemEnv;
import java.util.*;
/**
*
*/
public class KQFormatBiz extends BaseBean {
private String today = DateUtil.getCurrentDate();
protected KQLog kqLog = new KQLog();
/**
*
*
* @param lsFormatParams
*/
public void format(List<List<Object>> lsFormatParams) {
BatchRecordSet bRs = new BatchRecordSet();
String sql = "";
List<Object> params = null;
try {
if (KQSettingsBiz.getKqformatthread()) {
sql = " insert into kq_format_pool (resourceid, kqdate) values (?,?)";
if (KQSettingsBiz.getKqformatAccurate()){
sql = " insert into kq_format_pool (resourceid, kqdate, exectime) values (?,?,?)";
lsFormatParams = processFormatParams(lsFormatParams);
}
bRs.executeBatchSql(sql, lsFormatParams);
} else {
String resourceid = "";
String kqdate = "";
for (int i = 0; lsFormatParams != null && i < lsFormatParams.size(); i++) {
params = lsFormatParams.get(i);
resourceid = Util.null2String(params.get(0));
kqdate = Util.null2String(params.get(1));
new KQFormatData().formatKqDate(resourceid, kqdate);
}
}
} catch (Exception e) {
writeLog(" KQFormatData.formatKqDate lsFormatParams >>>>>>>>>" + e);
}
}
public void formatDateByKQDate(String kqdate) {
String sql = "";
RecordSet rs = new RecordSet();
List<List<Object>> lsFormatParams = new ArrayList<>();
List<Object> formatParams = null;
try {
if (DateUtil.timeInterval(kqdate, today) < 0) {
kqLog.info("今天之后的无需处理的数据kqdate==" + kqdate + "today==" + today);
return;//今天之后的无需处理
}
sql = " SELECT distinct resourceid FROM ( " +
new KQGroupBiz().getGroupMemberSql() + ") t ";
rs.executeQuery(sql);
while (rs.next()) {
String resourceid = rs.getString("resourceid");
if(Util.null2String(kqdate).length()!=10)return;
formatParams = new ArrayList<>();
formatParams.add(resourceid);
formatParams.add(kqdate);
lsFormatParams.add(formatParams);
}
this.format(lsFormatParams);
} catch (Exception e) {
writeLog(e);
kqLog.info(e);
}
}
public void formatDateByGroupId(String groupid, String kqdate) {
String sql = "";
RecordSet rs = new RecordSet();
List<List<Object>> lsFormatParams = new ArrayList<>();
List<Object> formatParams = null;
try {
if (DateUtil.timeInterval(kqdate, today) < 0) {
kqLog.info("今天之后的无需处理的数据groupid==" + groupid + "kqdate==" + kqdate + "today==" + today);
return;//今天之后的无需处理
}
KQGroupComInfo kqGroupComInfo = new KQGroupComInfo();
KQGroupBiz kqGroupBiz = new KQGroupBiz();
String kqtype = kqGroupComInfo.getKqtype(groupid);
if (kqtype.equals("2")) {//排班
sql = "select resourceid, kqdate from kq_shiftschedule where groupid=" + groupid + " and kqdate='" + kqdate + "' and (isdelete is null or isdelete <> '1') ";
} else {
sql = "select resourceid,'" + kqdate + "' from (" + kqGroupBiz.getGroupMemberSql(groupid) + ") t ";
}
rs.executeQuery(sql);
while (rs.next()) {
String resourceid = rs.getString("resourceid");
if(Util.null2String(kqdate).length()!=10)return;
formatParams = new ArrayList<>();
formatParams.add(resourceid);
formatParams.add(kqdate);
lsFormatParams.add(formatParams);
}
this.format(lsFormatParams);
} catch (Exception e) {
writeLog(e);
kqLog.info(e);
}
}
public void formatDate(String resourceid, String kqdate) {
List<List<Object>> lsFormatParams = new ArrayList<>();
List<Object> formatParams = null;
try {
if (DateUtil.timeInterval(kqdate, today) < 0) {
kqLog.info("今天之后的无需处理的数据resourceid==" + resourceid + "kqdate==" + kqdate + "today==" + today);
return;//今天之后的无需处理
}
if(Util.null2String(kqdate).length()!=10)return;
formatParams = new ArrayList<>();
formatParams.add(resourceid);
formatParams.add(kqdate);
lsFormatParams.add(formatParams);
this.format(lsFormatParams);
} catch (Exception e) {
writeLog(e);
kqLog.info(e);
}
}
public void delFormatData(String resourceid, String kqdate) {
RecordSet rs = new RecordSet();
String sql = "";
try {
sql = " delete from kq_format_detail where resourceid =" + resourceid + " and kqdate = ? ";//删除非工作日数据
rs.executeUpdate(sql, kqdate);
sql = " delete from kq_format_total where resourceid =" + resourceid + " and kqdate = ? ";//删除非工作日数据
rs.executeUpdate(sql, kqdate);
} catch (Exception e) {
writeLog(e);
kqLog.info(e);
}
}
public void clearFormatPool() {
RecordSet rs = new RecordSet();
String sql = "";
try {
//删除三天前的数据格式化数据
if (rs.getDBType().equals("sqlserver")) {
sql = " delete from kq_format_pool where status = 1 and datediff(day,created,getdate()) > 1";
} else if (rs.getDBType().equals("mysql")) {
sql = " delete from kq_format_pool where status = 1 and datediff(now(),created) > 1";
}
else if (rs.getDBType().equals("postgresql")) {
sql = " delete from kq_format_pool where status = 1 and datediff(now(),created) > 1";
}
else if (rs.getOrgindbtype().equals("st")) {
sql = " delete from kq_format_pool where status = 1 and to_number(trunc(sysdate) - trunc(created)) > 1";
} else {
sql = " delete from kq_format_pool where status = 1 and trunc(sysdate) - trunc(created) > 1";
}
rs.executeUpdate(sql);
} catch (Exception e) {
writeLog(e);
}
}
public Map<String,Object> getDefinedField(){
Map<String,Object> retMap = new HashMap<>();
String definedField = "";
String definedFieldSum = "";
String definedParam = "";
String definedParamSum = "";
KQReportFieldComInfo kqReportFieldComInfo = new KQReportFieldComInfo();
while (kqReportFieldComInfo.next()) {
if (!Util.null2String(kqReportFieldComInfo.getIsenable()).equals("1")) continue;
if (Util.null2String(kqReportFieldComInfo.getIsSystem()).equals("1")) continue;
if(KQReportFieldComInfo.cascadekey2fieldname.keySet().contains(kqReportFieldComInfo.getFieldname()))continue;
if(definedField.length()>0)definedField+=",";
definedField+=kqReportFieldComInfo.getFieldname();
if(definedFieldSum.length()>0)definedFieldSum+=",";
definedFieldSum+="sum("+kqReportFieldComInfo.getFieldname()+") as "+kqReportFieldComInfo.getFieldname();
if(definedParam.length()>0)definedParam+=",";
definedParam+="?";
if(definedParamSum.length()>0)definedParamSum+=",";
definedParamSum+="sum("+kqReportFieldComInfo.getFieldname()+")";
String[] cascadekeys = Util.splitString(Util.null2String(kqReportFieldComInfo.getCascadekey()),",");
for(int i=0;cascadekeys!=null&&i<cascadekeys.length;i++){
String fieldname = Util.null2String(cascadekeys[i]);
if(fieldname.length()==0)continue;
if(definedField.length()>0)definedField+=",";
definedField+=fieldname;
if(definedFieldSum.length()>0)definedFieldSum+=",";
definedFieldSum+="sum("+fieldname+") as "+fieldname;
if(definedParam.length()>0)definedParam+=",";
definedParam+="?";
if(definedParamSum.length()>0)definedParamSum+=",";
definedParamSum+="sum("+fieldname+")";
}
}
retMap.put("definedField",definedField);
retMap.put("definedFieldSum",definedFieldSum);
retMap.put("definedParam",definedParam);
retMap.put("definedParamSum",definedParamSum);
return retMap;
}
public boolean needCal(String workDate, String workTime){
boolean needCalForgotCheckMins = true;
if (KQSettingsBiz.getKqformatAccurate()) {
workTime = new KQTimesArrayComInfo().turn48to24Time(workTime);
if (workDate.length() > 0 && workTime.length() > 0) {
String currentFullTime = DateUtil.getFullDate();
String endTime = workDate + " " + workTime;
if (DateUtil.timeInterval(currentFullTime, endTime) > 0) {
//当前时间之后的状态无效计算
needCalForgotCheckMins = false;
}
}
}
return needCalForgotCheckMins;
}
private List<List<Object>> processFormatParams(List<List<Object>> lsFormatParams) {
List<List<Object>> lsFormatParamsTmp = new ArrayList<>();
try {
KQTimesArrayComInfo kqTimesArrayComInfo = new KQTimesArrayComInfo();
KQWorkTime kqWorkTime = new KQWorkTime();
List<Object> formatParams = null;
for(int i=0;i<lsFormatParams.size();i++){
formatParams = lsFormatParams.get(i);
String resourceId = Util.null2String(formatParams.get(0));
String kqDate = Util.null2String(formatParams.get(1));
formatParams = new ArrayList<>();
formatParams.add(resourceId);
formatParams.add(kqDate);
formatParams.add(new java.sql.Timestamp(DateUtil.getCalendar(DateUtil.getFullDate()).getTimeInMillis()));
lsFormatParamsTmp.add(formatParams);
String nextDate = DateUtil.addDate(kqDate, 1);//下一天日期
WorkTimeEntity workTime = kqWorkTime.getWorkTime(resourceId, kqDate);
List<TimeScopeEntity> lsWorkTime = new ArrayList<>();
if (workTime != null) {
lsWorkTime = workTime.getWorkTime();//工作时间
for (int j = 0; lsWorkTime != null && j < lsWorkTime.size(); j++) {
TimeScopeEntity workTimeScope = lsWorkTime.get(j);
String workBeginDateTime = workTimeScope.getBeginTimeAcross() ? nextDate : kqDate;
workBeginDateTime+=" "+kqTimesArrayComInfo.turn48to24Time(workTimeScope.getBeginTime())+":00:00";
String workEndDateTime = workTimeScope.getEndTimeAcross() ? nextDate : kqDate;
workEndDateTime+=" "+kqTimesArrayComInfo.turn48to24Time(workTimeScope.getEndTime())+":00:00";
formatParams = new ArrayList<>();
formatParams.add(resourceId);
formatParams.add(kqDate);
formatParams.add(new java.sql.Timestamp(DateUtil.getCalendar(workBeginDateTime).getTimeInMillis()));
lsFormatParamsTmp.add(formatParams);
formatParams = new ArrayList<>();
formatParams.add(resourceId);
formatParams.add(kqDate);
formatParams.add(new java.sql.Timestamp(DateUtil.getCalendar(workEndDateTime).getTimeInMillis()));
lsFormatParamsTmp.add(formatParams);
}
}else{
formatParams = new ArrayList<>();
formatParams.add(resourceId);
formatParams.add(kqDate);
lsFormatParamsTmp.add(formatParams);
}
}
}catch (Exception e) {
StringWriter errorsWriter = new StringWriter();
e.printStackTrace(new PrintWriter(errorsWriter));
kqLog.info(errorsWriter.toString());
}
return lsFormatParamsTmp;
}
}

File diff suppressed because it is too large Load Diff

@ -0,0 +1,90 @@
package com.engine.kq.biz;
import com.engine.kq.log.KQLog;
import com.weaver.util.threadPool.ThreadPoolUtil;
import com.weaver.util.threadPool.constant.ModulePoolEnum;
import weaver.common.DateUtil;
import weaver.conn.ConnStatement;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.WArrayList;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
*
*/
public class KQFormatJob extends TimerTask {
private static KQFormatJob instance = new KQFormatJob();
public static WArrayList kqformatIds = new WArrayList();
private static boolean flag = false;
private KQLog kqLog = new KQLog();
public static KQFormatJob getInstance(){
return instance;
}
public void run() {
KQFormatThread kqFormatThread = null;
ConnStatement cs = new ConnStatement();
String sql = "";
try{
if(flag) return;
flag = true;
if(kqformatIds.size()>0){
flag = false;
return;
}
sql = " select id, kqdate, resourceid from kq_format_pool where status = 0 order by kqdate, resourceid asc";
boolean kqformatAccurate = KQSettingsBiz.getKqformatAccurate();
if (kqformatAccurate){
String currentFullTime = DateUtil.getFullDate();
RecordSet rs = new RecordSet();
if(rs.getDBType().equals("oracle")){
sql = " select id, kqdate, resourceid,exectime from kq_format_pool where status = 0 and exectime is not null and exectime < to_date('"+currentFullTime+"','yyyy-mm-dd hh24:mi:ss') order by kqdate, resourceid, exectime asc";
}
else if(rs.getDBType().equals("postgresql")){
sql = " select id, kqdate, resourceid,exectime from kq_format_pool where status = 0 and exectime is not null and exectime < to_date('"+currentFullTime+"','yyyy-mm-dd hh24:mi:ss') order by kqdate, resourceid, exectime asc";
}
else if (rs.getDBType().equals("mysql")) {
sql = " select id, kqdate, resourceid,exectime from kq_format_pool where status = 0 and exectime is not null and exectime<STR_TO_DATE('"+currentFullTime+"', '%Y-%m-%d %H:%i:%s') order by kqdate, resourceid, exectime asc";
}else{
sql = " select id, kqdate, resourceid,exectime from kq_format_pool where status = 0 and exectime is not null and exectime<CONVERT(datetime,'"+currentFullTime+"',120) order by kqdate, resourceid, exectime asc";
}
}
//rs.executeQuery(sql);
cs.setStatementSql(sql);
cs.executeQuery();
while (cs.next()) {
String key = cs.getString("kqdate") +"|"+cs.getString("resourceid");
if(kqformatIds.contains(key))continue;
kqformatIds.add(key);
kqFormatThread = new KQFormatThread();
kqFormatThread.setId(cs.getString("id"));
kqFormatThread.setKqdate(cs.getString("kqdate"));
kqFormatThread.setResourceid(cs.getString("resourceid"));
if(kqformatAccurate) {
kqLog.info(Thread.currentThread().getId() + "===KQFormatJob in>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + cs.getString("id") + "==" + cs.getString("kqdate") + "==" + cs.getString("resourceid") + "==" + cs.getString("exectime"));
}else{
kqLog.info(Thread.currentThread().getId() + "===KQFormatJob in>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + cs.getString("id") + "==" + cs.getString("kqdate") + "==" + cs.getString("resourceid"));
}
//kqformatPool.execute(kqFormatThread);
ThreadPoolUtil.fixedPoolExecute(ModulePoolEnum.HRM, "KQFormatJob", kqFormatThread);
}
flag = false;
}catch (Exception e){
flag = false;
new BaseBean().writeLog(e);
kqLog.info("考勤数据格式化定时任务错误:",e);
}finally {
try {
cs.close();
}catch(Exception ex) {new BaseBean().writeLog("关闭考勤数据格式化定时任务数据库链接错误");}
}
}
}

@ -0,0 +1,544 @@
package com.engine.kq.biz;
import com.alibaba.fastjson.JSON;
import com.engine.kq.cmd.attendanceButton.ButtonStatusEnum;
import com.engine.kq.entity.TimeScopeEntity;
import com.engine.kq.entity.TimeSignScopeEntity;
import com.engine.kq.log.KQLog;
import com.engine.kq.util.UtilKQ;
import com.google.common.collect.Lists;
import java.io.PrintWriter;
import java.io.StringWriter;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import java.util.*;
/**
*
*/
public class KQFormatSignData extends BaseBean {
private KQLog kqLog = new KQLog();
public List<Object> getSignInfo(String userId, TimeScopeEntity signTimeScope,
TimeScopeEntity workTimeScope, String kqDate, String preDate,
String nextDate, KQTimesArrayComInfo kqTimesArrayComInfo) {
return getSignInfo(userId, signTimeScope, workTimeScope, kqDate, preDate, nextDate, kqTimesArrayComInfo,
Lists.newArrayList(), "");
}
/***
*
* @param userId
* @param signTimeScope
* @param workTimeScope
* @param kqDate
* @param preDate
* @param nextDate
* @param kqTimesArrayComInfo
* @return
*/
public List<Object> getSignInfo(String userId, TimeScopeEntity signTimeScope,
TimeScopeEntity workTimeScope, String kqDate, String preDate,
String nextDate, KQTimesArrayComInfo kqTimesArrayComInfo,ArrayList<String> hostIps,String uuid) {
kqLog.info("in getSignInfo ::userId" + userId + "kqDate==" + kqDate+":hostIps:"+hostIps+":uuid::"+uuid+" in ");
List<Object> lsCheckInfo = new ArrayList<>();
try{
Map<String, Object> checkInfo = null;
String base_sql = "";
RecordSet rs = new RecordSet();
String dbtype = rs.getDBType();
//获取工作上下班时间
String workBeginDateTime = workTimeScope.getBeginTimeAcross() ? nextDate : kqDate;
workBeginDateTime+=" "+kqTimesArrayComInfo.turn48to24Time(workTimeScope.getBeginTime())+":00";
kqLog.info("in getSignInfo ::userId" + userId + "kqDate==" + kqDate+":hostIps:"+hostIps+":uuid::"+uuid+"::workBeginDateTime::"+workBeginDateTime);
//获取工作上下班时间
String workEndDateTime = workTimeScope.getEndTimeAcross() ? nextDate : kqDate;
workEndDateTime+=" "+kqTimesArrayComInfo.turn48to24Time(workTimeScope.getEndTime())+":00";
kqLog.info("in getSignInfo ::userId" + userId + "kqDate==" + kqDate+":hostIps:"+hostIps+":uuid::"+uuid+"::workEndDateTime::"+workEndDateTime);
Map<String,String> flow_deduct_card_map = getflowDeductCardSql(userId,kqDate,workTimeScope.getBeginTime(),workTimeScope.getEndTime());
kqLog.info("in getSignInfo ::userId" + userId + "kqDate==" + kqDate+":hostIps:"+hostIps+":uuid::"+uuid+"::flow_deduct_card_map::"+flow_deduct_card_map);
List<Map<String,String>> sqlConditions = getCanSignInfo(signTimeScope,kqDate,preDate,nextDate,kqTimesArrayComInfo,workTimeScope);
base_sql = signSignSql(rs);
new KQLog().info("sqlConditions:(userId:"+userId+":base_sql"+base_sql+":::userId" + userId + "kqDate==" + kqDate+":hostIps:"+hostIps+":uuid::"+uuid+"::flow_deduct_card_map::"+flow_deduct_card_map);
if(sqlConditions != null && !sqlConditions.isEmpty()){
for(Map<String,String> sqlMap : sqlConditions){
String sql = "";
String orderSql = "";
int idx = 0;
String signBeginDateTime = Util.null2String(sqlMap.get("signBeginDateTime"));
String signEndDateTime = Util.null2String(sqlMap.get("signEndDateTime"));
String type = Util.null2String(sqlMap.get("type"));
if(type.length() > 0){
if("signoff".equalsIgnoreCase(type)){
orderSql = " order by signdate desc, signtime desc ";
}else if("signin".equalsIgnoreCase(type)){
orderSql = " order by signdate asc, signtime asc ";
}
if("oracle".equalsIgnoreCase(dbtype)){
sql = "select * from ("+base_sql+" "+orderSql+") a where rownum=1";
}else if("mysql".equalsIgnoreCase(dbtype)){
sql = "select * from ("+base_sql+" "+orderSql+") a limit 0,1";
}
else if("postgresql".equalsIgnoreCase(dbtype)){
sql = "select * from ("+base_sql+" "+orderSql+") a limit 1 offset 0";
}
else if("sqlserver".equalsIgnoreCase(dbtype)){
sql = "select top 1 * from ("+base_sql+") a "+" "+orderSql;
}else{
sql = "select * from ("+base_sql+" "+orderSql+") a where rownum=1";
}
}else{
orderSql = " order by signdate asc, signtime asc ";
sql = base_sql+" "+orderSql;
}
rs.executeQuery(sql, userId, signBeginDateTime, signEndDateTime);
new KQLog().info("getSignInfo:(userId:"+userId+":signBeginDateTime:"+
signBeginDateTime+":signEndDateTime:"+signEndDateTime+"):sql"+sql+":counts:"+rs.getCounts()+":::userId" + userId + "kqDate==" + kqDate+":hostIps:"+hostIps+":uuid::"+uuid+"::flow_deduct_card_map::"+flow_deduct_card_map);
while (rs.next()) {
String signId = Util.null2String(rs.getString("id"));
String signdate = Util.null2String(rs.getString("signdate"));
String signtime = Util.null2String(rs.getString("signtime"));
checkInfo = new HashMap<>();
checkInfo.put("signId", signId);//签到签退标识
checkInfo.put("signDate", signdate);//签到签退日期
checkInfo.put("signTime", signtime);//签到签退时间
String signDateTime = signdate + " " + signtime;
idx++;
if(type.length() > 0){
if("signin".equalsIgnoreCase(type)){
checkInfo.put("signType", "1");
if(workBeginDateTime.length()>0) {
checkInfo.put("signStatus", UtilKQ.getSignStatus("1", signDateTime, workBeginDateTime));
}
if(!Util.null2String(checkInfo.get("signStatus")).equalsIgnoreCase(ButtonStatusEnum.NORMAL.getStatusCode())){
if(flow_deduct_card_map.containsKey("signin")){
String deduct_signintime = Util.null2String(flow_deduct_card_map.get("signin"));
if(deduct_signintime.length() > 0){
signDateTime = signdate + " " + deduct_signintime;
checkInfo.put("deduct_signintime", deduct_signintime);//流程抵扣作为打卡时间
checkInfo.put("signStatus", UtilKQ.getSignStatus("1", signDateTime, workBeginDateTime));
}
}
}
lsCheckInfo.add(checkInfo);
}else {
checkInfo.put("signType", "2");
if(workEndDateTime.length()>0) {
checkInfo.put("signStatus", UtilKQ.getSignStatus("2", signDateTime, workEndDateTime));
}
if(!Util.null2String(checkInfo.get("signStatus")).equalsIgnoreCase(ButtonStatusEnum.NORMAL.getStatusCode())){
if(flow_deduct_card_map.containsKey("signoff")){
String deduct_signofftime = Util.null2String(flow_deduct_card_map.get("signoff"));
if(deduct_signofftime.length() > 0){
signDateTime = signdate + " " + deduct_signofftime;
checkInfo.put("deduct_signofftime", deduct_signofftime);//流程抵扣作为打卡时间
checkInfo.put("signStatus", UtilKQ.getSignStatus("2", signDateTime, workEndDateTime));
}
}
}
lsCheckInfo.add(checkInfo);
}
}else{
if(idx==1){//第一条算签到
checkInfo.put("signType", "1");
if(workBeginDateTime.length()>0) {
checkInfo.put("signStatus", UtilKQ.getSignStatus("1", signDateTime, workBeginDateTime));
}
if(!Util.null2String(checkInfo.get("signStatus")).equalsIgnoreCase(ButtonStatusEnum.NORMAL.getStatusCode())){
if(flow_deduct_card_map.containsKey("signin")){
String deduct_signintime = Util.null2String(flow_deduct_card_map.get("signin"));
if(deduct_signintime.length() > 0){
signDateTime = signdate + " " + deduct_signintime;
checkInfo.put("deduct_signintime", deduct_signintime);//流程抵扣作为打卡时间
checkInfo.put("signStatus", UtilKQ.getSignStatus("1", signDateTime, workBeginDateTime));
}
}
}
lsCheckInfo.add(checkInfo);
}else if(idx==rs.getCounts()){//最后一条算签退
checkInfo.put("signType", "2");
if(workEndDateTime.length()>0) {
checkInfo.put("signStatus", UtilKQ.getSignStatus("2", signDateTime, workEndDateTime));
}
if(!Util.null2String(checkInfo.get("signStatus")).equalsIgnoreCase(ButtonStatusEnum.NORMAL.getStatusCode())){
if(flow_deduct_card_map.containsKey("signoff")){
String deduct_signofftime = Util.null2String(flow_deduct_card_map.get("signoff"));
if(deduct_signofftime.length() > 0){
signDateTime = signdate + " " + deduct_signofftime;
checkInfo.put("deduct_signofftime", deduct_signofftime);//流程抵扣作为打卡时间
checkInfo.put("signStatus", UtilKQ.getSignStatus("2", signDateTime, workEndDateTime));
}
}
}
lsCheckInfo.add(checkInfo);
}
}
}
}
}
//如果签到,签退不成对,流程抵扣异常存在,那么需要判断下是不是可以补足
if(lsCheckInfo.size() < 2 && !flow_deduct_card_map.isEmpty()){
if(lsCheckInfo.isEmpty()){
if(flow_deduct_card_map.containsKey("signin")){
String deduct_signintime = Util.null2String(flow_deduct_card_map.get("signin"));
if(deduct_signintime.length() > 0){
checkInfo = new HashMap<>();
String[] workBeginDateTimes = workBeginDateTime.split(" ");
String tmp_workBeginDate = workBeginDateTimes[0];
String tmp_workBeginTime = workBeginDateTimes[1];
checkInfo.put("signType", "1");
checkInfo.put("signDate", tmp_workBeginDate);//签到签退日期
checkInfo.put("signTime", "");//签到签退时间
checkInfo.put("deduct_signintime", tmp_workBeginTime);//流程抵扣作为打卡时间
checkInfo.put("signStatus", ButtonStatusEnum.NORMAL.getStatusCode());
lsCheckInfo.add(checkInfo);
}
}
if(flow_deduct_card_map.containsKey("signoff")){
String deduct_signofftime = Util.null2String(flow_deduct_card_map.get("signoff"));
if(deduct_signofftime.length() > 0){
checkInfo = new HashMap<>();
String[] workEndDateTimes = workEndDateTime.split(" ");
String tmp_workEndDate = workEndDateTimes[0];
String tmp_workEndTime = workEndDateTimes[1];
checkInfo.put("signType", "2");
checkInfo.put("signDate", tmp_workEndDate);//签到签退日期
checkInfo.put("signTime", "");//签到签退时间
checkInfo.put("deduct_signofftime", tmp_workEndTime);//流程抵扣作为打卡时间
checkInfo.put("signStatus", ButtonStatusEnum.NORMAL.getStatusCode());
lsCheckInfo.add(checkInfo);
}
}
}else{
Map<String, Object> checkCardMap = (Map<String, Object>) lsCheckInfo.get(0);
if(!checkCardMap.isEmpty()){
String signType = Util.null2String(checkCardMap.get("signType"));
if("1".equalsIgnoreCase(signType)){
//如果签到数据有了,检测下是不是有签退的流程抵扣打卡
if(flow_deduct_card_map.containsKey("signoff")){
String deduct_signofftime = Util.null2String(flow_deduct_card_map.get("signoff"));
if(deduct_signofftime.length() > 0){
checkInfo = new HashMap<>();
String[] workEndDateTimes = workEndDateTime.split(" ");
String tmp_workEndDate = workEndDateTimes[0];
String tmp_workEndTime = workEndDateTimes[1];
checkInfo.put("signType", "2");
checkInfo.put("signDate", tmp_workEndDate);//签到签退日期
checkInfo.put("signTime", "");//签到签退时间
checkInfo.put("deduct_signofftime", tmp_workEndTime);//流程抵扣作为打卡时间
checkInfo.put("signStatus", ButtonStatusEnum.NORMAL.getStatusCode());
lsCheckInfo.add(checkInfo);
}
}
}else{
if(flow_deduct_card_map.containsKey("signin")){
String deduct_signintime = Util.null2String(flow_deduct_card_map.get("signin"));
if(deduct_signintime.length() > 0){
checkInfo = new HashMap<>();
String[] workBeginDateTimes = workBeginDateTime.split(" ");
String tmp_workBeginDate = workBeginDateTimes[0];
String tmp_workBeginTime = workBeginDateTimes[1];
checkInfo.put("signType", "1");
checkInfo.put("signDate", tmp_workBeginDate);//签到签退日期
checkInfo.put("signTime", "");//签到签退时间
checkInfo.put("deduct_signintime", tmp_workBeginTime);//流程抵扣作为打卡时间
checkInfo.put("signStatus", ButtonStatusEnum.NORMAL.getStatusCode());
lsCheckInfo.add(checkInfo);
}
}
}
}
}
}
}catch (Exception e){
kqLog.info("报表错:getSignInfo:");
StringWriter errorsWriter = new StringWriter();
e.printStackTrace(new PrintWriter(errorsWriter));
kqLog.info(errorsWriter.toString());
}
//writeLog(sql,userId +"=="+ signBeginDateTime+"=="+signEndDateTime);
return lsCheckInfo;
}
/**
*
* @param userId
* @param kqDate
* @param workBeginDateTime
* @param workEndDateTime
*/
public Map<String,String> getflowDeductCardSql(String userId, String kqDate, String workBeginDateTime, String workEndDateTime) {
Map<String,String> flow_deduct_card_map = new HashMap<>();
RecordSet rs = new RecordSet();
String flow_deduct_card_sql = "select * from kq_flow_deduct_card where 1=1 and (isclear is null or isclear<>1) ";
if(userId.length() > 0){
flow_deduct_card_sql += " and resourceid="+userId;
}
if(kqDate.length() > 0){
flow_deduct_card_sql += " and belongDate='"+kqDate+"'";
}
if(workBeginDateTime.length() > 0){
flow_deduct_card_sql += " and workBeginTime='"+workBeginDateTime+"'";
}
if(workEndDateTime.length() > 0){
flow_deduct_card_sql += " and workEndTime='"+workEndDateTime+"'";
}
rs.executeQuery(flow_deduct_card_sql);
while (rs.next()){
String signtype = rs.getString("signtype");
if("1".equalsIgnoreCase(signtype)){
flow_deduct_card_map.put("signin",workBeginDateTime);
}
if("2".equalsIgnoreCase(signtype)){
flow_deduct_card_map.put("signoff",workEndDateTime);
}
}
return flow_deduct_card_map;
}
/**
* sql
* @param signTimeScope
* @param kqDate
* @param preDate
* @param nextDate
* @param kqTimesArrayComInfo
* @return
*/
public List<Map<String,String>> getCanSignInfo(TimeScopeEntity signTimeScope, String kqDate, String preDate, String nextDate, KQTimesArrayComInfo kqTimesArrayComInfo) {
return getCanSignInfo(signTimeScope,kqDate,preDate,nextDate,kqTimesArrayComInfo,null);
}
public List<Map<String,String>> getCanSignInfo(TimeScopeEntity signTimeScope, String kqDate, String preDate, String nextDate, KQTimesArrayComInfo kqTimesArrayComInfo,TimeScopeEntity workTimeScope) {
List<Map<String,String>> sqlConditions = new ArrayList<>();
Map<String,String> conditionMap = new HashMap<>();
TimeSignScopeEntity timeSignScopeEntity = signTimeScope.getTimeSignScopeEntity();
String signBeginDateTime = "";
String signEndDateTime = "";
signBeginDateTime = signTimeScope.getBeginTimeAcross() ? nextDate : kqDate;
if(signTimeScope.isBeginTimePreAcross()){
signBeginDateTime = preDate;
}
signBeginDateTime+=" "+kqTimesArrayComInfo.turn48to24Time(signTimeScope.getBeginTime())+":00";
signEndDateTime = signTimeScope.getEndTimeAcross() ? nextDate : kqDate;
signEndDateTime+=" "+kqTimesArrayComInfo.turn48to24Time(signTimeScope.getEndTime())+":59";
if(timeSignScopeEntity == null){
//没有设置 签到最晚时间和签退最早时间
conditionMap = new HashMap<>();
conditionMap.put("signBeginDateTime", signBeginDateTime);
conditionMap.put("signEndDateTime", signEndDateTime);
sqlConditions.add(conditionMap);
}else{
String beginTimeEnd = timeSignScopeEntity.getBeginTimeEnd();
boolean beginTimeEndAcross = timeSignScopeEntity.isBeginTimeEndAcross();
String endTimeStart = timeSignScopeEntity.getEndTimeStart();
boolean endTimeStartAcross = timeSignScopeEntity.isEndTimeStartAcross();
if(beginTimeEnd.length() > 0){
//如果设置了 上班结束时间
if(endTimeStart.length() > 0){
//设置了下班开始时间
String signBeginDateEndTime = "";
String signEndDateStartTime = "";
signBeginDateEndTime = beginTimeEndAcross ? nextDate : kqDate;
signBeginDateEndTime+=" "+kqTimesArrayComInfo.turn48to24Time(beginTimeEnd)+":59";
conditionMap = new HashMap<>();
conditionMap.put("signBeginDateTime", signBeginDateTime);
conditionMap.put("signEndDateTime", signBeginDateEndTime);
conditionMap.put("type", "signin");
sqlConditions.add(conditionMap);
signEndDateStartTime = endTimeStartAcross ? nextDate : kqDate;
signEndDateStartTime+=" "+kqTimesArrayComInfo.turn48to24Time(endTimeStart)+":00";
conditionMap = new HashMap<>();
conditionMap.put("signBeginDateTime", signEndDateStartTime);
conditionMap.put("signEndDateTime", signEndDateTime);
conditionMap.put("type", "signoff");
sqlConditions.add(conditionMap);
}else{
//没有设置下班开始时间
String signBeginDateEndTime = "";
String signEndDateStartTime = "";
signBeginDateEndTime = beginTimeEndAcross ? nextDate : kqDate;
signBeginDateEndTime+=" "+kqTimesArrayComInfo.turn48to24Time(beginTimeEnd)+":59";
conditionMap = new HashMap<>();
conditionMap.put("signBeginDateTime", signBeginDateTime);
conditionMap.put("signEndDateTime", signBeginDateEndTime);
conditionMap.put("type", "signin");
sqlConditions.add(conditionMap);
//如果设置了上班结束时间,相当于下班开始时间也被限定了
String endTimeByBeginTime = kqTimesArrayComInfo.getTimesByArrayindex(kqTimesArrayComInfo.getArrayindexByTimes(beginTimeEnd)+1);
signEndDateStartTime = beginTimeEndAcross ? nextDate : kqDate;
signEndDateStartTime+=" "+kqTimesArrayComInfo.turn48to24Time(endTimeByBeginTime)+":00";
conditionMap = new HashMap<>();
conditionMap.put("signBeginDateTime", signEndDateStartTime);
conditionMap.put("signEndDateTime", signEndDateTime);
conditionMap.put("type", "signoff");
sqlConditions.add(conditionMap);
}
}else if(endTimeStart.length() > 0){
//如果没有设置上班结束时间,设置了下班开始时间
String signBeginDateEndTime = "";
String signEndDateStartTime = "";
//如果设置了下班开始时间,相当于上班结束时间也被限定了
String BeginTimeByendTime = kqTimesArrayComInfo.getTimesByArrayindex(kqTimesArrayComInfo.getArrayindexByTimes(endTimeStart)-1);
signBeginDateEndTime = endTimeStartAcross ? nextDate : kqDate;
signBeginDateEndTime+=" "+kqTimesArrayComInfo.turn48to24Time(BeginTimeByendTime)+":59";
conditionMap = new HashMap<>();
conditionMap.put("signBeginDateTime", signBeginDateTime);
conditionMap.put("signEndDateTime", signBeginDateEndTime);
conditionMap.put("type", "signin");
sqlConditions.add(conditionMap);
signEndDateStartTime = endTimeStartAcross ? nextDate : kqDate;
signEndDateStartTime+=" "+kqTimesArrayComInfo.turn48to24Time(endTimeStart)+":00";
conditionMap = new HashMap<>();
conditionMap.put("signBeginDateTime", signEndDateStartTime);
conditionMap.put("signEndDateTime", signEndDateTime);
conditionMap.put("type", "signoff");
sqlConditions.add(conditionMap);
}
}
return sqlConditions;
}
public String signSignSql(RecordSet rs){
String sql = "";
if(rs.getDBType().equals("oracle")){
sql = " select id,signdate,signtime from hrmschedulesign where isincom=1 and userid = ? and signdate||' '||signtime >= ? and signdate||' '||signtime <= ? " +
" ";
}else if("sqlserver".equals(rs.getDBType())){
sql = " select id,signdate,signtime from hrmschedulesign where isincom=1 and userid = ? and signdate + ' ' + signtime >= ? and signdate + ' ' + signtime <= ? " +
" ";
}else{
sql = " select id,signdate,signtime from hrmschedulesign where isincom=1 and userid = ? and concat(signdate,' ',signtime) >= ? and concat(signdate,' ',signtime) <= ? " +
" ";
}
return sql;
}
public List<Object> getSignInfoForAll(String userId, String signBeginDateTime, String signEndDateTime, String workBeginDateTime, String workEndDateTime) {
List<Object> lsCheckInfo = new ArrayList<>();
Map<String, Object> checkInfo = null;
String sql = "";
RecordSet rs = new RecordSet();
int idx = 0;
if(rs.getDBType().equals("oracle")){
sql = " select id,signdate,signtime from hrmschedulesign where isincom=1 and userid = ? and signdate||' '||signtime >= ? and signdate||' '||signtime <= ? " +
" order by signdate asc, signtime asc ";
}else if("sqlserver".equals(rs.getDBType())){
sql = " select id,signdate,signtime from hrmschedulesign where isincom=1 and userid = ? and signdate + ' ' + signtime >= ? and signdate + ' ' + signtime <= ? " +
" order by signdate asc, signtime asc ";
}else{
sql = " select id,signdate,signtime from hrmschedulesign where isincom=1 and userid = ? and concat(signdate,' ',signtime) >= ? and concat(signdate,' ',signtime) <= ? " +
" order by signdate asc, signtime asc ";
}
rs.executeQuery(sql, userId, signBeginDateTime, signEndDateTime);
//writeLog(sql,userId +"=="+ signBeginDateTime+"=="+signEndDateTime);
while (rs.next()) {
String signId = Util.null2String(rs.getString("id"));
String signdate = Util.null2String(rs.getString("signdate"));
String signtime = Util.null2String(rs.getString("signtime"));
checkInfo = new HashMap<>();
checkInfo.put("signId", signId);//签到签退标识
checkInfo.put("signDate", signdate);//签到签退日期
checkInfo.put("signTime", signtime);//签到签退时间
String signDateTime = signdate + " " + signtime;
idx++;
if(idx%2==1){
checkInfo.put("signType", "1");
}else{
checkInfo.put("signType", "2");
}
lsCheckInfo.add(checkInfo);
}
return lsCheckInfo;
}
public List<Object> getNonWorkSignInfo(String userId, String preDate, String kqDate,
List<TimeScopeEntity> pre_lsSignTime,
List<TimeScopeEntity> next_lsSignTime) {
List<Object> lsCheckInfo = new ArrayList<>();
Map<String, Object> checkInfo = null;
RecordSet rs = new RecordSet();
String pre_Worktime4Today = "";
if(!pre_lsSignTime.isEmpty()){
TimeScopeEntity pre_signTimeScope = pre_lsSignTime.get(pre_lsSignTime.size()-1);
if(pre_signTimeScope.getEndTimeAcross()){
pre_Worktime4Today = pre_signTimeScope.getEndTime();
}
}
String next_Worktime4Today = "";
if(!next_lsSignTime.isEmpty()){
TimeScopeEntity next_signTimeScope = next_lsSignTime.get(next_lsSignTime.size()-1);
if(next_signTimeScope.isBeginTimePreAcross()){
next_Worktime4Today = next_signTimeScope.getBeginTime();
}
}
String sql = "select * from hrmschedulesign where userid="+userId+" and signdate = '"+kqDate+"' ";
if(pre_Worktime4Today.length() > 0){
if(pre_Worktime4Today.length() == 5){
pre_Worktime4Today += ":59";
}
sql += " and signtime > '"+pre_Worktime4Today+"'";
}
if(next_Worktime4Today.length() > 0){
if(next_Worktime4Today.length() == 5){
next_Worktime4Today += ":00";
}
sql += " and signtime < '"+next_Worktime4Today+"'";
}
sql += " order by signdate asc,signtime asc ";
rs.executeQuery(sql);
int idx = 0;
while (rs.next()){
String signId = Util.null2String(rs.getString("id"));
String signdate = Util.null2String(rs.getString("signdate"));
String signtime = Util.null2String(rs.getString("signtime"));
checkInfo = new HashMap<>();
checkInfo.put("signId", signId);//签到签退标识
checkInfo.put("signDate", signdate);//签到签退日期
checkInfo.put("signTime", signtime);//签到签退时间
idx++;
if(idx==1){//第一条算签到
checkInfo.put("signType", "1");
lsCheckInfo.add(checkInfo);
}else if(idx==rs.getCounts()){//最后一条算签退
checkInfo.put("signType", "2");
lsCheckInfo.add(checkInfo);
}
}
return lsCheckInfo;
}
}

@ -0,0 +1,57 @@
package com.engine.kq.biz;
import com.engine.kq.log.KQLog;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
public class KQFormatThread extends com.weaver.util.threadPool.entity.LocalRunnable {
private String id;
private String resourceid;
private String kqdate;
private KQLog kqLog = new KQLog();
@Override
public void execute() {
RecordSet rs = new RecordSet();
//更新已处理的记录
String key = this.kqdate+ "|"+ this.resourceid;
try {
kqLog.info("执行KQFormatThread this.resourceid=="+this.resourceid+"this.kqdate=="+this.kqdate);
KQFormatData kqFormatData = new KQFormatData();
kqFormatData.formatKqDate(this.resourceid, this.kqdate);
boolean isremove = KQFormatJob.kqformatIds.remove(key);
if(isremove){
rs.execute("update kq_format_pool set status=1 where id=" + this.id);
}
} catch (Exception e) {
KQFormatJob.kqformatIds.remove(key);
kqLog.info(e);
writeLog(e);
}
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getResourceid() {
return resourceid;
}
public void setResourceid(String resourceid) {
this.resourceid = resourceid;
}
public String getKqdate() {
return kqdate;
}
public void setKqdate(String kqdate) {
this.kqdate = kqdate;
}
}

@ -0,0 +1,911 @@
package com.engine.kq.biz;
import com.alibaba.fastjson.JSONObject;
import com.engine.kq.log.KQLog;
import com.engine.kq.util.KQTransMethod;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.resource.ResourceComInfo;
import weaver.systeminfo.SystemEnv;
import java.util.*;
public class KQLeaveRulesBiz {
/**
*
*/
private static KQLog logger = new KQLog();
/**
* ID
*
* @param ruleId ID
* @return
*/
public static String getLeaveName(String ruleId) {
String leaveName = "";
KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo();
leaveName = kqLeaveRulesComInfo.getLeaveName(ruleId);
return leaveName;
}
/**
*
*
* @param ruleId
* @return
*/
public static boolean getBalanceEnable(String ruleId) {
int balanceEnable = 0;
KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo();
balanceEnable = Util.getIntValue(kqLeaveRulesComInfo.getBalanceEnable(ruleId), 0);
if (balanceEnable == 1) {
return true;
} else {
return false;
}
}
/**
*
* 1-
* 2-
* 3-
* 4-
*
*
* @param ruleId ID
* @return
*/
public static int getMinimumUnit(String ruleId) {
int minimumUnit = -1;//最小请假单位
KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo();
minimumUnit = Util.getIntValue(kqLeaveRulesComInfo.getMinimumUnit(ruleId), -1);
return minimumUnit;
}
/**
*
* 1-
* 2-
*
*
* @param ruleId ID
* @return
*/
public static int getComputingMode(String ruleId) {
int computingMode = -1;//计算请假时长方式
KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo();
computingMode = Util.getIntValue(kqLeaveRulesComInfo.getComputingMode(ruleId), -1);
return computingMode;
}
/**
*
* 0-
* 1-
* 2-
* 1,2-
*
* @param ruleId ID
* @return
*/
public static String getFilterHolidays(String ruleId) {
KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo();
String filterHolidays = Util.null2s(kqLeaveRulesComInfo.getFilterHolidays(ruleId), "0");
return filterHolidays;
}
/**
*
*
* @param ruleId ID
* @return
*/
public static String getHoursToDay(String ruleId) {
double hoursToDay = -1;//日折算时长
int computingMode = -1;//计算请假时长方式
int minimumUnit = -1;//最小请假单位
KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo();
hoursToDay = Util.getDoubleValue(kqLeaveRulesComInfo.getHoursToDay(ruleId), -1);
computingMode = Util.getIntValue(kqLeaveRulesComInfo.getComputingMode(ruleId), -1);
minimumUnit = Util.getIntValue(kqLeaveRulesComInfo.getMinimumUnit(ruleId), -1);
if (computingMode != 2) {
hoursToDay = -1;
}
return String.format("%.2f", hoursToDay);
}
/**
* 1-
* 2-
* 3-
* 4-
*
* @param minimumUnit
* @param lan
* @return
*/
public static String getMinimumUnitName(String minimumUnit, int lan) {
String minimumUnitName = "";
switch (minimumUnit) {
case "1":
minimumUnitName = SystemEnv.getHtmlLabelName(1925, lan);
break;
case "2":
minimumUnitName = SystemEnv.getHtmlLabelName(1925, lan);
break;
case "3":
case "5":
case "6":
minimumUnitName = SystemEnv.getHtmlLabelName(391, lan);
break;
case "4":
minimumUnitName = SystemEnv.getHtmlLabelName(1925, lan);
break;
default:
break;
}
return minimumUnitName;
}
/**
*
* unitType1-2-3-4--1
*
* @return
*/
public static List<Map<String, Object>> getAllLeaveRules() {
Map<String, Object> ruleMap = new HashMap<String, Object>();
List<Map<String, Object>> ruleList = new ArrayList<Map<String, Object>>();
KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo();
kqLeaveRulesComInfo.setTofirstRow();
while (kqLeaveRulesComInfo.next()) {
if (kqLeaveRulesComInfo.getIsEnable().equals("1")) {
ruleMap = new HashMap<String, Object>();
ruleMap.put("id", kqLeaveRulesComInfo.getId());
ruleMap.put("name", kqLeaveRulesComInfo.getLeaveName());
ruleMap.put("unitType", kqLeaveRulesComInfo.getMinimumUnit());
ruleMap.put("proportion", kqLeaveRulesComInfo.getProportion());
ruleList.add(ruleMap);
}
}
return ruleList;
}
/**
* ID
*
* @param resourceId ID
* @return
*/
public static String getAllLeaveRulesByUserId(String resourceId, String languageId) {
String resultStr = "";
try {
ResourceComInfo resourceComInfo = new ResourceComInfo();
String subcomId = resourceComInfo.getSubCompanyID(resourceId);
List<String> tempList = new ArrayList<String>();
Map<String, Object> itemMap = new HashMap<String, Object>();
List<Object> itemList = new ArrayList<Object>();
String sql = "select * from kq_leaveRules where 1=1 and (isDelete is null or isDelete <>1) and isEnable=1";
RecordSet recordSet = new RecordSet();
recordSet.executeQuery(sql);
while (recordSet.next()) {
String scopeType = recordSet.getString("scopeType");
String scopeValue = recordSet.getString("scopeValue");
String leaveName = recordSet.getString("leaveName");
String id = recordSet.getString("id");
if (scopeType.equals("1")) {
tempList = Util.TokenizerString(scopeValue, ",");
if (!tempList.contains(subcomId)) {
continue;
}
}
itemMap = new HashMap<String, Object>();
itemMap.put("name", Util.formatMultiLang(leaveName, languageId));
itemMap.put("id", id);
itemList.add(itemMap);
}
resultStr = JSONObject.toJSONString(itemList);
} catch (Exception e) {
e.printStackTrace();
}
return resultStr;
}
/**
*
*
* @param ruleId
* @return
*/
public static boolean initAnnualLeave(int ruleId) {
boolean isInitSuccess = false;
try {
/*判断年假是否初始化过*/
RecordSet recordSet = new RecordSet();
String sql = "select * from kq_LeaveRules where (isDelete is null or isDelete<>1) and id=" + ruleId;
recordSet.executeQuery(sql);
boolean initialized = recordSet.getCounts() > 0;
/*没有初始化过就新建,已经初始化过就更新*/
if (initialized) {
String updateSql = "update kq_LeaveRules set leaveName='年假-初始化',scopeType=0,scopeValue='',minimumUnit=1,hoursToDay=8,computingMode=1,balanceEnable=1," +
"isDelete=0,isEnable=1,leaveCode='annualLeave' where id=" + ruleId;
isInitSuccess = recordSet.executeUpdate(updateSql);
if (!isInitSuccess) {
return false;
}
String deleteDetailSql = "delete from kq_LeaveRulesDetail where scopeType=0 and ruleId=" + ruleId;
recordSet.executeUpdate(deleteDetailSql);
String insertDetailSql = "insert into kq_LeaveRulesDetail(ruleName,ruleId,scopeType,scopeValue,distributionMode,annualAmount,priority,validityRule,expirationMonth,expirationDay,extensionEnable,extendedDays,releaseRule,calcMethod)" +
"values('年假-总部规则'," + ruleId + ",0,'',3,0,1,0,'','',0,0,0,0)";
isInitSuccess = recordSet.executeUpdate(insertDetailSql);
if (!isInitSuccess) {
return false;
}
} else {
KQTransMethod kqTransMethod = new KQTransMethod();
int nextId = kqTransMethod.getNextId();
String insertSql = "insert into kq_LeaveRules(id,leaveName,scopeType,scopeValue,minimumUnit,hoursToDay,computingMode,balanceEnable,isDelete,isEnable,leaveCode)" +
"values(" + nextId + ",'年假-初始化',0,'',1,8,1,1,0,1,'annualLeave')";
isInitSuccess = recordSet.executeUpdate(insertSql);
if (!isInitSuccess) {
return false;
}
String insertDetailSql = "insert into kq_LeaveRulesDetail(ruleName,ruleId,scopeType,scopeValue,distributionMode,annualAmount,priority,validityRule,expirationMonth,expirationDay,extensionEnable,extendedDays,releaseRule,calcMethod)" +
"values('年假-总部规则'," + nextId + ",0,'',3,0,1,0,'','',0,0,0,0)";
isInitSuccess = recordSet.executeUpdate(insertDetailSql);
if (!isInitSuccess) {
return false;
}
String historySql = "update kq_initHistory set annualLeave=" + nextId + " where id=1";
isInitSuccess = recordSet.executeUpdate(historySql);
ruleId = nextId;
}
String detailId = "";
sql = "select * from kq_LeaveRulesDetail where scopeType=0 and ruleId=" + ruleId;
recordSet.executeQuery(sql);
if (recordSet.next()) {
detailId = recordSet.getString("id");
}
if (detailId.equals("")) {
return false;
}
/*先删除原来的明细记录,在插入新的明细记录*/
String detailSql = "delete from kq_WorkingAgeToLeave where leaveRulesId=" + detailId;
isInitSuccess = recordSet.executeUpdate(detailSql);
if (!isInitSuccess) {
sql = "delete from kq_LeaveRules where leaveRulesId=" + detailId;
recordSet.executeUpdate(sql);
return false;
}
/*插入明细记录*/
detailSql = "insert into kq_WorkingAgeToLeave(leaveRulesId,lowerLimit,upperLimit,amount) values(?,?,?,?)";
isInitSuccess = recordSet.executeUpdate(detailSql, detailId, 0, 1, 0);
isInitSuccess = recordSet.executeUpdate(detailSql, detailId, 1, 10, 5);
isInitSuccess = recordSet.executeUpdate(detailSql, detailId, 10, 20, 10);
isInitSuccess = recordSet.executeUpdate(detailSql, detailId, 20, 9999, 15);
} catch (Exception e) {
logger.info(e.getMessage());
}
return isInitSuccess;
}
/**
*
*
* @param ruleId
* @return
*/
public static boolean initPaidCompassionateLeave(int ruleId) {
/*判断是否初始化过*/
RecordSet recordSet = new RecordSet();
RecordSet rs = new RecordSet();
String sql = "select * from kq_LeaveRules where (isDelete is null or isDelete<>1) and id=" + ruleId;
recordSet.executeQuery(sql);
boolean initialized = recordSet.getCounts() > 0;
/*没有初始化过就新建,已经初始化过就更新*/
boolean isInitSuccess = false;
if (initialized) {
String updateSql = "update kq_LeaveRules set leaveName='带薪事假-初始化',scopeType=0,scopeValue='',minimumUnit=1,hoursToDay=8,computingMode=1,balanceEnable=0," +
"isDelete=0,isEnable=1,leaveCode='paidCompassionateLeave' where id=" + ruleId;
isInitSuccess = rs.executeUpdate(updateSql);
if (!isInitSuccess) {
return false;
}
} else {
KQTransMethod kqTransMethod = new KQTransMethod();
int nextId = kqTransMethod.getNextId();
String insertSql = "insert into kq_LeaveRules(id,leaveName,scopeType,scopeValue,minimumUnit,hoursToDay,computingMode,balanceEnable,isDelete,isEnable,leaveCode)" +
"values(" + nextId + ",'带薪事假-初始化',0,'',1,8,1,0,0,1,'paidCompassionateLeave')";
isInitSuccess = rs.executeUpdate(insertSql);
if (!isInitSuccess) {
return false;
}
String historySql = "update kq_initHistory set paidCompassionateLeave=" + nextId + " where id=1";
isInitSuccess = rs.executeUpdate(historySql);
}
return isInitSuccess;
}
/**
*
*
* @param ruleId
* @return
*/
public static boolean initPaidSickLeave(int ruleId) {
/*判断是否初始化过*/
RecordSet recordSet = new RecordSet();
RecordSet rs = new RecordSet();
String sql = "select * from kq_LeaveRules where (isDelete is null or isDelete<>1) and id=" + ruleId;
recordSet.executeQuery(sql);
boolean initialized = recordSet.getCounts() > 0;
/*没有初始化过就新建,已经初始化过就更新*/
boolean isInitSuccess = false;
if (initialized) {
String updateSql = "update kq_LeaveRules set leaveName='带薪病假-初始化',scopeType=0,scopeValue='',minimumUnit=1,hoursToDay=8,computingMode=1,balanceEnable=0," +
"isDelete=0,isEnable=1,leaveCode='paidSickLeave' where id=" + ruleId;
isInitSuccess = rs.executeUpdate(updateSql);
if (!isInitSuccess) {
return false;
}
} else {
KQTransMethod kqTransMethod = new KQTransMethod();
int nextId = kqTransMethod.getNextId();
String insertSql = "insert into kq_LeaveRules(id,leaveName,scopeType,scopeValue,minimumUnit,hoursToDay,computingMode,balanceEnable,isDelete,isEnable,leaveCode)" +
"values(" + nextId + ",'带薪病假-初始化',0,'',1,8,1,0,0,1,'paidSickLeave')";
isInitSuccess = rs.executeUpdate(insertSql);
if (!isInitSuccess) {
return false;
}
String historySql = "update kq_initHistory set paidSickLeave=" + nextId + " where id=1";
isInitSuccess = rs.executeUpdate(historySql);
}
return isInitSuccess;
}
/**
*
*
* @param ruleId
* @return
*/
public static boolean initVacationLeave(int ruleId) {
/*判断是否初始化过*/
RecordSet recordSet = new RecordSet();
RecordSet rs = new RecordSet();
String sql = "select * from kq_LeaveRules where (isDelete is null or isDelete<>1) and id=" + ruleId;
recordSet.executeQuery(sql);
boolean initialized = recordSet.getCounts() > 0;
/*没有初始化过就新建,已经初始化过就更新*/
boolean isInitSuccess = false;
if (initialized) {
String updateSql = "update kq_LeaveRules set leaveName='调休-初始化',scopeType=0,scopeValue='',minimumUnit=1,hoursToDay=8,computingMode=1,balanceEnable=1," +
"isDelete=0,isEnable=1,leaveCode='vacationLeave' where id=" + ruleId;
isInitSuccess = rs.executeUpdate(updateSql);
if (!isInitSuccess) {
return false;
}
String deleteDetailSql = "delete from kq_LeaveRulesDetail where scopeType=0 and ruleId=" + ruleId;
rs.executeUpdate(deleteDetailSql);
String insertDetailSql = "insert into kq_LeaveRulesDetail(ruleName,ruleId,scopeType,scopeValue,distributionMode,annualAmount,priority,validityRule,expirationMonth,expirationDay,extensionEnable,extendedDays,releaseRule,calcMethod)" +
"values('调休-总部规则'," + ruleId + ",0,'',5,0,1,0,'','',0,0,0,0)";
isInitSuccess = rs.executeUpdate(insertDetailSql);
if (!isInitSuccess) {
return false;
}
} else {
/*判断系统中是否已经存在调休了,如果已存在,则不允许新建新的调休假期*/
sql = "select * from kq_LeaveRules where (isDelete is null or isDelete<>1) and id in (select ruleId from kq_LeaveRulesDetail where (isDelete is null or isDelete<>1) and distributionMode=5)";
rs.executeQuery(sql);
if (rs.getCounts() > 0) {
return false;
}
KQTransMethod kqTransMethod = new KQTransMethod();
int nextId = kqTransMethod.getNextId();
String insertSql = "insert into kq_LeaveRules(id,leaveName,scopeType,scopeValue,minimumUnit,hoursToDay,computingMode,balanceEnable,isDelete,isEnable,leaveCode)" +
"values(" + nextId + ",'调休-初始化',0,'',1,8,1,1,0,1,'vacationLeave')";
isInitSuccess = rs.executeUpdate(insertSql);
if (!isInitSuccess) {
return false;
}
String insertDetailSql = "insert into kq_LeaveRulesDetail(ruleName,ruleId,scopeType,scopeValue,distributionMode,annualAmount,priority,validityRule,expirationMonth,expirationDay,extensionEnable,extendedDays,releaseRule,calcMethod)" +
"values('调休-总部规则'," + nextId + ",0,'',5,0,1,0,'','',0,0,0,0)";
isInitSuccess = rs.executeUpdate(insertDetailSql);
if (!isInitSuccess) {
return false;
}
String historySql = "update kq_initHistory set vacationLeave=" + nextId + " where id=1";
isInitSuccess = rs.executeUpdate(historySql);
}
return isInitSuccess;
}
/**
*
*
* @param ruleId
* @return
*/
public static boolean initCompassionateLeave(int ruleId) {
/*判断是否初始化过*/
RecordSet recordSet = new RecordSet();
RecordSet rs = new RecordSet();
String sql = "select * from kq_LeaveRules where (isDelete is null or isDelete<>1) and id=" + ruleId;
recordSet.executeQuery(sql);
boolean initialized = recordSet.getCounts() > 0;
/*没有初始化过就新建,已经初始化过就更新*/
boolean isInitSuccess = false;
if (initialized) {
String updateSql = "update kq_LeaveRules set leaveName='事假-初始化',scopeType=0,scopeValue='',minimumUnit=1,hoursToDay=8,computingMode=1,balanceEnable=0," +
"isDelete=0,isEnable=1,leaveCode='compassionateLeave' where id=" + ruleId;
isInitSuccess = rs.executeUpdate(updateSql);
if (!isInitSuccess) {
return false;
}
} else {
KQTransMethod kqTransMethod = new KQTransMethod();
int nextId = kqTransMethod.getNextId();
String insertSql = "insert into kq_LeaveRules(id,leaveName,scopeType,scopeValue,minimumUnit,hoursToDay,computingMode,balanceEnable,isDelete,isEnable,leaveCode)" +
"values(" + nextId + ",'事假-初始化',0,'',1,8,1,0,0,1,'compassionateLeave')";
isInitSuccess = rs.executeUpdate(insertSql);
if (!isInitSuccess) {
return false;
}
String historySql = "update kq_initHistory set compassionateLeave=" + nextId + " where id=1";
isInitSuccess = rs.executeUpdate(historySql);
}
return isInitSuccess;
}
/**
*
*
* @param ruleId
* @return
*/
public static boolean initSickLeave(int ruleId) {
/*判断是否初始化过*/
RecordSet recordSet = new RecordSet();
RecordSet rs = new RecordSet();
String sql = "select * from kq_LeaveRules where (isDelete is null or isDelete<>1) and id=" + ruleId;
recordSet.executeQuery(sql);
boolean initialized = recordSet.getCounts() > 0;
/*没有初始化过就新建,已经初始化过就更新*/
boolean isInitSuccess = false;
if (initialized) {
String updateSql = "update kq_LeaveRules set leaveName='病假-初始化',scopeType=0,scopeValue='',minimumUnit=1,hoursToDay=8,computingMode=1,balanceEnable=0," +
"isDelete=0,isEnable=1,leaveCode='sickLeave' where id=" + ruleId;
isInitSuccess = rs.executeUpdate(updateSql);
if (!isInitSuccess) {
return false;
}
} else {
KQTransMethod kqTransMethod = new KQTransMethod();
int nextId = kqTransMethod.getNextId();
String insertSql = "insert into kq_LeaveRules(id,leaveName,scopeType,scopeValue,minimumUnit,hoursToDay,computingMode,balanceEnable,isDelete,isEnable,leaveCode)" +
"values(" + nextId + ",'病假-初始化',0,'',1,8,1,0,0,1,'sickLeave')";
isInitSuccess = rs.executeUpdate(insertSql);
if (!isInitSuccess) {
return false;
}
String historySql = "update kq_initHistory set sickLeave=" + nextId + " where id=1";
isInitSuccess = rs.executeUpdate(historySql);
}
return isInitSuccess;
}
/**
*
*
* @param ruleId
* @return
*/
public static boolean initMaternityLeave(int ruleId) {
/*判断是否初始化过*/
RecordSet recordSet = new RecordSet();
RecordSet rs = new RecordSet();
String sql = "select * from kq_LeaveRules where (isDelete is null or isDelete<>1) and id=" + ruleId;
recordSet.executeQuery(sql);
boolean initialized = recordSet.getCounts() > 0;
/*没有初始化过就新建,已经初始化过就更新*/
boolean isInitSuccess = false;
if (initialized) {
String updateSql = "update kq_LeaveRules set leaveName='产假-初始化',scopeType=0,scopeValue='',minimumUnit=1,hoursToDay=8,computingMode=2,balanceEnable=0," +
"isDelete=0,isEnable=1,leaveCode='maternityLeave' where id=" + ruleId;
isInitSuccess = rs.executeUpdate(updateSql);
if (!isInitSuccess) {
return false;
}
} else {
KQTransMethod kqTransMethod = new KQTransMethod();
int nextId = kqTransMethod.getNextId();
String insertSql = "insert into kq_LeaveRules(id,leaveName,scopeType,scopeValue,minimumUnit,hoursToDay,computingMode,balanceEnable,isDelete,isEnable,leaveCode)" +
"values(" + nextId + ",'产假-初始化',0,'',1,8,2,0,0,1,'maternityLeave')";
isInitSuccess = rs.executeUpdate(insertSql);
if (!isInitSuccess) {
return false;
}
String historySql = "update kq_initHistory set maternityLeave=" + nextId + " where id=1";
isInitSuccess = rs.executeUpdate(historySql);
}
return isInitSuccess;
}
/**
*
*
* @param ruleId
* @return
*/
public static boolean initPaternityLeave(int ruleId) {
/*判断是否初始化过*/
RecordSet recordSet = new RecordSet();
RecordSet rs = new RecordSet();
String sql = "select * from kq_LeaveRules where (isDelete is null or isDelete<>1) and id=" + ruleId;
recordSet.executeQuery(sql);
boolean initialized = recordSet.getCounts() > 0;
/*没有初始化过就新建,已经初始化过就更新*/
boolean isInitSuccess = false;
if (recordSet.next()) {
String updateSql = "update kq_LeaveRules set leaveName='陪产假-初始化',scopeType=0,scopeValue='',minimumUnit=1,hoursToDay=8,computingMode=2,balanceEnable=0," +
"isDelete=0,isEnable=1,leaveCode='paternityLeave' where id=" + ruleId;
isInitSuccess = rs.executeUpdate(updateSql);
if (!isInitSuccess) {
return false;
}
} else {
KQTransMethod kqTransMethod = new KQTransMethod();
int nextId = kqTransMethod.getNextId();
String insertSql = "insert into kq_LeaveRules(id,leaveName,scopeType,scopeValue,minimumUnit,hoursToDay,computingMode,balanceEnable,isDelete,isEnable,leaveCode)" +
"values(" + nextId + ",'陪产假-初始化',0,'',1,8,2,0,0,1,'paternityLeave')";
isInitSuccess = rs.executeUpdate(insertSql);
if (!isInitSuccess) {
return false;
}
String historySql = "update kq_initHistory set paternityLeave=" + nextId + " where id=1";
isInitSuccess = rs.executeUpdate(historySql);
}
return isInitSuccess;
}
/**
*
*
* @param ruleId
* @return
*/
public static boolean initMarriageLeave(int ruleId) {
/*判断是否初始化过*/
RecordSet recordSet = new RecordSet();
RecordSet rs = new RecordSet();
String sql = "select * from kq_LeaveRules where (isDelete is null or isDelete<>1) and id=" + ruleId;
recordSet.executeQuery(sql);
boolean initialized = recordSet.getCounts() > 0;
/*没有初始化过就新建,已经初始化过就更新*/
boolean isInitSuccess = false;
if (initialized) {
String updateSql = "update kq_LeaveRules set leaveName='婚假-初始化',scopeType=0,scopeValue='',minimumUnit=1,hoursToDay=8,computingMode=2,balanceEnable=0," +
"isDelete=0,isEnable=1,leaveCode='marriageLeave' where id=" + ruleId;
isInitSuccess = rs.executeUpdate(updateSql);
if (!isInitSuccess) {
return false;
}
} else {
KQTransMethod kqTransMethod = new KQTransMethod();
int nextId = kqTransMethod.getNextId();
String insertSql = "insert into kq_LeaveRules(id,leaveName,scopeType,scopeValue,minimumUnit,hoursToDay,computingMode,balanceEnable,isDelete,isEnable,leaveCode)" +
"values(" + nextId + ",'婚假-初始化',0,'',1,8,2,0,0,1,'marriageLeave')";
isInitSuccess = rs.executeUpdate(insertSql);
if (!isInitSuccess) {
return false;
}
String historySql = "update kq_initHistory set marriageLeave=" + nextId + " where id=1";
isInitSuccess = rs.executeUpdate(historySql);
}
return isInitSuccess;
}
/**
*
*
* @param ruleId
* @return
*/
public static boolean initFuneralLeave(int ruleId) {
/*判断是否初始化过*/
RecordSet recordSet = new RecordSet();
RecordSet rs = new RecordSet();
String sql = "select * from kq_LeaveRules where (isDelete is null or isDelete<>1) and id=" + ruleId;
recordSet.executeQuery(sql);
boolean initialized = recordSet.getCounts() > 0;
/*没有初始化过就新建,已经初始化过就更新*/
boolean isInitSuccess = false;
if (initialized) {
String updateSql = "update kq_LeaveRules set leaveName='丧假-初始化',scopeType=0,scopeValue='',minimumUnit=1,hoursToDay=8,computingMode=1,balanceEnable=0," +
"isDelete=0,isEnable=1,leaveCode='funeralLeave' where id=" + ruleId;
isInitSuccess = rs.executeUpdate(updateSql);
if (!isInitSuccess) {
return false;
}
} else {
KQTransMethod kqTransMethod = new KQTransMethod();
int nextId = kqTransMethod.getNextId();
String insertSql = "insert into kq_LeaveRules(id,leaveName,scopeType,scopeValue,minimumUnit,hoursToDay,computingMode,balanceEnable,isDelete,isEnable,leaveCode)" +
"values(" + nextId + ",'丧假-初始化',0,'',1,8,1,0,0,1,'funeralLeave')";
isInitSuccess = rs.executeUpdate(insertSql);
if (!isInitSuccess) {
return false;
}
String historySql = "update kq_initHistory set funeralLeave=" + nextId + " where id=1";
isInitSuccess = rs.executeUpdate(historySql);
}
return isInitSuccess;
}
/**
*
*
* @param ruleId
* @return
*/
public static boolean initBreastfeedingLeave(int ruleId) {
/*判断是否初始化过*/
RecordSet recordSet = new RecordSet();
RecordSet rs = new RecordSet();
String sql = "select * from kq_LeaveRules where (isDelete is null or isDelete<>1) and id=" + ruleId;
recordSet.executeQuery(sql);
boolean initialized = recordSet.getCounts() > 0;
/*没有初始化过就新建,已经初始化过就更新*/
boolean isInitSuccess = false;
if (initialized) {
String updateSql = "update kq_LeaveRules set leaveName='哺乳假-初始化',scopeType=0,scopeValue='',minimumUnit=1,hoursToDay=8,computingMode=1,balanceEnable=0," +
"isDelete=0,isEnable=1,leaveCode='breastfeedingLeave' where id=" + ruleId;
isInitSuccess = rs.executeUpdate(updateSql);
if (!isInitSuccess) {
return false;
}
} else {
KQTransMethod kqTransMethod = new KQTransMethod();
int nextId = kqTransMethod.getNextId();
String insertSql = "insert into kq_LeaveRules(id,leaveName,scopeType,scopeValue,minimumUnit,hoursToDay,computingMode,balanceEnable,isDelete,isEnable,leaveCode)" +
"values(" + nextId + ",'哺乳假-初始化',0,'',1,8,1,0,0,1,'breastfeedingLeave')";
isInitSuccess = rs.executeUpdate(insertSql);
if (!isInitSuccess) {
return false;
}
String historySql = "update kq_initHistory set breastfeedingLeave=" + nextId + " where id=1";
isInitSuccess = rs.executeUpdate(historySql);
}
return isInitSuccess;
}
/**
* IDID(E)
*
* @param resourceId ID
* @param leaveName
* @return
*/
public static List<Object> getLeaveRuleIdByName(String resourceId, String leaveName) {
List<Object> dataList = new ArrayList<Object>();
try {
ResourceComInfo resourceComInfo = new ResourceComInfo();
String subcomId = resourceComInfo.getSubCompanyID(resourceId);
Map<String, Object> dataMap = new HashMap<String, Object>();
String sql = "select * from kq_LeaveRules where (isDelete is null or isDelete <>1) and isEnable=1 and leaveName like '%" + leaveName + "%'";
RecordSet recordSet = new RecordSet();
recordSet.executeQuery(sql);
while (recordSet.next()) {
int scopeType = Util.getIntValue(recordSet.getString("scopeType"), 0);
String scopeValue = Util.null2String(recordSet.getString("scopeValue"));
if (scopeType == 1) {
List<String> tempList = Util.TokenizerString(scopeValue, ",");
if (!tempList.contains(subcomId)) {
continue;
}
}
dataMap = new HashMap<String, Object>();
dataMap.put("ruleId", recordSet.getString("id"));
dataMap.put("name", Util.formatMultiLang(recordSet.getString("leaveName"), "7"));
dataList.add(dataMap);
}
} catch (Exception e) {
e.printStackTrace();
}
return dataList;
}
/**
* +
*
* @param ruleId id(kq_LeaveRulesID)
* @return true--false--
*/
public static boolean isMixMode(String ruleId) {
boolean flag = false;
try {
String sql = "select * from kq_LeaveRulesDetail where (isDelete is null or isDelete<>1) and distributionMode=6 and ruleId=?";
RecordSet recordSet = new RecordSet();
recordSet.executeQuery(sql, ruleId);
if (recordSet.next()) {
flag = true;
}
} catch (Exception e) {
logger.info(e.getMessage());
}
return flag;
}
/**
* ()
*
* @return
*/
public static String getColor() {
String color = "";
try {
StringBuffer result = new StringBuffer();
for (int i = 0; i < 6; i++) {
//随机生成0-15的数值并转换成16进制
result.append(Integer.toHexString(new Random().nextInt(16)));
}
color = "#" + result.toString().toUpperCase();
} catch (Exception e) {
System.out.println("获取16进制字符串异常返回默认...");
color = "#00CCCC";
}
return color;
}
/**
*
* @param ruleId
* @return
*/
public static boolean isTiaoXiu(String ruleId){
boolean flag = false;
try {
String sql = "select * from kq_LeaveRulesDetail where (isDelete is null or isDelete<>1) and distributionMode=5 and ruleId=?";
RecordSet recordSet = new RecordSet();
recordSet.executeQuery(sql, ruleId);
if (recordSet.next()) {
flag = true;
}
} catch (Exception e) {
logger.info(e.getMessage());
}
return flag;
}
/**
*
* @param ruleId
* @return
*/
public static boolean isTiaoXiu2(String ruleId){
boolean flag = false;
try {
String sql = "select * from kq_LeaveRulesDetail where (isDelete is null or isDelete<>1) and distributionMode in(9,10) and ruleId=?";
RecordSet recordSet = new RecordSet();
recordSet.executeQuery(sql, ruleId);
if (recordSet.next()) {
flag = true;
}
} catch (Exception e) {
logger.info(e.getMessage());
}
return flag;
}
/**
*
* @param ruleId
* @return
*/
public static boolean isTiaoXiuByMode(String ruleId,int distributionMode){
boolean flag = false;
try {
String sql = "select * from kq_LeaveRulesDetail where (isDelete is null or isDelete<>1) and distributionMode=? and ruleId=?";
RecordSet recordSet = new RecordSet();
recordSet.executeQuery(sql, distributionMode,ruleId);
if (recordSet.next()) {
flag = true;
}
} catch (Exception e) {
logger.info(e.getMessage());
}
return flag;
}
/**
*
* @param ruleId
* @return
*/
public static boolean isLeaveOfParental(String ruleId){
boolean flag = false;
try {
String sql = "select * from kq_LeaveRulesDetail where (isDelete is null or isDelete<>1) and distributionMode=8 and ruleId=?";
RecordSet recordSet = new RecordSet();
recordSet.executeQuery(sql, ruleId);
if (recordSet.next()) {
flag = true;
}
} catch (Exception e) {
logger.info(e.getMessage());
}
return flag;
}
/**
* 1- 2-
* @param ruleId
* @return
*/
public static int getTimeselection(String ruleId) {
int timeselection = 1;//最小请假单位
KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo();
timeselection = Util.getIntValue(kqLeaveRulesComInfo.getTimeSelection(ruleId), 1);
return timeselection;
}
}

@ -0,0 +1,848 @@
package com.engine.kq.biz;
import com.alibaba.fastjson.JSONObject;
import com.engine.kq.biz.chain.shiftinfo.ShiftInfoBean;
import com.engine.kq.entity.KQOvertimeRulesDetailEntity;
import com.engine.kq.log.KQLog;
import com.engine.kq.util.KQDurationCalculatorUtil;
import com.engine.kq.wfset.bean.OvertimeBalanceTimeBean;
import com.engine.kq.wfset.bean.SplitBean;
import com.engine.kq.wfset.util.KQFlowUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.springframework.beans.BeanUtils;
import weaver.common.StringUtil;
import weaver.general.Util;
import weaver.hrm.User;
/**
*
*
*/
public class KQOverTimeFlowBiz {
private KQLog kqLog = new KQLog();
/**
*
*
*
* A-B A24A
* A-A24A
* -A0A
*
*
*
* @param splitBean
* @param splitBeans
*/
public void getSplitDurationBean_new(SplitBean splitBean,List<SplitBean> splitBeans) {
try{
long a = System.currentTimeMillis();
double oneDayHour = KQFlowUtil.getOneDayHour(splitBean.getDurationTypeEnum(),"");
int workmins = (int)(oneDayHour * 60);
String resourceid = splitBean.getResourceId();
String fromDate = splitBean.getFromdatedb();
String toDate = splitBean.getTodatedb();
String overtime_type = splitBean.getOvertime_type();
User tmp_user = User.getUser(Util.getIntValue(resourceid), 0);
KQShiftManagementComInfo kQShiftManagementComInfo = new KQShiftManagementComInfo();
LocalDate localFromDate = LocalDate.parse(fromDate);
LocalDate localToDate = LocalDate.parse(toDate);
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate preFromDate = localFromDate.minusDays(1);
KQTimesArrayComInfo kqTimesArrayComInfo = new KQTimesArrayComInfo();
KQOvertimeRulesBiz kqOvertimeRulesBiz = new KQOvertimeRulesBiz();
KQOverTimeRuleCalBiz kqOverTimeRuleCalBiz = new KQOverTimeRuleCalBiz();
Map<String,Integer> changeTypeMap = Maps.newHashMap();
Map<String, KQOvertimeRulesDetailEntity> overRulesDetailMap = Maps.newHashMap();
Map<String,List<String[]>> restTimeMap = Maps.newHashMap();
Map<String,Integer> computingModeMap = Maps.newHashMap();
kqOverTimeRuleCalBiz.getOverTimeDataMap(resourceid, fromDate, toDate, dateFormatter,changeTypeMap,overRulesDetailMap,restTimeMap,computingModeMap);
if(overRulesDetailMap.isEmpty()){
return;
}
String fromTime = splitBean.getFromtimedb();
String toTime = splitBean.getTotimedb();
long betweenDays = localToDate.toEpochDay() - preFromDate.toEpochDay();
//默认是从加班开始日期的前一天开始计算 需要特殊处理的就三个情况i=0的时候i=1的时候就是加班流程开始日期那一天i=最后一天就是加班流程结束日期那一天
for (int i = 0; i <= betweenDays; i++) {
SplitBean overSplitBean = new SplitBean();
//然后把bean重新赋值下根据拆分后的时间
BeanUtils.copyProperties(splitBean, overSplitBean);
//从加班流程开始的前一天开始算归属
LocalDate curLocalDate = preFromDate.plusDays(i);
String splitDate = curLocalDate.format(dateFormatter);
String preSplitDate = LocalDate.parse(splitDate).minusDays(1).format(dateFormatter);
LocalDate nextLocalDate = curLocalDate.plusDays(1);
String nextSplitDate = nextLocalDate.format(dateFormatter);
String change_key = splitDate+"_"+resourceid;
String pre_change_key = preSplitDate+"_"+resourceid;
String next_change_key = nextSplitDate+"_"+resourceid;
int changeType = Util.getIntValue(""+changeTypeMap.get(change_key),-1);
int preChangeType = Util.getIntValue(""+changeTypeMap.get(pre_change_key),-1);
int next_changeType = Util.getIntValue(""+changeTypeMap.get(next_change_key),-1);
boolean shouldAcross = false;
String changeType_key = splitDate+"_"+changeType;
String preChangeType_key = preSplitDate+"_"+preChangeType;
String nextChangeType_key = nextSplitDate+"_"+next_changeType;
if(!computingModeMap.containsKey(changeType_key)){
continue;
}
int computingMode = computingModeMap.get(changeType_key);
if(computingMode == 3){
//如果是纯打卡为主的不生成加班
continue;
}
int[] initArrays = kqTimesArrayComInfo.getInitArr();
//当前日期的加班分割点 分割点都是次日的
String overtime_cut_point = "";
int before_startTime = 0;
int startTime = 0;
int curMins = 0 ;
//排除休息类型
int restTimeType = -1;
String next_beginwork_time = "";
String cur_beginwork_time = "";
String serialid = "";
boolean isRestshift_next = false;
boolean isRestshift = false;
String tmp_next_beginwork_time = "";
String tmp_cur_beginwork_time = "";
//需要知道明日的类型:如果今天是工作日的话,那么今天的加班临界点可能和明日的上班时间冲突,需要知道明日的上班时间进行比较,
// 如果今天是休息日,那么明天如果是工作日的话,默认规则下,明天的上班前都是属于今天的加班区间
if(next_changeType == 2){
ShiftInfoBean next_shiftInfoBean = KQDurationCalculatorUtil.getWorkTime(resourceid, nextSplitDate, false);
if(next_shiftInfoBean != null){
List<int[]> workLongTimeIndex = next_shiftInfoBean.getWorkLongTimeIndex();
List<int[]> real_workLongTimeIndex = Lists.newArrayList();
get_real_workLongTimeIndex(workLongTimeIndex,real_workLongTimeIndex,next_shiftInfoBean,kqTimesArrayComInfo,splitBean);
if(real_workLongTimeIndex != null && !real_workLongTimeIndex.isEmpty()){
next_beginwork_time = kqTimesArrayComInfo.getTimesByArrayindex(real_workLongTimeIndex.get(0)[0]);
}
}
}
//休息日有开发的休息班次,单独搞下
kqLog.info(i+">>>resourceid="+resourceid+",splitDate="+splitDate+",next_changeType="+next_changeType);
if(next_changeType == 3){
if(null != tmp_user){
ShiftInfoBean next_shiftInfoBean = KQDurationCalculatorUtil.getWorkTime(tmp_user, nextSplitDate, false,true,false);
if(next_shiftInfoBean != null){
int tmp_serialid = StringUtil.parseToInt(next_shiftInfoBean.getSerialid(), 0);
int restShift = StringUtil.parseToInt(kQShiftManagementComInfo.getRestShift(String.valueOf(tmp_serialid)), 0);
// kqLog.info(i+">>>resourceid="+resourceid+",splitDate="+splitDate+",tmp_serialid="+ tmp_serialid+",restShift="+ restShift);
if(tmp_serialid > 0 && restShift == 1) {
isRestshift_next = true;
}
List<int[]> workLongTimeIndex = next_shiftInfoBean.getWorkLongTimeIndex();
List<int[]> real_workLongTimeIndex = Lists.newArrayList();
get_real_workLongTimeIndex(workLongTimeIndex,real_workLongTimeIndex,next_shiftInfoBean,kqTimesArrayComInfo,splitBean);
if(real_workLongTimeIndex != null && !real_workLongTimeIndex.isEmpty()){
tmp_next_beginwork_time = kqTimesArrayComInfo.getTimesByArrayindex(real_workLongTimeIndex.get(0)[0]);
}
kqLog.info(i+">>>resourceid="+resourceid+",splitDate="+splitDate+",tmp_next_beginwork_time="+ tmp_next_beginwork_time+",isRestshift_next="+ isRestshift_next);
}
}
}
// kqLog.info(i+">>>resourceid="+resourceid+",splitDate="+splitDate+",changeType="+changeType);
if(changeType == 2){
ShiftInfoBean cur_shiftInfoBean = KQDurationCalculatorUtil.getWorkTime(resourceid, splitDate, false);
if(cur_shiftInfoBean != null){
List<int[]> workLongTimeIndex = cur_shiftInfoBean.getWorkLongTimeIndex();
List<int[]> real_workLongTimeIndex = Lists.newArrayList();
get_real_workLongTimeIndex(workLongTimeIndex,real_workLongTimeIndex,cur_shiftInfoBean,kqTimesArrayComInfo,splitBean);
if(real_workLongTimeIndex != null && !real_workLongTimeIndex.isEmpty()){
cur_beginwork_time = kqTimesArrayComInfo.getTimesByArrayindex(real_workLongTimeIndex.get(0)[0]);
}
}
}
//休息日有开发的休息班次,单独搞下
if(changeType == 3){
// kqLog.info(i+">>>resourceid="+resourceid+",splitDate="+splitDate+",tmp_user="+tmp_user);
if(null != tmp_user){
ShiftInfoBean tmp_shiftInfoBean = KQDurationCalculatorUtil.getWorkTime(tmp_user, splitDate,false,true,false);
// kqLog.info(i+">>>resourceid="+resourceid+",splitDate="+splitDate+",tmp_shiftInfoBean="+ JSONObject.toJSONString(tmp_shiftInfoBean));
if(tmp_shiftInfoBean != null){
int tmp_serialid = StringUtil.parseToInt(tmp_shiftInfoBean.getSerialid(), 0);
int restShift = StringUtil.parseToInt(kQShiftManagementComInfo.getRestShift(String.valueOf(tmp_serialid)), 0);
// kqLog.info(i+">>>resourceid="+resourceid+",splitDate="+splitDate+",tmp_serialid="+ tmp_serialid+",restShift="+ restShift);
if(tmp_serialid > 0 && restShift == 1) {
isRestshift = true;
}
List<int[]> workLongTimeIndex = tmp_shiftInfoBean.getWorkLongTimeIndex();
List<int[]> real_workLongTimeIndex = Lists.newArrayList();
get_real_workLongTimeIndex(workLongTimeIndex,real_workLongTimeIndex,tmp_shiftInfoBean,kqTimesArrayComInfo,splitBean);
if(real_workLongTimeIndex != null && !real_workLongTimeIndex.isEmpty()){
tmp_cur_beginwork_time = kqTimesArrayComInfo.getTimesByArrayindex(real_workLongTimeIndex.get(0)[0]);
}
kqLog.info(i+">>>resourceid="+resourceid+",splitDate="+splitDate+",tmp_cur_beginwork_time="+ tmp_cur_beginwork_time+",isRestshift="+ isRestshift);
}
}
}
boolean needSplitByTime = false;
// 按照加班时长转调休的 时长设置
List<String> timepointList = null;
List<OvertimeBalanceTimeBean> 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<String,List<String>> balanceTimethDetailMap = kqOvertimeRulesBiz.getBalanceTimeDetailMap(ruleDetailid);
if(balanceTimethDetailMap != null && !balanceTimethDetailMap.isEmpty()){
timepointList = balanceTimethDetailMap.get("timepointList");
}
}
kqLog.info(i+">>>resourceid="+resourceid+",splitDate="+splitDate+",has_cut_point="+ has_cut_point+",changeType="+ changeType+",isRestshift="+ isRestshift+",isRestshift_next="+ isRestshift_next);
if(has_cut_point == 0){
if(changeType == 2){
overtime_cut_point = cur_beginwork_time;
}else {
if(changeType == 3){
if(isRestshift){
overtime_cut_point = tmp_cur_beginwork_time;
}
/**
* 09:00-18:0012:00-22:0012:00
*
*
if(isRestshift_next && overtime_cut_point.length() > 0 && tmp_next_beginwork_time.length() > 0){
int next_beginwork_time_index = kqTimesArrayComInfo.getArrayindexByTimes(tmp_next_beginwork_time);
int overtime_cut_point_index = kqTimesArrayComInfo.getArrayindexByTimes(overtime_cut_point);
if(overtime_cut_point_index > next_beginwork_time_index){
overtime_cut_point = next_beginwork_time;
}
}
*/
}
if(next_beginwork_time.length() > 0){
overtime_cut_point = next_beginwork_time;
}
}
}else{
overtime_cut_point = curKqOvertimeRulesDetailEntity.getCut_point();
if(next_beginwork_time.length() > 0){
int next_beginwork_time_index = kqTimesArrayComInfo.getArrayindexByTimes(next_beginwork_time);
int overtime_cut_point_index = kqTimesArrayComInfo.getArrayindexByTimes(overtime_cut_point);
if(overtime_cut_point_index > next_beginwork_time_index){
overtime_cut_point = next_beginwork_time;
}
}
}
if(overtime_cut_point.length() == 0){
overtime_cut_point = "00:00";
}
}else{
continue;
}
int fromTime_index = 0;
int toTime_index = 0;
kqLog.info(i+"resourceid="+resourceid+",splitDate="+splitDate+",overtime_cut_point11="+ overtime_cut_point);
if(i == 0){
//i=0就是加班开始日期的前一天只有当加班临界点超过了加班流程开始时间的话i=0才会有可能计算出时长
if(overtime_cut_point.compareTo(fromTime) > 0){
fromTime_index = kqTimesArrayComInfo.getArrayindexByTimes(kqTimesArrayComInfo.turn24to48Time(fromTime));
toTime_index = kqTimesArrayComInfo.getArrayindexByTimes(kqTimesArrayComInfo.turn24to48Time(overtime_cut_point));
if(fromDate.equalsIgnoreCase(toDate)){
//如果开始日期和结束日期是同一天,还需要比较流程的结束时间和归属点的大小
int oriTotime_index = kqTimesArrayComInfo.getArrayindexByTimes(kqTimesArrayComInfo.turn24to48Time(toTime));
if(toTime_index > oriTotime_index){
toTime_index = oriTotime_index;
}
}
kqLog.info(i+">>>resourceid="+resourceid+",splitDate="+splitDate+",fromTime_index="+ fromTime_index+",toTime_index="+ toTime_index);
Arrays.fill(initArrays, fromTime_index, toTime_index, 0);
// 1-节假日、2-工作日、3-休息日
if(changeType == 1){
handle_changeType_1(initArrays,overRulesDetailMap,nextChangeType_key,next_changeType,next_beginwork_time);
}else if(changeType == 2){
boolean isok = handle_changeType_2(initArrays, resourceid, splitDate, before_startTime, startTime, fromTime_index,kqTimesArrayComInfo,splitBean,
toTime_index);
serialid = splitBean.getSerialid();
if(!isok){
continue;
}
}else if(changeType == 3){
handle_changeType_3(initArrays,overRulesDetailMap,nextChangeType_key,next_changeType,next_beginwork_time);
}
if(restTimeType == 1){
//如果排除设置的休息时间
handle_resttime(restTimeMap,changeType_key,kqTimesArrayComInfo,shouldAcross,initArrays);
}
curMins = kqTimesArrayComInfo.getCnt(initArrays, fromTime_index,toTime_index,0);
if(restTimeType == 2){
//如果排除休息时间是扣除时长
curMins = handle_restlength(curMins,restTimeMap,changeType_key);
}
kqLog.info(i+">>>resourceid="+resourceid+",splitDate="+splitDate+",curMins="+ curMins);
}else{
continue;
}
}else{
//除了i=0的情况其他的每一天都是要获取一下昨日的临界点的
String pre_overtime_cut_point = get_pre_overtime_cut_point(overRulesDetailMap,preChangeType_key,resourceid,preSplitDate,splitDate,preChangeType,kqTimesArrayComInfo,splitBean,changeType);
if(changeType == 2){
//如果今天是工作日,昨日的打卡归属会受到今日的上班前开始加班分钟数的影响
int cur_beginwork_time_index = kqTimesArrayComInfo.getArrayindexByTimes(cur_beginwork_time);
if(before_startTime > -1){
int pre_overtime_cut_point_index = kqTimesArrayComInfo.getArrayindexByTimes(pre_overtime_cut_point);
int before_cur_beginwork_time_index = cur_beginwork_time_index - before_startTime;
}
}
//计算区间加班开始日期和加班结束日期这两天都是要特殊处理的
fromTime_index = kqTimesArrayComInfo.getArrayindexByTimes(pre_overtime_cut_point);
if(i == 1){
if(fromTime.compareTo(pre_overtime_cut_point) > 0){
fromTime_index = kqTimesArrayComInfo.getArrayindexByTimes(fromTime);
}
}
kqLog.info(i+">>>resourceid="+resourceid+",splitDate="+splitDate+",betweenDays="+ betweenDays);
if(i == betweenDays){
toTime_index = kqTimesArrayComInfo.getArrayindexByTimes(toTime);
}else{
toTime_index = kqTimesArrayComInfo.turn24to48TimeIndex(kqTimesArrayComInfo.getArrayindexByTimes(overtime_cut_point));
// kqLog.info(i+">>>resourceid="+resourceid+",splitDate="+splitDate+",toTime_index22="+ toTime_index);
if(tmp_next_beginwork_time.length() > 0){
int overtime_cut_point_index = kqTimesArrayComInfo.getArrayindexByTimes(overtime_cut_point);
int next_beginwork_time_index = kqTimesArrayComInfo.getArrayindexByTimes(tmp_next_beginwork_time);
//如果临界点都已经超过第二天上班的开始时间了,要相应的缩短成第二天上班时间
if(overtime_cut_point_index > next_beginwork_time_index){
toTime_index = kqTimesArrayComInfo.turn24to48TimeIndex(next_beginwork_time_index);
}
}
if(next_beginwork_time.length() > 0){
int overtime_cut_point_index = kqTimesArrayComInfo.getArrayindexByTimes(overtime_cut_point);
int next_beginwork_time_index = kqTimesArrayComInfo.getArrayindexByTimes(next_beginwork_time);
//如果临界点都已经超过第二天上班的开始时间了,要相应的缩短成第二天上班时间
if(overtime_cut_point_index > next_beginwork_time_index){
toTime_index = kqTimesArrayComInfo.turn24to48TimeIndex(next_beginwork_time_index);
}
}
if(i == betweenDays-1){
int ori_totime_index = kqTimesArrayComInfo.turn48to24TimeIndex(toTime_index);
int last_toTime_index = kqTimesArrayComInfo.getArrayindexByTimes(toTime);
if(ori_totime_index > last_toTime_index){
toTime_index = kqTimesArrayComInfo.turn24to48TimeIndex(last_toTime_index);
}
}
}
System.out.println(i+":betweenDays:"+betweenDays+":fromTime_index:"+fromTime_index+":toTime_index:"+toTime_index+":changeType:"+changeType);
if(fromTime_index > toTime_index){
continue;
}
Arrays.fill(initArrays, fromTime_index, toTime_index, 0);
if(changeType == 1){
handle_changeType_1(initArrays, overRulesDetailMap, nextChangeType_key, next_changeType,
next_beginwork_time);
}else if(changeType == 2){
serialid = splitBean.getSerialid();
boolean isok = handle_changeType_2(initArrays, resourceid, splitDate, before_startTime, startTime, fromTime_index,
kqTimesArrayComInfo, splitBean, toTime_index);
if(!isok){
continue;
}
}else if(changeType == 3){
handle_changeType_3(initArrays, overRulesDetailMap, nextChangeType_key, next_changeType,
overtime_cut_point);
}
if(restTimeType == 1) {
//如果排除设置的休息时间
handle_resttime(restTimeMap, changeType_key, kqTimesArrayComInfo, shouldAcross,initArrays);
}
curMins = kqTimesArrayComInfo.getCnt(initArrays, fromTime_index,toTime_index,0);
if(restTimeType == 2){
//如果排除休息时间是扣除时长
curMins = handle_restlength(curMins,restTimeMap,changeType_key);
}
kqLog.info(i+">>>resourceid="+resourceid+",splitDate="+splitDate+",curMins111="+ curMins);
}
int minimumUnit = curKqOvertimeRulesDetailEntity.getMinimumLen();
if(curMins < minimumUnit){
continue;
}
if(needSplitByTime){
kqOverTimeRuleCalBiz.get_overtimeBalanceTimeBeans(timepointList,overtimeBalanceTimeBeans,kqTimesArrayComInfo,initArrays,toTime_index,fromTime_index,0);
if(overtimeBalanceTimeBeans != null && !overtimeBalanceTimeBeans.isEmpty()){
String bean_cross_fromtime = kqTimesArrayComInfo.getTimesByArrayindex(fromTime_index);
String bean_cross_totime = kqTimesArrayComInfo.getTimesByArrayindex(toTime_index);
for(int timeIndex = 0 ; timeIndex < overtimeBalanceTimeBeans.size() ;timeIndex++) {
OvertimeBalanceTimeBean overtimeBalanceTimeBean = overtimeBalanceTimeBeans.get(timeIndex);
String timePointStart = overtimeBalanceTimeBean.getTimepoint_start();
String timePointEnd = overtimeBalanceTimeBean.getTimepoint_end();
boolean isNeedTX = overtimeBalanceTimeBean.isNeedTX();
int timePointStart_index = kqTimesArrayComInfo.getArrayindexByTimes(timePointStart);
int timePointEnd_index = kqTimesArrayComInfo.getArrayindexByTimes(timePointEnd);
if(timePointStart_index > fromTime_index){
bean_cross_fromtime = kqTimesArrayComInfo.getTimesByArrayindex(timePointStart_index);
}else{
bean_cross_fromtime = kqTimesArrayComInfo.getTimesByArrayindex(fromTime_index);
}
if(timePointEnd_index < toTime_index){
bean_cross_totime = kqTimesArrayComInfo.getTimesByArrayindex(timePointEnd_index);
}else{
bean_cross_totime = kqTimesArrayComInfo.getTimesByArrayindex(toTime_index);
}
int timepoint_mins = overtimeBalanceTimeBean.getTimepoint_mins();
if(isNeedTX){
if(timepoint_mins > 0){
overSplitBean = new SplitBean();
//然后把bean重新赋值下根据拆分后的时间
BeanUtils.copyProperties(splitBean, overSplitBean);
overSplitBean.setChangeType(changeType);
overSplitBean.setPreChangeType(preChangeType);
overSplitBean.setOneDayHour(oneDayHour);
overSplitBean.setWorkmins(workmins);
overSplitBean.setComputingMode(computingMode+"");
overSplitBean.setChangeType(changeType);
overSplitBean.setFromDate(splitDate);
overSplitBean.setFromTime(bean_cross_fromtime);
overSplitBean.setToDate(splitDate);
overSplitBean.setToTime(bean_cross_totime);
overSplitBean.setBelongDate(splitDate);
overSplitBean.setD_Mins(timepoint_mins);
overSplitBean.setOvertimeBalanceTimeBeans(overtimeBalanceTimeBeans);
overSplitBean.setSerialid(serialid);
getDurationByRule(overSplitBean);
splitBeans.add(overSplitBean);
}
}
}
}
}else{
curMins = (int) kqOverTimeRuleCalBiz.getD_MinsByUnit(curMins);
overSplitBean.setChangeType(changeType);
overSplitBean.setPreChangeType(preChangeType);
overSplitBean.setOneDayHour(oneDayHour);
overSplitBean.setWorkmins(workmins);
overSplitBean.setComputingMode(computingMode+"");
overSplitBean.setChangeType(changeType);
overSplitBean.setFromDate(splitDate);
overSplitBean.setFromTime(kqTimesArrayComInfo.getTimesByArrayindex(fromTime_index));
overSplitBean.setToDate(splitDate);
overSplitBean.setToTime(kqTimesArrayComInfo.getTimesByArrayindex(toTime_index));
overSplitBean.setBelongDate(splitDate);
overSplitBean.setD_Mins(curMins);
overSplitBean.setOvertimeBalanceTimeBeans(overtimeBalanceTimeBeans);
overSplitBean.setSerialid(serialid);
getDurationByRule(overSplitBean);
splitBeans.add(overSplitBean);
}
}
long b = System.currentTimeMillis();
System.out.println("::"+(b-a));
}catch (Exception e){
StringWriter errorsWriter = new StringWriter();
e.printStackTrace(new PrintWriter(errorsWriter));
kqLog.info(errorsWriter.toString());
}
}
/**
*
* @param workLongTimeIndex
* @param real_workLongTimeIndex
* @param shiftInfoBean
* @param kqTimesArrayComInfo
* @param splitBean
*/
public void get_real_workLongTimeIndex(List<int[]> workLongTimeIndex,
List<int[]> 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<String, KQOvertimeRulesDetailEntity> 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<int[]> workLongTimeIndex = pre_shiftInfoBean.getWorkLongTimeIndex();
List<int[]> real_workLongTimeIndex = Lists.newArrayList();
get_real_workLongTimeIndex(workLongTimeIndex,real_workLongTimeIndex,pre_shiftInfoBean,kqTimesArrayComInfo,splitBean);
if(real_workLongTimeIndex != null && !real_workLongTimeIndex.isEmpty()){
pre_overtime_cut_point = kqTimesArrayComInfo.getTimesByArrayindex(real_workLongTimeIndex.get(0)[0]);
}
}
}else {
String next_beginwork_time = "";
//单独搞下开发的休息班次
if(preChangeType == 3){
ShiftInfoBean pre_shiftInfoBean = KQDurationCalculatorUtil.getWorkTimeNew(resourceid, preSplitDate, false);
if(pre_shiftInfoBean != null){
int serialid = StringUtil.parseToInt(pre_shiftInfoBean.getSerialid(), 0);
KQShiftManagementComInfo kQShiftManagementComInfo = new KQShiftManagementComInfo();
int restShift = StringUtil.parseToInt(kQShiftManagementComInfo.getRestShift(String.valueOf(serialid)), 0);
if(serialid > 0 && restShift == 1) {
List<int[]> workLongTimeIndex = pre_shiftInfoBean.getWorkLongTimeIndex();
List<int[]> real_workLongTimeIndex = Lists.newArrayList();
get_real_workLongTimeIndex(workLongTimeIndex,real_workLongTimeIndex,pre_shiftInfoBean,kqTimesArrayComInfo,splitBean);
if(real_workLongTimeIndex != null && !real_workLongTimeIndex.isEmpty()){
pre_overtime_cut_point = kqTimesArrayComInfo.getTimesByArrayindex(real_workLongTimeIndex.get(0)[0]);
}
}
}
// ShiftInfoBean next_shiftInfoBean = KQDurationCalculatorUtil.getWorkTimeNew(resourceid, splitDate, false);
// if(next_shiftInfoBean != null){
// int serialid = StringUtil.parseToInt(next_shiftInfoBean.getSerialid(), 0);
// KQShiftManagementComInfo kQShiftManagementComInfo = new KQShiftManagementComInfo();
// int restShift = StringUtil.parseToInt(kQShiftManagementComInfo.getRestShift(String.valueOf(serialid)), 0);
// if(serialid > 0 && restShift == 1) {
// List<int[]> workLongTimeIndex = next_shiftInfoBean.getWorkLongTimeIndex();
// List<int[]> real_workLongTimeIndex = Lists.newArrayList();
// get_real_workLongTimeIndex(workLongTimeIndex,real_workLongTimeIndex,next_shiftInfoBean,kqTimesArrayComInfo,splitBean);
//
// if(real_workLongTimeIndex != null && !real_workLongTimeIndex.isEmpty()){
// next_beginwork_time = kqTimesArrayComInfo.getTimesByArrayindex(real_workLongTimeIndex.get(0)[0]);
// }
// }
// }
}
if(changeType == 2){
ShiftInfoBean next_shiftInfoBean = KQDurationCalculatorUtil.getWorkTime(resourceid, splitDate, false);
if(next_shiftInfoBean != null){
List<int[]> workLongTimeIndex = next_shiftInfoBean.getWorkLongTimeIndex();
List<int[]> 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<String, KQOvertimeRulesDetailEntity> 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<String, List<String[]>> restTimeMap, String changeType_key, KQTimesArrayComInfo kqTimesArrayComInfo, boolean shouldAcross, int[] initArrays) {
if(restTimeMap.containsKey(changeType_key)){
List<String[]> restTimeList = restTimeMap.get(changeType_key);
//再把休息时间填充上去
if(!restTimeList.isEmpty()){
for(int k =0 ; k < restTimeList.size() ; k++){
String[] restTimes = restTimeList.get(k);
if(restTimes.length == 2){
int restStart = kqTimesArrayComInfo.getArrayindexByTimes(restTimes[0]);
int restEnd = kqTimesArrayComInfo.getArrayindexByTimes(restTimes[1]);
// if(shouldAcross && restEnd == 1439){
if(restEnd == 1439){
//针对跨天的休息时段单独处理排除掉23:59-00:00的时间
restEnd = 1440;
}
int hasRestMins = kqTimesArrayComInfo.getCnt(initArrays, restStart,restEnd,0);
if(hasRestMins == 0) {
restStart = kqTimesArrayComInfo.turn24to48TimeIndex(restStart);
restEnd = kqTimesArrayComInfo.turn24to48TimeIndex(restEnd);
}
Arrays.fill(initArrays, restStart, restEnd, 1);
}
}
}
}
}
/**
*
* @param curMins
* @param restTimeMap
* @param changeType_key
* @return
*/
public int handle_restlength(int curMins, Map<String, List<String[]>> restTimeMap, String changeType_key) {
if(restTimeMap.containsKey(changeType_key)) {
List<String[]> restTimeList = restTimeMap.get(changeType_key);
//再把休息时间填充上去
if (!restTimeList.isEmpty()) {
for(int k = restTimeList.size()-1 ; k >= 0 ; k--) {
String[] restTimes = restTimeList.get(k);
if (restTimes.length == 2) {
//overlength 是满多少小时 cutlength是减去多少小时
double overlength = Util.getDoubleValue(restTimes[0],-1);
double cutlength = Util.getDoubleValue(restTimes[1],-1);
if(overlength > -1 && cutlength > -1){
double min_overlength = overlength * 60;
double min_cutlength = cutlength * 60;
if(curMins >= min_overlength){
curMins = (int) (curMins-min_cutlength);
break;
}
}
}
}
}
}
return curMins;
}
/**
*
* @param initArrays
* @param resourceid
* @param splitDate
* @param before_startTime
* @param startTime
* @param fromTime_index
* @param kqTimesArrayComInfo
* @param splitBean
* @param toTime_index
* @return
*/
public boolean handle_changeType_2(int[] initArrays, String resourceid, String splitDate,
int before_startTime, int startTime, int fromTime_index,
KQTimesArrayComInfo kqTimesArrayComInfo, SplitBean splitBean, int toTime_index){
boolean isok = true;
ShiftInfoBean cur_shiftInfoBean = KQDurationCalculatorUtil.getWorkTime(resourceid, splitDate, false);
if(cur_shiftInfoBean != null){
splitBean.setSerialid(cur_shiftInfoBean.getSerialid());
List<int[]> workLongTimeIndex = cur_shiftInfoBean.getWorkLongTimeIndex();
List<int[]> 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<int[]> 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<String, KQOvertimeRulesDetailEntity> 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));
}
}
}

File diff suppressed because it is too large Load Diff

@ -0,0 +1,261 @@
package com.engine.kq.biz;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import java.io.Writer;
import java.util.Map;
import java.util.UUID;
import com.engine.kq.log.KQLog;
import weaver.conn.ConnStatement;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.common.DbFunctionUtil;
/**
*
*
*/
public class KQOvertimeLogBiz {
private KQLog kqLog = new KQLog();
/**
*
* @param resourceid
* @param workTimeEntityLogMap
* @param main_uuid
* @param worktimeType
* @return
*/
public String logDetailWorkTimeEntity(String resourceid, Map<String, Object> workTimeEntityLogMap,
String main_uuid,String worktimeType) {
RecordSet rs = new RecordSet();
String serial_info = "";
if(workTimeEntityLogMap != null){
serial_info = JSON.toJSONString(workTimeEntityLogMap,SerializerFeature.DisableCheckSpecialChar,SerializerFeature.DisableCircularReferenceDetect);
}
String uuid = UUID.randomUUID().toString();
kqLog.info("serial_info::::"+serial_info+":::uuid:::"+uuid);
if(true) {
return uuid;
}
boolean isok = false;
if(rs.getDBType().equalsIgnoreCase("oracle")&& Util.null2String(rs.getOrgindbtype()).equals("oracle")){
String sql = "insert into kq_overtime_log_detail(resourceid,createdatetime,serial_info,overtime_info,event_info,uuid,overtimetype,main_uuid) "
+ " values(?,"+ DbFunctionUtil.getCurrentFullTimeFunction(rs.getDBType())+",empty_clob(),empty_clob(),empty_clob(),?,?,?) ";
isok = rs.executeUpdate(sql,resourceid,uuid,worktimeType,main_uuid);
}else{
String sql = "insert into kq_overtime_log_detail(resourceid,createdatetime,serial_info,uuid,overtimetype,main_uuid) "
+ " values("+resourceid+","+DbFunctionUtil.getCurrentFullTimeFunction(rs.getDBType())+",'"+serial_info+"','"+uuid+"','"+worktimeType+"','"+main_uuid+"') ";
rs.executeUpdate(sql);
}
if(rs.getDBType().equalsIgnoreCase("oracle")&& Util.null2String(rs.getOrgindbtype()).equals("oracle")){
ConnStatement stat=null;
try {
stat = new ConnStatement();
// 需要使用for update方法来进行更新
// 但是特别需要注意如果原来CLOB字段有值需要使用empty_clob()将其清空。
// 如果原来是null也不能更新必须是empty_clob()返回的结果。
stat.setStatementSql("select serial_info from kq_overtime_log_detail where uuid=? for update", false);
stat.setString(1,uuid);
stat.executeQuery();
if (stat.next()) {
oracle.sql.CLOB clob = (oracle.sql.CLOB) stat.getClob("serial_info");
Writer outStream = clob.getCharacterOutputStream();
char[] c = serial_info.toCharArray();
outStream.write(c, 0, c.length);
outStream.flush();
outStream.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stat != null) {
stat.close();
}
}
}
return uuid;
}
/**
* id
* id
* @param uuid
* @param overtimeid
* @return
*/
public void updateOvertimeId(String uuid,String overtimeid) {
if(true) {
return;
}
RecordSet rs = new RecordSet();
String sql = "update kq_overtime_log_detail set overtimeid="+overtimeid+" where uuid='"+uuid+"' ";
boolean isOk = rs.executeUpdate(sql);
}
/**
*
* @param resourceid
* @param overtimeLogMap
* @param uuid
*/
public void logDetailOvertimeMap(String resourceid, Map<String, Object> overtimeLogMap,String uuid) {
RecordSet rs = new RecordSet();
String overtime_info = "";
if(overtimeLogMap != null){
overtime_info = JSON.toJSONString(overtimeLogMap, SerializerFeature.DisableCheckSpecialChar,SerializerFeature.DisableCircularReferenceDetect);
}
kqLog.info("overtime_info::::"+overtime_info+":::uuid:::"+uuid);
if(true) {
return;
}
if(rs.getDBType().equalsIgnoreCase("oracle")&& Util.null2String(rs.getOrgindbtype()).equals("oracle")){
ConnStatement stat=null;
try {
stat = new ConnStatement();
// 需要使用for update方法来进行更新
// 但是特别需要注意如果原来CLOB字段有值需要使用empty_clob()将其清空。
// 如果原来是null也不能更新必须是empty_clob()返回的结果。
stat.setStatementSql("select overtime_info from kq_overtime_log_detail where uuid=? for update", false);
stat.setString(1,uuid);
stat.executeQuery();
if (stat.next()) {
oracle.sql.CLOB clob = (oracle.sql.CLOB) stat.getClob("overtime_info");
Writer outStream = clob.getCharacterOutputStream();
char[] c = overtime_info.toCharArray();
outStream.write(c, 0, c.length);
outStream.flush();
outStream.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stat != null) {
stat.close();
}
}
}else{
String sql = "update kq_overtime_log_detail set overtime_info='"+overtime_info+"' where uuid='"+uuid+"'";
rs.executeUpdate(sql);
}
}
/**
*
* @param resourceid
* @param eventLogMap
* @param overtimetype
* @return
*/
public String logEvent(String resourceid, Map<String, Object> eventLogMap, String overtimetype) {
RecordSet rs = new RecordSet();
String event_info = "";
if(eventLogMap != null){
event_info = JSON.toJSONString(eventLogMap,SerializerFeature.DisableCheckSpecialChar,SerializerFeature.DisableCircularReferenceDetect);
}
String uuid = UUID.randomUUID().toString();
kqLog.info("event_info::::"+event_info+":::uuid:::"+uuid);
if(true) {
return uuid;
}
boolean isok = false;
if(rs.getDBType().equalsIgnoreCase("oracle")&& Util.null2String(rs.getOrgindbtype()).equals("oracle")){
String sql = "insert into kq_overtime_log(resourceid,createdatetime,event_info,uuid,overtimetype) "
+ " values("+resourceid+","+ DbFunctionUtil.getCurrentFullTimeFunction(rs.getDBType())+",empty_clob(),'"+uuid+"','"+overtimetype+"') ";
isok = rs.executeUpdate(sql);
}else{
String sql = "insert into kq_overtime_log(resourceid,createdatetime,event_info,uuid,overtimetype) "
+ " values("+resourceid+","+DbFunctionUtil.getCurrentFullTimeFunction(rs.getDBType())+",'"+event_info+"','"+uuid+"','"+overtimetype+"') ";
rs.executeUpdate(sql);
}
if(isok && rs.getDBType().equalsIgnoreCase("oracle")&& Util.null2String(rs.getOrgindbtype()).equals("oracle")){
ConnStatement stat=null;
try {
stat = new ConnStatement();
// 需要使用for update方法来进行更新
// 但是特别需要注意如果原来CLOB字段有值需要使用empty_clob()将其清空。
// 如果原来是null也不能更新必须是empty_clob()返回的结果。
stat.setStatementSql("select event_info from kq_overtime_log where uuid=? for update", false);
stat.setString(1,uuid);
stat.executeQuery();
if (stat.next()) {
oracle.sql.CLOB clob = (oracle.sql.CLOB) stat.getClob("event_info");
Writer outStream = clob.getCharacterOutputStream();
char[] c = event_info.toCharArray();
outStream.write(c, 0, c.length);
outStream.flush();
outStream.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stat != null) {
stat.close();
}
}
}
return uuid;
}
/**
* 使sql
* @param resourceid
* @param eventLogMap
* @param uuid
* @param overtimetype
*/
public void logDetailEvent(String resourceid, Map<String, Object> eventLogMap, String uuid, String overtimetype) {
RecordSet rs = new RecordSet();
String event_info = "";
if(eventLogMap != null){
event_info = JSON.toJSONString(eventLogMap,SerializerFeature.DisableCheckSpecialChar,SerializerFeature.DisableCircularReferenceDetect);
}
kqLog.info("event_info::::"+event_info+":::uuid:::"+uuid);
if(true) {
return;
}
if(rs.getDBType().equalsIgnoreCase("oracle")&&rs.getOrgindbtype().equalsIgnoreCase("oracle")){
ConnStatement stat=null;
try {
stat = new ConnStatement();
// 需要使用for update方法来进行更新
// 但是特别需要注意如果原来CLOB字段有值需要使用empty_clob()将其清空。
// 如果原来是null也不能更新必须是empty_clob()返回的结果。
stat.setStatementSql("select event_info from kq_overtime_log_detail where uuid=? for update", false);
stat.setString(1,uuid);
stat.executeQuery();
if (stat.next()) {
oracle.sql.CLOB clob = (oracle.sql.CLOB) stat.getClob("event_info");
Writer outStream = clob.getCharacterOutputStream();
char[] c = event_info.toCharArray();
outStream.write(c, 0, c.length);
outStream.flush();
outStream.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stat != null) {
stat.close();
}
}
}else{
String regexp = "\'";
event_info =event_info.replaceAll(regexp, "\"");
String sql = "update kq_overtime_log_detail set event_info='"+event_info+"' where uuid='"+uuid+"'";
rs.executeUpdate(sql);
}
}
}

File diff suppressed because it is too large Load Diff

@ -0,0 +1,220 @@
package com.engine.kq.biz;
import com.engine.kq.log.KQLog;
import weaver.conn.RecordSet;
import weaver.general.Util;
/**
*
*/
public class KQSettingsBiz {
public static KQLog kqLog = new KQLog();
public static boolean showLeaveTypeSet(String main_key) {
RecordSet rs = new RecordSet();
String main_val = "1";
String sql = "select * from kq_settings where main_key=? ";
rs.executeQuery(sql, main_key);
if (rs.next()) {
main_val = Util.null2String(rs.getString("main_val"));
}
return "1".equalsIgnoreCase(main_val);
}
/**
* 使线
* @return
*/
public static boolean getKqformatthread() {
RecordSet rs = new RecordSet();
String main_val = "1";
String sql = "select * from kq_settings where main_key='kqformatthread' ";
rs.executeQuery(sql);
if (rs.next()) {
main_val = Util.null2String(rs.getString("main_val"));
}
return "1".equalsIgnoreCase(main_val);
}
/**
*
* @return
*/
public static boolean getKqformatAccurate() {
RecordSet rs = new RecordSet();
String main_val = "1";
String sql = "select * from kq_settings where main_key='kqformataccurate' ";
rs.executeQuery(sql);
if (rs.next()) {
main_val = Util.null2String(rs.getString("main_val"));
}
return "1".equalsIgnoreCase(main_val);
}
/**
*
* @return
*/
public static boolean is_leaveback_clear() {
RecordSet rs = new RecordSet();
String is_leaveback_clear = "0";
String show_ajax_balance_sql = "select * from kq_settings where main_key='leaveback_clear'";
rs.executeQuery(show_ajax_balance_sql);
if(rs.next()) {
String main_val = rs.getString("main_val");
if ("1".equalsIgnoreCase(main_val)) {
is_leaveback_clear = "1";
}
}
return "1".equalsIgnoreCase(is_leaveback_clear);
}
/**
*
* @return
*/
public static boolean is_flow_humanized() {
RecordSet rs = new RecordSet();
String is_flow_humanized = "0";
String show_flow_humanized_sql = "select * from kq_settings where main_key='flow_humanized'";
rs.executeQuery(show_flow_humanized_sql);
if(rs.next()) {
String main_val = rs.getString("main_val");
if ("1".equalsIgnoreCase(main_val)) {
is_flow_humanized = "1";
}
}
return "1".equalsIgnoreCase(is_flow_humanized);
}
/**
*
* @return
*/
public static boolean is_lateinlateout_outrule() {
RecordSet rs = new RecordSet();
String is_lateinlateout_outrule = "0";
String show_lateinlateout_outrule_sql = "select * from kq_settings where main_key='lateinlateout_outrule'";
rs.executeQuery(show_lateinlateout_outrule_sql);
if(rs.next()) {
String main_val = rs.getString("main_val");
if ("1".equalsIgnoreCase(main_val)) {
is_lateinlateout_outrule = "1";
}
}
return "1".equalsIgnoreCase(is_lateinlateout_outrule);
}
/**
*
* @return
*/
public static boolean is_balanceofleave() {
RecordSet rs = new RecordSet();
String is_balanceofleave = "0";
String show_is_balanceofleave_sql = "select * from kq_settings where main_key='is_balanceofleave'";
rs.executeQuery(show_is_balanceofleave_sql);
if(rs.next()) {
String main_val = rs.getString("main_val");
if ("1".equalsIgnoreCase(main_val)) {
is_balanceofleave = "1";
}
}
return "1".equalsIgnoreCase(is_balanceofleave);
}
/**
*
* @return
*/
public static boolean is_lateoutlatein() {
RecordSet rs = new RecordSet();
String is_lateoutlatein = "1";
String show_is_lateoutlatein_sql = "select main_val from kq_settings where main_key='is_lateoutlatein'";
rs.executeQuery(show_is_lateoutlatein_sql);
if(rs.next()) {
String main_val = rs.getString("main_val");
if ("1".equalsIgnoreCase(main_val)) {
is_lateoutlatein = "1";
}else{
is_lateoutlatein = "0";
}
}
return "1".equalsIgnoreCase(is_lateoutlatein);
}
/**
*
* @return
*/
public static boolean is_freeAcross() {
RecordSet rs = new RecordSet();
String is_balanceofleave = "0";
String show_is_balanceofleave_sql = "select * from kq_settings where main_key='is_freeAcross'";
rs.executeQuery(show_is_balanceofleave_sql);
if(rs.next()) {
String main_val = rs.getString("main_val");
if ("1".equalsIgnoreCase(main_val)) {
is_balanceofleave = "1";
}
}
return "1".equalsIgnoreCase(is_balanceofleave);
}
/**
*
* @return
*/
public static boolean isFirstLocation() {
RecordSet rs = new RecordSet();
String is_balanceofleave = "0";
String show_is_balanceofleave_sql = "select * from kq_settings where main_key='isFirstLocation'";
rs.executeQuery(show_is_balanceofleave_sql);
if(rs.next()) {
String main_val = rs.getString("main_val");
if ("1".equalsIgnoreCase(main_val)) {
is_balanceofleave = "1";
}
}
return "1".equalsIgnoreCase(is_balanceofleave);
}
/**
* true
* false
* @return
*/
public static boolean isforceflow_attend() {
RecordSet rs = new RecordSet();
String isforceflow_attend = "1";
String show_isforceflow_attend_sql = "select * from kq_settings where main_key='forceflow_attend'";
rs.executeQuery(show_isforceflow_attend_sql);
if(rs.next()) {
String main_val = rs.getString("main_val");
if ("0".equalsIgnoreCase(main_val)) {
isforceflow_attend = "0";
}
}
return "1".equalsIgnoreCase(isforceflow_attend);
}
/**
* ,1
* @return
*/
public static boolean show_split_balance() {
boolean show_split_balance = true;
RecordSet rs = new RecordSet();
String settingSql = "select * from KQ_SETTINGS where main_key='show_split_balance'";
rs.executeQuery(settingSql);
if(rs.next()){
String main_val = rs.getString("main_val");
if(!"1".equalsIgnoreCase(main_val)){
show_split_balance = false;
}
}
return show_split_balance;
}
}

@ -0,0 +1,759 @@
package com.engine.kq.biz;
import com.alibaba.fastjson.JSON;
import com.engine.kq.biz.chain.cominfo.HalfShiftComIndex;
import com.engine.kq.biz.chain.cominfo.RestShiftComIndex;
import com.engine.kq.biz.chain.cominfo.ShiftComIndex;
import com.engine.kq.biz.chain.cominfo.ShiftInfoCominfoBean;
import com.engine.kq.biz.chain.cominfo.WorkShiftComIndex;
import com.engine.kq.biz.chain.shiftinfo.ShiftInfoBean;
import com.engine.kq.cmd.shiftmanagement.toolkit.ShiftManagementToolKit;
import com.engine.kq.entity.TimeScopeEntity;
import com.engine.kq.log.KQLog;
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import org.apache.commons.lang.math.NumberUtils;
import weaver.cache.CacheBase;
import weaver.cache.CacheColumn;
import weaver.cache.CacheColumnType;
import weaver.cache.CacheItem;
import weaver.cache.CacheMap;
import weaver.cache.PKColumn;
import weaver.conn.RecordSet;
import weaver.general.Util;
/**
*
*/
public class KQShiftManagementComInfo extends CacheBase implements Serializable {
/*
* : initCache
*/
protected static String TABLE_NAME = "";
/*
* : initCache
* sqlwherewhere
*/
protected static String TABLE_WHERE = null;
/*
* : initCache sqlorder
* byorder by
*
*/
protected static String TABLE_ORDER = null;
@PKColumn(type = CacheColumnType.NUMBER)
protected static String PK_NAME = "id";
@CacheColumn
protected static int shiftbean;
@CacheColumn
protected static int color;
@CacheColumn
protected static int isoffdutyfreecheck;
@CacheColumn
protected static int shiftonoffworkcount;
@CacheColumn
protected static int serial;
@CacheColumn
protected static int isresttimeopen;
@CacheColumn
protected static int worktime;
@CacheColumn
protected static int punchsetting;
@CacheColumn
protected static int cardRemind;
@CacheColumn
protected static int cardRemOfSignIn;
@CacheColumn
protected static int minsBeforeSignIn;
@CacheColumn
protected static int cardRemOfSignOut;
@CacheColumn
protected static int minsAfterSignOut;
@CacheColumn
protected static int remindMode;
@CacheColumn
protected static int remindOnPC;
@CacheColumn
protected static int rest_shift;
private KQLog kqLog = new KQLog();
@Override
public CacheItem initCache(String key) {
if (key == null || "".equals(key.trim())) {
return null;
}
CacheMap localData = createCacheMap();
String sql = "";
kqLog = new KQLog();
ConcurrentHashMap<String, Object> resourceKQGroups = new ConcurrentHashMap<>();
//考勤组优先级
try {
ConcurrentHashMap<String,Object> shiftInfoBeanMap = new ConcurrentHashMap<>();
ConcurrentHashMap<String,Object> idMap = new ConcurrentHashMap<>();
ConcurrentHashMap<String,Object> colorsMap = new ConcurrentHashMap<>();
ConcurrentHashMap<String,Object> isoffdutyfreechecksMap = new ConcurrentHashMap<>();
ConcurrentHashMap<String,Object> shiftonoffworkcountsMap = new ConcurrentHashMap<>();
ConcurrentHashMap<String,Object> serialsMap = new ConcurrentHashMap<>();
ConcurrentHashMap<String,Object> isresttimeopensMap = new ConcurrentHashMap<>();
ConcurrentHashMap<String,Object> worktimesMap = new ConcurrentHashMap<>();
ConcurrentHashMap<String,Object> punchsettingsMap = new ConcurrentHashMap<>();
ConcurrentHashMap<String,Object> cardRemindMap = new ConcurrentHashMap<>();
ConcurrentHashMap<String,Object> cardRemOfSignInMap = new ConcurrentHashMap<>();
ConcurrentHashMap<String,Object> minsBeforeSignInMap = new ConcurrentHashMap<>();
ConcurrentHashMap<String,Object> cardRemOfSignOutMap = new ConcurrentHashMap<>();
ConcurrentHashMap<String,Object> minsAfterSignOutMap = new ConcurrentHashMap<>();
ConcurrentHashMap<String,Object> remindModeMap = new ConcurrentHashMap<>();
ConcurrentHashMap<String,Object> remindOnPCMap = new ConcurrentHashMap<>();
ConcurrentHashMap<String,Object> restShiftMap = new ConcurrentHashMap<>();
RecordSet rs = new RecordSet();
String getShiftInfo = "select * from kq_ShiftManagement where 1=1 and id="+key+" order by id ";
rs.execute(getShiftInfo);
while(rs.next()){
String serialid = rs.getString("id");
String isresttimeopen = rs.getString("isresttimeopen");
String color = rs.getString("color");
String shiftonoffworkcount = rs.getString("shiftonoffworkcount");
String worktime = rs.getString("worktime");
String serial = rs.getString("serial");
String punchsetting = "1";
String isoffdutyfreecheck = rs.getString("isoffdutyfreecheck");
String cardRemind = rs.getString("cardRemind");
String cardRemOfSignIn = rs.getString("cardRemOfSignIn");
String minsBeforeSignIn = rs.getString("minsBeforeSignIn");
String cardRemOfSignOut = rs.getString("cardRemOfSignOut");
String minsAfterSignOut = rs.getString("minsAfterSignOut");
String remindMode = rs.getString("remindMode");
String remindOnPC = rs.getString("remindOnPC");
String halfcalrule = rs.getString("halfcalrule");
halfcalrule = Util.null2String(halfcalrule).length() == 0 ? "0" : halfcalrule;
String halfcalpoint = rs.getString("halfcalpoint");
String halfcalpoint2cross = rs.getString("halfcalpoint2cross");
String restShift = rs.getString("rest_shift");
getShiftInfoBean(serialid,isresttimeopen,worktime,punchsetting,shiftInfoBeanMap,halfcalrule,halfcalpoint,halfcalpoint2cross,restShift);
idMap.put(serialid, serialid);
colorsMap.put(serialid, color);
isoffdutyfreechecksMap.put(serialid, isoffdutyfreecheck);
shiftonoffworkcountsMap.put(serialid, shiftonoffworkcount);
serialsMap.put(serialid, serial);
isresttimeopensMap.put(serialid, isresttimeopen);
worktimesMap.put(serialid, worktime);
punchsettingsMap.put(serialid, punchsetting);
cardRemindMap.put(serialid,cardRemind);
cardRemOfSignInMap.put(serialid,cardRemOfSignIn);
minsBeforeSignInMap.put(serialid,minsBeforeSignIn);
cardRemOfSignOutMap.put(serialid,cardRemOfSignOut);
minsAfterSignOutMap.put(serialid,minsAfterSignOut);
remindModeMap.put(serialid,remindMode);
remindOnPCMap.put(serialid,remindOnPC);
restShiftMap.put(serialid,restShift);
}
if(shiftInfoBeanMap.size()>0){
CacheItem cacheItem = createCacheItem();
Iterator<Entry<String, Object>> iterator = shiftInfoBeanMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Object> entry = iterator.next();
String id = entry.getKey();
Object value = entry.getValue();
cacheItem.set(PK_INDEX, id);
cacheItem.set(shiftbean, value);
cacheItem.set(isoffdutyfreecheck, isoffdutyfreechecksMap.get(id));
cacheItem.set(shiftonoffworkcount, shiftonoffworkcountsMap.get(id));
cacheItem.set(serial, serialsMap.get(id));
cacheItem.set(isresttimeopen, isresttimeopensMap.get(id));
cacheItem.set(worktime, worktimesMap.get(id));
cacheItem.set(punchsetting, punchsettingsMap.get(id));
cacheItem.set(cardRemind,cardRemindMap.get(id));
cacheItem.set(cardRemOfSignIn,cardRemOfSignInMap.get(id));
cacheItem.set(minsBeforeSignIn,minsBeforeSignInMap.get(id));
cacheItem.set(cardRemOfSignOut,cardRemOfSignOutMap.get(id));
cacheItem.set(minsAfterSignOut,minsAfterSignOutMap.get(id));
cacheItem.set(remindMode,remindModeMap.get(id));
cacheItem.set(remindOnPC,remindOnPCMap.get(id));
cacheItem.set(rest_shift,restShiftMap.get(id));
modifyCacheItem(id, cacheItem);
}
return cacheItem;
}
} catch (Exception e) {
kqLog.info(e);
}
return null;
}
@Override
public CacheMap initCache() {
CacheMap localData = createCacheMap();
String sql = "";
kqLog = new KQLog();
ConcurrentHashMap<String, Object> resourceKQGroups = new ConcurrentHashMap<>();
//考勤组优先级
try {
ConcurrentHashMap<String,Object> shiftInfoBeanMap = new ConcurrentHashMap<>();
ConcurrentHashMap<String,Object> idMap = new ConcurrentHashMap<>();
ConcurrentHashMap<String,Object> colorsMap = new ConcurrentHashMap<>();
ConcurrentHashMap<String,Object> isoffdutyfreechecksMap = new ConcurrentHashMap<>();
ConcurrentHashMap<String,Object> shiftonoffworkcountsMap = new ConcurrentHashMap<>();
ConcurrentHashMap<String,Object> serialsMap = new ConcurrentHashMap<>();
ConcurrentHashMap<String,Object> isresttimeopensMap = new ConcurrentHashMap<>();
ConcurrentHashMap<String,Object> worktimesMap = new ConcurrentHashMap<>();
ConcurrentHashMap<String,Object> punchsettingsMap = new ConcurrentHashMap<>();
ConcurrentHashMap<String,Object> cardRemindMap = new ConcurrentHashMap<>();
ConcurrentHashMap<String,Object> cardRemOfSignInMap = new ConcurrentHashMap<>();
ConcurrentHashMap<String,Object> minsBeforeSignInMap = new ConcurrentHashMap<>();
ConcurrentHashMap<String,Object> cardRemOfSignOutMap = new ConcurrentHashMap<>();
ConcurrentHashMap<String,Object> minsAfterSignOutMap = new ConcurrentHashMap<>();
ConcurrentHashMap<String,Object> remindModeMap = new ConcurrentHashMap<>();
ConcurrentHashMap<String,Object> remindOnPCMap = new ConcurrentHashMap<>();
ConcurrentHashMap<String,Object> restShiftMap = new ConcurrentHashMap<>();
RecordSet rs = new RecordSet();
String getShiftInfo = "select * from kq_ShiftManagement where 1=1 order by id ";
rs.execute(getShiftInfo);
while(rs.next()){
String serialid = rs.getString("id");
String isresttimeopen = rs.getString("isresttimeopen");
String color = rs.getString("color");
String shiftonoffworkcount = rs.getString("shiftonoffworkcount");
String worktime = rs.getString("worktime");
String serial = rs.getString("serial");
String punchsetting = "1";
String isoffdutyfreecheck = rs.getString("isoffdutyfreecheck");
String cardRemind = rs.getString("cardRemind");
String cardRemOfSignIn = rs.getString("cardRemOfSignIn");
String minsBeforeSignIn = rs.getString("minsBeforeSignIn");
String cardRemOfSignOut = rs.getString("cardRemOfSignOut");
String minsAfterSignOut = rs.getString("minsAfterSignOut");
String remindMode = rs.getString("remindMode");
String remindOnPC = rs.getString("remindOnPC");
String halfcalrule = rs.getString("halfcalrule");
halfcalrule = Util.null2String(halfcalrule).length() == 0 ? "0" : halfcalrule;
String halfcalpoint = rs.getString("halfcalpoint");
String halfcalpoint2cross = rs.getString("halfcalpoint2cross");
String restShift = rs.getString("rest_shift");
getShiftInfoBean(serialid,isresttimeopen,worktime,punchsetting,shiftInfoBeanMap,halfcalrule,halfcalpoint,halfcalpoint2cross,restShift);
idMap.put(serialid, serialid);
colorsMap.put(serialid, color);
isoffdutyfreechecksMap.put(serialid, isoffdutyfreecheck);
shiftonoffworkcountsMap.put(serialid, shiftonoffworkcount);
serialsMap.put(serialid, serial);
isresttimeopensMap.put(serialid, isresttimeopen);
worktimesMap.put(serialid, worktime);
punchsettingsMap.put(serialid, punchsetting);
cardRemindMap.put(serialid,cardRemind);
cardRemOfSignInMap.put(serialid,cardRemOfSignIn);
minsBeforeSignInMap.put(serialid,minsBeforeSignIn);
cardRemOfSignOutMap.put(serialid,cardRemOfSignOut);
minsAfterSignOutMap.put(serialid,minsAfterSignOut);
remindModeMap.put(serialid,remindMode);
remindOnPCMap.put(serialid,remindOnPC);
restShiftMap.put(serialid,restShift);
}
if(shiftInfoBeanMap.size()>0){
Iterator<Entry<String, Object>> iterator = shiftInfoBeanMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Object> entry = iterator.next();
String id = entry.getKey();
Object value = entry.getValue();
CacheItem cacheItem = createCacheItem();
cacheItem.set(PK_INDEX, id);
cacheItem.set(shiftbean, value);
cacheItem.set(isoffdutyfreecheck, isoffdutyfreechecksMap.get(id));
cacheItem.set(shiftonoffworkcount, shiftonoffworkcountsMap.get(id));
cacheItem.set(serial, serialsMap.get(id));
cacheItem.set(isresttimeopen, isresttimeopensMap.get(id));
cacheItem.set(worktime, worktimesMap.get(id));
cacheItem.set(punchsetting, punchsettingsMap.get(id));
cacheItem.set(cardRemind,cardRemindMap.get(id));
cacheItem.set(cardRemOfSignIn,cardRemOfSignInMap.get(id));
cacheItem.set(minsBeforeSignIn,minsBeforeSignInMap.get(id));
cacheItem.set(cardRemOfSignOut,cardRemOfSignOutMap.get(id));
cacheItem.set(minsAfterSignOut,minsAfterSignOutMap.get(id));
cacheItem.set(remindMode,remindModeMap.get(id));
cacheItem.set(remindOnPC,remindOnPCMap.get(id));
cacheItem.set(rest_shift,restShiftMap.get(id));
modifyCacheItem(id, cacheItem);
localData.put(id, cacheItem);
}
}
} catch (Exception e) {
StringWriter errorsWriter = new StringWriter();
e.printStackTrace(new PrintWriter(errorsWriter));
kqLog.info(errorsWriter.toString());
}
return localData;
}
public String getId(){
return (String)getRowValue(PK_INDEX);
}
public String getColor() { return (String)getRowValue(color); }
public String getColor(String key)
{
return (String)getValue(color,key);
}
public String getIsoffdutyfreecheck() { return (String)getRowValue(isoffdutyfreecheck); }
public String getIsoffdutyfreecheck(String key)
{
return (String)getValue(isoffdutyfreecheck,key);
}
public String getShiftonoffworkcounts() { return (String)getRowValue(shiftonoffworkcount); }
public String getShiftonoffworkcounts(String key)
{
return (String)getValue(shiftonoffworkcount,key);
}
public String getSerial() { return (String)getRowValue(serial); }
public String getSerial(String key)
{
return (String)getValue(serial,key);
}
public String getIsresttimeopen() { return (String)getRowValue(isresttimeopen); }
public String getIsresttimeopen(String key)
{
return (String)getValue(isresttimeopen,key);
}
public String getWorktime() { return (String)getRowValue(worktime); }
public String getWorktime(String key)
{
return (String)getValue(worktime,key);
}
public String getPunchsetting() {
return (String) getRowValue(punchsetting);
}
public String getPunchsetting(String key) {
return (String) getValue(punchsetting, key);
}
public String getCardRemind() {
return (String) getRowValue(cardRemind);
}
public String getCardRemind(String key) {
return (String) getValue(cardRemind,key);
}
public String getCardRemOfSignIn() {
return (String) getRowValue(cardRemOfSignIn);
}
public String getCardRemOfSignIn(String key) {
return (String) getValue(cardRemOfSignIn, key);
}
public String getMinsBeforeSignIn() {
return (String) getRowValue(minsBeforeSignIn);
}
public String getMinsBeforeSignIn(String key) {
return (String) getValue(minsBeforeSignIn, key);
}
public String getCardRemOfSignOut() {
return (String) getRowValue(cardRemOfSignOut);
}
public String getCardRemOfSignOut(String key) {
return (String) getValue(cardRemOfSignOut, key);
}
public String getMinsAfterSignOut() {
return (String) getRowValue(minsAfterSignOut);
}
public String getMinsAfterSignOut(String key) {
return (String) getValue(minsAfterSignOut, key);
}
public String getRemindMode() {
return (String) getRowValue(remindMode);
}
public String getRemindMode(String key) {
return (String) getValue(remindMode, key);
}
public String getRemindOnPC() {
return (String) getRowValue(remindOnPC);
}
public String getRemindOnPC(String key) {
return (String) getValue(remindOnPC, key);
}
public String getRestShift() {
return (String) getRowValue(rest_shift);
}
public String getRestShift(String key) {
return (String) getValue(rest_shift, key);
}
private void getShiftInfoBean(String serialid, String isresttimeopen, String worktime,
String punchsettings,
ConcurrentHashMap<String, Object> serialMap,
String halfcalrule,String halfcalpoint,String halfcalpoint2cross, String restShift) throws Exception {
Map<String,Object> workTimeMap = new HashMap<>();
int workmins = 0;
List<Object> workTimes = Collections.synchronizedList(new ArrayList<>());
List<Object> restTimes = Collections.synchronizedList(new ArrayList<>());
KQShiftOnOffWorkSectionComInfo kqShiftOnOffWorkSectionComInfo = new KQShiftOnOffWorkSectionComInfo();
KQShiftRestTimeSectionComInfo kqShiftRestTimeSectionComInfo = new KQShiftRestTimeSectionComInfo();
workTimes = kqShiftOnOffWorkSectionComInfo.getWorkSectionTimes(serialid);
if(workTimes != null && !workTimes.isEmpty()){
if("1".equalsIgnoreCase(isresttimeopen)) {
//如果开启了才去判断
restTimes = kqShiftRestTimeSectionComInfo.getRestSectionTimes(serialid);
}
if(NumberUtils.isNumber(worktime)){
if(worktime.indexOf('.') == -1){
workmins = Util.getIntValue(worktime,0);
}else {
worktime = worktime.substring(0,worktime.indexOf('.'));
workmins = Util.getIntValue(worktime,0);
}
}else{
workmins = 0;
kqLog.info("班次有问题serialid:"+serialid+"工作时长为:"+worktime);
}
workTimeMap.put("workTime", workTimes);
workTimeMap.put("restTime", restTimes);
workTimeMap.put("serialid", serialid);
//工作时长分钟数
workTimeMap.put("workmins", workmins+"");
workTimeMap.put("punchsettings", punchsettings);
workTimeMap.put("isresttimeopen", isresttimeopen);
workTimeMap.put("halfcalrule", halfcalrule);
workTimeMap.put("halfcalpoint", halfcalpoint);
workTimeMap.put("halfcalpoint2cross", halfcalpoint2cross);
workTimeMap.put("restShift", restShift.equals("1") ? "1" : "0");
ShiftInfoCominfoBean shiftInfoCominfoBean = setShiftInfoBean(workTimeMap);
serialMap.put(serialid, shiftInfoCominfoBean);
}
}
private ShiftInfoCominfoBean setShiftInfoBean(Map<String,Object> workTimeMap) throws Exception {
ShiftComIndex workComIndex = new WorkShiftComIndex(""+weaver.systeminfo.SystemEnv.getHtmlLabelName(10005306,weaver.general.ThreadVarLanguage.getLang())+"",workTimeMap);
ShiftComIndex restComIndex = new RestShiftComIndex(""+weaver.systeminfo.SystemEnv.getHtmlLabelName(10005307,weaver.general.ThreadVarLanguage.getLang())+"",workTimeMap);
ShiftComIndex halfComIndex = new HalfShiftComIndex(""+weaver.systeminfo.SystemEnv.getHtmlLabelName(10005308,weaver.general.ThreadVarLanguage.getLang())+"",workTimeMap);
//创建执行链
//前一天的都执行完了,去获取当天工作时段,再执行半天的规则
workComIndex.setDuration(restComIndex);
//执行完了半天的规则,再最后判断休息的时段
restComIndex.setDuration(halfComIndex);
ShiftInfoCominfoBean shiftInfoCominfoBean = new ShiftInfoCominfoBean();
workComIndex.handleDuration(shiftInfoCominfoBean);
return shiftInfoCominfoBean;
}
/**
*
* @param workdate
* @param serialidInfo
* @param containYesterday
* @return
*/
public Map<String,Object> getWorkButton(String workdate,Map<String,Object> serialidInfo, boolean containYesterday){
Map<String,Object> shiftMap = new HashMap<>();
//考勤按钮还是走缓存
KQShiftManagementRedis kqShiftManagementRedis = new KQShiftManagementRedis();
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
if(serialidInfo != null && !serialidInfo.isEmpty()){
LocalDate preLocalDate = LocalDate.parse(workdate);
String preSplitDate = "";
preLocalDate = preLocalDate.minusDays(1);
preSplitDate = preLocalDate.format(dateFormatter);
String serialid = Util.null2String(serialidInfo.get(workdate));
String preSerialid = Util.null2String(serialidInfo.get(preSplitDate));
if(containYesterday){
if(Util.getIntValue(preSerialid) > 0){
ShiftInfoCominfoBean pre_shiftInfoCominfoBean = kqShiftManagementRedis.getShiftInfoBean(preSerialid);
List<Object> timelineList = pre_shiftInfoCominfoBean.getTimelineList();
if(timelineList!=null && !timelineList.isEmpty()){
shiftMap.put("pre_timelineList", timelineList);
}
shiftMap.put("pre_isAcross", pre_shiftInfoCominfoBean.getIsAcross());
shiftMap.put("pre_allWorkTime", pre_shiftInfoCominfoBean.getAllWorkTime());
shiftMap.put("pre_allAcrossWorkTime", pre_shiftInfoCominfoBean.getAllAcrossWorkTime());
shiftMap.put("pre_signTime", pre_shiftInfoCominfoBean.getSignWorkTime());
shiftMap.put("pre_restTime", pre_shiftInfoCominfoBean.getRestAcrossLongTime());
}
}
if(Util.getIntValue(serialid) > 0){
ShiftInfoCominfoBean cur_shiftInfoCominfoBean = kqShiftManagementRedis.getShiftInfoBean(serialid);
Map<String,Object> shiftRuleMap = ShiftManagementToolKit.getShiftRuleInfo(serialid,false);
List<Object> timelineList = cur_shiftInfoCominfoBean.getTimelineList();
if(timelineList!=null && !timelineList.isEmpty()){
shiftMap.put("timelineList", timelineList);
}
shiftMap.put("isAcross", cur_shiftInfoCominfoBean.getIsAcross());
shiftMap.put("allWorkTime", cur_shiftInfoCominfoBean.getAllWorkTime());
shiftMap.put("allAcrossWorkTime", cur_shiftInfoCominfoBean.getAllAcrossWorkTime());
shiftMap.put("signTime", cur_shiftInfoCominfoBean.getSignWorkTime());
shiftMap.put("restTime", cur_shiftInfoCominfoBean.getRestAcrossLongTime());
if(shiftRuleMap != null && !shiftRuleMap.isEmpty()){
shiftMap.put("shiftRuleMap", shiftRuleMap);
}
}
}
return shiftMap;
}
/**
*
* @param workdate
* @param serialidInfo
* @param containYesterday
* @return
* shiftInfoBean ,0-24
* shiftLongInfoBean 0-48
*/
public Map<String,Object> getWorkDuration(String workdate,Map<String,Object> serialidInfo,boolean containYesterday){
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
Map<String,Object> dateWorkTimeMap = new HashMap<>();
LocalDate preLocalDate = LocalDate.parse(workdate);
String preSplitDate = "";
preLocalDate = preLocalDate.minusDays(1);
preSplitDate = preLocalDate.format(dateFormatter);
if(serialidInfo != null && !serialidInfo.isEmpty()){
String preSerialid = Util.null2String(serialidInfo.get(preSplitDate));
String serialid = Util.null2String(serialidInfo.get(workdate));
ShiftInfoBean shiftInfoBean = new ShiftInfoBean();
shiftInfoBean.setPreSplitDate(preSplitDate);
shiftInfoBean.setSplitDate(workdate);
shiftInfoBean.setD_Mins(0.0);
shiftInfoBean.setPreSerialid(preSerialid);
shiftInfoBean.setSerialid(serialid);
if(containYesterday){
if(Util.getIntValue(serialid) > 0 || Util.getIntValue(preSerialid) > 0){
fillShiftInfoBean(shiftInfoBean, preSerialid, serialid);
dateWorkTimeMap.put("shiftInfoBean", shiftInfoBean);
}
}else{
if(Util.getIntValue(serialid) > 0){
fillShiftInfoBean(shiftInfoBean, preSerialid, serialid);
dateWorkTimeMap.put("shiftInfoBean", shiftInfoBean);
}
}
}
return dateWorkTimeMap;
}
/**
* id+
* @param workdate
* @param serialidInfo
* @return
*/
public Map<String,Object> getWorkTimeMap(String workdate,Map<String,Object> serialidInfo){
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
Map<String,Object> dateWorkTimeMap = new HashMap<>();
LocalDate preLocalDate = LocalDate.parse(workdate);
String preSplitDate = "";
preLocalDate = preLocalDate.minusDays(1);
preSplitDate = preLocalDate.format(dateFormatter);
if(serialidInfo != null && !serialidInfo.isEmpty()){
String preSerialid = Util.null2String(serialidInfo.get(preSplitDate));
String serialid = Util.null2String(serialidInfo.get(workdate));
getShiftInfoBeanMap(dateWorkTimeMap,preSerialid, serialid);
}
return dateWorkTimeMap;
}
/**
*
* @param dateWorkTimeMap
* @param preSerialid
* @param serialid
*/
private void getShiftInfoBeanMap(Map<String,Object> dateWorkTimeMap,String preSerialid, String serialid) {
ShiftInfoCominfoBean cur_shiftInfoCominfoBean = getShiftInfoCominfoBean(serialid);
if(cur_shiftInfoCominfoBean != null){
dateWorkTimeMap.put("restTime",cur_shiftInfoCominfoBean.getRestAcrossLongTime());
dateWorkTimeMap.put("workTime",cur_shiftInfoCominfoBean.getWorkAcrossLongTime());
dateWorkTimeMap.put("workMins",cur_shiftInfoCominfoBean.getWorkmins());
dateWorkTimeMap.put("isAcross",cur_shiftInfoCominfoBean.getIsAcross());
dateWorkTimeMap.put("signTime", cur_shiftInfoCominfoBean.getSignWorkTime());
}
}
/**
*
* @param shiftInfoBean
* @param preSerialid
* @param serialid
*/
private void fillShiftInfoBean(ShiftInfoBean shiftInfoBean,String preSerialid,String serialid){
ShiftInfoCominfoBean pre_shiftInfoCominfoBean = getShiftInfoCominfoBean(preSerialid);
ShiftInfoCominfoBean cur_shiftInfoCominfoBean = getShiftInfoCominfoBean(serialid);
Map<String,Object> pre_shiftRuleMap = ShiftManagementToolKit.getShiftRuleInfo(preSerialid,false);
Map<String,Object> shiftRuleMap = ShiftManagementToolKit.getShiftRuleInfo(serialid,false);
//把前一个班次的填充好
if(pre_shiftInfoCominfoBean != null){
shiftInfoBean.setPreWorkIndex(pre_shiftInfoCominfoBean.getPreWorkTimeIndex());
shiftInfoBean.setPreWorkAcrossIndex(pre_shiftInfoCominfoBean.getWorkAcrossTimeIndex());
shiftInfoBean.setPreWorkMinsAcrossIndex(pre_shiftInfoCominfoBean.getWorkPunchMins());
shiftInfoBean.setPreRestIndex(pre_shiftInfoCominfoBean.getPreRestTimeIndex());
shiftInfoBean.setPreHalfWorkIndex(pre_shiftInfoCominfoBean.getHalfWorkIndex());
shiftInfoBean.setPreWorkmins(pre_shiftInfoCominfoBean.getWorkmins());
shiftInfoBean.setPreAllWorkTime(pre_shiftInfoCominfoBean.getAllWorkTime());
shiftInfoBean.setPreAllAcrossWorkTime(pre_shiftInfoCominfoBean.getAllAcrossWorkTime());
shiftInfoBean.setPreAllRestTime(pre_shiftInfoCominfoBean.getAllRestTime());
shiftInfoBean.setPreAllAcrossRestTime(pre_shiftInfoCominfoBean.getAllAcrossRestTime());
shiftInfoBean.setPreSerialid(preSerialid);
shiftInfoBean.setIsPreAcross(pre_shiftInfoCominfoBean.getIsAcross());
shiftInfoBean.setShiftRuleMap(pre_shiftRuleMap);
}
//把当前班次的填充好
if(cur_shiftInfoCominfoBean != null){
shiftInfoBean.setWorkIndex(cur_shiftInfoCominfoBean.getWorkTimeIndex());
shiftInfoBean.setWorkAcrossIndex(cur_shiftInfoCominfoBean.getWorkAcrossTimeIndex());
shiftInfoBean.setWorkMinsAcrossIndex(cur_shiftInfoCominfoBean.getWorkPunchMins());
shiftInfoBean.setRestIndex(cur_shiftInfoCominfoBean.getRestTimeIndex());
shiftInfoBean.setHalfWorkIndex(cur_shiftInfoCominfoBean.getHalfWorkIndex());
shiftInfoBean.setWorkmins(cur_shiftInfoCominfoBean.getWorkmins());
shiftInfoBean.setAllWorkTime(cur_shiftInfoCominfoBean.getAllWorkTime());
shiftInfoBean.setAllAcrossWorkTime(cur_shiftInfoCominfoBean.getAllAcrossWorkTime());
shiftInfoBean.setAllRestTime(cur_shiftInfoCominfoBean.getAllRestTime());
shiftInfoBean.setAllAcrossRestTime(cur_shiftInfoCominfoBean.getAllAcrossRestTime());
shiftInfoBean.setAllLongWorkTime(cur_shiftInfoCominfoBean.getAllLongWorkTime());
shiftInfoBean.setRestLongTimeIndex(cur_shiftInfoCominfoBean.getRestLongTimeIndex());
shiftInfoBean.setWorkLongTimeIndex(cur_shiftInfoCominfoBean.getWorkLongTimeIndex());
shiftInfoBean.setIsAcross(cur_shiftInfoCominfoBean.getIsAcross());
shiftInfoBean.setSerialid(serialid);
shiftInfoBean.setShiftRuleMap(shiftRuleMap);
if(cur_shiftInfoCominfoBean.getWorkAcrossLongTime() != null){
List<Object> workTime1 = cur_shiftInfoCominfoBean.getWorkAcrossLongTime().stream().collect(Collectors.toList());
List<TimeScopeEntity> lsWorkTime = new KQWorkTime().formatTimeScope(workTime1, false);
shiftInfoBean.setWorkTime(lsWorkTime);
}
if(cur_shiftInfoCominfoBean.getSignWorkTime() != null){
List<Object> signTime1 = cur_shiftInfoCominfoBean.getSignWorkTime().stream().collect(Collectors.toList());
List<TimeScopeEntity> lsSignTime = new KQWorkTime().formatTimeScope(signTime1, true);
shiftInfoBean.setSignTime(lsSignTime);
}
shiftInfoBean.setHalfcalrule(cur_shiftInfoCominfoBean.getHalfcalrule());
shiftInfoBean.setHalfcalpoint(cur_shiftInfoCominfoBean.getHalfcalpoint());
shiftInfoBean.setHalfcalpoint2cross(cur_shiftInfoCominfoBean.getHalfcalpoint2cross());
shiftInfoBean.setWorkAcrossTime(cur_shiftInfoCominfoBean.getWorkAcrossTime());
shiftInfoBean.setEachWorkMins(cur_shiftInfoCominfoBean.getEachWorkMins());
}
}
public void removeShiftManagementCache(){
KQShiftRestTimeSectionComInfo kqShiftRestTimeSectionComInfo = new KQShiftRestTimeSectionComInfo();
KQShiftOnOffWorkSectionComInfo kqShiftOnOffWorkSectionComInfo = new KQShiftOnOffWorkSectionComInfo();
kqShiftRestTimeSectionComInfo.removeShiftRestTimeSectionCache();
kqShiftOnOffWorkSectionComInfo.removeShiftWorkSectionCache();
super.removeCache();
//改用redis和staticobj的方式
KQShiftManagementRedis kqShiftManagementRedis = new KQShiftManagementRedis();
kqShiftManagementRedis.resetShiftValWithRedis();
}
/**
* shiftInfoCominfoBean
* @param serialid
* @return
*/
public ShiftInfoCominfoBean getShiftInfoCominfoBean(String serialid){
// Object object = getObjValue(shiftbean, serialid);
// if(object != null){
// return (ShiftInfoCominfoBean) object;
// }else{
// return null;
// }
//改用redis和staticobj的方式
KQShiftManagementRedis kqShiftManagementRedis = new KQShiftManagementRedis();
return kqShiftManagementRedis.getShiftInfoBeanMapBySql(serialid);
}
/**
* shiftInfoCominfoBean
* @param workdate
* @param serialidInfo
* @return
*/
public ShiftInfoCominfoBean getShiftInfoCominfoBean(String workdate,Map<String,Object> serialidInfo){
ShiftInfoCominfoBean shiftInfoCominfoBean = null;
if(serialidInfo != null && !serialidInfo.isEmpty()){
String serialid = Util.null2String(serialidInfo.get(workdate));
if(Util.getIntValue(serialid) > 0){
shiftInfoCominfoBean = getShiftInfoCominfoBean(serialid);
}
}
return shiftInfoCominfoBean;
}
}

@ -0,0 +1,299 @@
package com.engine.kq.biz;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cloudstore.dev.api.util.Util_DataCache;
import com.engine.kq.biz.chain.cominfo.HalfShiftComIndex;
import com.engine.kq.biz.chain.cominfo.RestShiftComIndex;
import com.engine.kq.biz.chain.cominfo.ShiftComIndex;
import com.engine.kq.biz.chain.cominfo.ShiftInfoCominfoBean;
import com.engine.kq.biz.chain.cominfo.WorkShiftComIndex;
import com.engine.kq.biz.chain.shiftinfo.ShiftInfoBean;
import com.engine.kq.cmd.shiftmanagement.toolkit.ShiftManagementToolKit;
import com.engine.kq.entity.TimeScopeEntity;
import com.engine.kq.log.KQLog;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import org.apache.commons.lang.math.NumberUtils;
import weaver.cache.CacheBase;
import weaver.cache.CacheColumn;
import weaver.cache.CacheColumnType;
import weaver.cache.CacheItem;
import weaver.cache.CacheMap;
import weaver.cache.PKColumn;
import weaver.cluster.CacheManager;
import weaver.cluster.CacheMessage;
import weaver.conn.RecordSet;
import weaver.email.MailReciveStatusUtils;
import weaver.email.domain.AccountStautsBean;
import weaver.general.BaseBean;
import weaver.general.StaticObj;
import weaver.general.Util;
/**
* redis
*/
public class KQShiftManagementRedis {
public static final String KQ_SHIFT_COMINFO_STATUS = "KQ_SHIFT_COMINFO_STATUS";
private static final BaseBean baseBean = new BaseBean();
/**
* E9 radisfalseradistrue使radis
*/
public static boolean isNewSession = false;
/**
* 线
*/
public static ConcurrentHashMap<String, Object> KQ_SHIFT_COMINFO_STATUS_MAP = new ConcurrentHashMap<String, Object>();
// 初始化执行
static {
useNewSessionMode();
}
/**
* redis
*/
public static void useNewSessionMode() {
String status = Util.null2String(baseBean.getPropValue("weaver_new_session", "status")).trim();
isNewSession = "1".equals(status);
}
private KQLog kqLog = new KQLog();
public void getShiftInfoBean(String serialid, String isresttimeopen, String worktime,
String punchsettings,
ConcurrentHashMap<String, ShiftInfoCominfoBean> shiftInfoBeanMap,
String halfcalrule,String halfcalpoint,String halfcalpoint2cross) throws Exception {
getShiftInfoBean(serialid, isresttimeopen, worktime, punchsettings, shiftInfoBeanMap, halfcalrule, halfcalpoint, halfcalpoint2cross, "0");
}
public void getShiftInfoBean(String serialid, String isresttimeopen, String worktime,
String punchsettings,
ConcurrentHashMap<String, ShiftInfoCominfoBean> shiftInfoBeanMap,
String halfcalrule,String halfcalpoint,String halfcalpoint2cross, String restShift) throws Exception {
Map<String,Object> workTimeMap = new HashMap<>();
int workmins = 0;
List<Object> workTimes = Collections.synchronizedList(new ArrayList<>());
List<Object> restTimes = Collections.synchronizedList(new ArrayList<>());
KQShiftOnOffWorkSectionComInfo kqShiftOnOffWorkSectionComInfo = new KQShiftOnOffWorkSectionComInfo();
KQShiftRestTimeSectionComInfo kqShiftRestTimeSectionComInfo = new KQShiftRestTimeSectionComInfo();
workTimes = kqShiftOnOffWorkSectionComInfo.getWorkSectionTimes(serialid);
if(workTimes != null && !workTimes.isEmpty()){
if("1".equalsIgnoreCase(isresttimeopen)) {
//如果开启了才去判断
restTimes = kqShiftRestTimeSectionComInfo.getRestSectionTimes(serialid);
}
if(NumberUtils.isNumber(worktime)){
if(worktime.indexOf('.') == -1){
workmins = Util.getIntValue(worktime,0);
}else {
worktime = worktime.substring(0,worktime.indexOf('.'));
workmins = Util.getIntValue(worktime,0);
}
}else{
workmins = 0;
kqLog.info("班次有问题serialid:"+serialid+"工作时长为:"+worktime);
}
workTimeMap.put("workTime", workTimes);
workTimeMap.put("restTime", restTimes);
workTimeMap.put("serialid", serialid);
//工作时长分钟数
workTimeMap.put("workmins", workmins+"");
workTimeMap.put("punchsettings", punchsettings);
workTimeMap.put("isresttimeopen", isresttimeopen);
workTimeMap.put("halfcalrule", halfcalrule);
workTimeMap.put("halfcalpoint", halfcalpoint);
workTimeMap.put("halfcalpoint2cross", halfcalpoint2cross);
workTimeMap.put("restShift", restShift.equals("1") ? "1" : "0");
ShiftInfoCominfoBean shiftInfoCominfoBean = setShiftInfoBean(workTimeMap);
shiftInfoBeanMap.put(serialid, shiftInfoCominfoBean);
}
}
public ShiftInfoCominfoBean setShiftInfoBean(Map<String,Object> workTimeMap) throws Exception {
ShiftComIndex workComIndex = new WorkShiftComIndex(""+weaver.systeminfo.SystemEnv.getHtmlLabelName(10005306,weaver.general.ThreadVarLanguage.getLang())+"",workTimeMap);
ShiftComIndex restComIndex = new RestShiftComIndex(""+weaver.systeminfo.SystemEnv.getHtmlLabelName(10005307,weaver.general.ThreadVarLanguage.getLang())+"",workTimeMap);
ShiftComIndex halfComIndex = new HalfShiftComIndex(""+weaver.systeminfo.SystemEnv.getHtmlLabelName(10005308,weaver.general.ThreadVarLanguage.getLang())+"",workTimeMap);
//创建执行链
//前一天的都执行完了,去获取当天工作时段,再执行半天的规则
workComIndex.setDuration(restComIndex);
//执行完了半天的规则,再最后判断休息的时段
restComIndex.setDuration(halfComIndex);
ShiftInfoCominfoBean shiftInfoCominfoBean = new ShiftInfoCominfoBean();
workComIndex.handleDuration(shiftInfoCominfoBean);
return shiftInfoCominfoBean;
}
public ConcurrentHashMap<String,ShiftInfoCominfoBean> getShiftInfoBeanMap() {
ConcurrentHashMap<String,ShiftInfoCominfoBean> shiftInfoBeanMap = new ConcurrentHashMap<>();
kqLog = new KQLog();
try {
RecordSet rs = new RecordSet();
String getShiftInfo = "select * from kq_ShiftManagement where 1=1 order by id ";
rs.executeQuery(getShiftInfo);
while(rs.next()){
String serialid = rs.getString("id");
try {
String isresttimeopen = rs.getString("isresttimeopen");
String worktime = rs.getString("worktime");
String punchsetting = "1";
String halfcalrule = rs.getString("halfcalrule");
halfcalrule = Util.null2String(halfcalrule).length() == 0 ? "0" : halfcalrule;
String halfcalpoint = rs.getString("halfcalpoint");
String halfcalpoint2cross = rs.getString("halfcalpoint2cross");
String restShift = rs.getString("rest_shift");
getShiftInfoBean(serialid,isresttimeopen,worktime,punchsetting,shiftInfoBeanMap,halfcalrule,halfcalpoint,halfcalpoint2cross,restShift);
} catch (Exception e) {
kqLog.info("班次缓存报错:getShiftInfoBeanMap:serialid:"+serialid);
StringWriter errorsWriter = new StringWriter();
e.printStackTrace(new PrintWriter(errorsWriter));
kqLog.info(errorsWriter.toString());
}
}
} catch (Exception e) {
kqLog.info("班次缓存报错:getShiftInfoBeanMap:");
StringWriter errorsWriter = new StringWriter();
e.printStackTrace(new PrintWriter(errorsWriter));
kqLog.info(errorsWriter.toString());
}
return shiftInfoBeanMap;
}
public ShiftInfoCominfoBean getShiftInfoBeanMapBySql(String serialid) {
ConcurrentHashMap<String,ShiftInfoCominfoBean> shiftInfoBeanMap = new ConcurrentHashMap<>();
kqLog = new KQLog();
try {
RecordSet rs = new RecordSet();
String getShiftInfo = "select * from kq_ShiftManagement where 1=1 and id=? order by id ";
rs.executeQuery(getShiftInfo,serialid);
if(rs.next()){
String isresttimeopen = rs.getString("isresttimeopen");
String worktime = rs.getString("worktime");
String punchsetting = "1";
String halfcalrule = rs.getString("halfcalrule");
halfcalrule = Util.null2String(halfcalrule).length() == 0 ? "0" : halfcalrule;
String halfcalpoint = rs.getString("halfcalpoint");
String halfcalpoint2cross = rs.getString("halfcalpoint2cross");
String restShift = rs.getString("rest_shift");
getShiftInfoBean(serialid,isresttimeopen,worktime,punchsetting,shiftInfoBeanMap,halfcalrule,halfcalpoint,halfcalpoint2cross,restShift);
}
if(shiftInfoBeanMap.containsKey(serialid)){
return shiftInfoBeanMap.get(serialid);
}
} catch (Exception e) {
kqLog.info("班次缓存报错:getShiftInfoBeanMapBySql:");
StringWriter errorsWriter = new StringWriter();
e.printStackTrace(new PrintWriter(errorsWriter));
kqLog.info(errorsWriter.toString());
}
return null;
}
/**
* redis staticobj map
*
*/
public void resetShiftValWithRedis(){
boolean isCluster = StaticObj.getInstance().isCluster();
Map<String, ShiftInfoCominfoBean> shiftInfoBeanMap = getShiftInfoBeanMap();
if(isCluster) {
if(isNewSession) {
try {
Util_DataCache.setObjValWithRedis(KQ_SHIFT_COMINFO_STATUS, shiftInfoBeanMap);
} catch (IOException e) {
baseBean.writeLog(e);
StaticObj staticObj = StaticObj.getInstance();
staticObj.putObject(KQ_SHIFT_COMINFO_STATUS, shiftInfoBeanMap);
sendNotificationToCache(CacheManager.ACTION_UPDATE, KQ_SHIFT_COMINFO_STATUS);
}
}else{
StaticObj staticObj = StaticObj.getInstance();
staticObj.putObject(KQ_SHIFT_COMINFO_STATUS, shiftInfoBeanMap);
sendNotificationToCache(CacheManager.ACTION_UPDATE, KQ_SHIFT_COMINFO_STATUS);
}
} else {
KQ_SHIFT_COMINFO_STATUS_MAP.put(KQ_SHIFT_COMINFO_STATUS, shiftInfoBeanMap);
}
}
public ShiftInfoCominfoBean getShiftInfoBean(String serialid){
ShiftInfoCominfoBean shiftInfoCominfoBean = null;
Map<String, ShiftInfoCominfoBean> shiftInfoBeanMap = getShiftBeanMapValWithRedis();
if(shiftInfoBeanMap == null){
resetShiftValWithRedis();
shiftInfoBeanMap = getShiftBeanMapValWithRedis();
}
if(shiftInfoBeanMap != null && shiftInfoBeanMap.containsKey(serialid)){
shiftInfoCominfoBean = shiftInfoBeanMap.get(serialid);
}
return shiftInfoCominfoBean;
}
public Map<String, ShiftInfoCominfoBean> getShiftBeanMapValWithRedis() {
Map<String, ShiftInfoCominfoBean> shiftInfoBeanMap = null;
boolean isCluster = StaticObj.getInstance().isCluster();
if(isCluster) { // 判断是否是集群环境。true 是集群false非集群
if(isNewSession){
try {
if(Util_DataCache.containsKeyWithRedis(KQ_SHIFT_COMINFO_STATUS)) {
shiftInfoBeanMap = (Map<String, ShiftInfoCominfoBean>) Util_DataCache.getObjValWithRedis(KQ_SHIFT_COMINFO_STATUS);
}
}catch (Exception e){
StaticObj staticObj = StaticObj.getInstance();
shiftInfoBeanMap = (Map<String, ShiftInfoCominfoBean>) staticObj.getObject(KQ_SHIFT_COMINFO_STATUS);
}
}else{
StaticObj staticObj = StaticObj.getInstance();
shiftInfoBeanMap = (Map<String, ShiftInfoCominfoBean>) staticObj.getObject(KQ_SHIFT_COMINFO_STATUS);
}
} else {
shiftInfoBeanMap = (Map<String, ShiftInfoCominfoBean>) KQ_SHIFT_COMINFO_STATUS_MAP.get(KQ_SHIFT_COMINFO_STATUS);
}
return shiftInfoBeanMap;
}
/**
* .
* @param optType
* @param cacheKey
*/
public static void sendNotificationToCache(String optType, String cacheKey) {
StaticObj staticObj = StaticObj.getInstance();
if(staticObj.isCluster()) {
CacheMessage msg = new CacheMessage();
msg.setAction(optType);
msg.setCacheType(cacheKey);
staticObj.sendNotification(msg);
}
}
}

@ -0,0 +1,426 @@
package com.engine.kq.biz;
import com.alibaba.fastjson.JSON;
import com.api.customization.qc2988837.Util.KqCustomUtil;
import com.engine.kq.biz.chain.cominfo.ShiftInfoCominfoBean;
import com.engine.kq.cmd.shiftmanagement.toolkit.ShiftManagementToolKit;
import com.engine.kq.entity.KQGroupEntity;
import com.engine.kq.entity.TimeScopeEntity;
import com.engine.kq.entity.TimeSignScopeEntity;
import com.engine.kq.entity.WorkTimeEntity;
import com.engine.kq.log.KQLog;
import weaver.common.DateUtil;
import weaver.common.StringUtil;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.resource.ResourceComInfo;
import java.util.*;
public class KQWorkTime extends BaseBean {
private KQLog kqLog = new KQLog();
private boolean isFormat = false;
public WorkTimeEntity getWorkTime(String userId) {
return getWorkTime(userId, null);
}
/**
*
* @param userId
* @param workdate
* @return
*/
public boolean isWorkDay(String userId, String workdate) {
boolean isWorkDay = false;
if(!KQHolidaySetBiz.isHoliday(userId,workdate)) {//不是节假日,且有班次
Map<String, Object> serialInfo = getSerialInfo( userId, workdate, false);
if(!serialInfo.isEmpty()){
if(Util.null2String(serialInfo.get("kqType")).equals("3")){
Map<String, Object> result = (Map<String, Object>) serialInfo.get(workdate);
if(result!=null && result.size()>0 && Util.null2String(result.get("signStart")).length()>0 && Util.null2String(result.get("workMins")).length()>0){
isWorkDay = true;
}
}else{
int serialid = Util.getIntValue(Util.null2String(serialInfo.get(workdate)), 0);
KQShiftManagementComInfo kQShiftManagementComInfo = new KQShiftManagementComInfo();
int restShift = StringUtil.parseToInt(kQShiftManagementComInfo.getRestShift(String.valueOf(serialid)), 0);
isWorkDay = restShift == 1 ? false : serialid > 0;
}
}
}
return isWorkDay;
}
public Map<String, Object> getWorkButton(String userId, String workdate, boolean containYesterday) {
Map<String, Object> result = new HashMap<>();
try {
KQShiftManagementComInfo kQShiftManagementComInfo = new KQShiftManagementComInfo();
Map<String,Object> serialInfo = getSerialInfo(userId, workdate, containYesterday, true);
kqLog.info("考勤组获取成员所在的班次 getWorkButton:serialInfo:"+ serialInfo);
String kqType = Util.null2String(serialInfo.get("kqType"));
if(serialInfo!=null&&serialInfo.size()>0){
if("3".equalsIgnoreCase(kqType)){
//自由班制的单独处理
result = (Map<String, Object>) 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<String, Object> getWorkDuration(String userId, String workdate,boolean containYesterday,boolean isLog) {
Map<String, Object> result = new HashMap<>();
try {
Map<String,Object> workTimeMap = null;
KQShiftManagementComInfo kQShiftManagementComInfo = new KQShiftManagementComInfo();
Map<String,Object> 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<String, Object>) 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<String, Object> 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<String,Object> workTimeMap = null;
KQShiftManagementComInfo kQShiftManagementComInfo = new KQShiftManagementComInfo();
Map<String,Object> 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<String,Object> serialInfo = getSerialInfo(userId, workdate, false, true);
workTimeEntity.setIsExclude(Util.null2String(serialInfo.get("isExclude")).equals("1"));
workTimeEntity.setGroupId(Util.null2String(serialInfo.get("groupId")));
if(serialInfo!=null&&serialInfo.size()>0) {
String kqType = Util.null2String(serialInfo.get("kqType"));
if(kqType.equals("3")){
Map<String,Object> map = (Map<String,Object>)serialInfo.get(workdate);
workTimeEntity.setGroupId(Util.null2String(serialInfo.get("groupId")));
workTimeEntity.setGroupName(Util.null2String(serialInfo.get("groupName")));
workTimeEntity.setKQType(Util.null2String(kqType));
workTimeEntity.setIsExclude(Util.null2String(serialInfo.get("isExclude")).equals("1"));
if(map!=null) {
workTimeEntity.setSignStart(Util.null2String(map.get("signStart")));
workTimeEntity.setWorkMins(Util.getIntValue(Util.null2String(map.get("workMins"))));
workTimeEntity.setCalmethod(Util.null2String(map.get("calmethod")));
}
workTimeEntity.setRestShift(0);
}else{
int serialid = Util.getIntValue(Util.null2String(serialInfo.get(workdate)), 0);
int restShift = StringUtil.parseToInt(kQShiftManagementComInfo.getRestShift(String.valueOf(serialid)), 0);
if(kqType.equals("1") && KQHolidaySetBiz.isHoliday(userId,workdate)) restShift = 1;
workTimeEntity.setRestShift(restShift);
if (serialid > 0){
Map<String,Object> dateWorkTimeMap = kQShiftManagementComInfo.getWorkTimeMap(workdate, serialInfo);
workTimeEntity.setGroupId(Util.null2String(serialInfo.get("groupId")));
workTimeEntity.setGroupName(Util.null2String(serialInfo.get("groupName")));
workTimeEntity.setKQType(kqType);
workTimeEntity.setSerialId(""+serialid);
workTimeEntity.setRestTime(formatTimeScope((List<Object>)dateWorkTimeMap.get("restTime"),false));
workTimeEntity.setShiftRuleInfo(ShiftManagementToolKit.getShiftRuleInfo(""+serialid,true));
workTimeEntity.setSignTime(formatTimeScope((List<Object>)dateWorkTimeMap.get("signTime"),false));
workTimeEntity.setWorkTime(formatTimeScope((List<Object>)dateWorkTimeMap.get("workTime"),true));
workTimeEntity.setRestTime(formatTimeScope((List<Object>)dateWorkTimeMap.get("restTime"),false));
if(restShift != 1) {
workTimeEntity.setWorkMins(Util.getIntValue(Util.null2String(dateWorkTimeMap.get("workMins"))));
}
workTimeEntity.setIsAcross(Util.null2String(dateWorkTimeMap.get("isAcross")));
}
}
}
//如果在建模表维护的人员对应日期无需考勤
KqCustomUtil kqCustomUtil = new KqCustomUtil();
boolean isExculde = kqCustomUtil.isExclude(userId,workdate);
if (isExculde){
workTimeEntity.setIsExclude(true);
}
} catch (Exception e) {
writeLog(e);
}
return workTimeEntity;
}
public List<TimeScopeEntity> formatTimeScope(List<Object> timeScope, boolean needWorkMins){
List<TimeScopeEntity> timeScopes = new ArrayList<>();
KQTimesArrayComInfo kqTimesArrayComInfo = new KQTimesArrayComInfo();
TimeScopeEntity timeScopeEntity = null;
for(int i=0;timeScope!=null && i<timeScope.size();i++){
Map<String,Object> obj = (Map<String,Object>)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<String, Object> serialInfo = getSerialInfo( userId, workdate, false);
return serialInfo!=null?Util.null2String(serialInfo.get(workdate)):"";
}
/**
*
* @param userId
* @param workdate
* @param containYesterday
* @return
*/
public Map<String,Object> getSerialInfo(String userId, String workdate, boolean containYesterday) {
return getSerialInfo(userId, workdate, containYesterday, false);
}
public Map<String,Object> getSerialInfo(String userId, String workdate, boolean containYesterday, boolean includeHoliday) {
Map<String, Object> 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<String, Object> pre_serialInfo = getSerialInfo(userId, preworkdate, false, includeHoliday);
if(pre_serialInfo != null && !pre_serialInfo.isEmpty()){
if(pre_serialInfo.containsKey(preworkdate)){
serialInfo.put(preworkdate,pre_serialInfo.get(preworkdate));//获取前一天的班次
}
}
}
if(kqGroupEntity==null){//不在考勤组内
return serialInfo;
}
//无需考勤人员需要计算考勤时间,但不计算异常状态
// if (("," + kqGroupEntity.getExcludeid() + ",").indexOf("," + userId + ",")>-1) {//排除人员无需计算考勤时间
// return serialInfo;
// }
if (("," + kqGroupEntity.getExcludeid() + ",").indexOf("," + userId + ",")>-1) {//排除人员无需计算考勤时间
serialInfo.put("isExclude","1");
}
String begindate = Util.null2String(resourceComInfo.getCreatedate(userId)).trim();
String companyStartDate = Util.null2String(resourceComInfo.getCompanyStartDate(userId)).trim();
if(companyStartDate.length()!=10){
companyStartDate = "";
}
if(companyStartDate.length()>0 && companyStartDate.indexOf("-")>0){
begindate=companyStartDate;
}
if(begindate.length()>0 && DateUtil.compDate(begindate,workdate)<0 ){//人员入职日期前无需计算考勤,如果没有入职日期,已创建日期为准
// kqLog.writeLog("getSerialInfo 入职日期不满足条件:userId:"+userId+":workdate:"+workdate+":companyStartDate:"+companyStartDate+":begindate:"+begindate+":DateUtil.compDate(begindate,workdate):"+DateUtil.compDate(begindate,workdate));
return serialInfo;
}
String endDate = Util.null2String(resourceComInfo.getEndDate(userId));
String status = Util.null2String(resourceComInfo.getStatus(userId));
if(status.equals("0")||status.equals("1")||status.equals("2")||status.equals("3")){
//在职
}else{
//其他状态
if(endDate.length()>0 && DateUtil.compDate(endDate,workdate)>0){//人员合同结束日期无需计算考勤
// kqLog.writeLog("getSerialInfo 人员合同结束日期不满足条件:userId:"+userId+":workdate:"+workdate+":endDate:"+endDate+":status:"+status+":DateUtil.compDate(endDate,workdate):"+DateUtil.compDate(endDate,workdate));
return serialInfo;
}
}
String groupid = kqGroupEntity.getId();
String groupname = kqGroupEntity.getGroupname();
String kqtype = kqGroupEntity.getKqtype();
int dayOfweek = DateUtil.getWeek(workdate)-1;
int preDayOfweek = DateUtil.getWeek(preworkdate)-1;
boolean preDayIsHoliday = KQHolidaySetBiz.isHoliday(userId,preworkdate);
boolean isHoliday = KQHolidaySetBiz.isHoliday(userId,workdate);
String serialid = "";
if(!kqtype.equals("2")){//处理调配工作日(除排班外)
if(KQHolidaySetBiz.getChangeType(groupid,preworkdate)==2){
preDayOfweek = KQHolidaySetBiz.getRelatedDay(userId,preworkdate);
}
if(KQHolidaySetBiz.getChangeType(groupid,workdate)==2){
dayOfweek = KQHolidaySetBiz.getRelatedDay(userId,workdate);
}
}
serialInfo.put("groupId",groupid);
serialInfo.put("groupName",groupname);
serialInfo.put("kqType",kqtype);
serialInfo.put("isHoliday",isHoliday);
if(includeHoliday) isHoliday = false;
if (kqtype.equals("1")) {//固定班
// if(containYesterday && !serialInfo.containsKey(preworkdate)) {
// serialid = Util.null2String(kqFixedSchedulceComInfo.getSerialid(groupid,preDayOfweek));
// if(!preDayIsHoliday&&serialid.length()>0 && Util.getIntValue(serialid) > 0){
// serialInfo.put(preworkdate,serialid);//获取前一天的班次
// }
// }
if(!serialInfo.containsKey(workdate)){
serialid = Util.null2String(kqFixedSchedulceComInfo.getSerialid(groupid,dayOfweek));
if( !isHoliday&&serialid.length()>0 && Util.getIntValue(serialid) > 0){
serialInfo.put(workdate, serialid);//获取当天的班次
}
}
} else if (kqtype.equals("2")) {//排班
//先取排班设置里的班次
// serialid = Util.null2String(kqShiftScheduleComInfo.getSerialId(userId,preworkdate));
// if(containYesterday && serialid.length()>0 && !preDayIsHoliday && Util.getIntValue(serialid) > 0){
// serialInfo.put(preworkdate,Util.null2String(kqShiftScheduleComInfo.getSerialId(userId,preworkdate)));//获取前一天的班次
// }
serialid = Util.null2String(kqShiftScheduleComInfo.getSerialId(userId,workdate));
if(serialid.length()>0 && !isHoliday && Util.getIntValue(serialid) > 0){
serialInfo.put(workdate,Util.null2String(kqShiftScheduleComInfo.getSerialId(userId,workdate)));//获取当天的班次
}
} else if (kqtype.equals("3")) {//自由班
List weekDay = Util.splitString2List(kqGroupEntity.getWeekday(), ",");
String signStart = Util.null2String(kqGroupEntity.getSignstart());//签到开始时间
int workMins = Util.getIntValue(Util.getIntValues(""+Util.getDoubleValue(Util.null2String(kqGroupEntity.getWorkhour()))*60));//工作时长
if(signStart.length()>0 && workMins>0) {
String calmethod = Util.null2s(kqGroupEntity.getCalmethod(),"1");
Map<String, Object> 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;
}
}

@ -0,0 +1,519 @@
package com.engine.kq.biz.chain.cominfo;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
*/
public class ShiftInfoCominfoBean implements Serializable {
private static final long serialVersionUID = -1735765502081116461L;
/**
*
*/
private List<String[]> preWorkTime;
/**
* 0-24
*/
private List<String[]> workTime;
/**
* 0-24
*/
private List<String[]> workAcrossTime;
/**
*
*/
private List<int[]> preWorkTimeIndex;
/**
* 0-24
*/
private List<int[]> workTimeIndex;
/**
* 0-48
*/
private List<int[]> workLongTimeIndex;
/**
* 0-48
*/
private List<int[]> restLongTimeIndex;
/**
* 48
*/
private List<String> allLongWorkTime;
/**
* 0-24
*/
private List<int[]> workAcrossTimeIndex;
/**
* 48
*/
private List<Map<String,String>> workAcrossLongTime;
/**
* 退
*/
private List<String[][]> workPunchMins;
/**
*
*/
private List<String[]> preRestTime;
/**
* 0-24
*/
private List<String[]> restTime;
/**
* r0-24
*/
private List<String[]> restAcrossTime;
/**
*
*/
private List<int[]> preRestTimeIndex;
/**
* 0-24
*/
private List<int[]> restTimeIndex;
/**
* r0-24
*/
private List<int[]> restAcrossTimeIndex;
/**
* 48
*/
private List<Map<String,String>> restAcrossLongTime;
/**
*
*
*/
private List<String> halfWorkTime;
/**
*
*
*/
private List<int[]> halfWorkIndex;
/**
*
*/
private List<String> allWorkTime;
/**
*
*/
private List<String> allAcrossWorkTime;
/**
*
*/
private List<String> allRestTime;
/**
*
*/
private List<String> allAcrossRestTime;
/**
*
*/
private List<Integer> eachWorkMins;
/**
*
*/
private int workmins;
/**
*
*/
private String serialid;
/**
*
*/
private String isAcross;
/**
*
*/
private String halfcalrule;
/**
*
*/
private String halfcalpoint;
private String halfcalpoint2cross;
private List<Object> timelineList;
/**
* 退
*/
private List<Map<String,String>> signWorkTime;
/**
* allWorkTime
*/
private List<String> allWorkTimeisAcross;
private String uuid = "";
private String restShift;
public ShiftInfoCominfoBean() {
this.preWorkTime = new ArrayList<>();
this.workTime = new ArrayList<>();
this.workAcrossTime = new ArrayList<>();
this.preWorkTimeIndex = new ArrayList<>();
this.workTimeIndex = new ArrayList<>();
this.workAcrossTimeIndex = new ArrayList<>();
this.workAcrossLongTime = new ArrayList<>();
this.workPunchMins = new ArrayList<>();
this.preRestTime = new ArrayList<>();
this.restTime = new ArrayList<>();
this.restAcrossTime = new ArrayList<>();
this.preRestTimeIndex = new ArrayList<>();
this.restTimeIndex = new ArrayList<>();
this.restAcrossTimeIndex = new ArrayList<>();
this.restAcrossLongTime = new ArrayList<>();
this.halfWorkTime = new ArrayList<>();
this.allWorkTime = new ArrayList<>();
this.allAcrossWorkTime = new ArrayList<>();
this.allRestTime = new ArrayList<>();
this.allAcrossRestTime = new ArrayList<>();
this.eachWorkMins = new ArrayList<>();
this.workmins = 0;
this.serialid = "";
this.isAcross = "0";
this.halfcalrule = "0";
this.halfWorkIndex = new ArrayList<>();
this.timelineList = new ArrayList<>();
this.workLongTimeIndex = new ArrayList<>();
this.restLongTimeIndex = new ArrayList<>();
this.allLongWorkTime = new ArrayList<>();
this.signWorkTime = new ArrayList<>();
this.allWorkTimeisAcross = new ArrayList<>();
this.uuid = UUID.randomUUID().toString();
this.halfcalpoint = "0";
this.halfcalpoint2cross = "0";
this.restShift = "0";
}
public List<String[]> getPreWorkTime() {
return preWorkTime;
}
public void setPreWorkTime(List<String[]> preWorkTime) {
this.preWorkTime = preWorkTime;
}
public List<String[]> getWorkTime() {
return workTime;
}
public void setWorkTime(List<String[]> workTime) {
this.workTime = workTime;
}
public List<String[]> getWorkAcrossTime() {
return workAcrossTime;
}
public void setWorkAcrossTime(List<String[]> workAcrossTime) {
this.workAcrossTime = workAcrossTime;
}
public List<Map<String, String>> getWorkAcrossLongTime() {
return workAcrossLongTime;
}
public void setWorkAcrossLongTime(
List<Map<String, String>> workAcrossLongTime) {
this.workAcrossLongTime = workAcrossLongTime;
}
public List<String[][]> getWorkPunchMins() {
return workPunchMins;
}
public void setWorkPunchMins(List<String[][]> workPunchMins) {
this.workPunchMins = workPunchMins;
}
public List<String> getHalfWorkTime() {
return halfWorkTime;
}
public void setHalfWorkTime(List<String> 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<String> getAllWorkTime() {
return allWorkTime;
}
public void setAllWorkTime(List<String> allWorkTime) {
this.allWorkTime = allWorkTime;
}
public List<String> getAllAcrossWorkTime() {
return allAcrossWorkTime;
}
public void setAllAcrossWorkTime(List<String> allAcrossWorkTime) {
this.allAcrossWorkTime = allAcrossWorkTime;
}
public List<String[]> getRestTime() {
return restTime;
}
public void setRestTime(List<String[]> restTime) {
this.restTime = restTime;
}
public String getIsAcross() {
return isAcross;
}
public void setIsAcross(String isAcross) {
this.isAcross = isAcross;
}
public List<String[]> getPreRestTime() {
return preRestTime;
}
public void setPreRestTime(List<String[]> preRestTime) {
this.preRestTime = preRestTime;
}
public List<String[]> getRestAcrossTime() {
return restAcrossTime;
}
public void setRestAcrossTime(List<String[]> restAcrossTime) {
this.restAcrossTime = restAcrossTime;
}
public List<Map<String, String>> getRestAcrossLongTime() {
return restAcrossLongTime;
}
public void setRestAcrossLongTime(
List<Map<String, String>> restAcrossLongTime) {
this.restAcrossLongTime = restAcrossLongTime;
}
public List<String> getAllRestTime() {
return allRestTime;
}
public void setAllRestTime(List<String> allRestTime) {
this.allRestTime = allRestTime;
}
public List<String> getAllAcrossRestTime() {
return allAcrossRestTime;
}
public void setAllAcrossRestTime(List<String> allAcrossRestTime) {
this.allAcrossRestTime = allAcrossRestTime;
}
public List<Integer> getEachWorkMins() {
return eachWorkMins;
}
public void setEachWorkMins(List<Integer> eachWorkMins) {
this.eachWorkMins = eachWorkMins;
}
public List<int[]> getPreWorkTimeIndex() {
return preWorkTimeIndex;
}
public void setPreWorkTimeIndex(List<int[]> preWorkTimeIndex) {
this.preWorkTimeIndex = preWorkTimeIndex;
}
public List<int[]> getWorkTimeIndex() {
return workTimeIndex;
}
public void setWorkTimeIndex(List<int[]> workTimeIndex) {
this.workTimeIndex = workTimeIndex;
}
public List<int[]> getWorkAcrossTimeIndex() {
return workAcrossTimeIndex;
}
public void setWorkAcrossTimeIndex(List<int[]> workAcrossTimeIndex) {
this.workAcrossTimeIndex = workAcrossTimeIndex;
}
public List<int[]> getPreRestTimeIndex() {
return preRestTimeIndex;
}
public void setPreRestTimeIndex(List<int[]> preRestTimeIndex) {
this.preRestTimeIndex = preRestTimeIndex;
}
public List<int[]> getRestTimeIndex() {
return restTimeIndex;
}
public void setRestTimeIndex(List<int[]> restTimeIndex) {
this.restTimeIndex = restTimeIndex;
}
public List<int[]> getRestAcrossTimeIndex() {
return restAcrossTimeIndex;
}
public void setRestAcrossTimeIndex(List<int[]> restAcrossTimeIndex) {
this.restAcrossTimeIndex = restAcrossTimeIndex;
}
public List<int[]> getHalfWorkIndex() {
return halfWorkIndex;
}
public void setHalfWorkIndex(List<int[]> halfWorkIndex) {
this.halfWorkIndex = halfWorkIndex;
}
public List<Object> getTimelineList() {
return timelineList;
}
public void setTimelineList(List<Object> timelineList) {
this.timelineList = timelineList;
}
public List<int[]> getWorkLongTimeIndex() {
return workLongTimeIndex;
}
public void setWorkLongTimeIndex(List<int[]> workLongTimeIndex) {
this.workLongTimeIndex = workLongTimeIndex;
}
public List<int[]> getRestLongTimeIndex() {
return restLongTimeIndex;
}
public void setRestLongTimeIndex(List<int[]> restLongTimeIndex) {
this.restLongTimeIndex = restLongTimeIndex;
}
public List<String> getAllLongWorkTime() {
return allLongWorkTime;
}
public void setAllLongWorkTime(List<String> allLongWorkTime) {
this.allLongWorkTime = allLongWorkTime;
}
public List<Map<String, String>> getSignWorkTime() {
return signWorkTime;
}
public void setSignWorkTime(
List<Map<String, String>> signWorkTime) {
this.signWorkTime = signWorkTime;
}
public List<String> getAllWorkTimeisAcross() {
return allWorkTimeisAcross;
}
public void setAllWorkTimeisAcross(List<String> allWorkTimeisAcross) {
this.allWorkTimeisAcross = allWorkTimeisAcross;
}
public String getHalfcalrule() {
return halfcalrule;
}
public void setHalfcalrule(String halfcalrule) {
this.halfcalrule = halfcalrule;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getHalfcalpoint() {
return halfcalpoint;
}
public void setHalfcalpoint(String halfcalpoint) {
this.halfcalpoint = halfcalpoint;
}
public String getHalfcalpoint2cross() {
return halfcalpoint2cross;
}
public void setHalfcalpoint2cross(String halfcalpoint2cross) {
this.halfcalpoint2cross = halfcalpoint2cross;
}
public String getRestShift() {
return restShift;
}
public void setRestShift(String restShift) {
this.restShift = restShift;
}
}

@ -0,0 +1,37 @@
package com.engine.kq.biz.chain.cominfo;
import java.util.List;
import java.util.Map;
import weaver.common.StringUtil;
import weaver.general.Util;
/**
*
*/
public class WorkShiftComIndex extends ShiftComIndex {
public WorkShiftComIndex(String name,Map<String,Object> 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<Object> workTimes = (List<Object>)workTimeMap.get("workTime");
int workmins = Util.getIntValue(Util.null2String(workTimeMap.get("workmins")));
shiftInfoCominfoBean.setWorkmins(workmins);
String serialid = Util.null2String(workTimeMap.get("serialid"));
shiftInfoCominfoBean.setSerialid(serialid);
shiftInfoCominfoBean.setRestShift(StringUtil.vString(workTimeMap.get("restShift"), "0"));
setWorkDuration(workTimes, shiftInfoCominfoBean);
}
}

@ -0,0 +1,618 @@
package com.engine.kq.cmd.attendanceButton;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cloudstore.dev.api.util.EMManager;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.kq.biz.KQShiftManagementComInfo;
import com.engine.kq.biz.KQCardLogBiz;
import com.engine.kq.biz.KQFormatBiz;
import com.engine.kq.biz.KQGroupBiz;
import com.engine.kq.biz.KQGroupMemberComInfo;
import com.engine.kq.biz.KQLoactionComInfo;
import com.engine.kq.biz.KQShiftRuleInfoBiz;
import com.engine.kq.biz.KQTimesArrayComInfo;
import com.engine.kq.biz.KQWorkTime;
import com.engine.kq.biz.chain.shiftinfo.ShiftInfoBean;
import com.engine.kq.entity.KQGroupEntity;
import com.engine.kq.entity.WorkTimeEntity;
import com.engine.kq.log.KQLog;
import com.engine.kq.timer.KQQueue;
import com.engine.kq.timer.KQTaskBean;
import com.engine.kq.util.KQDurationCalculatorUtil;
import com.engine.kq.wfset.util.SplitActionUtil;
import com.google.common.collect.Maps;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import weaver.common.DateUtil;
import weaver.common.StringUtil;
import weaver.conn.RecordSet;
import weaver.dateformat.DateTransformer;
import weaver.dateformat.TimeZoneVar;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.systeminfo.SystemEnv;
/**
* 退
*/
public class PunchButtonCmd extends AbstractCommonCommand<Map<String, Object>> {
public KQLog kqLog = new KQLog();
private HttpServletRequest request;
private Map<String,Object> logMap = Maps.newHashMap();
private Map<String,Object> workTimeEntityLogMap = Maps.newHashMap();
public PunchButtonCmd(HttpServletRequest request,Map<String, Object> params, User user) {
this.request = request;
this.user = user;
this.params = params;
}
@Override
public Map<String, Object> execute(CommandContext commandContext) {
Map<String, Object> retmap = new HashMap<String, Object>();
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<String, Object> 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<Entry<String, Object>> jsonSet = jsonObject.entrySet();
for(Entry<String, Object> 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<String,Object> 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<String,Object> 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<KQTaskBean> tasks = new ArrayList<>();
List<KQTaskBean> 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<KQTaskBean> tasks = new ArrayList<>();
List<KQTaskBean> before_tasks = new ArrayList<>();
SplitActionUtil.pushOverTimeTasks(belongdate, belongdate, ""+userId,tasks);
if(!tasks.isEmpty()){
for(KQTaskBean kqTaskBean : tasks){
kqTaskBean.setTasktype("punchcard");
before_tasks.add(kqTaskBean);
}
}
logMap.put("before_tasks", before_tasks);
if(!before_tasks.isEmpty()){
KQQueue.writeTasks(before_tasks);
}
}
}
String reSignStatus = reSignStatus(user.getUID()+"",signType,nowDateTime,belongdate);
if(Util.null2String(reSignStatus,"").length() > 0){
signStatus = reSignStatus;
}
retmap.put("status", "1");
retmap.put("signdate", signDate);
retmap.put("signtime", signTime);
retmap.put("kqstatus", signStatus);
if(!"1".equalsIgnoreCase(signStatus) && !"2".equalsIgnoreCase(signStatus)){
if("".equalsIgnoreCase(Util.null2String(retmap.get("message")))){
retmap.put("success", "1");
retmap.put("message", SystemEnv.getHtmlLabelName(512596,weaver.general.Util.getIntValue(user.getLanguage())));
}
}
logMap.put("retmap", retmap);
}
public String reSignStatus(String userid, String signType, LocalDateTime nowDateTime,
String workdate) {
String signStatus = "";
String shift_begindateworktime = "";
String shift_enddateworktime = "";
ShiftInfoBean shiftInfoBean = KQDurationCalculatorUtil.getWorkTime(userid, workdate,false);
if(shiftInfoBean == null){
return signStatus;
}
//休息班次打卡去掉迟到、早退的打卡异常提醒
int serialid = StringUtil.parseToInt(shiftInfoBean.getSerialid(), 0);
KQShiftManagementComInfo kQShiftManagementComInfo = new KQShiftManagementComInfo();
int restShift = StringUtil.parseToInt(kQShiftManagementComInfo.getRestShift(String.valueOf(serialid)), 0);
if(serialid <= 0 || restShift == 1) {
return "-1";
}
Map<String,String> 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;
}
}

@ -0,0 +1,100 @@
package com.engine.kq.cmd.attendanceEvent;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.kq.biz.KQGroupMemberComInfo;
import com.engine.kq.biz.KQOvertimeRulesBiz;
import com.engine.kq.biz.KQWorkTime;
import com.engine.kq.entity.WorkTimeEntity;
import com.engine.kq.enums.DurationTypeEnum;
import com.engine.kq.util.KQDurationCalculatorUtil;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.resource.ResourceComInfo;
import weaver.systeminfo.SystemEnv;
/**
*
*/
public class GetOverTimeWorkDurationCmd extends AbstractCommonCommand<Map<String, Object>> {
public GetOverTimeWorkDurationCmd(Map<String, Object> params, User user) {
this.user = user;
this.params = params;
}
@Override
public Map<String, Object> execute(CommandContext commandContext) {
Map<String, Object> retmap = new HashMap<String, Object>();
RecordSet rs = new RecordSet();
String sql = "";
ReentrantLock lock = new ReentrantLock();
try {
lock.lock();
String resourceId = Util.null2String(params.get("resourceId"));
String fromDate = Util.null2String(params.get("fromDate"));
String toDate = Util.null2String(params.get("toDate"));
String fromTime = Util.null2String(params.get("fromTime"));
String toTime = Util.null2String(params.get("toTime"));
String overtime_type = Util.null2String(params.get("overtime_type"));
String timestamp = Util.null2String(params.get("timestamp"));
writeLog("resourceId="+resourceId+",fromDate="+fromDate+",toDate="+toDate+",fromTime="+fromTime+",toTime="+toTime+",timestamp="+timestamp);
int minimumUnit = KQOvertimeRulesBiz.getMinimumUnit();
//
KQWorkTime kqWorkTime = new KQWorkTime();
WorkTimeEntity kqWorkTimeEntity = kqWorkTime.getWorkTime(resourceId, fromDate);
if (kqWorkTimeEntity != null) {
String kqType = Util.null2String(kqWorkTimeEntity.getKQType());
if ("3".equalsIgnoreCase(kqType)) {
writeLog("自由班制不计算加班");
retmap.put("status", "1");
retmap.put("message", "" + weaver.systeminfo.SystemEnv.getHtmlLabelName(10005330, weaver.general.ThreadVarLanguage.getLang()) + "");
return retmap;
}
}
ResourceComInfo rci = new ResourceComInfo();
KQGroupMemberComInfo kqGroupMemberComInfo = new KQGroupMemberComInfo();
String groupid = kqGroupMemberComInfo.getKQGroupId(resourceId, fromDate);
if (resourceId.length() > 0 && groupid.length() == 0) {
retmap.put("status", "-1");
retmap.put("message", rci.getLastname(resourceId) + "," + fromDate + "" + weaver.systeminfo.SystemEnv.getHtmlLabelName(10005329, weaver.general.ThreadVarLanguage.getLang()) + "");
return retmap;
}
//加班默认是工作日加班
KQDurationCalculatorUtil kqDurationCalculatorUtil = new KQDurationCalculatorUtil.DurationParamBuilder(resourceId).
fromDateParam(fromDate).toDateParam(toDate).fromTimeParam(fromTime).toTimeParam(toTime).computingModeParam("1").
durationRuleParam(minimumUnit + "").durationTypeEnumParam(DurationTypeEnum.OVERTIME).
overtime_typeParam(overtime_type).build();
Map<String, Object> durationMap = kqDurationCalculatorUtil.getWorkDuration();
retmap.put("duration", Util.null2String(durationMap.get("duration")));
retmap.put("timestamp", timestamp);
retmap.put("status", "1");
} catch (Exception e) {
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(382661, user.getLanguage()));
writeLog(e);
}finally {
lock.unlock();
}
return retmap;
}
@Override
public BizLogContext getLogContext() {
return null;
}
}

@ -0,0 +1,468 @@
package com.engine.kq.cmd.balanceofleaverp;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.kq.biz.*;
import com.engine.kq.util.KQTransMethod;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.company.SubCompanyComInfo;
import weaver.hrm.job.JobTitlesComInfo;
import weaver.systeminfo.SystemEnv;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* --Excel
*/
public class ExportExcelCmd extends AbstractCommonCommand<Map<String, Object>> {
private HttpServletRequest request;
private HttpServletResponse response;
public ExportExcelCmd(Map<String, Object> params, User user, HttpServletRequest request, HttpServletResponse response) {
this.user = user;
this.params = params;
this.request = request;
this.response = response;
}
@Override
public BizLogContext getLogContext() {
return null;
}
@Override
public Map<String, Object> execute(CommandContext commandContext) {
long startTime = System.currentTimeMillis();
Map<String, Object> resultMap = new HashMap<String, Object>();
/**
*
*/
String displayColumn = Util.null2String(params.get("displayColumn"));
List<String> displayColumnList = Util.TokenizerString(displayColumn, ",");
/**
*
* dateScope5-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);
}
/**
*
* dataScope0-1-2-3-4-
* subcomIdID
* deptIdID
* resourceIdID
* allLevel0-1-
*/
String dataScope = Util.null2String(params.get("dataScope"));
String subcomId = Util.null2String(params.get("subcomId"));
String deptId = Util.null2String(params.get("deptId"));
String resourceId = Util.null2String(params.get("resourceId"));
String allLevel = Util.null2String(params.get("allLevel"));
//人员状态
String resourceStatus = Util.null2String(params.get("status"));
/**
* isNoAccounttrue-false-
*/
String isNoAccount = Util.null2String(params.get("isNoAccount"));
try {
/**
*
*/
KQReportBiz kqReportBiz = new KQReportBiz();
String rightStr = kqReportBiz.getReportRight("4", "" + user.getUID(), "a");
/**
* Excel
*/
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet(SystemEnv.getHtmlLabelName(389441, user.getLanguage()));//员工假期余额
// 设置字体
Font font = workbook.createFont();
//设置字体大小
font.setFontHeightInPoints((short) 14);
//字体加粗
font.setBold(true);
//设置字体名字
font.setFontName("宋体");
//设置样式;
CellStyle style = workbook.createCellStyle();
//设置底边框;
style.setBorderBottom(BorderStyle.THIN);
//设置底边框颜色;
style.setBottomBorderColor(IndexedColors.BLACK.index);
//设置左边框;
style.setBorderLeft(BorderStyle.THIN);
//设置左边框颜色;
style.setLeftBorderColor(IndexedColors.BLACK.index);
//设置右边框;
style.setBorderRight(BorderStyle.THIN);
//设置右边框颜色;
style.setRightBorderColor(IndexedColors.BLACK.index);
//设置顶边框;
style.setBorderTop(BorderStyle.THIN);
//设置顶边框颜色;
style.setTopBorderColor(IndexedColors.BLACK.index);
//在样式用应用设置的字体;
style.setFont(font);
//设置自动换行;
style.setWrapText(false);
//设置水平对齐的样式为居中对齐;
style.setAlignment(HorizontalAlignment.CENTER);
//设置垂直对齐的样式为居中对齐;
style.setVerticalAlignment(VerticalAlignment.CENTER);
int index = 0;
HSSFRow headerRow = sheet.createRow(0);
String[] tempArr = new String[]{SystemEnv.getHtmlLabelName(413, user.getLanguage()) + ",lastName", SystemEnv.getHtmlLabelName(141, user.getLanguage()) + ",subcom", SystemEnv.getHtmlLabelName(124, user.getLanguage()) + ",dept", SystemEnv.getHtmlLabelName(6086, user.getLanguage()) + ",jobtitle", SystemEnv.getHtmlLabelName(714, user.getLanguage()) + ",workcode"};
for (int i = 0; i < tempArr.length; i++) {
String[] fieldInfo = tempArr[i].split(",");
if (fieldInfo[1].equals("lastName") || displayColumnList.indexOf(fieldInfo[1]) > -1) {
headerRow.setHeight((short) 312);
HSSFCell headCell = headerRow.createCell(index);
headCell.setCellValue(fieldInfo[0]);
headCell.setCellStyle(style);
sheet.setColumnWidth((short) index, (short) (6 * 1000));
index++;
}
}
/**********************************************************************************************************/
/**获取假期类型的相关设置*/
/*请假类型的ID*/
String leaveRulesId = "";
/*假期类型的名称,用作查询结果列表的表头显示*/
String leaveName = "";
/*最小请假单位1-按天请假、2-按半天请假、3-按小时请假、4-按整天请假*/
int minimumUnit = 1;
/*请假单位的显示名称是天还是小时*/
String unitName = "";
/*是否开启假期余额,没有开启假期余额时需要提示“不限制余额*/
int balanceEnable = 0;
/**********************************************************************************************************/
/*是否是混合模式(福利年假+法定年假)*/
boolean isMixMode = false;
//是否是调休
boolean isTiaoXiu = false;
/**********************************************************************************************************/
/*获取当前日期*/
String currentDate = DateUtil.getCurrentDate();
Map<String, BigDecimal> balanceMap = new HashMap<String, BigDecimal>();
KQLeaveRulesComInfo rulesComInfo = new KQLeaveRulesComInfo();
rulesComInfo.setTofirstRow();
while (rulesComInfo.next()) {
/*该假期没有启用,不显示*/
if (!rulesComInfo.getIsEnable().equals("1")) {
continue;
}
/*展示列不展示,不显示*/
if (displayColumnList.indexOf(rulesComInfo.getId()) < 0) {
continue;
}
/*获取假期类型的设置 start*/
leaveRulesId = rulesComInfo.getId();
leaveName = Util.formatMultiLang(rulesComInfo.getLeaveName(), "" + user.getLanguage());
minimumUnit = Util.getIntValue(rulesComInfo.getMinimumUnit(), 1);
if (minimumUnit == 1 || minimumUnit == 2 || minimumUnit == 4) {
unitName = SystemEnv.getHtmlLabelName(389325, user.getLanguage());//(天)
} else {
unitName = SystemEnv.getHtmlLabelName(389326, user.getLanguage());//(小时)
}
String showName = leaveName + unitName;
balanceEnable = Util.getIntValue(rulesComInfo.getBalanceEnable(), 0);
isMixMode = KQLeaveRulesBiz.isMixMode(leaveRulesId);
//isTiaoXiu = KQLeaveRulesBiz.isTiaoXiu(leaveRulesId);
isTiaoXiu = KQLeaveRulesBiz.isTiaoXiu2(leaveRulesId);
/*获取假期类型的设置 end*/
headerRow.setHeight((short) 312);
HSSFCell headCell = headerRow.createCell(index);
headCell.setCellValue(showName);
headCell.setCellStyle(style);
sheet.setColumnWidth((short) index, (short) (6 * 1000));
index++;
/*判断该假期规则是否开启了假期余额,若没有开启,则无需查找该假期的余额,直接遍历下一个假期*/
if (balanceEnable == 0) {
continue;
}
//如果是调休,获取假期余额的方式有些不同
if (isTiaoXiu) {
params.put("leaveRulesId", leaveRulesId);
params.put("showAll", "true");
Map<String, BigDecimal> _balanceMap = KQBalanceOfLeaveBiz.getRestAmountMapByDis5(params, user);
balanceMap.putAll(_balanceMap);
continue;
}
/*查询指定年份指定假期的余额数据,并放入集合中,用于后续拼凑查询结果数据*/
KQTransMethod transMethod = new KQTransMethod();
RecordSet recordSet = new RecordSet();
String sql = "select a.id hrmResourceId,b.* from HrmResource a left join kq_balanceOfLeave b on a.id=b.resourceId " +
"and belongYear='" + selectedYear + "' and b.leaveRulesId=" + leaveRulesId + " where 1=1 ";
if (dataScope.equals("0")) {
//总部
} else if (dataScope.equals("1")) {
sql += " and a.subcompanyId1 in (" + subcomId + ") ";
} else if (dataScope.equals("2")) {
sql += " and a.departmentId in (" + deptId + ") ";
} else if (dataScope.equals("3")) {
sql += " and a.id in (" + resourceId + ")";
} else if (dataScope.equals("4")) {
if (allLevel.equals("1")) {
sql += " and (a.id=" + user.getUID() + " or a.managerStr like '%," + user.getUID() + ",%' )";
} else {
sql += " and (a.id=" + user.getUID() + " or a.managerid = " + user.getUID() + ")";
}
}
if (isNoAccount.equals("false")) {
if (recordSet.getDBType().equalsIgnoreCase("sqlserver")
|| recordSet.getDBType().equalsIgnoreCase("mysql")) {
sql += " and (loginId is not null and loginId<>'')";
} else if (recordSet.getDBType().equalsIgnoreCase("postgresql")) {
sql += " and (loginId is not null and loginId<>'')";
} else {
sql += " and (loginId is not null)";
}
}
if(resourceStatus.length()>0){
if (!resourceStatus.equals("8") && !resourceStatus.equals("9")) {
sql += " and a.status = "+resourceStatus+ "";
}else if (resourceStatus.equals("8")) {
sql += " and (a.status = 0 or a.status = 1 or a.status = 2 or a.status = 3) ";
}
}
//考勤报表共享设置
if (!rightStr.equals("") && !dataScope.equals("4")) {
sql += rightStr;
}
sql += " order by dspOrder,hrmResourceId ";
recordSet.executeQuery(sql);
while (recordSet.next()) {
String hrmResourceId = recordSet.getString("hrmResourceId");
//所属年份
String belongYear = recordSet.getString("belongYear");
//失效日期
String effectiveDate = recordSet.getString("effectiveDate");
//失效日期
String expirationDate = recordSet.getString("expirationDate");
/*判断假期余额的有效期*/
boolean status = KQBalanceOfLeaveBiz.getBalanceStatus(leaveRulesId, hrmResourceId, belongYear, currentDate, effectiveDate, expirationDate);
if (!status) {
continue;
}
BigDecimal baseAmount = new BigDecimal(Util.getDoubleValue(recordSet.getString("baseAmount"), 0.00));//假期基数
BigDecimal usedAmount = new BigDecimal(Util.getDoubleValue(recordSet.getString("usedAmount"), 0.00));//已用假期
BigDecimal extraAmount = new BigDecimal(Util.getDoubleValue(recordSet.getString("extraAmount"), 0.00));//额外假期
BigDecimal baseAmount2 = new BigDecimal(Util.getDoubleValue(recordSet.getString("baseAmount2"), 0.00));//用于混合模式时:福利年假基数
BigDecimal usedAmount2 = new BigDecimal(Util.getDoubleValue(recordSet.getString("usedAmount2"), 0.00));//用于混合模式时:已用福利年假
BigDecimal extraAmount2 = new BigDecimal(Util.getDoubleValue(recordSet.getString("extraAmount2"), 0.00));//用于混合模式时:额外福利年假
BigDecimal restAmount = new BigDecimal(0);
if (isMixMode) {
/*释放规则*/
baseAmount = KQBalanceOfLeaveBiz.getCanUseAmount(hrmResourceId, leaveRulesId, belongYear, baseAmount, "legal", currentDate);
baseAmount2 = KQBalanceOfLeaveBiz.getCanUseAmount(hrmResourceId, leaveRulesId, belongYear, baseAmount2, "welfare", currentDate);
restAmount = baseAmount.add(extraAmount).subtract(usedAmount).add(baseAmount2).add(extraAmount2).subtract(usedAmount2);
} else {
/*释放规则*/
baseAmount = KQBalanceOfLeaveBiz.getCanUseAmount(hrmResourceId, leaveRulesId, belongYear, baseAmount, "", currentDate);
restAmount = baseAmount.add(extraAmount).subtract(usedAmount);
}
balanceMap.put(hrmResourceId + "_" + leaveRulesId, restAmount);
}
}
/**
*
*/
SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo();
DepartmentComInfo departmentComInfo = new DepartmentComInfo();
JobTitlesComInfo jobTitlesComInfo = new JobTitlesComInfo();
index = 0;
String sql = "select * from HrmResource a where 1=1";
if (dataScope.equals("0")) {
//总部
} else if (dataScope.equals("1")) {
sql += " and a.subcompanyId1 in (" + subcomId + ") ";
} else if (dataScope.equals("2")) {
sql += " and a.departmentId in (" + deptId + ") ";
} else if (dataScope.equals("3")) {
sql += " and a.id in (" + resourceId + ")";
} else if (dataScope.equals("4")) {
if (allLevel.equals("1")) {
sql += " and (a.id=" + user.getUID() + " or a.managerStr like '%," + user.getUID() + ",%' )";
} else {
sql += " and (a.id=" + user.getUID() + " or a.managerid = " + user.getUID() + ")";
}
}
RecordSet recordSet = new RecordSet();
if (isNoAccount.equals("false")) {
if (recordSet.getDBType().equalsIgnoreCase("sqlserver")
|| recordSet.getDBType().equalsIgnoreCase("mysql")) {
sql += " and (a.loginId is not null and a.loginId<>'')";
}else if (recordSet.getDBType().equalsIgnoreCase("postgresql")) {
sql += " and (a.loginId is not null and a.loginId<>'')";
} else {
sql += " and (a.loginId is not null)";
}
}
if(resourceStatus.length()>0){
if (!resourceStatus.equals("8") && !resourceStatus.equals("9")) {
sql += " and a.status = "+resourceStatus+ "";
}else if (resourceStatus.equals("8")) {
sql += " and (a.status = 0 or a.status = 1 or a.status = 2 or a.status = 3) ";
}
}
//考勤报表共享设置
if (!rightStr.equals("") && !dataScope.equals("4")) {
sql += rightStr;
}
sql += " order by dspOrder,id ";
recordSet.executeQuery(sql);
// #1475814-概述:满足考勤报分部部门显示及导出时显示全路径
String fullPathMainKey = "show_full_path";
KQSettingsComInfo kqSettingsComInfo = new KQSettingsComInfo();
String isShowFullPath = Util.null2String(kqSettingsComInfo.getMain_val(fullPathMainKey),"0");
String subCompanyNameTmp = "";
String departmentNameTmp = "";
while (recordSet.next()) {
HSSFRow row = sheet.createRow(++index);
String id = recordSet.getString("id");
String lastName = recordSet.getString("lastName");
String departmentId = recordSet.getString("departmentId");
String subcompanyId = recordSet.getString("subcompanyId1");
String jobtitleId = recordSet.getString("jobtitle");
String workcode = recordSet.getString("workcode");
int cellIndex = 0;
HSSFCell cell = row.createCell(cellIndex);
cell.setCellValue(Util.formatMultiLang(lastName, "" + user.getLanguage()));
cellIndex++;
if (displayColumnList.indexOf("subcom") > -1) {
cell = row.createCell(cellIndex);
// 导出时,是否显示全路径
subCompanyNameTmp = "1".equals(isShowFullPath) ?
SubCompanyComInfo.getSubcompanyRealPath(subcompanyId, "/", "0") :
subCompanyComInfo.getSubCompanyname(subcompanyId);
cell.setCellValue(Util.formatMultiLang(subCompanyNameTmp, "" + user.getLanguage()));
// cell.setCellValue(Util.formatMultiLang(subCompanyComInfo.getSubcompanyname(subcompanyId), "" + user.getLanguage()));
cellIndex++;
}
if (displayColumnList.indexOf("dept") > -1) {
cell = row.createCell(cellIndex);
// 导出时,是否显示全路径
departmentNameTmp = "1".equals(isShowFullPath) ?
departmentComInfo.getDepartmentRealPath(departmentId, "/", "0") :
departmentComInfo.getDepartmentname(departmentId);
cell.setCellValue(Util.formatMultiLang(departmentNameTmp, "" + user.getLanguage()));
// cell.setCellValue(Util.formatMultiLang(departmentComInfo.getDepartmentname(departmentId), "" + user.getLanguage()));
cellIndex++;
}
if (displayColumnList.indexOf("jobtitle") > -1) {
cell = row.createCell(cellIndex);
cell.setCellValue(Util.formatMultiLang(jobTitlesComInfo.getJobTitlesname(jobtitleId), "" + user.getLanguage()));
cellIndex++;
}
if (displayColumnList.indexOf("workcode") > -1) {
cell = row.createCell(cellIndex);
cell.setCellValue(Util.formatMultiLang(workcode, "" + user.getLanguage()));
cellIndex++;
}
rulesComInfo.setTofirstRow();
while (rulesComInfo.next()) {
/*展示列不展示,不显示*/
if (displayColumnList.indexOf(rulesComInfo.getId()) < 0) {
continue;
}
/*该假期没有启用,不显示*/
if (!rulesComInfo.getIsEnable().equals("1")) {
continue;
}
/*该假期没有开启余额限制,显示不限制余额*/
if (rulesComInfo.getBalanceEnable().equals("0")) {
cell = row.createCell(cellIndex);
cell.setCellValue(SystemEnv.getHtmlLabelName(389731, user.getLanguage()));
cellIndex++;
continue;
}
BigDecimal restAmount = balanceMap.get(id + "_" + rulesComInfo.getId());
cell = row.createCell(cellIndex);
cell.setCellValue(restAmount != null ? restAmount.setScale(2, RoundingMode.HALF_UP).doubleValue() : 0);
cellIndex++;
}
}
String encodedFileName = SystemEnv.getHtmlLabelName(389441, user.getLanguage());
response.reset();
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setCharacterEncoding("utf-8");
String header = request.getHeader("User-Agent").toUpperCase();
if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
encodedFileName = URLEncoder.encode(encodedFileName, "utf-8");
encodedFileName = encodedFileName.replace("+", "%20"); //IE下载文件名空格变+号问题
} else {
encodedFileName = new String(encodedFileName.getBytes("utf-8"), "ISO_8859_1");
}
writeLog("balanceofleaverp>>>ExportExcelCmd>>>encodedFileName="+encodedFileName);
response.setHeader("Content-disposition", "attachment;filename=" + encodedFileName + "excel.xls");
response.setContentType("application/msexcel");
response.setContentType("application/x-msdownload");
OutputStream responseOutput = response.getOutputStream();
workbook.write(responseOutput);
responseOutput.flush();
} catch (Exception e) {
writeLog(e);
}
long endTime = System.currentTimeMillis();
float seconds = (endTime - startTime) / 1000F;
System.out.println(Float.toString(seconds) + " seconds.");
return resultMap;
}
}

@ -0,0 +1,426 @@
package com.engine.kq.cmd.balanceofleaverp;
import com.api.hrm.bean.HrmFieldBean;
import com.api.hrm.util.HrmFieldUtil;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.kq.biz.*;
import com.engine.kq.util.KQTransMethod;
import com.engine.kq.util.UtilKQHS;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.company.SubCompanyComInfo;
import weaver.hrm.job.JobTitlesComInfo;
import weaver.hrm.resource.ResourceComInfo;
import weaver.systeminfo.SystemEnv;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
/**
* --
*/
public class GetSearchListCmd extends AbstractCommonCommand<Map<String, Object>> {
public GetSearchListCmd(Map<String, Object> params, User user) {
this.user = user;
this.params = params;
}
@Override
public BizLogContext getLogContext() {
return null;
}
@Override
public Map<String, Object> execute(CommandContext commandContext) {
Map<String, Object> resultMap = new HashMap<String, Object>();
/**
*
* currentPage
* pageSize
*/
int currentPage = Util.getIntValue((String) params.get("currentPage"), 1);
int pageSize = Util.getIntValue((String) params.get("pageSize"), 10);
/**
*
* dateScope5-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);
}
/**
*
* dataScope0-1-2-3-4-
* subcomIdID
* deptIdID
* resourceIdID
* allLevel0-1-
*/
String dataScope = Util.null2String(params.get("dataScope"));
String subcomId = Util.null2String(params.get("subcomId"));
String deptId = Util.null2String(params.get("deptId"));
String resourceId = Util.null2String(params.get("resourceId"));
String allLevel = Util.null2String(params.get("allLevel"));
//人员状态
String resourceStatus = Util.null2String(params.get("status"));
/**
* isNoAccounttrue-false-
*/
String isNoAccount = Util.null2String(params.get("isNoAccount"));
try {
/**
*
*/
KQReportBiz kqReportBiz = new KQReportBiz();
String rightStr = kqReportBiz.getReportRight("4", "" + user.getUID(), "a");
/**
*
*/
List<Map<String, Object>> columnsList = new ArrayList<Map<String, Object>>();
List<HrmFieldBean> hrmFieldBeanList = new ArrayList<HrmFieldBean>();
HrmFieldBean hrmFieldBean = null;
String[] tempArr = new String[]{"lastName,413", "subcom,141", "dept,124", "jobtitle,6086","workcode,714", "companyStartDate,1516"};
for (int i = 0; i < tempArr.length; i++) {
String[] fieldInfo = tempArr[i].split(",");
hrmFieldBean = new HrmFieldBean();
hrmFieldBean.setFieldname(fieldInfo[0]);
hrmFieldBean.setFieldlabel(fieldInfo[1]);
hrmFieldBean.setFieldhtmltype("1");
hrmFieldBean.setType("1");
hrmFieldBean.setViewAttr(1);
hrmFieldBean.setIsFormField(true);
hrmFieldBeanList.add(hrmFieldBean);
}
/**********************************************************************************************************/
/**获取假期类型的相关设置*/
/*请假类型的ID*/
String leaveRulesId = "";
/*假期类型的名称,用作查询结果列表的表头显示*/
String leaveName = "";
/*最小请假单位1-按天请假、2-按半天请假、3-按小时请假、4-按整天请假*/
int minimumUnit = 1;
/*请假单位的显示名称是天还是小时*/
String unitName = "";
/*是否开启假期余额,没有开启假期余额时需要提示“不限制余额*/
int balanceEnable = 0;
/**********************************************************************************************************/
/*是否是混合模式(福利年假+法定年假)*/
boolean isMixMode = false;
//是否是调休
boolean isTiaoXiu = false;
/**********************************************************************************************************/
/*获取当前日期*/
String currentDate = DateUtil.getCurrentDate();
Map<String, BigDecimal> balanceMap = new HashMap<String, BigDecimal>();
Map<String, BigDecimal> baseBalanceMap = new HashMap<String, BigDecimal>();
KQLeaveRulesComInfo rulesComInfo = new KQLeaveRulesComInfo();
rulesComInfo.setTofirstRow();
while (rulesComInfo.next()) {
if (rulesComInfo.getIsEnable().equals("0")) {
continue;//此假期类型没有启用
}
/*获取假期类型的设置 start*/
leaveRulesId = rulesComInfo.getId();
leaveName = Util.formatMultiLang(rulesComInfo.getLeaveName(), "" + user.getLanguage());
minimumUnit = Util.getIntValue(rulesComInfo.getMinimumUnit(), 1);
if (minimumUnit == 1 || minimumUnit == 2 || minimumUnit == 4) {
unitName = SystemEnv.getHtmlLabelName(389325, user.getLanguage());//(天)
} else {
unitName = SystemEnv.getHtmlLabelName(389326, user.getLanguage());//(小时)
}
String showName = leaveName + unitName;
balanceEnable = Util.getIntValue(rulesComInfo.getBalanceEnable(), 0);
isMixMode = KQLeaveRulesBiz.isMixMode(leaveRulesId);
//isTiaoXiu = KQLeaveRulesBiz.isTiaoXiu(leaveRulesId);
isTiaoXiu = KQLeaveRulesBiz.isTiaoXiu2(leaveRulesId);
/*获取假期类型的设置 end*/
hrmFieldBean = new HrmFieldBean();
hrmFieldBean.setFieldname(rulesComInfo.getId());
hrmFieldBean.setFieldlabelname(showName);
hrmFieldBean.setFieldhtmltype("1");
hrmFieldBean.setType("1");
hrmFieldBean.setViewAttr(1);
hrmFieldBean.setIsFormField(true);
hrmFieldBeanList.add(hrmFieldBean);
/*判断该假期规则是否开启了假期余额,若没有开启,则无需查找该假期的余额,直接遍历下一个假期*/
if (balanceEnable == 0) {
continue;
}
//如果是调休,获取假期余额的方式有些不同
if(isTiaoXiu){
params.put("leaveRulesId",leaveRulesId);
params.put("showAll","false");
Map<String, BigDecimal> _balanceMap = KQBalanceOfLeaveBiz.getRestAmountMapByDis5(params,user);
balanceMap.putAll(_balanceMap);
continue;
}
/*查询指定年份指定假期的余额数据,并放入集合中,用于后续拼凑查询结果数据*/
KQTransMethod transMethod = new KQTransMethod();
RecordSet recordSet = new RecordSet();
String sql = "select a.id hrmResourceId,a.companyStartDate,a.workStartDate,b.* from HrmResource a left join kq_balanceOfLeave b on a.id=b.resourceId " +
"and belongYear='" + selectedYear + "' and b.leaveRulesId=" + leaveRulesId + " where 1=1 ";
if (recordSet.getDBType().equalsIgnoreCase("sqlserver")) {
sql = "select a.id hrmResourceId,a.companyStartDate,a.workStartDate,b.*,ROW_NUMBER() OVER(order by dspOrder,a.id) as rn from HrmResource a left join kq_balanceOfLeave b on a.id=b.resourceId " +
"and belongYear='" + selectedYear + "' and b.leaveRulesId=" + leaveRulesId + " where 1=1 ";
} else if (recordSet.getDBType().equalsIgnoreCase("mysql")) {
sql = "select a.id hrmResourceId,a.companyStartDate,a.workStartDate,b.* from HrmResource a left join kq_balanceOfLeave b on a.id=b.resourceId " +
"and belongYear='" + selectedYear + "' and b.leaveRulesId=" + leaveRulesId + " where 1=1 ";
}
if (dataScope.equals("0")) {
//总部
} else if (dataScope.equals("1")) {
sql += " and a.subcompanyId1 in (" + subcomId + ") ";
} else if (dataScope.equals("2")) {
sql += " and a.departmentId in (" + deptId + ") ";
} else if (dataScope.equals("3")) {
sql += " and a.id in (" + resourceId + ")";
} else if (dataScope.equals("4")) {
if (allLevel.equals("1")) {
sql += " and (a.id=" + user.getUID() + " or a.managerStr like '%," + user.getUID() + ",%' )";
} else {
sql += " and (a.id=" + user.getUID() + " or a.managerid = " + user.getUID() + ")";
}
}
if (isNoAccount.equals("false")) {
if (recordSet.getDBType().equalsIgnoreCase("sqlserver")
|| recordSet.getDBType().equalsIgnoreCase("mysql")) {
sql += " and (loginId is not null and loginId<>'')";
}else if (recordSet.getDBType().equalsIgnoreCase("postgresql")) {
sql += " and (loginId is not null and loginId<>'')";
} else {
sql += " and (loginId is not null)";
}
}
if(resourceStatus.length()>0){
if (!resourceStatus.equals("8") && !resourceStatus.equals("9")) {
sql += " and a.status = "+resourceStatus+ "";
}else if (resourceStatus.equals("8")) {
sql += " and (a.status = 0 or a.status = 1 or a.status = 2 or a.status = 3) ";
}
}
//考勤报表共享设置
if (!rightStr.equals("") && !dataScope.equals("4")) {
sql += rightStr;
}
if (!recordSet.getDBType().equalsIgnoreCase("sqlserver")) {
sql += " order by dspOrder,hrmResourceId ";
}
String pageSql = "select * from (select tmp.*,rownum rn from (" + sql + ") tmp where rownum<=" + (pageSize * currentPage) + ") where rn>=" + (pageSize * (currentPage - 1) + 1);
if (recordSet.getDBType().equalsIgnoreCase("sqlserver")) {
pageSql = "select t.* from (" + sql + ") t where 1=1 and rn>=" + (pageSize * (currentPage - 1) + 1) + " and rn<=" + (pageSize * currentPage);
} else if (recordSet.getDBType().equalsIgnoreCase("mysql")) {
pageSql = sql + " limit " + (currentPage - 1) * pageSize + "," + pageSize;
}else if (recordSet.getDBType().equalsIgnoreCase("postgresql")) {
pageSql = sql + " limit " +pageSize + " offset " + (currentPage - 1) * pageSize;
}
recordSet.executeQuery(pageSql);
while (recordSet.next()) {
String hrmResourceId = recordSet.getString("hrmResourceId");
//所属年份
String belongYear = recordSet.getString("belongYear");
//失效日期
String effectiveDate = recordSet.getString("effectiveDate");
//失效日期
String expirationDate = recordSet.getString("expirationDate");
/*判断假期余额的有效期*/
boolean status = KQBalanceOfLeaveBiz.getBalanceStatus(leaveRulesId, hrmResourceId, belongYear, currentDate,effectiveDate,expirationDate);
if (!status) {
continue;
}
BigDecimal baseAmount = new BigDecimal(Util.getDoubleValue(recordSet.getString("baseAmount"), 0.00));//假期基数
BigDecimal usedAmount = new BigDecimal(Util.getDoubleValue(recordSet.getString("usedAmount"), 0.00));//已用假期
BigDecimal extraAmount = new BigDecimal(Util.getDoubleValue(recordSet.getString("extraAmount"), 0.00));//额外假期
BigDecimal baseAmount2 = new BigDecimal(Util.getDoubleValue(recordSet.getString("baseAmount2"), 0.00));//用于混合模式时:福利年假基数
BigDecimal usedAmount2 = new BigDecimal(Util.getDoubleValue(recordSet.getString("usedAmount2"), 0.00));//用于混合模式时:已用福利年假
BigDecimal extraAmount2 = new BigDecimal(Util.getDoubleValue(recordSet.getString("extraAmount2"), 0.00));//用于混合模式时:额外福利年假
BigDecimal restAmount = new BigDecimal(0);
if (isMixMode) {
/*释放规则*/
baseAmount = KQBalanceOfLeaveBiz.getCanUseAmount(hrmResourceId, leaveRulesId, belongYear, baseAmount, "legal", currentDate);
baseAmount2 = KQBalanceOfLeaveBiz.getCanUseAmount(hrmResourceId, leaveRulesId, belongYear, baseAmount2, "welfare", currentDate);
restAmount = baseAmount.add(extraAmount).subtract(usedAmount).add(baseAmount2).add(extraAmount2).subtract(usedAmount2);
} else {
if ("36".equals(leaveRulesId)) {
//育儿假
boolean isLastYearChildcareLeave = UtilKQHS.isLastYearChildcareLeave(resourceId, selectedYear);
//根据释放规则获取已释放的天数/小时数
baseAmount = KQBalanceOfLeaveBiz.getCanUseAmountChildcareLeave(resourceId, leaveRulesId, belongYear, baseAmount, "", currentDate, isLastYearChildcareLeave);
}else{
/*释放规则*/
baseAmount = KQBalanceOfLeaveBiz.getCanUseAmount(hrmResourceId, leaveRulesId, belongYear, baseAmount, "", currentDate);
}
restAmount = baseAmount.add(extraAmount).subtract(usedAmount);
}
baseBalanceMap.put(hrmResourceId + "_" + leaveRulesId, baseAmount);
balanceMap.put(hrmResourceId + "_" + leaveRulesId, restAmount);
}
}
/**
*
*/
SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo();
DepartmentComInfo departmentComInfo = new DepartmentComInfo();
JobTitlesComInfo jobTitlesComInfo = new JobTitlesComInfo();
List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
Map<String, Object> dataMap = new HashMap<String, Object>();
RecordSet recordSet = new RecordSet();
String sql = "select * from HrmResource a where 1=1 ";
if (recordSet.getDBType().equalsIgnoreCase("sqlserver")) {
sql = "select *,ROW_NUMBER() OVER(order by dspOrder,id) as rn from HrmResource a where 1=1 ";
}
if (dataScope.equals("0")) {
//总部
} else if (dataScope.equals("1")) {
sql += " and a.subcompanyId1 in (" + subcomId + ") ";
} else if (dataScope.equals("2")) {
sql += " and a.departmentId in (" + deptId + ") ";
} else if (dataScope.equals("3")) {
sql += " and a.id in (" + resourceId + ")";
} else if (dataScope.equals("4")) {
if (allLevel.equals("1")) {
sql += " and (a.id=" + user.getUID() + " or a.managerStr like '%," + user.getUID() + ",%' )";
} else {
sql += " and (a.id=" + user.getUID() + " or a.managerid = " + user.getUID() + ")";
}
}
if (isNoAccount.equals("false")) {
if (recordSet.getDBType().equalsIgnoreCase("sqlserver")
|| recordSet.getDBType().equalsIgnoreCase("mysql")) {
sql += " and (a.loginId is not null and a.loginId<>'')";
}else if (recordSet.getDBType().equalsIgnoreCase("postgresql")) {
sql += " and (a.loginId is not null and a.loginId<>'')";
} else {
sql += " and (a.loginId is not null)";
}
}
if(resourceStatus.length()>0){
if (!resourceStatus.equals("8") && !resourceStatus.equals("9")) {
sql += " and a.status = "+resourceStatus+ "";
}else if (resourceStatus.equals("8")) {
sql += " and (a.status = 0 or a.status = 1 or a.status = 2 or a.status = 3) ";
}
}
//考勤报表共享设置
if (!rightStr.equals("") && !dataScope.equals("4")) {
sql += rightStr;
}
if (!recordSet.getDBType().equalsIgnoreCase("sqlserver")) {
sql += " order by dspOrder,id ";
}
String pageSql = "select * from (select tmp.*,rownum rn from (" + sql + ") tmp where rownum<=" + (pageSize * currentPage) + ") where rn>=" + (pageSize * (currentPage - 1) + 1);
if (recordSet.getDBType().equalsIgnoreCase("sqlserver")) {
pageSql = "select t.* from (" + sql + ") t where 1=1 and rn>=" + (pageSize * (currentPage - 1) + 1) + " and rn<=" + (pageSize * currentPage);
} else if (recordSet.getDBType().equalsIgnoreCase("mysql")) {
pageSql = sql + " limit " + (currentPage - 1) * pageSize + "," + pageSize;
}else if (recordSet.getDBType().equalsIgnoreCase("postgresql")) {
pageSql = sql + " limit " +pageSize + " offset " + (currentPage - 1) * pageSize;
}
recordSet.executeQuery(pageSql);
// #1473334-概述:满足考勤报分部部门显示及导出时显示全路径
String fullPathMainKey = "show_full_path";
KQSettingsComInfo kqSettingsComInfo = new KQSettingsComInfo();
String isShowFullPath = Util.null2String(kqSettingsComInfo.getMain_val(fullPathMainKey),"0");
String departmentNameTmp = "";
String subCompanyNameTmp = "";
while (recordSet.next()) {
dataMap = new HashMap<String, Object>();
String id = recordSet.getString("id");
String lastName = Util.formatMultiLang(recordSet.getString("lastName"), "" + user.getLanguage());
String departmentId = recordSet.getString("departmentId");
String subcompanyId = recordSet.getString("subcompanyId1");
String jobtitleId = recordSet.getString("jobtitle");
String workcode = recordSet.getString("workcode");
String companyStartdate = recordSet.getString("companyStartdate");
dataMap.put("id", id);
dataMap.put("lastName", lastName);
// 根据开关决定是否显示分部部门全路径
subCompanyNameTmp = "1".equals(isShowFullPath) ?
SubCompanyComInfo.getSubcompanyRealPath(subcompanyId, "/", "0") :
subCompanyComInfo.getSubCompanyname(subcompanyId);
departmentNameTmp = "1".equals(isShowFullPath) ?
departmentComInfo.getDepartmentRealPath(departmentId, "/", "0") :
departmentComInfo.getDepartmentname(departmentId);
dataMap.put("subcom", Util.formatMultiLang(subCompanyNameTmp, "" + user.getLanguage()));
dataMap.put("dept", Util.formatMultiLang(departmentNameTmp, "" + user.getLanguage()));
// dataMap.put("subcom", Util.formatMultiLang(subCompanyComInfo.getSubcompanyname(subcompanyId), "" + user.getLanguage()));
// dataMap.put("dept", Util.formatMultiLang(departmentComInfo.getDepartmentname(departmentId), "" + user.getLanguage()));
dataMap.put("jobtitle", Util.formatMultiLang(jobTitlesComInfo.getJobTitlesname(jobtitleId), "" + user.getLanguage()));
dataMap.put("workcode", workcode);
dataMap.put("companyStartDate", companyStartdate);
dataMap.put("subcomId", subcompanyId);
dataMap.put("deptId", departmentId);
dataMap.put("jobtitleId", jobtitleId);
rulesComInfo.setTofirstRow();
while (rulesComInfo.next()) {
if (rulesComInfo.getIsEnable().equals("0")) {
continue;
}
/*该假期没有开启余额限制,显示不限制余额*/
if (rulesComInfo.getBalanceEnable().equals("0")) {
dataMap.put(rulesComInfo.getId(), SystemEnv.getHtmlLabelName(389731, user.getLanguage()));//不限制余额
continue;
}
BigDecimal restAmount = balanceMap.get(id + "_" + rulesComInfo.getId());
dataMap.put(rulesComInfo.getId(), restAmount != null ? restAmount.setScale(2, RoundingMode.HALF_UP).toPlainString() : "0");
}
dataList.add(dataMap);
}
columnsList = HrmFieldUtil.getHrmDetailTable(hrmFieldBeanList, null, user);
resultMap.put("columns", columnsList);
resultMap.put("datas", dataList);
} catch (Exception e) {
e.printStackTrace();
}
return resultMap;
}
}

@ -0,0 +1,808 @@
package com.engine.kq.cmd.leaverules;
import com.api.browser.bean.SearchConditionItem;
import com.api.browser.bean.SearchConditionOption;
import com.api.hrm.bean.HrmFieldBean;
import com.api.hrm.util.HrmFieldSearchConditionComInfo;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.kq.biz.KQLeaveRulesComInfo;
import weaver.conn.RecordSet;
import weaver.filter.XssUtil;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.systeminfo.SystemEnv;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* --
*/
public class GetLeaveRulesFormCmd extends AbstractCommonCommand<Map<String, Object>> {
public GetLeaveRulesFormCmd(Map<String, Object> params, User user) {
this.user = user;
this.params = params;
}
@Override
public BizLogContext getLogContext() {
return null;
}
@Override
public Map<String, Object> execute(CommandContext commandContext) {
Map<String, Object> resultMap = new HashMap<String, Object>();
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<String, Object> entryMap = new HashMap<String, Object>();
List entryList = new ArrayList();
/*工龄--年假*/
Map<String, Object> workingAgeMap = new HashMap<String, Object>();
List workingAgeList = new ArrayList();
/*入职时长+工龄混合--年假*/
Map<String, Object> mixedModeMap = new HashMap<String, Object>();
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<String, Object>();
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<String, Object>();
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<String, Object>();
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<String, Object>();
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<Map<String, Object>> groupList = new ArrayList<Map<String, Object>>();
Map<String, Object> groupItem = new HashMap<String, Object>();
List<Object> itemList = new ArrayList<Object>();
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<SearchConditionOption> optionsList = new ArrayList<SearchConditionOption>();
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<String, Object> OtherParamsMap = new HashMap<String, Object>();
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<String, Object> OtherParamsMap = new HashMap<String, Object>();
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<SearchConditionOption>();
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<String, Object> OtherParamsMap = new HashMap<String, Object>();
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<String, Object> OtherParamsMap = new HashMap<String, Object>();
OtherParamsMap.put("hasBorder", true);
searchConditionItem.setOtherParams(OtherParamsMap);
}
itemList.add(searchConditionItem);
groupItem.put("items", itemList);
groupList.add(groupItem);
/****************************************************发放规则****************************************************/
groupItem = new HashMap<String, Object>();
itemList = new ArrayList<Object>();
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<SearchConditionOption>();
optionsList.add(new SearchConditionOption("1", SystemEnv.getHtmlLabelName(388947, user.getLanguage()), distributionMode == 1));
optionsList.add(new SearchConditionOption("2", SystemEnv.getHtmlLabelName(390374, user.getLanguage()), distributionMode == 2));
optionsList.add(new SearchConditionOption("3", SystemEnv.getHtmlLabelName(388949, user.getLanguage()), distributionMode == 3));
optionsList.add(new SearchConditionOption("4", SystemEnv.getHtmlLabelName(390323, user.getLanguage()), distributionMode == 4));
optionsList.add(new SearchConditionOption("5", SystemEnv.getHtmlLabelName(388951, user.getLanguage()), distributionMode == 5));
SearchConditionOption searchConditionOption = new SearchConditionOption("6", SystemEnv.getHtmlLabelName(390822, user.getLanguage()), distributionMode == 6);
searchConditionOption.setDisabled((isEdit && distributionMode != 6) ? true : false);
optionsList.add(searchConditionOption);
optionsList.add(new SearchConditionOption("7", SystemEnv.getHtmlLabelName(514025, user.getLanguage()), distributionMode == 7));
optionsList.add(new SearchConditionOption("8", SystemEnv.getHtmlLabelName(536880, user.getLanguage()), distributionMode == 8));
//增加加班调休规则
optionsList.add(new SearchConditionOption("9", "工作日加班时长自动计入", distributionMode == 9));
optionsList.add(new SearchConditionOption("10", "休息日加班时长自动计入", distributionMode == 10));
searchConditionItem.setOptions(optionsList);
searchConditionItem.setHelpfulTip("★" + SystemEnv.getHtmlLabelName(10000815,user.getLanguage()) + "★" + SystemEnv.getHtmlLabelName(501107, user.getLanguage()));
if (hrmFieldBean.getViewAttr() == 1) {
Map<String, Object> OtherParamsMap = new HashMap<String, Object>();
OtherParamsMap.put("hasBorder", true);
searchConditionItem.setOtherParams(OtherParamsMap);
}
itemList.add(searchConditionItem);
List<String> distributionModeTips = new ArrayList<String>();
distributionModeTips.add(SystemEnv.getHtmlLabelName(389735, user.getLanguage()) + " <font color=\"#FF0000\"><b>" + SystemEnv.getHtmlLabelName(511045, user.getLanguage()) + "</b></font>");
distributionModeTips.add(SystemEnv.getHtmlLabelName(500952, user.getLanguage()) + " <font color=\"#FF0000\"><b>" + SystemEnv.getHtmlLabelName(511045, user.getLanguage()) + "</b></font>");
distributionModeTips.add(SystemEnv.getHtmlLabelName(500953, user.getLanguage()) + " <font color=\"#FF0000\"><b>" + SystemEnv.getHtmlLabelName(511046, user.getLanguage()) + "</b></font>");
distributionModeTips.add(SystemEnv.getHtmlLabelName(389736, user.getLanguage()) + " <font color=\"#FF0000\"><b>" + SystemEnv.getHtmlLabelName(511045, user.getLanguage()) + "</b></font>");
distributionModeTips.add(SystemEnv.getHtmlLabelName(389737, user.getLanguage()) + " <font color=\"#FF0000\"><b>" + SystemEnv.getHtmlLabelName(511045, user.getLanguage()) + "</b></font>");
distributionModeTips.add(SystemEnv.getHtmlLabelName(500954, user.getLanguage()) + " <font color=\"#FF0000\"><b>" + SystemEnv.getHtmlLabelName(511046, user.getLanguage()) + "</b></font>");
distributionModeTips.add(SystemEnv.getHtmlLabelName(514026, user.getLanguage()) + " <font color=\"#FF0000\"><b>" + SystemEnv.getHtmlLabelName(511045, user.getLanguage()) + "</b></font>");
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<SearchConditionOption>();
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<String, Object> OtherParamsMap = new HashMap<String, Object>();
OtherParamsMap.put("hasBorder", true);
searchConditionItem.setOtherParams(OtherParamsMap);
}
itemList.add(searchConditionItem);
List<String> calcMethodTips = new ArrayList<String>();
//以入职日期(或参加工作日期)为分隔点将一年划分为上半年和下半年,全年可用假期天数=上半年天数/全年总天数*上半年司龄(或工龄)对应的假期天数+下半年天数/全年总天数*下半年司龄(或工龄)对应的假期天数。每年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<SearchConditionOption>();
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<String, Object> OtherParamsMap = new HashMap<String, Object>();
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<String, Object> OtherParamsMap = new HashMap<String, Object>();
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<SearchConditionOption>();
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<String, Object> OtherParamsMap = new HashMap<String, Object>();
OtherParamsMap.put("hasBorder", true);
searchConditionItem.setOtherParams(OtherParamsMap);
}
itemList.add(searchConditionItem);
List<String> convertModeTips = new ArrayList<String>();
//指不考虑是否是入职当年还是初始获得年即年初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<String, Object>();
itemList = new ArrayList<Object>();
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<SearchConditionOption>();
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<String, Object> OtherParamsMap = new HashMap<String, Object>();
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<String, Object> OtherParamsMap = new HashMap<String, Object>();
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<String, Object> OtherParamsMap = new HashMap<String, Object>();
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<SearchConditionOption>();
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<String, Object> OtherParamsMap = new HashMap<String, Object>();
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<SearchConditionOption>();
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<String, Object> OtherParamsMap = new HashMap<String, Object>();
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<String, Object> otherParamsMap = new HashMap<String, Object>();
otherParamsMap.put("display", "switch");
searchConditionItem.setOtherParams(otherParamsMap);
if (hrmFieldBean.getViewAttr() == 1) {
Map<String, Object> OtherParamsMap = new HashMap<String, Object>();
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<String, Object> OtherParamsMap = new HashMap<String, Object>();
OtherParamsMap.put("hasBorder", true);
searchConditionItem.setOtherParams(OtherParamsMap);
}
itemList.add(searchConditionItem);
groupItem.put("items", itemList);
groupList.add(groupItem);
/****************************************************其他设置****************************************************/
groupItem = new HashMap<String, Object>();
itemList = new ArrayList<Object>();
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<SearchConditionOption>();
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<String, Object> OtherParamsMap = new HashMap<String, Object>();
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<String, Object>();
otherParamsMap.put("display", "switch");
searchConditionItem.setOtherParams(otherParamsMap);
if (hrmFieldBean.getViewAttr() == 1) {
Map<String, Object> OtherParamsMap = new HashMap<String, Object>();
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<String, Object>();
otherParamsMap.put("display", "switch");
searchConditionItem.setOtherParams(otherParamsMap);
if (hrmFieldBean.getViewAttr() == 1) {
Map<String, Object> OtherParamsMap = new HashMap<String, Object>();
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;
}
}

@ -0,0 +1,430 @@
package com.engine.kq.cmd.myattendance;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.kq.biz.*;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.hrm.resource.ResourceComInfo;
import weaver.systeminfo.SystemEnv;
import org.apache.commons.lang3.StringUtils;
import java.util.*;
/**
* ----
*/
public class GetHrmKQReportInfoCmd extends AbstractCommonCommand<Map<String, Object>> {
public GetHrmKQReportInfoCmd(Map<String, Object> params, User user) {
this.user = user;
this.params = params;
}
@Override
public BizLogContext getLogContext() {
return null;
}
private static boolean isIndirectSuperId(String id,String checkSuperId,ResourceComInfo info){
int loopBreakTimes = 20 ;
for(String loopId = id;
isRightResourceId(loopId) && (loopBreakTimes--)>0 ;
loopId = info.getManagerID(loopId)){
if(isDirectSuperId(loopId,checkSuperId,info)) return true ;
}
return false ;
}
private static boolean isDirectSuperId(String id,String checkSuperId,ResourceComInfo info){
String superId = Util.null2String(info.getManagerID(id)) ;
return isRightResourceId(superId) && superId.equals(checkSuperId) ;
}
/**
*
* @param id
* @param checkSuperId
* @return
*/
private static boolean isTeamMembers(String id,String checkSuperId){
boolean isMember = false;
String sql = " select id from cus_fielddata where id=? and field89=? ";
RecordSet rs = new RecordSet();
rs.executeQuery(sql,id,checkSuperId);
if(rs.next()){
isMember = true;
}
String kqwySql = " select b.id from hrmdepartmentdefined a,hrmresource b " +
"where a.kqwy=? and a.deptid=b.departmentid and b.id=?";
rs.executeQuery(kqwySql,checkSuperId,id);
if(rs.next()){
isMember = true;
}
return isMember;
}
private static boolean isRightResourceId(String id){
return StringUtils.isNotBlank(id) && !"0".equals(id) ;
}
@Override
public Map<String, Object> execute(CommandContext commandContext) {
Map<String, Object> resultMap = new HashMap<String, Object>();
try {
ResourceComInfo resourceComInfo = new ResourceComInfo();
/**
*
*/
int subCompanyId = Util.getIntValue((String) params.get("subCompanyId"), 0);
int departmentId = Util.getIntValue((String) params.get("departmentId"), 0);
String resourceId = Util.null2String(params.get("resourceId"));
if (resourceId.equals("")) {
resourceId = "" + user.getUID();
}
String lastName = resourceComInfo.getResourcename(resourceId);
if (resourceId.equals("" + user.getUID())) {
resultMap.put("title", SystemEnv.getHtmlLabelName(513095, user.getLanguage()));
} else {
resultMap.put("title", SystemEnv.getHtmlLabelName(515562, user.getLanguage()).replace("{name}", lastName));
}
if (subCompanyId == 0 || departmentId == 0) {
subCompanyId = Util.getIntValue(resourceComInfo.getSubCompanyID(resourceId), 0);
departmentId = Util.getIntValue(resourceComInfo.getDepartmentID(resourceId), 0);
}
//if (!resourceId.equals("" + user.getUID()) && !isIndirectSuperId(resourceId, user.getUID() + "", resourceComInfo) && !HrmUserVarify.checkUserRight("HrmResource:Absense", user, departmentId)) {
// resultMap.put("status", "-1");
// resultMap.put("hasRight", false);
// return resultMap;
//}
//二开线长查看组员考勤
if (!resourceId.equals("" + user.getUID()) && !isTeamMembers(resourceId, user.getUID() + "") && !isIndirectSuperId(resourceId, user.getUID() + "", resourceComInfo)
&& !HrmUserVarify.checkUserRight("HrmResource:Absense", user, departmentId)) {
resultMap.put("status", "-1");
resultMap.put("hasRight", false);
return resultMap;
}
String fromDate = Util.null2String(params.get("fromDate"));
String toDate = Util.null2String(params.get("toDate"));
Calendar today = Calendar.getInstance();
/**今年*/
String currentDate = Util.add0(today.get(Calendar.YEAR), 4) + "-"
+ Util.add0(today.get(Calendar.MONTH) + 1, 2) + "-"
+ Util.add0(today.get(Calendar.DAY_OF_MONTH), 2);
/**上一年*/
String lastYearDate = Util.add0(today.get(Calendar.YEAR) - 1, 4) + "-12-31";
/**
*
*/
Map<String, Object> groupMap = new HashMap<String, Object>();
List<Object> groupItemList = new ArrayList<Object>();
Map<String, Object> groupItem = new HashMap<String, Object>();
List<Object> itemList = new ArrayList<Object>();
Map<String, Object> itemMap = new HashMap<String, Object>();
List<Object> itemList5 = new ArrayList<Object>();
Map<String, Object> groupItem5 = new HashMap<String, Object>();
/**
*
* workDays
* realWorkDays
* leaveDays
*/
double workDays = 0.00;
double realWorkDays = 0.00;
double leaveDays = 0.00;
/**
* beLate
* graveBeLate
* leaveEearly退
* graveLeaveEarly
* absenteeism
* forgotCheck
*/
int beLate = 0;
int graveBeLate = 0;
int leaveEearly = 0;
int graveLeaveEarly = 0;
int absenteeism = 0;
int forgotCheck = 0;
/**
* or_minimumUnit
* or_unitName()/()
* tr_minimumUnit
* tr_unitName()/()
* er_minimumUnit
* er_unitName()/()
*/
int or_minimumUnit = KQOvertimeRulesBiz.getMinimumUnit();//最小加班单位
String or_unitName = (or_minimumUnit == 3 || or_minimumUnit == 5 || or_minimumUnit == 6) ? SystemEnv.getHtmlLabelName(389326, user.getLanguage()) : SystemEnv.getHtmlLabelName(389325, user.getLanguage());
KQTravelRulesComInfo kqTravelRulesComInfo = new KQTravelRulesComInfo();
int tr_minimumUnit = Util.getIntValue(kqTravelRulesComInfo.getMinimumUnit("1"));//最小出差单位
String tr_unitName = tr_minimumUnit == 3 ? SystemEnv.getHtmlLabelName(389326, user.getLanguage()) : SystemEnv.getHtmlLabelName(389325, user.getLanguage());
KQExitRulesComInfo kqExitRulesComInfo = new KQExitRulesComInfo();
int er_minimumUnit = Util.getIntValue(kqExitRulesComInfo.getMinimumUnit("1"));//最小公出单位
String er_unitName = er_minimumUnit == 3 ? SystemEnv.getHtmlLabelName(389326, user.getLanguage()) : SystemEnv.getHtmlLabelName(389325, user.getLanguage());
/**
* overtimeTotal
* businessLeave
* officialBusiness
*/
double overtimeTotal = 0.00;//加班时长
double businessLeave = 0.00;//出差时长
double officialBusiness = 0.00;//公出时长
/**
* ()
*/
KQLeaveRulesComInfo rulesComInfo = new KQLeaveRulesComInfo();
Map<String, Object> leaveMap = new HashMap<String, Object>();
/**
* service
* com/engine/kq/cmd/report/GetKQReportCmd.java
*/
List<Map<String, Object>> datasList = new ArrayList<Map<String, Object>>();
Map<String, Object> datasMap = new HashMap<>();
datasList = (List<Map<String, Object>>) params.get("datas");
for (int i = 0; datasList != null && i < datasList.size(); i++) {
datasMap = (Map<String, Object>) datasList.get(i);
workDays += Util.getDoubleValue((String) datasMap.get("workdays"), 0.00);//应出勤天数
realWorkDays += Util.getDoubleValue((String) datasMap.get("attendancedays"), 0.00);//实际出勤天数
leaveDays = workDays - realWorkDays;//缺勤天数
beLate += Util.getIntValue((String) datasMap.get("beLate"), 0);//迟到次数
graveBeLate += Util.getIntValue((String) datasMap.get("graveBeLate"), 0);//严重迟到次数
leaveEearly += Util.getIntValue((String) datasMap.get("leaveEearly"), 0);//早退次数
graveLeaveEarly += Util.getIntValue((String) datasMap.get("graveLeaveEarly"), 0);//严重迟到次数
absenteeism += Util.getIntValue((String) datasMap.get("absenteeism"), 0);//旷工次数
forgotCheck += Util.getIntValue((String) datasMap.get("forgotCheck"), 0);//漏签次数
overtimeTotal += Util.getDoubleValue((String) datasMap.get("overtimeTotal"), 0.00);//加班时长
businessLeave += Util.getDoubleValue((String) datasMap.get("businessLeave"), 0.00);//出差时长
officialBusiness += Util.getDoubleValue((String) datasMap.get("officialBusiness"), 0.00);//公出时长
rulesComInfo.setTofirstRow();
while (i == 0 && rulesComInfo.next()) {
double value = Util.getDoubleValue(String.valueOf(leaveMap.get("leaveType_" + rulesComInfo.getId())), 0.00);
value += Util.getDoubleValue((String) datasMap.get("leaveType_" + rulesComInfo.getId()), 0.00);//请假时长
leaveMap.put("leaveType_" + rulesComInfo.getId(), value);
}
}
/**统计应出勤天数*/
KQWorkTime kqWorkTime = new KQWorkTime();
if (!toDate.equals("") && toDate.compareTo(currentDate) > 0 && Util.getIntValue(resourceComInfo.getStatus(resourceId), 0) < 4) {
workDays = 0.00;
if (!fromDate.equals("") && fromDate.compareTo(currentDate) > 0) {
//查询没有到的月份缺勤天数以及出勤天数应该都为0
realWorkDays = 0.00;
leaveDays = 0.00;
}
boolean isEnd = false;
for (String date = fromDate; !isEnd; ) {
if (date.compareTo(toDate)>=0) {
isEnd = true;
}
boolean isWorkDay = kqWorkTime.isWorkDay(resourceId, date);
if (isWorkDay) {
workDays += 1.00;
}
date = DateUtil.getDate(date, 1);
}
}
/**********************************************************************************************************/
itemList = new ArrayList<Object>();
itemMap = new HashMap<String, Object>();
itemMap.put("id", "leaveDays");
itemMap.put("name", SystemEnv.getHtmlLabelName(506345, user.getLanguage()));//未出勤
itemMap.put("title", SystemEnv.getHtmlLabelName(506345, user.getLanguage()));
itemMap.put("type", "ABSENT");
itemMap.put("value", String.format("%.2f", leaveDays));
itemList.add(itemMap);
itemMap = new HashMap<String, Object>();
itemMap.put("id", "realWorkDays");
itemMap.put("name", SystemEnv.getHtmlLabelName(130566, user.getLanguage()));//实际出勤
itemMap.put("title", SystemEnv.getHtmlLabelName(130566, user.getLanguage()));
itemMap.put("type", "REALWORKDAYS");
itemMap.put("value", String.format("%.2f", realWorkDays));
itemList.add(itemMap);
groupItem = new HashMap<String, Object>();
groupItem.put("id", "workDays");
groupItem.put("name", SystemEnv.getHtmlLabelName(513089, user.getLanguage()));//应出勤(天)
groupItem.put("title", SystemEnv.getHtmlLabelName(16732, user.getLanguage()));
groupItem.put("value", String.format("%.2f", workDays));
groupItem.put("items", itemList);
resultMap.put("groupitem1", groupItem);
/**********************************************************************************************************/
itemList = new ArrayList<Object>();
itemMap = new HashMap<String, Object>();
itemMap.put("name", "evection");
itemMap.put("title", SystemEnv.getHtmlLabelName(20084, user.getLanguage()) + tr_unitName);//出差
itemMap.put("type", "EVECTION");
itemMap.put("value", String.format("%.2f",businessLeave));
itemList.add(itemMap);
itemMap = new HashMap<String, Object>();
itemMap.put("name", "outDays");
itemMap.put("title", SystemEnv.getHtmlLabelName(24058, user.getLanguage()) + er_unitName);//公出
itemMap.put("type", "OUTDAYS");
itemMap.put("value",String.format("%.2f",officialBusiness));
itemList.add(itemMap);
itemMap = new HashMap<String, Object>();
itemMap.put("name", "overTimes");
itemMap.put("title", SystemEnv.getHtmlLabelName(6151, user.getLanguage()) + or_unitName);//加班
itemMap.put("type", "OVERTIME");
itemMap.put("value", String.format("%.2f",overtimeTotal));
itemList.add(itemMap);
groupItem = new HashMap<String, Object>();
groupItem.put("items", itemList);
resultMap.put("groupitem2", groupItem);
/**********************************************************************************************************/
itemList = new ArrayList<Object>();
itemMap = new HashMap<String, Object>();
itemMap.put("name", "beLate");
itemMap.put("title", SystemEnv.getHtmlLabelName(34089, user.getLanguage()));//迟到
itemMap.put("type", "BELATE");
itemMap.put("value", beLate);
itemList.add(itemMap);
itemMap = new HashMap<String, Object>();
itemMap.put("name", "graveBeLate");
itemMap.put("title", SystemEnv.getHtmlLabelName(535131, user.getLanguage()));//严重迟到
itemMap.put("type", "graveBeLate");
itemMap.put("value", graveBeLate);
itemList.add(itemMap);
itemMap = new HashMap<String, Object>();
itemMap.put("name", "leaveEarly");
itemMap.put("title", SystemEnv.getHtmlLabelName(34098, user.getLanguage()));//早退
itemMap.put("type", "LEAVEEARLY");
itemMap.put("value", leaveEearly);
itemList.add(itemMap);
itemMap = new HashMap<String, Object>();
itemMap.put("name", "graveLeaveEarly");
itemMap.put("title", SystemEnv.getHtmlLabelName(535132, user.getLanguage()));//严重早退
itemMap.put("type", "graveLeaveEarly");
itemMap.put("value", graveLeaveEarly);
itemList.add(itemMap);
itemMap = new HashMap<String, Object>();
itemMap.put("name", "absentFromWork");
itemMap.put("title", SystemEnv.getHtmlLabelName(10000344, user.getLanguage()));//旷工
itemMap.put("type", "ABSENT");
itemMap.put("value", absenteeism);
itemList.add(itemMap);
itemMap = new HashMap<String, Object>();
itemMap.put("name", "noSign");
itemMap.put("title", SystemEnv.getHtmlLabelName(34099, user.getLanguage()));//漏签
itemMap.put("type", "noSign");
itemMap.put("value", forgotCheck);
itemList.add(itemMap);
groupItem = new HashMap<String, Object>();
groupItem.put("items", itemList);
resultMap.put("groupitem3", groupItem);
/**********************************************************************************************************/
rulesComInfo.setTofirstRow();
while (rulesComInfo.next()) {
if (!rulesComInfo.getIsEnable().equals("1") || !rulesComInfo.getBalanceEnable().equals("1")) {
continue;
}
String scopeType = rulesComInfo.getScopeType();
if (scopeType.equals("1")) {
String scopeValue = rulesComInfo.getScopeValue();
List<String> scopeValueList = Util.TokenizerString(scopeValue, ",");
if (scopeValueList.indexOf("" + resourceComInfo.getSubCompanyID(resourceId)) < 0) {
continue;
}
}
String allRestAmount = KQBalanceOfLeaveBiz.getRestAmount("" + resourceId, rulesComInfo.getId(), currentDate, true, true);
String currentRestAmount = KQBalanceOfLeaveBiz.getRestAmount("" + resourceId, rulesComInfo.getId(), currentDate, true, false);
String beforeRestAmount = String.format("%.2f", Util.getDoubleValue(allRestAmount, 0) - Util.getDoubleValue(currentRestAmount, 0));
itemList = new ArrayList<Object>();
if(KQSettingsBiz.show_split_balance()) {
itemMap = new HashMap<String, Object>();
itemMap.put("title", (KQUnitBiz.isLeaveHour(rulesComInfo.getMinimumUnit())) ? SystemEnv.getHtmlLabelName(513286, user.getLanguage()) : SystemEnv.getHtmlLabelName(513287, user.getLanguage()));
itemMap.put("value", beforeRestAmount);
itemList.add(itemMap);
itemMap = new HashMap<String, Object>();
itemMap.put("title", (KQUnitBiz.isLeaveHour(rulesComInfo.getMinimumUnit())) ? SystemEnv.getHtmlLabelName(504395, user.getLanguage()) : SystemEnv.getHtmlLabelName(504394, user.getLanguage()));
itemMap.put("value", currentRestAmount);
itemList.add(itemMap);
itemMap = new HashMap<String, Object>();
itemMap.put("title", (KQUnitBiz.isLeaveHour(rulesComInfo.getMinimumUnit())) ? SystemEnv.getHtmlLabelName(513288, user.getLanguage()) : SystemEnv.getHtmlLabelName(513289, user.getLanguage()));
itemMap.put("value", allRestAmount);
itemList.add(itemMap);
}else{
itemMap = new HashMap<String, Object>();
itemMap.put("title", (KQUnitBiz.isLeaveHour(rulesComInfo.getMinimumUnit())) ? SystemEnv.getHtmlLabelName(513288, user.getLanguage()) : SystemEnv.getHtmlLabelName(513289, user.getLanguage()));
itemMap.put("value", allRestAmount);
itemList.add(itemMap);
}
groupItem = new HashMap<String, Object>();
groupItem.put("color", "#25C6DA");
groupItem.put("icon", "icon-Human-resources-adjustment");
groupItem.put("title", rulesComInfo.getLeaveName());
groupItem.put("item", itemList);
groupItemList.add(groupItem);
}
groupMap.put("items", groupItemList);
groupMap.put("title", SystemEnv.getHtmlLabelName(132058, user.getLanguage()));
resultMap.put("groupitem4", groupMap);
/**********************************************************************************************************/
rulesComInfo.setTofirstRow();
while (rulesComInfo.next()) {
double value = Util.getDoubleValue(String.valueOf(leaveMap.get("leaveType_" + rulesComInfo.getId())), 0.00);//请假时长
if (value > 0) {
String leaveName = Util.formatMultiLang(rulesComInfo.getLeaveName(), "" + user.getLanguage());
int le_minimumUnit = Util.getIntValue(rulesComInfo.getMinimumUnit(), 1);//最小请假单位
String le_unitName = (le_minimumUnit == 3 || le_minimumUnit == 5 || le_minimumUnit == 6) ? SystemEnv.getHtmlLabelName(389326, user.getLanguage()) : SystemEnv.getHtmlLabelName(389325, user.getLanguage());
itemMap = new HashMap<String, Object>();
itemMap.put("name", "leaveType_" + rulesComInfo.getId());
itemMap.put("title", leaveName + le_unitName);
itemMap.put("type", "leaveType_" + rulesComInfo.getId());
itemMap.put("value", Util.toDecimalDigits("" + value, 2));
itemList5.add(itemMap);
}
}
groupItem5.put("items", itemList5);
resultMap.put("groupitem5", groupItem5);
resultMap.put("status", "1");
} catch (Exception e) {
writeLog(e);
}
return resultMap;
}
}

@ -0,0 +1,466 @@
package com.engine.kq.cmd.myattendance;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.kq.biz.*;
import com.engine.kq.cmd.shiftmanagement.toolkit.ShiftManagementToolKit;
import com.engine.kq.entity.WorkTimeEntity;
import com.engine.kq.enums.KqSplitFlowTypeEnum;
import com.engine.kq.wfset.util.KQSignUtil;
import org.checkerframework.checker.units.qual.K;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.systeminfo.SystemEnv;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* 退
*/
public class GetHrmKQSignInfoCmd extends AbstractCommonCommand<Map<String, Object>> {
public GetHrmKQSignInfoCmd(Map<String, Object> params, User user) {
this.user = user;
this.params = params;
}
@Override
public BizLogContext getLogContext() {
return null;
}
@Override
public Map<String, Object> execute(CommandContext commandContext) {
Map<String, Object> resultMap = new HashMap<String, Object>();
try {
String date = Util.null2String(params.get("date"));
String resourceId = Util.null2String(params.get("resourceId"));
if (resourceId.equals("")) {
resourceId = String.valueOf(user.getUID());
}
String isMobile = Util.null2String(params.get("isMobile"));//是否是移动端的【我的考勤】
/**判断是否显示补打卡数据*/
boolean showCard = false;
String settingSql = "select * from KQ_SETTINGS where main_key='showSignFromCard'";
RecordSet recordSet = new RecordSet();
recordSet.executeQuery(settingSql);
if (recordSet.next()) {
String main_val = recordSet.getString("main_val");
showCard = main_val.equals("1");
}
Map<String, Object> signStatusInfo = new HashMap<String, Object>();
List<Object> dataList = new ArrayList<>();
Map<String, Object> dataMap = new HashMap<>();
List<Object> dataItemList = new ArrayList<>();
Map<String, Object> dataItemMap = new HashMap<>();
BaseBean bb = new BaseBean();
//所有的休息班次id
String xxrSerialId = bb.getPropValue("hskq_main","xxrSerialId");
Boolean checkXxr = false;
String serialId = "";
String sql = "SELECT a.RESOURCEID, a.KQDATE, a.GROUPID, a.SERIALID, a.SERIALNUMBER, a.WORKBEGINDATE,\n " +
"a.WORKBEGINTIME, a.WORKENDDATE, a.WORKENDTIME, a.WORKMINS, a.SIGNINDATE, a.SIGNINTIME,\n " +
"a.SIGNINID, a.SIGNOUTDATE, a.SIGNOUTTIME, a.SIGNOUTID, a.ATTENDANCEMINS, a.BELATEMINS,\n " +
"a.GRAVEBELATEMINS, a.LEAVEEARLYMINS, a.GRAVELEAVEEARLYMINS, a.ABSENTEEISMMINS, a.LEAVEMINS,\n " +
"a.EVECTIONMINS, a.OUTMINS, a.FORGOTCHECKMINS, a.SIGNMINS, a.LEAVEINFO, a.FORGOTBEGINWORKCHECKMINS,\n " +
"'signIn' signType,a.signInDate signDate,a.signInTime signTime,b.clientAddress,b.addr\n " +
"FROM KQ_FORMAT_DETAIL a LEFT JOIN HrmScheduleSign b ON a.signInId=b.id " +
"WHERE kqDate='" + date + "' AND resourceId=" + resourceId + "\n ";
if (!showCard) {
sql += " AND (signFrom is null or signFrom not like 'card%') ";
}
sql += "UNION ALL\n " +
"SELECT a.RESOURCEID, a.KQDATE, a.GROUPID, a.SERIALID, a.SERIALNUMBER, a.WORKBEGINDATE,\n " +
"a.WORKBEGINTIME, a.WORKENDDATE, a.WORKENDTIME, a.WORKMINS, a.SIGNINDATE, a.SIGNINTIME,\n " +
"a.SIGNINID, a.SIGNOUTDATE, a.SIGNOUTTIME, a.SIGNOUTID, a.ATTENDANCEMINS, a.BELATEMINS,\n " +
"a.GRAVEBELATEMINS, a.LEAVEEARLYMINS, a.GRAVELEAVEEARLYMINS, a.ABSENTEEISMMINS, a.LEAVEMINS,\n " +
"a.EVECTIONMINS, a.OUTMINS, a.FORGOTCHECKMINS, a.SIGNMINS, a.LEAVEINFO, a.FORGOTBEGINWORKCHECKMINS,\n " +
"'signOut' signType,a.signOutDate signDate,a.signOutTime signTime,b.clientAddress,b.addr\n " +
"FROM KQ_FORMAT_DETAIL a LEFT JOIN HrmScheduleSign b ON a.signOutId=b.id " +
"WHERE kqDate='" + date + "' AND resourceId=" + resourceId + "\n ";
if (!showCard) {
sql += " AND (signFrom is null or signFrom not like 'card%') ";
}
sql += "ORDER BY kqDate,resourceId,serialNumber,signType ";
recordSet.executeQuery(sql);
while (recordSet.next()) {
String signType = recordSet.getString("signType");
String signDate = recordSet.getString("signDate");
String signTime = recordSet.getString("signTime");
String clientAddress = recordSet.getString("clientAddress");
String addr = recordSet.getString("addr");
serialId = Util.null2String(recordSet.getString("serialId"));
int serialNumber = recordSet.getInt("serialnumber") + 1;
String workBeginTime = Util.null2String(recordSet.getString("workbegintime")).trim();
String workEndTime = Util.null2String(recordSet.getString("workendtime")).trim();
int workMins = recordSet.getInt("workMins");
int attendanceMins = recordSet.getInt("attendanceMins");
String beLateMins = Util.null2String(recordSet.getString("beLateMins")).trim();
String graveBeLateMins = Util.null2String(recordSet.getString("graveBeLateMins")).trim();
String leaveEarlyMins = Util.null2String(recordSet.getString("leaveEarlyMins")).trim();
String graveLeaveEarlyMins = Util.null2String(recordSet.getString("graveLeaveEarlyMins")).trim();
String absenteeismMins = Util.null2String(recordSet.getString("absenteeismMins")).trim();
String forgotCheckMins = Util.null2String(recordSet.getString("forgotcheckMins")).trim();
String forgotBeginWorkCheckMins = Util.null2String(recordSet.getString("forgotBeginWorkCheckMins")).trim();
int leaveMins = recordSet.getInt("leaveMins");
String leaveInfo = Util.null2String(recordSet.getString("leaveInfo"));
int evectionMins = recordSet.getInt("evectionMins");
int outMins = recordSet.getInt("outMins");
signStatusInfo = new HashMap<String, Object>();
signStatusInfo.put("worktime", workBeginTime);
signStatusInfo.put("absenteeismMins", absenteeismMins);
signStatusInfo.put("leaveMins", leaveMins);
signStatusInfo.put("leaveInfo", leaveInfo);
signStatusInfo.put("evectionMins", evectionMins);
signStatusInfo.put("outMins", outMins);
String signStatus = "";
boolean needWorkFlow = false;//是否需要提交考勤异常流程
if ("signIn".equals(signType)) {
signStatusInfo.put("beLateMins", beLateMins);
signStatusInfo.put("graveBeLateMins", graveBeLateMins);
signStatusInfo.put("forgotBeginWorkCheckMins", forgotBeginWorkCheckMins);
signStatus = "on";
if (Util.getDoubleValue(beLateMins, 0) > 0 || Util.getDoubleValue(graveBeLateMins, 0) > 0 || Util.getDoubleValue(forgotBeginWorkCheckMins, 0) > 0 || Util.getDoubleValue(absenteeismMins, 0) > 0) {
needWorkFlow = true;
}
} else {
signStatusInfo.put("leaveEarlyMins", leaveEarlyMins);
signStatusInfo.put("graveLeaveEarlyMins", graveLeaveEarlyMins);
signStatusInfo.put("forgotCheckMins", forgotCheckMins);
signStatusInfo.put("forgotBeginWorkCheckMins", forgotBeginWorkCheckMins);
signStatus = "off";
if (Util.getDoubleValue(leaveEarlyMins, 0) > 0 || Util.getDoubleValue(graveLeaveEarlyMins, 0) > 0 || Util.getDoubleValue(forgotCheckMins, 0) > 0 || Util.getDoubleValue(absenteeismMins, 0) > 0) {
needWorkFlow = true;
}
}
if (!resourceId.equals("" + user.getUID())) {
needWorkFlow = false;
}
String status = KQReportBiz.getSignStatus2(signStatusInfo, user, signStatus);
// if (serialId.equalsIgnoreCase("")) {
// continue;
// }
if ("signIn".equals(signType)) {
//签到 start
String signDateTime = signDate + " " + signTime;
if (signTime.trim().length() <= 0) {
signDateTime = SystemEnv.getHtmlLabelName(25994, user.getLanguage());
}else{
if(Arrays.asList(xxrSerialId.split(",")).contains(serialId)){
//是休息班的班次,并且有打卡记录
checkXxr = true;
}
}
dataMap = new HashMap<>();
dataItemList = new ArrayList<Object>();
dataItemMap = new HashMap<String, Object>();
dataItemMap.put("title", SystemEnv.getHtmlLabelName(512504, user.getLanguage()));
dataItemMap.put("value", signDateTime);
dataItemList.add(dataItemMap);
dataItemMap = new HashMap<String, Object>();
dataItemMap.put("title", SystemEnv.getHtmlLabelName(20032, user.getLanguage()) + "IP");
dataItemMap.put("value", clientAddress);
dataItemList.add(dataItemMap);
dataItemMap = new HashMap<String, Object>();
dataItemMap.put("title", SystemEnv.getHtmlLabelName(125531, user.getLanguage()));
dataItemMap.put("value", addr);
dataItemList.add(dataItemMap);
dataMap.put("item", dataItemList);
dataMap.put("status", status);
dataMap.put("needWorkFlow", needWorkFlow);
dataList.add(dataMap);
//签到 end
} else {
//签退 start
String signDateTime = signDate + " " + signTime;
if (signTime.trim().length() <= 0) {
signDateTime = SystemEnv.getHtmlLabelName(25994, user.getLanguage());
}else{
if(Arrays.asList(xxrSerialId.split(",")).contains(serialId)){
//是休息班的班次,并且有打卡记录
checkXxr = true;
}
}
dataMap = new HashMap<>();
dataItemList = new ArrayList<Object>();
dataItemMap = new HashMap<String, Object>();
dataItemMap.put("title", SystemEnv.getHtmlLabelName(512505, user.getLanguage()));
dataItemMap.put("value", signDateTime);
dataItemList.add(dataItemMap);
dataItemMap = new HashMap<String, Object>();
dataItemMap.put("title", SystemEnv.getHtmlLabelName(20033, user.getLanguage()) + "IP");
dataItemMap.put("value", clientAddress);
dataItemList.add(dataItemMap);
dataItemMap = new HashMap<String, Object>();
dataItemMap.put("title", SystemEnv.getHtmlLabelName(132060, user.getLanguage()));
dataItemMap.put("value", addr);
dataItemList.add(dataItemMap);
dataMap.put("item", dataItemList);
dataMap.put("status", status);
dataMap.put("needWorkFlow", needWorkFlow);
dataList.add(dataMap);
//签退 end
}
}
if(Arrays.asList(xxrSerialId.split(",")).contains(serialId)){
//是休息班的班次
if(!checkXxr){
//不存在打卡记录
dataList = new ArrayList<>();
}
}
Map<String, Object> signDateMap = new HashMap<String, Object>();
signDateMap.put("date", date);
signDateMap.put("signInfo", dataList);
//班次时间
ShiftManagementToolKit shiftManagementToolKit = new ShiftManagementToolKit();
// String serialInfo = shiftManagementToolKit.getShiftOnOffWorkSections(serialId, user.getLanguage());
//移动端显示未到日期班次
String freeserial = "";
if ("".equals(serialId) && "true".equals(isMobile)){
try {
KQWorkTime kqWorkTime = new KQWorkTime();
WorkTimeEntity workTime = kqWorkTime.getWorkTime(resourceId, date);
serialId = workTime == null ? "" : Util.null2String(workTime.getSerialId());
if (Util.getIntValue(serialId,-1)>0){
signDateMap.put("isWork",1);
}
if("3".equals(workTime.getKQType())){
if(!"0".equals(Util.null2String(workTime.getWorkMins()))){
freeserial = SystemEnv.getHtmlLabelName(389129, user.getLanguage());
signDateMap.put("isWork",1);
}
}
}catch (Exception e){
new BaseBean().writeLog("========hb=======e:"+e);
}
}
//班次信息--加入自由班制的判断
String serialInfo = shiftManagementToolKit.getShiftOnOffWorkSections(serialId, user.getLanguage(),date,resourceId);
if (freeserial.length()>0){
serialInfo = freeserial;
}
signDateMap.put("serialInfo", SystemEnv.getHtmlLabelName(24803, user.getLanguage()) + "" + serialInfo);
resultMap.put("data", signDateMap);
new BaseBean().writeLog("GetHrmKQSignInfoCmd>>isMobile="+isMobile+";date="+date);
//只有移动端的【我的考勤】才需要显示流程相关的数据
if ("true".equals(isMobile)) {
//获取考勤流程的相关数据
List<Map<String, Object>> workflowList = new ArrayList<Map<String, Object>>();
//请假
workflowList = getFlowData(KqSplitFlowTypeEnum.LEAVE.getFlowtype());
if (workflowList == null) {
workflowList = new ArrayList<Map<String, Object>>();
}
//出差
workflowList.addAll(getFlowData(KqSplitFlowTypeEnum.EVECTION.getFlowtype()));
if (workflowList == null) {
workflowList = new ArrayList<Map<String, Object>>();
}
//公出
workflowList.addAll(getFlowData(KqSplitFlowTypeEnum.OUT.getFlowtype()));
if (workflowList == null) {
workflowList = new ArrayList<Map<String, Object>>();
}
//加班
workflowList.addAll(getFlowData(KqSplitFlowTypeEnum.OVERTIME.getFlowtype()));
resultMap.put("workflowInfo", workflowList);
}
} catch (Exception e) {
e.printStackTrace();
}
return resultMap;
}
public List<Map<String, Object>> getFlowData(int flowType) {
List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
try {
String resourceId = Util.null2String(params.get("resourceId"));
if ("".equals(resourceId)) {
resourceId = "" + user.getUID();
}
String date = Util.null2String(params.get("date"));
if ("".equals(date)) {
date = DateUtil.getCurrentDate();
}
String firstDateOfMonth = DateUtil.getFirstDayOfMonth(date);
String lastDateOfMonth = DateUtil.getLastDayOfMonth(date);
/**获取销假*/
List<String> leaveBackList = getLeaveDate();
Map<String, Object> dataMap = new HashMap<String, Object>();
Map<String, Object> workflowMap = new HashMap<String, Object>();
List<Map<String, Object>> workflowList = new ArrayList<Map<String, Object>>();
boolean showOnHoliday = true;//非工作日是否显示流程(出差、公出、请假)
KQExitRulesComInfo exitRulesComInfo = new KQExitRulesComInfo();
KQTravelRulesComInfo travelRulesComInfo = new KQTravelRulesComInfo();
KQLeaveRulesComInfo rulesComInfo = new KQLeaveRulesComInfo();
KQWorkTime kqWorkTime = new KQWorkTime();
if (flowType == 2) {
showOnHoliday = exitRulesComInfo.getComputingMode("1").equals("2");
} else if (flowType == 1) {
showOnHoliday = travelRulesComInfo.getComputingMode("1").equals("2");
}
Map<String, Object> paramsMap = new HashMap<String, Object>();
paramsMap.put("typeselect", "6");
paramsMap.put("tabKey", "1");
paramsMap.put("kqtype", "" + flowType);
paramsMap.put("resourceId", resourceId);
paramsMap.put("fromDate", firstDateOfMonth);
paramsMap.put("toDate", lastDateOfMonth);
paramsMap.put("isMyKQ", "1");
KQAttFlowSetBiz kqAttFlowSetBiz = new KQAttFlowSetBiz();
Map<String, String> sqlMap = kqAttFlowSetBiz.getFLowSql(paramsMap, user);
String sqlFrom = sqlMap.get("from");
String sqlWhere = sqlMap.get("where");
String sql = "select * " + sqlFrom + sqlWhere;
RecordSet recordSet = new RecordSet();
recordSet.executeQuery(sql);
while (recordSet.next()) {
String requestId = recordSet.getString("requestId");
double duration = Util.getDoubleValue(recordSet.getString("duration"), 0.00);
double backDuration = 0.00;
String requestName = recordSet.getString("requestName");
int durationRule = Util.getIntValue(recordSet.getString("durationrule"));
String unitName = "";
if (durationRule == 3 || durationRule == 5 || durationRule == 6) {
unitName = SystemEnv.getHtmlLabelName(389326, user.getLanguage());
} else {
unitName = SystemEnv.getHtmlLabelName(389325, user.getLanguage());
}
String fromDateTemp = recordSet.getString("fromDate");
String fromTimeTemp = recordSet.getString("fromTime");
String toDateTemp = recordSet.getString("toDate");
String toTimeTemp = recordSet.getString("toTime");
String leaveRulesId = "";
String period = SystemEnv.getHtmlLabelName(506047, user.getLanguage()) + ":" + String.format("%.2f", duration) + unitName;
if (flowType == 0) {
backDuration = Util.getDoubleValue(recordSet.getString("backDuraion"), 0.00);
if (backDuration > 0) {
period = SystemEnv.getHtmlLabelName(506047, user.getLanguage()) + ":" + String.format("%.2f", duration) + "(" + SystemEnv.getHtmlLabelName(24473, user.getLanguage()) + ":" + String.format("%.2f", backDuration) + ")" + unitName;
}
leaveRulesId = recordSet.getString("newleavetype");
showOnHoliday = rulesComInfo.getComputingMode(leaveRulesId).equals("2");
}
boolean isEnd = false;
for (String dateTemp = fromDateTemp; !isEnd; ) {
if (dateTemp.equals(toDateTemp)) {
isEnd = true;
}
if (!leaveBackList.contains(resourceId + "|" + date + "|" + requestId)) {
workflowList = (ArrayList<Map<String, Object>>) dataMap.get(resourceId + "|" + dateTemp);
if (null == workflowList) {
workflowList = new ArrayList<Map<String, Object>>();
}
workflowMap = new HashMap<String, Object>();
workflowMap.put("title", requestName);
workflowMap.put("period", period);
workflowMap.put("requestId", requestId);
workflowList.add(workflowMap);
boolean isWorkDay = kqWorkTime.isWorkDay(resourceId, date);
if (!(!isWorkDay && !showOnHoliday)) {
dataMap.put(resourceId + "|" + dateTemp, workflowList);
}
}
dateTemp = DateUtil.getDate(dateTemp, 1);
}
}
if (dataMap.get(resourceId + "|" + date) != null) {
resultList = (ArrayList<Map<String, Object>>) dataMap.get(resourceId + "|" + date);
}
} catch (Exception e) {
e.printStackTrace();
}
return resultList;
}
/**
*
*
* @return
*/
private List<String> getLeaveDate() {
List<String> resultList = new ArrayList<String>();
try {
String resourceId = Util.null2String(params.get("resourceId"));
if ("".equals(resourceId)) {
resourceId = "" + user.getUID();
}
String date = Util.null2String(params.get("date"));
if ("".equals(date)) {
date = DateUtil.getCurrentDate();
}
String firstDateOfMonth = DateUtil.getFirstDayOfMonth(date);
String lastDateOfMonth = DateUtil.getLastDayOfMonth(date);
String leaveBackTableName = KqSplitFlowTypeEnum.LEAVEBACK.getTablename();
String leaveTableName = KqSplitFlowTypeEnum.LEAVE.getTablename();
String sql = " select requestId,resourceId,belongDate,duration,durationRule," +
" (select sum(duration) from " + leaveBackTableName + " where " + leaveBackTableName + ".leavebackrequestid=" + leaveTableName + ".requestid " +
" and " + leaveBackTableName + ".newleavetype=" + leaveTableName + ".newleavetype " +
" and " + leaveBackTableName + ".belongdate=" + leaveTableName + ".belongDate ) as backDuration " +
" from " + leaveTableName + " where 1=1 ";
if (!resourceId.equals("")) {
sql += " and " + leaveTableName + ".resourceId=" + resourceId;
}
if (firstDateOfMonth.length() > 0 && lastDateOfMonth.length() > 0) {
sql += " and " + leaveTableName + ".belongdate between'" + firstDateOfMonth + "' and '" + lastDateOfMonth + "' ";
}
RecordSet recordSet = new RecordSet();
recordSet.executeQuery(sql);
while (recordSet.next()) {
String requestId = recordSet.getString("requestId");
String belongDate = recordSet.getString("belongDate");
double duration = Util.getDoubleValue(recordSet.getString("duration"), 0.00);
double backDuration = Util.getDoubleValue(recordSet.getString("backDuration"), 0.00);
if (backDuration >= duration) {
resultList.add(resourceId + "|" + belongDate + "|" + requestId);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return resultList;
}
}

@ -0,0 +1,941 @@
package com.engine.kq.cmd.report;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.kq.biz.*;
import com.engine.kq.util.ExcelUtil;
import com.engine.kq.util.KQDurationCalculatorUtil;
import com.engine.kq.util.UtilKQ;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.company.SubCompanyComInfo;
import weaver.hrm.job.JobTitlesComInfo;
import weaver.hrm.resource.ResourceComInfo;
import weaver.systeminfo.SystemEnv;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;
public class ExportExcelCmd extends AbstractCommonCommand<Map<String, Object>> {
private HttpServletRequest request;
private HttpServletResponse response;
private List<String> lsFieldDataKey;
public ExportExcelCmd(Map<String, Object> params, HttpServletRequest request, HttpServletResponse response, User user) {
this.user = user;
this.params = params;
this.request = request;
this.response = response;
this.lsFieldDataKey = new ArrayList<>();
}
@Override
public Map<String, Object> execute(CommandContext commandContext) {
Map<String, Object> retmap = new HashMap<String, Object>();
RecordSet rs = new RecordSet();
String sql = "";
try {
SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo();
DepartmentComInfo departmentComInfo = new DepartmentComInfo();
ResourceComInfo resourceComInfo = new ResourceComInfo();
JobTitlesComInfo jobTitlesComInfo = new JobTitlesComInfo();
KQLeaveRulesBiz kqLeaveRulesBiz = new KQLeaveRulesBiz();
KQReportBiz kqReportBiz = new KQReportBiz();
JSONObject jsonObj = JSON.parseObject(Util.null2String(params.get("data")));
String attendanceSerial = Util.null2String(jsonObj.get("attendanceSerial"));
String fromDate = Util.null2String(jsonObj.get("fromDate"));
String toDate = Util.null2String(jsonObj.get("toDate"));
String typeselect = Util.null2String(jsonObj.get("typeselect"));
if (typeselect.length() == 0) typeselect = "3";
if (!typeselect.equals("") && !typeselect.equals("0") && !typeselect.equals("6")) {
if (typeselect.equals("1")) {
fromDate = TimeUtil.getCurrentDateString();
toDate = TimeUtil.getCurrentDateString();
} else {
fromDate = TimeUtil.getDateByOption(typeselect, "0");
toDate = TimeUtil.getDateByOption(typeselect, "1");
}
}
//人员状态
String status = Util.null2String(jsonObj.get("status"));
String subCompanyId = Util.null2String(jsonObj.get("subCompanyId"));
String departmentId = Util.null2String(jsonObj.get("departmentId"));
String resourceId = Util.null2String(jsonObj.get("resourceId"));
String allLevel = Util.null2String(jsonObj.get("allLevel"));
String isNoAccount = Util.null2String(jsonObj.get("isNoAccount"));
String viewScope = Util.null2String(jsonObj.get("viewScope"));
List<String> showColumns = Util.splitString2List(Util.null2String(jsonObj.get("showColumns")), ",");
showColumns.add("lastname");
showColumns.removeIf(showColumn->showColumn.trim().equals(""));
List<String> tmpShowColumns = new ArrayList<>();
for(String showColumn:showColumns){
tmpShowColumns.add(showColumn);
String cascadekey = "";
if(showColumn.equals("beLate")){
cascadekey = "beLateMins";
}else if(showColumn.equals("leaveEearly")){
cascadekey = "leaveEarlyMins";
}else if(showColumn.equals("graveBeLate")){
cascadekey = "graveBeLateMins";
}else if(showColumn.equals("graveLeaveEarly")){
cascadekey = "graveLeaveEarlyMins";
}else if(showColumn.equals("absenteeism")){
cascadekey = "absenteeismMins";
}else if(showColumn.equals("overtime")){
tmpShowColumns.add("overtime_4leave");
tmpShowColumns.add("overtime_nonleave");
tmpShowColumns.add("workingDayOvertime_nonleave");
tmpShowColumns.add("workingDayOvertime_4leave");
tmpShowColumns.add("restDayOvertime_nonleave");
tmpShowColumns.add("restDayOvertime_4leave");
tmpShowColumns.add("holidayOvertime_4leave");
tmpShowColumns.add("holidayOvertime_nonleave");
}
if(cascadekey.length()>0){
tmpShowColumns.add(cascadekey);
}
}
showColumns = tmpShowColumns;
String rightSql = new KQReportBiz().getReportRight("1", "" + user.getUID(), "a");
LinkedHashMap<String, Object> workbook = new LinkedHashMap<>();
List<Object> lsSheet = new ArrayList<>();
Map<String, Object> sheet = null;
List<Object> titleList = new ArrayList<>();
Map<String, Object> title = null;
List<List<Object>> dataList = new ArrayList<>();
List<Object> data = null;
List<Map<String, Object>> constraintList = null;
sheet = new HashMap<>();
sheet.put("sheetName", SystemEnv.getHtmlLabelName(390351, user.getLanguage()));
sheet.put("sheetTitle", SystemEnv.getHtmlLabelName(390351, user.getLanguage()));
boolean isEnd = false;
Calendar cal = DateUtil.getCalendar();
List<Map<String, Object>> leaveRules = kqLeaveRulesBiz.getAllLeaveRules();
Map<String, Object> mapChildColumnInfo = null;
List<Object> childColumns = null;
KQReportFieldComInfo kqReportFieldComInfo = new KQReportFieldComInfo();
while (kqReportFieldComInfo.next()) {
if (Util.null2String(kqReportFieldComInfo.getParentid()).length() > 0) continue;
if(kqReportFieldComInfo.getFieldname().equals("kqCalendar"))continue;
if(KQReportFieldComInfo.cascadekey2fieldname.keySet().contains(kqReportFieldComInfo.getFieldname()))continue;
if (!kqReportFieldComInfo.getReportType().equals("all") && !kqReportFieldComInfo.getReportType().equals("month"))
continue;
if (!showColumns.contains(kqReportFieldComInfo.getFieldname())&&!showColumns.contains(kqReportFieldComInfo.getParentid())) continue;
if("leave".equalsIgnoreCase(kqReportFieldComInfo.getFieldname())&&leaveRules.size()==0){
continue;
}
title = new HashMap<>();
String unitType = KQReportBiz.getUnitType(kqReportFieldComInfo, user);
if(unitType.length()>0){
title.put("title", SystemEnv.getHtmlLabelNames(kqReportFieldComInfo.getFieldlabel(), user.getLanguage())+ "(" + unitType + ")");
}else{
title.put("title", SystemEnv.getHtmlLabelNames(kqReportFieldComInfo.getFieldlabel(), user.getLanguage()));
}
title.put("width", 30 * 256);
this.lsFieldDataKey.add(kqReportFieldComInfo.getFieldname());
mapChildColumnInfo = this.getChildColumnsInfo(kqReportFieldComInfo.getFieldname(), user);
childColumns = (List<Object>) mapChildColumnInfo.get("childColumns");
if (childColumns.size() > 0) {//跨列width取子列的width
title.put("children", childColumns);
title.put("colSpan", childColumns.size());
} else {
title.put("rowSpan", 3);
}
titleList.add(title);
titleList.addAll(this.getCascadeKeyColumnsInfo(kqReportFieldComInfo.getCascadekey(),user));
}
String today = DateUtil.getCurrentDate();
// if (DateUtil.compDate(today, toDate) > 0) {//结束如期不大于今天
// toDate = today;
// }
if(showColumns.contains("kqCalendar")) {
childColumns = new ArrayList<>();
for (String date = fromDate; !isEnd; ) {
if (date.equals(toDate)) isEnd = true;
title = new HashMap<>();
title.put("title", UtilKQ.getWeekDayShort(DateUtil.getWeek(date)-1,user.getLanguage()) +"\r\n"+ DateUtil.geDayOfMonth(date));
title.put("width", 30 * 256);
childColumns.add(title);
cal.setTime(DateUtil.parseToDate(date));
date = DateUtil.getDate(cal.getTime(), 1);
}
title = new HashMap();
title.put("title", SystemEnv.getHtmlLabelName(386476, user.getLanguage()));
if (childColumns.size() > 0) {//跨列width取子列的width
title.put("children", childColumns);
title.put("colSpan", childColumns.size());
}
titleList.add(title);
}
sheet.put("titleList", titleList);
String forgotBeginWorkCheck_field = " sum(b.forgotBeginWorkCheck) ";
if(rs.getDBType().equalsIgnoreCase("oracle")) {
forgotBeginWorkCheck_field = " sum(nvl(b.forgotBeginWorkCheck,0)) ";
}else if((rs.getDBType()).equalsIgnoreCase("mysql")){
forgotBeginWorkCheck_field = " sum(ifnull(b.forgotBeginWorkCheck,0)) ";
}else {
forgotBeginWorkCheck_field = " sum(isnull(b.forgotBeginWorkCheck,0)) ";
}
Map<String,Object> definedFieldInfo = new KQFormatBiz().getDefinedField();
String definedFieldSum = Util.null2String(definedFieldInfo.get("definedFieldSum"));
String backFields = "a.id,a.lastname,a.workcode,a.dsporder,b.resourceid,a.subcompanyid1 as subcompanyid,a.departmentid,a.jobtitle," +
" sum(b.workdays) as workdays,sum(b.workMins) as workMins,sum(b.attendancedays) as attendancedays," +
" sum(b.attendanceMins) as attendanceMins,sum(b.beLate) as beLate,sum(b.beLateMins) as beLateMins, " +
" sum(b.graveBeLate) as graveBeLate, sum(b.graveBeLateMins) as graveBeLateMins,sum(b.leaveEearly) as leaveEearly," +
" sum(b.leaveEarlyMins) as leaveEarlyMins, sum(b.graveLeaveEarly) as graveLeaveEarly, " +
" sum(b.graveLeaveEarlyMins) as graveLeaveEarlyMins,sum(b.absenteeism) as absenteeism, " +
" sum(b.signdays) as signdays,sum(b.signmins) as signmins, "+
" sum(b.absenteeismMins) as absenteeismMins, sum(b.forgotCheck)+"+forgotBeginWorkCheck_field+" as forgotCheck "+(definedFieldSum.length()>0?","+definedFieldSum+"":"");
if(rs.getDBType().equals("oracle")){
backFields = "/*+ index(kq_format_total IDX_KQ_FORMAT_TOTAL_KQDATE) */ "+backFields;
}
String sqlFrom = " from hrmresource a, kq_format_total b where a.id= b.resourceid and b.kqdate >='" + fromDate + "' and b.kqdate <='" + toDate + "'";
String sqlWhere = rightSql;
String groupBy = " group by a.id,a.lastname,a.workcode,a.dsporder,b.resourceid,a.subcompanyid1,a.departmentid,a.jobtitle ";
if (subCompanyId.length() > 0) {
sqlWhere += " and a.subcompanyid1 in(" + subCompanyId + ") ";
}
if (departmentId.length() > 0) {
sqlWhere += " and a.departmentid in(" + departmentId + ") ";
}
if (resourceId.length() > 0) {
sqlWhere += " and a.id in(" + resourceId + ") ";
}
if (viewScope.equals("4")) {//我的下属
if (allLevel.equals("1")) {//所有下属
sqlWhere += " and a.managerstr like '%," + user.getUID() + ",%'";
} else {
sqlWhere += " and a.managerid=" + user.getUID();//直接下属
}
}
if (!"1".equals(isNoAccount)) {
sqlWhere += " and a.loginid is not null " + (rs.getDBType().equals("oracle") ? "" : " and a.loginid<>'' ");
}
if(status.length()>0){
if (!status.equals("8") && !status.equals("9")) {
sqlWhere += " and a.status = "+status+ "";
}else if (status.equals("8")) {
sqlWhere += " and (a.status = 0 or a.status = 1 or a.status = 2 or a.status = 3) ";
}
}
String orderBy = " order by a.dsporder asc, a.lastname asc ";
String descOrderBy = " order by a.dsporder desc, a.lastname desc ";
sql = "select " + backFields + sqlFrom + sqlWhere + groupBy + orderBy;
//System.out.println("start" + DateUtil.getFullDate());
Map<String, Object> flowData = new KQReportBiz().getFlowData(params, user);
//System.out.println("end" + DateUtil.getFullDate());
// #1475814-概述:满足考勤报分部部门显示及导出时显示全路径
String fullPathMainKey = "show_full_path";
KQSettingsComInfo kqSettingsComInfo = new KQSettingsComInfo();
String isShowFullPath = Util.null2String(kqSettingsComInfo.getMain_val(fullPathMainKey),"0");
rs.execute(sql);
while (rs.next()) {
data = new ArrayList<>();
String id = rs.getString("id");
String deptid = rs.getString("departmentid");
for (int fieldDataKeyIdx =0;fieldDataKeyIdx<lsFieldDataKey.size();fieldDataKeyIdx++) {
String fieldName = lsFieldDataKey.get(fieldDataKeyIdx);
String fieldid = KQReportFieldComInfo.field2Id.get(fieldName);
String fieldValue = "";
if (fieldName.equals("subcompany")) {
String tmpSubcompanyId = Util.null2String(rs.getString("subcompanyid"));
if (tmpSubcompanyId.length() == 0) {
tmpSubcompanyId = Util.null2String(resourceComInfo.getSubCompanyID(id));
}
fieldValue = "1".equals(isShowFullPath) ?
SubCompanyComInfo.getSubcompanyRealPath(tmpSubcompanyId, "/", "0") :
subCompanyComInfo.getSubCompanyname(tmpSubcompanyId);
// fieldValue = subCompanyComInfo.getSubCompanyname(tmpSubcompanyId);
} else if (fieldName.equals("department")) {
String tmpDepartmentId = Util.null2String(rs.getString("departmentid"));
if (tmpDepartmentId.length() == 0) {
tmpDepartmentId = Util.null2String(resourceComInfo.getDepartmentID(id));
}
//fieldValue = "1".equals(isShowFullPath) ?
// departmentComInfo.getDepartmentRealPath(tmpDepartmentId, "/", "0") :
// departmentComInfo.getDepartmentname(tmpDepartmentId);
fieldValue = departmentComInfo.getDepartmentname(tmpDepartmentId);
} else if (fieldName.equals("jobtitle")) {
String tmpJobtitleId = Util.null2String(rs.getString("jobtitle"));
if (tmpJobtitleId.length() == 0) {
tmpJobtitleId = Util.null2String(resourceComInfo.getJobTitle(id));
}
fieldValue = jobTitlesComInfo.getJobTitlesname(tmpJobtitleId);
} else if (fieldName.equals("attendanceSerial")) {
List<String> serialIds = null;
if (Util.null2String(jsonObj.get("attendanceSerial")).length() > 0) {
serialIds = Util.splitString2List(Util.null2String(jsonObj.get("attendanceSerial")), ",");
for(int i=0;serialIds!=null&&i<serialIds.size();i++){
data.add(kqReportBiz.getSerialCount(id,fromDate,toDate,serialIds.get(i)));
}
}else{
data.add("");
}
continue;
} else if (fieldName.equals("leave")) {//请假
List<Map<String, Object>> allLeaveRules = kqLeaveRulesBiz.getAllLeaveRules();
Map<String, Object> leaveRule = null;
for (int i = 0; allLeaveRules != null && i < allLeaveRules.size(); i++) {
leaveRule = allLeaveRules.get(i);
String flowType = Util.null2String("leaveType_" + leaveRule.get("id"));
String leaveData = Util.null2String(flowData.get(id + "|" + flowType));
String flowLeaveBackType = Util.null2String("leavebackType_" + leaveRule.get("id"));
String leavebackData = Util.null2s(Util.null2String(flowData.get(id + "|" + flowLeaveBackType)), "0.0");
String b_flowLeaveData = "";
String flowLeaveData = "";
try {
//以防止出现精度问题
if (leaveData.length() == 0) {
leaveData = "0.0";
}
if (leavebackData.length() == 0) {
leavebackData = "0.0";
}
BigDecimal b_leaveData = new BigDecimal(leaveData);
BigDecimal b_leavebackData = new BigDecimal(leavebackData);
b_flowLeaveData = b_leaveData.subtract(b_leavebackData).toString();
if(Util.getDoubleValue(b_flowLeaveData, -1) < 0){
b_flowLeaveData = "0.0";
}
} catch (Exception e) {
writeLog("GetKQReportCmd:leaveData" + leaveData + ":leavebackData:" + leavebackData + ":" + e);
}
if (b_flowLeaveData.length() > 0) {
flowLeaveData = KQDurationCalculatorUtil.getDurationRound(b_flowLeaveData);
} else {
flowLeaveData = KQDurationCalculatorUtil.getDurationRound(Util.null2String(Util.getDoubleValue(leaveData, 0.0) - Util.getDoubleValue(leavebackData, 0.0)));
}
data.add(flowLeaveData);
}
continue;
}else if(fieldName.equals("overtime")){
fieldValue = KQDurationCalculatorUtil.getDurationRound(Util.null2String(flowData.get(id + "|workingDayOvertime_nonleave")));
data.add(getFieldValueByUnitType(fieldValue,kqReportFieldComInfo.getUnittype(KQReportFieldComInfo.field2Id.get("workingDayOvertime_nonleave"))));
fieldValue = KQDurationCalculatorUtil.getDurationRound(Util.null2String(flowData.get(id + "|restDayOvertime_nonleave")));
data.add(getFieldValueByUnitType(fieldValue,kqReportFieldComInfo.getUnittype(KQReportFieldComInfo.field2Id.get("restDayOvertime_nonleave"))));
fieldValue = KQDurationCalculatorUtil.getDurationRound(Util.null2String(flowData.get(id + "|holidayOvertime_nonleave")));
data.add(getFieldValueByUnitType(fieldValue,kqReportFieldComInfo.getUnittype(KQReportFieldComInfo.field2Id.get("holidayOvertime_nonleave"))));
fieldValue = KQDurationCalculatorUtil.getDurationRound(Util.null2String(flowData.get(id + "|workingDayOvertime_4leave")));
data.add(getFieldValueByUnitType(fieldValue,kqReportFieldComInfo.getUnittype(KQReportFieldComInfo.field2Id.get("workingDayOvertime_4leave"))));
fieldValue = KQDurationCalculatorUtil.getDurationRound(Util.null2String(flowData.get(id + "|restDayOvertime_4leave")));
data.add(getFieldValueByUnitType(fieldValue,kqReportFieldComInfo.getUnittype(KQReportFieldComInfo.field2Id.get("restDayOvertime_4leave"))));
fieldValue = KQDurationCalculatorUtil.getDurationRound(Util.null2String(flowData.get(id + "|holidayOvertime_4leave")));
data.add(getFieldValueByUnitType(fieldValue,kqReportFieldComInfo.getUnittype(KQReportFieldComInfo.field2Id.get("holidayOvertime_4leave"))));
double workingDayOvertime_4leave = Util.getDoubleValue(Util.null2String(flowData.get(id+"|workingDayOvertime_4leave")));
workingDayOvertime_4leave = workingDayOvertime_4leave<0?0:workingDayOvertime_4leave;
double restDayOvertime_4leave = Util.getDoubleValue(Util.null2String(flowData.get(id+"|restDayOvertime_4leave")));
restDayOvertime_4leave = restDayOvertime_4leave<0?0:restDayOvertime_4leave;
double holidayOvertime_4leave = Util.getDoubleValue(Util.null2String(flowData.get(id+"|holidayOvertime_4leave")));
holidayOvertime_4leave = holidayOvertime_4leave<0?0:holidayOvertime_4leave;
double workingDayOvertime_nonleave = Util.getDoubleValue(Util.null2String(flowData.get(id+"|workingDayOvertime_nonleave")));
workingDayOvertime_nonleave = workingDayOvertime_nonleave<0?0:workingDayOvertime_nonleave;
double restDayOvertime_nonleave = Util.getDoubleValue(Util.null2String(flowData.get(id+"|restDayOvertime_nonleave")));
restDayOvertime_nonleave = restDayOvertime_nonleave<0?0:restDayOvertime_nonleave;
double holidayOvertime_nonleave = Util.getDoubleValue(Util.null2String(flowData.get(id+"|holidayOvertime_nonleave")));
holidayOvertime_nonleave = holidayOvertime_nonleave<0?0:holidayOvertime_nonleave;
fieldValue = KQDurationCalculatorUtil.getDurationRound(String.valueOf(workingDayOvertime_4leave+restDayOvertime_4leave+holidayOvertime_4leave+
workingDayOvertime_nonleave+restDayOvertime_nonleave+holidayOvertime_nonleave));
String valueOverTimeTotal = getFieldValueByUnitType(fieldValue,kqReportFieldComInfo.getUnittype(KQReportFieldComInfo.field2Id.get("overtimeTotal")));
data.add(valueOverTimeTotal);
continue;
}else if(fieldName.equals("businessLeave") || fieldName.equals("officialBusiness")){
String businessLeaveData = Util.null2s(Util.null2String(flowData.get(id+"|"+fieldName)),"0.0");
String backType = fieldName+"_back";
String businessLeavebackData = Util.null2s(Util.null2String(flowData.get(id+"|"+backType)),"0.0");
String businessLeave = "";
try{
//以防止出现精度问题
if(businessLeaveData.length() == 0){
businessLeaveData = "0.0";
}
if(businessLeavebackData.length() == 0){
businessLeavebackData = "0.0";
}
BigDecimal b_businessLeaveData = new BigDecimal(businessLeaveData);
BigDecimal b_businessLeavebackData = new BigDecimal(businessLeavebackData);
businessLeave = b_businessLeaveData.subtract(b_businessLeavebackData).toString();
if(Util.getDoubleValue(businessLeave, -1) < 0){
businessLeave = "0.0";
}
}catch (Exception e){
}
fieldValue = KQDurationCalculatorUtil.getDurationRound(businessLeave);
} else if(Util.null2String(kqReportFieldComInfo.getCascadekey(fieldid)).length()>0){
fieldValue = Util.formatMultiLang(Util.null2String(rs.getString(fieldName)),""+user.getLanguage());
data.add(fieldValue);
List<String> lsCascadekey = Util.splitString2List(kqReportFieldComInfo.getCascadekey(fieldid),",");
for(int i=0;i<lsCascadekey.size();i++){
if(Util.null2String(rs.getString(lsCascadekey.get(i))).length()>0){
fieldid = KQReportFieldComInfo.field2Id.get(lsCascadekey.get(i));
fieldValue = getFieldValueByUnitType(rs.getString(lsCascadekey.get(i)),kqReportFieldComInfo.getUnittype(fieldid));
}else{
fieldValue = "0";
}
data.add(fieldValue);
}
continue;
} else if (fieldName.equals("jiabancishu")) {
// 计算加班次数(晚餐次数)
//fieldValue = StringUtil.isEmpty(Util.null2String(flowData.get(id + "|" + fieldName))) ? "0" : Util.null2String(flowData.get(id + "|" + fieldName));
fieldValue = getDinnerCount(id,fromDate,toDate)+"";
} else if (fieldName.equals("jiabancishuYb")) {
// 计算加班次数(晚餐次数)(含夜班)
//fieldValue = StringUtil.isEmpty(Util.null2String(flowData.get(id + "|" + fieldName))) ? "0" : Util.null2String(flowData.get(id + "|" + fieldName));
fieldValue = getDinnerCountOfNight(id,fromDate,toDate)+"";
} else if (fieldName.equals("yebancishu")) {
// 计算夜班次数
fieldValue = getYbcsNew(id,fromDate,toDate)+"";
}else if (fieldName.equals("wucancishu")) {
// 午餐次数
// fieldValue = StringUtil.isEmpty(Util.null2String(flowData.get(id + "|" + fieldName))) ? "0" : Util.null2String(flowData.get(id + "|" + fieldName));
fieldValue = getLanchCount(id,fromDate,toDate)+"";
} else if (fieldName.equals("wucancishuYb")) {
// 午餐次数(含夜班)
// fieldValue = StringUtil.isEmpty(Util.null2String(flowData.get(id + "|" + fieldName))) ? "0" : Util.null2String(flowData.get(id + "|" + fieldName));
fieldValue = getLanchCountOfNight(id,fromDate,toDate)+"";
} else if (fieldName.equals("deptcode")) {
fieldValue = departmentComInfo.getDepartmentCode(deptid);
} else if (fieldName.equals("supdept")) {
//fieldValue = departmentComInfo.getDepartmentRealPath(deptid, "/", "0",false) ;
fieldValue = departmentComInfo.getDepartmentname(departmentComInfo.getDepartmentsupdepid(deptid));
} else if (fieldName.equals("ofr08name")) {
fieldValue = getCusFieldData(id,"field36",-1);
fieldValue = getCusSelectName(36,fieldValue);
} else if (fieldName.equals("ofr07name")) {
fieldValue = getCusFieldData(id,"field35",-1);
fieldValue = getCusSelectName(35,fieldValue);
}else if (fieldName.equals("attendanceMins")) {
String attendanceMinsN = Util.formatMultiLang(Util.null2String(rs.getString("attendanceMins")),""+user.getLanguage());
attendanceMinsN = getFieldValueByUnitType(attendanceMinsN,kqReportFieldComInfo.getUnittype(fieldid));
fieldValue = attendanceMinsN;
attendanceMinsN = Util.formatMultiLang(fieldValue,""+user.getLanguage());
//二开,重新计算工作时长(包含加班)
double workingDayOvertime_4leave = Util.getDoubleValue(Util.null2String(flowData.get(id+"|workingDayOvertime_4leave")));
workingDayOvertime_4leave = workingDayOvertime_4leave<0?0:workingDayOvertime_4leave;
double restDayOvertime_4leave = Util.getDoubleValue(Util.null2String(flowData.get(id+"|restDayOvertime_4leave")));
restDayOvertime_4leave = restDayOvertime_4leave<0?0:restDayOvertime_4leave;
double holidayOvertime_4leave = Util.getDoubleValue(Util.null2String(flowData.get(id+"|holidayOvertime_4leave")));
holidayOvertime_4leave = holidayOvertime_4leave<0?0:holidayOvertime_4leave;
double workingDayOvertime_nonleave = Util.getDoubleValue(Util.null2String(flowData.get(id+"|workingDayOvertime_nonleave")));
workingDayOvertime_nonleave = workingDayOvertime_nonleave<0?0:workingDayOvertime_nonleave;
double restDayOvertime_nonleave = Util.getDoubleValue(Util.null2String(flowData.get(id+"|restDayOvertime_nonleave")));
restDayOvertime_nonleave = restDayOvertime_nonleave<0?0:restDayOvertime_nonleave;
double holidayOvertime_nonleave = Util.getDoubleValue(Util.null2String(flowData.get(id+"|holidayOvertime_nonleave")));
holidayOvertime_nonleave = holidayOvertime_nonleave<0?0:holidayOvertime_nonleave;
fieldValue = KQDurationCalculatorUtil.getDurationRound(String.valueOf(workingDayOvertime_4leave+restDayOvertime_4leave+holidayOvertime_4leave+
workingDayOvertime_nonleave+restDayOvertime_nonleave+holidayOvertime_nonleave));
String valueOverTimeTotal = getFieldValueByUnitType(fieldValue,kqReportFieldComInfo.getUnittype(KQReportFieldComInfo.field2Id.get("overtimeTotal")));
double attendanceMins = Util.getDoubleValue((String) attendanceMinsN,0)+Util.getDoubleValue((String) valueOverTimeTotal,0);
fieldValue = KQDurationCalculatorUtil.getDurationRound(attendanceMins+"");
} else {
fieldValue = Util.formatMultiLang(Util.null2String(rs.getString(fieldName)),""+user.getLanguage());
fieldValue = getFieldValueByUnitType(fieldValue,kqReportFieldComInfo.getUnittype(fieldid));
}
fieldValue = Util.formatMultiLang(fieldValue,""+user.getLanguage());
data.add(fieldValue);
}
//二开,重新计算工作时长(包含加班)
// double attendanceMins = Util.getDoubleValue((String) data.get(11),0)+Util.getDoubleValue((String) data.get(57),0);
// data.set(11,KQDurationCalculatorUtil.getDurationRound(attendanceMins+""));
// if(showColumns.contains("kqCalendar")) {
// Map<String, Object> detialDatas = kqReportBiz.getDetialDatasOnlyTime(id, fromDate, toDate, user);
// isEnd = false;
// for (String date = fromDate; !isEnd; ) {
// if (date.equals(toDate)) isEnd = true;
// if (DateUtil.compDate(today, date) > 0) {
// data.add("");
// } else {
// if (detialDatas.get(id + "|" + date) != null) {
// String atttimeNew = getTimesByDay(id,date);
// //从建模取数据
// double atttime = Double.valueOf(atttimeNew);
// data.add(atttime);
// } else {
// data.add(SystemEnv.getHtmlLabelName(26593, user.getLanguage()));
// }
// }
// cal.setTime(DateUtil.parseToDate(date));
// date = DateUtil.getDate(cal.getTime(), 1);
// }
// }
if(showColumns.contains("kqCalendar")) {
Map<String, Object> detialDatas = kqReportBiz.getDetialDatasOnlyTime(id, fromDate, toDate, user);
Map<String, Object> detialOvtimeDatas = kqReportBiz.getDetialOvtimeData(id, fromDate, toDate);
isEnd = false;
for (String date = fromDate; !isEnd; ) {
if (date.equals(toDate)) isEnd = true;
if (DateUtil.compDate(today, date) > 0) {
data.add("");
} else {
if (detialDatas.get(id + "|" + date) != null) {
double atttime = Util.getDoubleValue((String) detialDatas.get(id + "|" + date),0);
if(detialOvtimeDatas.get(id + "|" + date) !=null ){
atttime += (double) detialOvtimeDatas.get(id + "|" + date);
}
data.add(atttime);
} else {
data.add(SystemEnv.getHtmlLabelName(26593, user.getLanguage()));
}
}
cal.setTime(DateUtil.parseToDate(date));
date = DateUtil.getDate(cal.getTime(), 1);
}
}
dataList.add(data);
}
sheet.put("dataList", dataList);
sheet.put("constraintList", constraintList);
sheet.put("createFile", "1");
lsSheet.add(sheet);
workbook.put("sheet", lsSheet);
String fileName = SystemEnv.getHtmlLabelName(390351, user.getLanguage())+" "+fromDate+" "+toDate;
workbook.put("fileName", fileName);
ExcelUtil ExcelUtil = new ExcelUtil();
Map<String, Object> exportMap = ExcelUtil.export(workbook, request, response);
retmap.putAll(exportMap);
retmap.put("status", "1");
} catch (Exception e) {
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(382661, user.getLanguage()));
writeLog(e);
}
return retmap;
}
private Map<String, Object> getChildColumnsInfo(String parentid, User user) {
Map<String, Object> returnMap = new HashMap<>();
List<Object> titleList = new ArrayList<>();
Map<String, Object> title = null;
if (parentid.equals("attendanceSerial")) {//考勤班次
KQShiftManagementComInfo kqShiftManagementComInfo = new KQShiftManagementComInfo();
JSONObject jsonObj = JSON.parseObject(Util.null2String(params.get("data")));
List<String> serialIds = null;
if (Util.null2String(jsonObj.get("attendanceSerial")).length() > 0) {
serialIds = Util.splitString2List(Util.null2String(jsonObj.get("attendanceSerial")), ",");
}
for (int i = 0; serialIds != null && i < serialIds.size(); i++) {
title = new HashMap<>();
title.put("title", Util.formatMultiLang(kqShiftManagementComInfo.getSerial(serialIds.get(i)),""+user.getLanguage()));
title.put("width", 30 * 256);
titleList.add(title);
}
} else if (parentid.equals("leave")) {
KQLeaveRulesBiz kqLeaveRulesBiz = new KQLeaveRulesBiz();
List<Map<String, Object>> leaveRules = kqLeaveRulesBiz.getAllLeaveRules();
for (int i = 0; leaveRules != null && i < leaveRules.size(); i++) {
Map<String, Object> leaveRule = leaveRules.get(i);
String name = Util.formatMultiLang(Util.null2String(leaveRule.get("name")),""+user.getLanguage());
String unitType = Util.null2String(leaveRule.get("unitType"));
String unitName = (KQUnitBiz.isLeaveHour(unitType)) ? SystemEnv.getHtmlLabelName(391, user.getLanguage()) : SystemEnv.getHtmlLabelName(1925, user.getLanguage());
title = new HashMap<>();
title.put("title", name + "(" + unitName + ")");
title.put("width", 30 * 256);
titleList.add(title);
}
}else if(parentid.equals("overtime")){
String[] overtimeChild = {"overtime_nonleave","overtime_4leave","overtimeTotal"};
for(int i=0;i<overtimeChild.length;i++){
String id = overtimeChild[i];
title = new HashMap();
String fieldlabel = "";
if("overtime_nonleave".equalsIgnoreCase(id)){
fieldlabel = "125805";
title.put("title", SystemEnv.getHtmlLabelNames(fieldlabel, user.getLanguage()));
title.put("rowSpan","2");
}else if("overtime_4leave".equalsIgnoreCase(id)){
fieldlabel = "125804";
title.put("title", SystemEnv.getHtmlLabelNames(fieldlabel, user.getLanguage()));
title.put("rowSpan","2");
}else{
fieldlabel = "523";
title.put("showDetial","1");
String unitType = (KQOvertimeRulesBiz.getMinimumUnit()==3 || KQOvertimeRulesBiz.getMinimumUnit()==5 ||KQOvertimeRulesBiz.getMinimumUnit()==6)?"2":"1";
String unitTypeName = "";
if(Util.null2String(unitType).length()>0){
if(unitType.equals("1")){
unitTypeName=SystemEnv.getHtmlLabelName(1925, user.getLanguage());
}else if(unitType.equals("2")){
unitTypeName=SystemEnv.getHtmlLabelName(391, user.getLanguage());
}else if(unitType.equals("3")){
unitTypeName=SystemEnv.getHtmlLabelName(18083, user.getLanguage());
}
}
title.put("title", SystemEnv.getHtmlLabelNames(fieldlabel, user.getLanguage())+ "(" + unitTypeName + ")");
}
Map<String,Object> mapChildColumnInfo = getChildColumnsInfo(id, user);
int childWidth = 65;
List<Object> childColumns = (List<Object>)mapChildColumnInfo.get("childColumns");
if(childColumns.size()>0) {//跨列width取子列的width
title.put("children", childColumns);
childWidth = Util.getIntValue(Util.null2String(mapChildColumnInfo.get("sumChildColumnWidth")),65);
}
title.put("width", childWidth+"");
titleList.add(title);
}
} else {
KQReportFieldComInfo kqReportFieldComInfo = new KQReportFieldComInfo();
while (kqReportFieldComInfo.next()) {
if (kqReportFieldComInfo.getParentid().equals(parentid)) {
if(!kqReportFieldComInfo.getReportType().equals("month"))continue;
title = new HashMap<>();
title.put("title", SystemEnv.getHtmlLabelNames(kqReportFieldComInfo.getFieldlabel(), user.getLanguage()) + "(" + KQReportBiz.getUnitType(kqReportFieldComInfo, user) + ")");
title.put("width", 30 * 256);
titleList.add(title);
}
}
}
returnMap.put("childColumns", titleList);
return returnMap;
}
private List<Object> getCascadeKeyColumnsInfo(String cascadeKey, User user){
List<Object> titleList = new ArrayList<>();
Map<String, Object> title = null;
if(Util.null2String(cascadeKey).length()==0){
return titleList;
}
List<String> lsCascadeKey = Util.splitString2List(cascadeKey,",");
KQReportFieldComInfo kqReportFieldComInfo = new KQReportFieldComInfo();
for(int i=0;i<lsCascadeKey.size();i++){
kqReportFieldComInfo.setTofirstRow();
while (kqReportFieldComInfo.next()) {
if(!kqReportFieldComInfo.getReportType().equals("month"))continue;
if (kqReportFieldComInfo.getFieldname().equals(lsCascadeKey.get(i))){
title = new HashMap<>();
title.put("title", SystemEnv.getHtmlLabelNames(kqReportFieldComInfo.getFieldlabel(), user.getLanguage()) + "(" + KQReportBiz.getUnitType(kqReportFieldComInfo, user) + ")");
title.put("width", 30 * 256);
titleList.add(title);
}
}
}
return titleList;
}
private String getFieldValueByUnitType(String fieldValue,String unittype){
if (Util.null2String(unittype).length() > 0) {
if (fieldValue.length() == 0) {
fieldValue = "0";
} else {
if (unittype.equals("2")) {
fieldValue = KQDurationCalculatorUtil.getDurationRound(("" + (Util.getDoubleValue(fieldValue) / 60.0)));
}
}
}
return fieldValue;
}
/**
*
* @param id
* @param fieldname
* @param scopeid
* @return
*/
public String getCusFieldData(String id,String fieldname,int scopeid){
String fieldVal = "";
RecordSet rs = new RecordSet();
String sql = "select "+fieldname+" from cus_fielddata where id=? and scopeid=? and scope='HrmCustomFieldByInfoType' ";
rs.executeQuery(sql,id,scopeid);
if(rs.next()){
fieldVal = Util.null2String(rs.getString(fieldname));
}
return fieldVal;
}
/**
*
* @param fieldid
* @param selectvalue
* @return
*/
public String getCusSelectName(int fieldid,String selectvalue){
String selectname = "";
if(!"".equals(selectvalue)){
RecordSet rs = new RecordSet();
String sql = " select selectname from cus_selectitem where fieldid=? and selectvalue=? ";
rs.executeQuery(sql,fieldid,selectvalue);
if(rs.next()){
selectname = Util.null2String(rs.getString("selectname"));
}
}
return selectname;
}
/**
*
* @param resourceid
* @param fromDate
* @param toDate
* @return
*/
public int getYbcs(String resourceid,String fromDate,String toDate){
int ybcs = 0;
RecordSet rs = new RecordSet();
rs.executeQuery(" select field35 from cus_fielddata where id = ? ",resourceid);
rs.next();
int field35 = rs.getInt("field35");
//有加班流程且打卡时间在第二天0点-6点30之间才算夜班次数
String jbSql = "select count(1) ybcs from kq_flow_overtime where resourceid =? " +
" and belongdate>=? and belongdate<=? " +
" and totimedb>='00:00' and totimedb<='06:30'";
rs.executeQuery(jbSql,resourceid,fromDate,toDate);
if(rs.next()){
ybcs += Util.getIntValue(rs.getString("ybcs"),0);
}
//制造人员、劳务人员、实习生234需要加上正常的夜班和特殊夜班
if(field35==2 || field35==4 || field35==4){
String ybSql = " select count(1) ybcs from kq_format_detail " +
" where resourceid=? and serialid in(3,4) and attendanceMins>0 " +
" and kqdate>=? and kqdate<=? ";
rs.executeQuery(ybSql,resourceid,fromDate,toDate);
if(rs.next()){
ybcs += Util.getIntValue(rs.getString("ybcs"),0);
}
}
return ybcs;
}
/**
*
* @param resourceid
* @param fromDate
* @param toDate
* @return
*/
public int getLanchCount(String resourceid, String fromDate, String toDate){
int dinnerCount = 0;
RecordSet rs = new RecordSet();
String sql = "select sum(wuccs) as wuccsAll from uf_zdyzdgsh where xm = "+resourceid+" and rq>='"+fromDate+"' and rq<= '"+toDate+"'";
rs.executeQuery(sql);
if(rs.next()){
dinnerCount = Util.getIntValue(rs.getString("wuccsAll"),0);
}
return dinnerCount;
}
/**
* ()
* @param resourceid
* @param fromDate
* @param toDate
* @return
*/
public int getLanchCountOfNight(String resourceid,String fromDate,String toDate){
int dinnerCount = 0;
RecordSet rs = new RecordSet();
String sql = "select sum(wccshyb) as wccshybAll from uf_zdyzdgsh where xm = "+resourceid+" and rq>='"+fromDate+"' and rq<= '"+toDate+"'";
rs.executeQuery(sql);
if(rs.next()){
dinnerCount = Util.getIntValue(rs.getString("wccshybAll"),0);
}
return dinnerCount;
}
/**
*
* @param resourceid
* @param fromDate
* @param toDate
* @return
*/
public int getDinnerCount(String resourceid,String fromDate,String toDate){
int dinnerCount = 0;
RecordSet rs = new RecordSet();
String sql = "select sum(wccs) as jiabancishu from uf_zdyzdgsh where xm = "+resourceid+" and rq>='"+fromDate+"' and rq<= '"+toDate+"'";
rs.executeQuery(sql);
if(rs.next()){
dinnerCount = Util.getIntValue(rs.getString("jiabancishu"),0);
}
return dinnerCount;
}
/**
* ()
* @param resourceid
* @param fromDate
* @param toDate
* @return
*/
public int getDinnerCountOfNight(String resourceid,String fromDate,String toDate){
int dinnerCount = 0;
RecordSet rs = new RecordSet();
String sql = "select sum(waccshyb) as jiabancishuYb from uf_zdyzdgsh where xm = "+resourceid+" and rq>='"+fromDate+"' and rq<= '"+toDate+"'";
rs.executeQuery(sql);
if(rs.next()){
dinnerCount = Util.getIntValue(rs.getString("jiabancishuYb"),0);
}
return dinnerCount;
}
/**
* ()
* @param resourceid
* @param fromDate
* @param toDate
* @return
*/
public int getYbcsNew(String resourceid,String fromDate,String toDate){
int dinnerCount = 0;
RecordSet rs = new RecordSet();
String sql = "select sum(ybcs) as ybcsAll from uf_zdyzdgsh where xm = "+resourceid+" and rq>='"+fromDate+"' and rq<= '"+toDate+"'";
rs.executeQuery(sql);
if(rs.next()){
dinnerCount = Util.getIntValue(rs.getString("ybcsAll"),0);
}
return dinnerCount;
}
/**
*
* @param resourceid
* @param fromDate
* @param toDate
* @return
*/
public Map<String,Object> getNightShiftInfo(String resourceid,String fromDate,String toDate){
Map<String, Object> ybInfo = new HashMap<>();
RecordSet rs = new RecordSet();
//1.夜班、特殊夜班班次,判断在班次内是否有过零点的打卡记录 记1次2023-9-13下班卡最晚到次日9:00、当日有效出勤>=3.5H;
String ybSql = " select * from kq_format_detail " +
" where resourceid=? and kqdate>=? and kqdate<=? " +
" and serialid in(3,4) and attendanceMins/60>=3.5 and signouttime>='00:00:00' and signouttime<='12:00:00' ";
rs.executeQuery(ybSql,resourceid,fromDate,toDate);
while(rs.next()){
ybInfo.put(Util.null2String(rs.getString("kqdate")),1);
}
//2.白班班次加班情况白班不存在跨0点加班下班卡最晚到次日9:00且有效出勤>=3.5H记1次
// 休息日/法定节假日加班有效出勤时长>=3.5H非工作日跨0点加班必须提外出流程且下班卡过0点记1次
//0913修改不用考虑加班流程只看打卡时间和出勤时长
//String jbSql = " select a.*,b.signindate ,b.signintime ,b.signoutdate ,b.signouttime from kq_flow_overtime a " +
// " left join kq_format_detail b on a.resourceid=b.resourceid and a.belongdate =b.kqdate " +
// " where a.resourceid =? and a.belongdate >=? and a.belongdate <=? " +
// " and (b.signouttime >='00:00:00' and b.signouttime <='09:00:00') and (attendanceMins+duration_min)/60>=3.5 ";
//
String ybsql = " select a.* from kq_format_detail a " +
" left join kq_flow_overtime b on a.resourceid=b.resourceid and a.kqdate =b.belongdate " +
" where a.resourceid=? and kqdate>=? and kqdate<=? " +
" and signouttime >='00:00:00' and signouttime <='12:00:00' and (ifnull(attendanceMins,0)+ifnull(duration_min,0)) /60>=3.5 ";
rs.executeQuery(ybsql,resourceid,fromDate,toDate);
while(rs.next()){
ybInfo.put(Util.null2String(rs.getString("kqdate")),1);
}
return ybInfo;
}
/**
*
* @param userid
* @return
*/
public boolean timingStaff(String userid){
RecordSet rs = new RecordSet();
String sql = " select 1 from cus_fielddata where field112 in(1,2) and id=? ";
rs.executeQuery(sql,userid);
return rs.next();
}
/**
*
* @param userid
* @return
*/
public String getTimesByDay(String userid,String date){
RecordSet rs = new RecordSet();
String times = "";
String ny = date.substring(0,7);
String ts = date.substring(8,10);
String fieldDay = "h" + Integer.valueOf(ts);
String sql = "select "+fieldDay+" from uf_kqhzbx where xm = "+userid+" and ny = '"+ny+"'";
rs.executeQuery(sql);
if(rs.next()){
times = Util.null2String(rs.getString(fieldDay));
}
return times;
}
/**
*
* @param userid
* @return
*/
public boolean cleanStaff(String userid){
RecordSet rs = new RecordSet();
String sql = " select 1 from hrmroles a, hrmrolemembers b where a.rolesmark='保洁人员' and a.id=b.roleid and b.resourceid=? ";
rs.executeQuery(sql,userid);
return rs.next();
}
@Override
public BizLogContext getLogContext() {
return null;
}
}

@ -0,0 +1,906 @@
package com.engine.kq.cmd.report;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.kq.biz.*;
import com.engine.kq.util.KQDurationCalculatorUtil;
import com.engine.kq.util.PageUidFactory;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.company.SubCompanyComInfo;
import weaver.hrm.job.JobTitlesComInfo;
import weaver.hrm.resource.ResourceComInfo;
import weaver.systeminfo.SystemEnv;
import java.math.BigDecimal;
import java.util.*;
public class GetKQReportCmd extends AbstractCommonCommand<Map<String, Object>> {
public GetKQReportCmd(Map<String, Object> params, User user) {
this.user = user;
this.params = params;
}
@Override
public Map<String, Object> execute(CommandContext commandContext) {
Map<String,Object> retmap = new HashMap<String,Object>();
RecordSet rs = new RecordSet();
String sql = "";
try{
String pageUid = PageUidFactory.getHrmPageUid("KQReport");
SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo();
DepartmentComInfo departmentComInfo = new DepartmentComInfo();
ResourceComInfo resourceComInfo = new ResourceComInfo();
JobTitlesComInfo jobTitlesComInfo = new JobTitlesComInfo();
KQLeaveRulesBiz kqLeaveRulesBiz = new KQLeaveRulesBiz();
KQReportBiz kqReportBiz = new KQReportBiz();
JSONObject jsonObj = JSON.parseObject(Util.null2String(params.get("data")));
String attendanceSerial = Util.null2String(jsonObj.get("attendanceSerial"));
String fromDate = Util.null2String(jsonObj.get("fromDate"));
String toDate = Util.null2String(jsonObj.get("toDate"));
String typeselect =Util.null2String(jsonObj.get("typeselect"));
if(typeselect.length()==0)typeselect = "3";
if(!typeselect.equals("") && !typeselect.equals("0")&& !typeselect.equals("6")){
if(typeselect.equals("1")){
fromDate = TimeUtil.getCurrentDateString();
toDate = TimeUtil.getCurrentDateString();
}else{
fromDate = TimeUtil.getDateByOption(typeselect,"0");
toDate = TimeUtil.getDateByOption(typeselect,"1");
}
}
//人员状态
String status = Util.null2String(jsonObj.get("status"));
String subCompanyId = Util.null2String(jsonObj.get("subCompanyId"));
String departmentId = Util.null2String(jsonObj.get("departmentId"));
String resourceId = Util.null2String(jsonObj.get("resourceId"));
String allLevel = Util.null2String(jsonObj.get("allLevel"));
String isNoAccount = Util.null2String(jsonObj.get("isNoAccount"));
String viewScope = Util.null2String(jsonObj.get("viewScope"));
String isFromMyAttendance = Util.null2String(jsonObj.get("isFromMyAttendance"));//是否是来自我的考勤的请求,如果是,不加载考勤报表权限共享的限制,不然我的考勤会提示无权限
int pageIndex = Util.getIntValue(Util.null2String(jsonObj.get("pageIndex")), 1);
int pageSize = KQReportBiz.getPageSize(Util.null2String(jsonObj.get("pageSize")),pageUid,user.getUID());
int count = 0;
int pageCount = 0;
int isHavePre = 0;
int isHaveNext = 0;
String rightSql = kqReportBiz.getReportRight("1",""+user.getUID(),"a");
if(isFromMyAttendance.equals("1")){
rightSql = "";
}
List<Map<String, Object>> leaveRules = kqLeaveRulesBiz.getAllLeaveRules();
List<Object> columns = new ArrayList();
Map<String,Object> column = null;
List<Object> datas = new ArrayList();
Map<String,Object> data = null;
Map<String,Object> mapChildColumnInfo = null;
List<Object> childColumns = null;
KQReportFieldComInfo kqReportFieldComInfo = new KQReportFieldComInfo();
while (kqReportFieldComInfo.next()){
if(Util.null2String(kqReportFieldComInfo.getParentid()).length()>0)continue;
if(kqReportFieldComInfo.getFieldname().equals("kqCalendar"))continue;
if(KQReportFieldComInfo.cascadekey2fieldname.keySet().contains(kqReportFieldComInfo.getFieldname()))continue;
if(!kqReportFieldComInfo.getReportType().equals("all") && !kqReportFieldComInfo.getReportType().equals("month"))continue;
if("leave".equalsIgnoreCase(kqReportFieldComInfo.getFieldname())&&leaveRules.size()==0)continue;
column = new HashMap();
column.put("title", SystemEnv.getHtmlLabelNames(kqReportFieldComInfo.getFieldlabel(), user.getLanguage()));
column.put("unit", KQReportBiz.getUnitType(kqReportFieldComInfo, user));
column.put("dataIndex", kqReportFieldComInfo.getFieldname());
column.put("type", kqReportFieldComInfo.getFieldname());
column.put("key", kqReportFieldComInfo.getFieldname());
column.put("isSystem", kqReportFieldComInfo.getIsSystem());
mapChildColumnInfo = this.getChildColumnsInfo(kqReportFieldComInfo.getFieldname(),user);
childColumns = (List<Object>)mapChildColumnInfo.get("childColumns");
if(childColumns.size()>0) {//跨列width取子列的width
column.put("rowSpan", 1);
column.put("width", mapChildColumnInfo.get("sumChildColumnWidth"));
column.put("children", childColumns);
}else{
column.put("rowSpan", 3);
column.put("width", Util.getIntValue(kqReportFieldComInfo.getWidth()));
}
column.put("showDetial",kqReportFieldComInfo.getShowDetial());
columns.add(column);
columns.addAll(this.getCascadeKeyColumnsInfo(kqReportFieldComInfo.getCascadekey(),user));
}
boolean isEnd = false;
Calendar cal = DateUtil.getCalendar();
String today = DateUtil.getCurrentDate();
// if(DateUtil.compDate(today, toDate)>0){//结束日期不大于今天
// toDate = today;
// if(DateUtil.compDate(today, fromDate)>0){//结束日期不大于今天
// fromDate = today;
// }
// }
childColumns = new ArrayList<>();
for(String date=fromDate; !isEnd;) {
if(date.equals(toDate)) isEnd = true;
column = new HashMap();
column.put("title", DateUtil.geDayOfMonth(date));
column.put("dataIndex", date);
column.put("key", date);
column.put("type", date);
column.put("rowSpan", 1);
column.put("width", 65);
column.put("isCalendar", 1);
childColumns.add(column);
cal.setTime(DateUtil.parseToDate(date));
date = DateUtil.getDate(cal.getTime(), 1);
}
column = new HashMap();
column.put("title", SystemEnv.getHtmlLabelName(386476, user.getLanguage()));
column.put("dataIndex", "kqCalendar");
column.put("key", "kqCalendar");
if(childColumns.size()>0) {//跨列width取子列的width
column.put("rowSpan", 1);
column.put("width", childColumns.size()*65);
column.put("children", childColumns);
}
columns.add(column);
String forgotBeginWorkCheck_field = " sum(b.forgotBeginWorkCheck) ";
if(rs.getDBType().equalsIgnoreCase("oracle")) {
forgotBeginWorkCheck_field = " sum(nvl(b.forgotBeginWorkCheck,0)) ";
}else if((rs.getDBType()).equalsIgnoreCase("mysql")){
forgotBeginWorkCheck_field = " sum(ifnull(b.forgotBeginWorkCheck,0)) ";
}else {
forgotBeginWorkCheck_field = " sum(isnull(b.forgotBeginWorkCheck,0)) ";
}
Map<String,Object> definedFieldInfo = new KQFormatBiz().getDefinedField();
String definedFieldSum = Util.null2String(definedFieldInfo.get("definedFieldSum"));
String backFields = "a.id,a.lastname,a.workcode,a.dsporder,b.resourceid,a.subcompanyid1 as subcompanyid,a.departmentid,a.jobtitle," +
" sum(b.workdays) as workdays,sum(b.workMins) as workMins,sum(b.attendancedays) as attendancedays," +
" sum(b.attendanceMins) as attendanceMins,sum(b.beLate) as beLate,sum(b.beLateMins) as beLateMins, " +
" sum(b.graveBeLate) as graveBeLate, sum(b.graveBeLateMins) as graveBeLateMins,sum(b.leaveEearly) as leaveEearly," +
" sum(b.leaveEarlyMins) as leaveEarlyMins, sum(b.graveLeaveEarly) as graveLeaveEarly, " +
" sum(b.graveLeaveEarlyMins) as graveLeaveEarlyMins,sum(b.absenteeism) as absenteeism, " +
" sum(b.signdays) as signdays,sum(b.signmins) as signmins, "+
" sum(b.absenteeismMins) as absenteeismMins, sum(b.forgotCheck)+"+forgotBeginWorkCheck_field+" as forgotCheck "+(definedFieldSum.length()>0?","+definedFieldSum+"":"");
if(rs.getDBType().equals("oracle")){
backFields = "/*+ index(kq_format_total IDX_KQ_FORMAT_TOTAL_KQDATE) */ "+backFields;
}
String sqlFrom = " from hrmresource a, kq_format_total b where a.id= b.resourceid and b.kqdate >='"+fromDate+"' and b.kqdate <='"+toDate+"'";
String sqlWhere = rightSql;
String groupBy = " group by a.id,a.lastname,a.workcode,a.dsporder,b.resourceid,a.subcompanyid1,a.departmentid,a.jobtitle ";
if(subCompanyId.length()>0){
sqlWhere +=" and a.subcompanyid1 in("+subCompanyId+") ";
}
if(departmentId.length()>0){
sqlWhere +=" and a.departmentid in("+departmentId+") ";
}
if(resourceId.length()>0){
sqlWhere +=" and a.id in("+resourceId+") ";
}
if(viewScope.equals("4")){//我的下属
if(allLevel.equals("1")){//所有下属
sqlWhere+=" and a.managerstr like '%,"+user.getUID()+",%'";
}else{
sqlWhere+=" and a.managerid="+user.getUID();//直接下属
}
}
if (!"1".equals(isNoAccount)) {
sqlWhere += " and a.loginid is not null "+(rs.getDBType().equals("oracle")?"":" and a.loginid<>'' ");
}
if(status.length()>0){
if (!status.equals("8") && !status.equals("9")) {
sqlWhere += " and a.status = "+status+ "";
}else if (status.equals("8")) {
sqlWhere += " and (a.status = 0 or a.status = 1 or a.status = 2 or a.status = 3) ";
}
}
sql = " select count(*) as c from ( select 1 as c "+sqlFrom+sqlWhere+groupBy+") t";
rs.execute(sql);
if (rs.next()){
count = rs.getInt("c");
}
if (count <= 0) {
pageCount = 0;
}
pageCount = count / pageSize + ((count % pageSize > 0) ? 1 : 0);
isHaveNext = (pageIndex + 1 <= pageCount) ? 1 : 0;
isHavePre = (pageIndex - 1 >= 1) ? 1 : 0;
String orderBy = " order by t.dsporder asc, t.lastname asc ";
String descOrderBy = " order by t.dsporder desc, t.lastname desc ";
//默认排序设置 start有性能问题先取消后面再看看有没有好的方式
// String orderBySql = "select * from kq_report_order where userId=? and sort=1 order by orders";
// rs.executeQuery(orderBySql, user.getUID());
// if (rs.getCounts() <= 0) {
// orderBySql = "select * from kq_report_order where userId=0 and sort=1 order by orders";
// rs.executeQuery(orderBySql);
// }
// while (rs.next()) {
// String dataIndex = rs.getString("dataIndex");
// String ascOrDesc = rs.getString("ascOrDesc");
// String ascOrDesc1 = (ascOrDesc.equals("")||ascOrDesc.equals("asc"))?"desc":"asc";
// if (dataIndex.equals("organization")) {
// orderBy += ",showOrderOfDeptTree " + ascOrDesc + ",dept_id " + ascOrDesc;
// descOrderBy += ",showOrderOfDeptTree " + ascOrDesc1 + ",dept_id " + ascOrDesc1;
// }
// if (dataIndex.equalsIgnoreCase("dspOrder") || dataIndex.equalsIgnoreCase("lastName")) {
// orderBy += "," + dataIndex + " " + ascOrDesc + ",id " + ascOrDesc;
// descOrderBy += "," + dataIndex + " " + ascOrDesc1 + ",id " + ascOrDesc1;
// } else if (dataIndex.equalsIgnoreCase("deptShowOrder") || dataIndex.equalsIgnoreCase("deptName")) {
// orderBy += "," + dataIndex + " " + ascOrDesc + ",dept_id " + ascOrDesc;
// descOrderBy += "," + dataIndex + " " + ascOrDesc1 + ",dept_id " + ascOrDesc1;
// } else if (dataIndex.equalsIgnoreCase("subcomShowOrder") || dataIndex.equalsIgnoreCase("subcomName")) {
// orderBy += "," + dataIndex + " " + ascOrDesc + ",subcom_id " + ascOrDesc;
// descOrderBy += "," + dataIndex + " " + ascOrDesc1 + ",subcom_id " + ascOrDesc1;
// }
// }
// orderBy = orderBy.startsWith(",") ? orderBy.substring(1) : orderBy;
// descOrderBy = descOrderBy.startsWith(",") ? descOrderBy.substring(1) : descOrderBy;
// orderBy = orderBy.equals("") ? " t.dspOrder,t.id " : orderBy;
// descOrderBy = descOrderBy.equals("") ? " t.dspOrder,t.id " : descOrderBy;
// orderBy = "order by "+orderBy;
sql = backFields + sqlFrom + sqlWhere + groupBy;
if (pageIndex > 0 && pageSize > 0) {
if (rs.getDBType().equals("oracle")) {
sql = " select * from (select " + sql+") t "+orderBy;
sql = "select * from ( select row_.*, rownum rownum_ from ( " + sql + " ) row_ where rownum <= "
+ (pageIndex * pageSize) + ") where rownum_ > " + ((pageIndex - 1) * pageSize);
} else if (rs.getDBType().equals("mysql")) {
sql = " select * from (select " + sql+") t "+orderBy;
sql = "select t1.* from (" + sql + ") t1 limit " + ((pageIndex - 1) * pageSize) + "," + pageSize;
}
else if (rs.getDBType().equals("postgresql")) {
sql = " select * from (select " + sql+") t "+orderBy;
sql = "select t1.* from (" + sql + ") t1 limit " +pageSize + " offset " + ((pageIndex - 1) * pageSize);
}
else {
orderBy = " order by dsporder asc, lastname asc ";
descOrderBy = " order by dsporder desc, lastname desc ";
if (pageIndex > 1) {
int topSize = pageSize;
if (pageSize * pageIndex > count) {
topSize = count - (pageSize * (pageIndex - 1));
}
sql = " select top " + topSize + " * from ( select top " + topSize + " * from ( select top "
+ (pageIndex * pageSize) + sql + orderBy+ " ) tbltemp1 " + descOrderBy + ") tbltemp2 " + orderBy;
} else {
sql = " select top " + pageSize + sql+orderBy;
}
}
} else {
sql = " select " + sql;
}
// #1475814-概述:满足考勤报分部部门显示及导出时显示全路径
String fullPathMainKey = "show_full_path";
KQSettingsComInfo kqSettingsComInfo = new KQSettingsComInfo();
String isShowFullPath = Util.null2String(kqSettingsComInfo.getMain_val(fullPathMainKey),"0");
Map<String,Object> flowData = kqReportBiz.getFlowData(params,user);
rs.execute(sql);
while (rs.next()) {
data = new HashMap<>();
kqReportFieldComInfo.setTofirstRow();
String id = rs.getString("id");
String deptid = rs.getString("departmentid");
data.put("resourceId",id);
while (kqReportFieldComInfo.next()){
if(!Util.null2String(kqReportFieldComInfo.getIsdataColumn()).equals("1"))continue;
if(!kqReportFieldComInfo.getReportType().equals("all") && !kqReportFieldComInfo.getReportType().equals("month"))continue;
if("leave".equalsIgnoreCase(kqReportFieldComInfo.getFieldname())&&leaveRules.size()==0){
continue;
}
String fieldName = kqReportFieldComInfo.getFieldname();
String fieldValue = "";
if(fieldName.equals("subcompany")){
String tmpSubcompanyId = Util.null2String(rs.getString("subcompanyid"));
if(tmpSubcompanyId.length()==0){
tmpSubcompanyId = Util.null2String(resourceComInfo.getSubCompanyID(id));
}
data.put("subcompanyId",tmpSubcompanyId);
fieldValue = "1".equals(isShowFullPath) ?
SubCompanyComInfo.getSubcompanyRealPath(tmpSubcompanyId, "/", "0") :
subCompanyComInfo.getSubCompanyname(tmpSubcompanyId);
// fieldValue = subCompanyComInfo.getSubCompanyname(tmpSubcompanyId);
}else if(fieldName.equals("department")){
String tmpDepartmentId = Util.null2String(rs.getString("departmentid"));
if(tmpDepartmentId.length()==0){
tmpDepartmentId = Util.null2String(resourceComInfo.getDepartmentID(id));
}
data.put("departmentId",tmpDepartmentId);
//fieldValue = "1".equals(isShowFullPath) ?
// departmentComInfo.getDepartmentRealPath(tmpDepartmentId, "/", "0") :
// departmentComInfo.getDepartmentname(tmpDepartmentId);
fieldValue = departmentComInfo.getDepartmentname(tmpDepartmentId);
}else if(fieldName.equals("jobtitle")){
String tmpJobtitleId = Util.null2String(rs.getString("jobtitle"));
if(tmpJobtitleId.length()==0){
tmpJobtitleId = Util.null2String(resourceComInfo.getJobTitle(id));
}
data.put("jobtitleId",tmpJobtitleId);
fieldValue = jobTitlesComInfo.getJobTitlesname(tmpJobtitleId);
}else if(fieldName.equals("attendanceSerial")){
List<String> serialIds = null;
if(attendanceSerial.length()>0){
serialIds = Util.splitString2List(attendanceSerial,",");
}
for(int i=0;serialIds!=null&&i<serialIds.size();i++){
data.put(serialIds.get(i), kqReportBiz.getSerialCount(id,fromDate,toDate,serialIds.get(i)));
}
}else if(kqReportFieldComInfo.getParentid().equals("overtime")||kqReportFieldComInfo.getParentid().equals("overtime_nonleave")
||kqReportFieldComInfo.getParentid().equals("overtime_4leave")||fieldName.equals("businessLeave") || fieldName.equals("officialBusiness")){
if(fieldName.equals("overtimeTotal")){
double workingDayOvertime_4leave = Util.getDoubleValue(Util.null2String(flowData.get(id+"|workingDayOvertime_4leave")));
workingDayOvertime_4leave = workingDayOvertime_4leave<0?0:workingDayOvertime_4leave;
double restDayOvertime_4leave = Util.getDoubleValue(Util.null2String(flowData.get(id+"|restDayOvertime_4leave")));
restDayOvertime_4leave = restDayOvertime_4leave<0?0:restDayOvertime_4leave;
double holidayOvertime_4leave = Util.getDoubleValue(Util.null2String(flowData.get(id+"|holidayOvertime_4leave")));
holidayOvertime_4leave = holidayOvertime_4leave<0?0:holidayOvertime_4leave;
double workingDayOvertime_nonleave = Util.getDoubleValue(Util.null2String(flowData.get(id+"|workingDayOvertime_nonleave")));
workingDayOvertime_nonleave = workingDayOvertime_nonleave<0?0:workingDayOvertime_nonleave;
double restDayOvertime_nonleave = Util.getDoubleValue(Util.null2String(flowData.get(id+"|restDayOvertime_nonleave")));
restDayOvertime_nonleave = restDayOvertime_nonleave<0?0:restDayOvertime_nonleave;
double holidayOvertime_nonleave = Util.getDoubleValue(Util.null2String(flowData.get(id+"|holidayOvertime_nonleave")));
holidayOvertime_nonleave = holidayOvertime_nonleave<0?0:holidayOvertime_nonleave;
fieldValue = KQDurationCalculatorUtil.getDurationRound(String.valueOf(workingDayOvertime_4leave+restDayOvertime_4leave+holidayOvertime_4leave+
workingDayOvertime_nonleave+restDayOvertime_nonleave+holidayOvertime_nonleave));
}else if(fieldName.equals("businessLeave") || fieldName.equals("officialBusiness")){
String businessLeaveData = Util.null2s(Util.null2String(flowData.get(id+"|"+fieldName)),"0.0");
String backType = fieldName+"_back";
String businessLeavebackData = Util.null2s(Util.null2String(flowData.get(id+"|"+backType)),"0.0");
String businessLeave = "";
try{
//以防止出现精度问题
if(businessLeaveData.length() == 0){
businessLeaveData = "0.0";
}
if(businessLeavebackData.length() == 0){
businessLeavebackData = "0.0";
}
BigDecimal b_businessLeaveData = new BigDecimal(businessLeaveData);
BigDecimal b_businessLeavebackData = new BigDecimal(businessLeavebackData);
businessLeave = b_businessLeaveData.subtract(b_businessLeavebackData).toString();
if(Util.getDoubleValue(businessLeave, -1) < 0){
businessLeave = "0.0";
}
}catch (Exception e){
}
fieldValue = KQDurationCalculatorUtil.getDurationRound(businessLeave);
}else{
fieldValue = KQDurationCalculatorUtil.getDurationRound(Util.null2String(flowData.get(id+"|"+fieldName)));
}
}else if (fieldName.equals("jiabancishu")) {
// 计算加班次数(晚餐次数)
//fieldValue = StringUtil.isEmpty(Util.null2String(flowData.get(id + "|" + fieldName))) ? "0" : Util.null2String(flowData.get(id + "|" + fieldName));
fieldValue = getDinnerCount(id,fromDate,toDate)+"";
} else if (fieldName.equals("jiabancishuYb")) {
// 计算加班次数(晚餐次数)(含夜班)
//fieldValue = StringUtil.isEmpty(Util.null2String(flowData.get(id + "|" + fieldName))) ? "0" : Util.null2String(flowData.get(id + "|" + fieldName));
fieldValue = getDinnerCountOfNight(id,fromDate,toDate)+"";
} else if (fieldName.equals("yebancishu")) {
// 计算夜班次数
fieldValue = getYbcsNew(id,fromDate,toDate)+"";
}else if (fieldName.equals("wucancishu")) {
// 午餐次数
// fieldValue = StringUtil.isEmpty(Util.null2String(flowData.get(id + "|" + fieldName))) ? "0" : Util.null2String(flowData.get(id + "|" + fieldName));
fieldValue = getLanchCount(id,fromDate,toDate)+"";
} else if (fieldName.equals("wucancishuYb")) {
// 午餐次数(含夜班)
// fieldValue = StringUtil.isEmpty(Util.null2String(flowData.get(id + "|" + fieldName))) ? "0" : Util.null2String(flowData.get(id + "|" + fieldName));
fieldValue = getLanchCountOfNight(id,fromDate,toDate)+"";
}else if (fieldName.equals("deptcode")) {
fieldValue = departmentComInfo.getDepartmentCode(deptid);
} else if (fieldName.equals("supdept")) {
//fieldValue = departmentComInfo.getDepartmentRealPath(deptid, "/", "0",false) ;
fieldValue = departmentComInfo.getDepartmentname(departmentComInfo.getDepartmentsupdepid(deptid));
} else if (fieldName.equals("ofr08name")) {
fieldValue = getCusFieldData(id,"field36",-1);
fieldValue = getCusSelectName(36,fieldValue);
} else if (fieldName.equals("ofr07name")) {
fieldValue = getCusFieldData(id,"field35",-1);
fieldValue = getCusSelectName(35,fieldValue);
}else {
fieldValue = Util.null2String(rs.getString(fieldName));
if(Util.null2String(kqReportFieldComInfo.getUnittype()).length()>0) {
if(fieldValue.length() == 0){
fieldValue="0";
}else{
if (kqReportFieldComInfo.getUnittype().equals("2")) {
fieldValue = KQDurationCalculatorUtil.getDurationRound(("" + (Util.getDoubleValue(fieldValue) / 60.0)));
}
}
}
}
data.put(fieldName,fieldValue);
}
//请假
List<Map<String, Object>> allLeaveRules = kqLeaveRulesBiz.getAllLeaveRules();
Map<String, Object> leaveRule = null;
for(int i=0;allLeaveRules!=null&&i<allLeaveRules.size();i++){
leaveRule = (Map<String, Object>)allLeaveRules.get(i);
String flowType = Util.null2String("leaveType_"+leaveRule.get("id"));
String leaveData = Util.null2String(flowData.get(id+"|"+flowType));
String flowLeaveBackType = Util.null2String("leavebackType_"+leaveRule.get("id"));
String leavebackData = Util.null2s(Util.null2String(flowData.get(id+"|"+flowLeaveBackType)),"0.0");
String b_flowLeaveData = "";
String flowLeaveData = "";
try{
//以防止出现精度问题
if(leaveData.length() == 0){
leaveData = "0.0";
}
if(leavebackData.length() == 0){
leavebackData = "0.0";
}
BigDecimal b_leaveData = new BigDecimal(leaveData);
BigDecimal b_leavebackData = new BigDecimal(leavebackData);
b_flowLeaveData = b_leaveData.subtract(b_leavebackData).toString();
if(Util.getDoubleValue(b_flowLeaveData, -1) < 0){
b_flowLeaveData = "0.0";
}
}catch (Exception e){
writeLog("GetKQReportCmd:leaveData"+leaveData+":leavebackData:"+leavebackData+":"+e);
}
//考虑下冻结的数据
if(b_flowLeaveData.length() > 0){
flowLeaveData = KQDurationCalculatorUtil.getDurationRound(b_flowLeaveData);
}else{
flowLeaveData = KQDurationCalculatorUtil.getDurationRound(Util.null2String(Util.getDoubleValue(leaveData,0.0)-Util.getDoubleValue(leavebackData,0.0)));
}
data.put(flowType,flowLeaveData);
}
//二开,重新计算工作时长(包含加班)
double attendanceMins = Util.getDoubleValue((String) data.get("attendanceMins"),0)+Util.getDoubleValue((String) data.get("overtimeTotal"),0);
data.put("attendanceMins",KQDurationCalculatorUtil.getDurationRound(attendanceMins+""));
Map<String,Object> detialDatas = kqReportBiz.getDetialDatas(id,fromDate,toDate,user);
// new KQLog().info("id:"+id+":detialDatas:"+detialDatas);
isEnd = false;
for(String date=fromDate; !isEnd;) {
if(date.equals(toDate)) isEnd = true;
if(DateUtil.compDate(today, date)>0){
data.put(date,"");
}else{
// new KQLog().info("id:date:"+(id+"|"+date)+":detialDatas.get:"+detialDatas.get(id+"|"+date));
data.put(date,detialDatas.get(id+"|"+date)==null?SystemEnv.getHtmlLabelName(26593, user.getLanguage()):detialDatas.get(id+"|"+date));
}
cal.setTime(DateUtil.parseToDate(date));
date = DateUtil.getDate(cal.getTime(), 1);
}
datas.add(data);
}
List<Object> lsHolidays = KQHolidaySetBiz.getHolidaySetListByScope(""+user.getUID(),fromDate,toDate);
retmap.put("holidays", lsHolidays);
retmap.put("columns",columns);
retmap.put("datas",datas);
retmap.put("pagesize", pageSize);
retmap.put("pageindex", pageIndex);
retmap.put("count", count);
retmap.put("pagecount", pageCount);
retmap.put("ishavepre", isHavePre);
retmap.put("ishavenext", isHaveNext);
}catch (Exception e){
writeLog(e);
}
return retmap;
}
private Map<String,Object> getChildColumnsInfo(String parentid, User user){
Map<String,Object> returnMap = new HashMap<>();
List<Object> lsChildColumns = new ArrayList<>();
Map column = null;
int sumChildColumnWidth = 0;
if(parentid.equals("attendanceSerial")){//考勤班次
KQShiftManagementComInfo kqShiftManagementComInfo = new KQShiftManagementComInfo();
JSONObject jsonObj = JSON.parseObject(Util.null2String(params.get("data")));
List<String> serialIds = null;
if(Util.null2String(jsonObj.get("attendanceSerial")).length()>0){
serialIds = Util.splitString2List(Util.null2String(jsonObj.get("attendanceSerial")),",");
}
for(int i=0;serialIds!=null&&i<serialIds.size();i++){
column = new HashMap();
column.put("title", kqShiftManagementComInfo.getSerial(serialIds.get(i)));
column.put("unit", "");
column.put("width", 65);
column.put("dataIndex", serialIds.get(i));
column.put("key", serialIds.get(i));
column.put("rowSpan", 2);
column.put("colSpan", 1);
sumChildColumnWidth+=65;
lsChildColumns.add(column);
}
}else if(parentid.equals("leave")){
KQLeaveRulesBiz kqLeaveRulesBiz = new KQLeaveRulesBiz();
List<Map<String, Object>> leaveRules = kqLeaveRulesBiz.getAllLeaveRules();
for(int i=0;leaveRules!=null&&i<leaveRules.size();i++){
Map<String, Object> leaveRule = leaveRules.get(i);
String id = "leaveType_"+Util.null2String(leaveRule.get("id"));
String name = Util.null2String(leaveRule.get("name"));
String unitType = Util.null2String(leaveRule.get("unitType"));
column = new HashMap();
column.put("title", name);
column.put("unit", KQUnitBiz.isLeaveHour(unitType) ?SystemEnv.getHtmlLabelName(391, user.getLanguage()):SystemEnv.getHtmlLabelName(1925, user.getLanguage()));
column.put("width", 65);
column.put("dataIndex", id);
column.put("key", id);
column.put("rowSpan", 2);
column.put("colSpan", 1);
column.put("showDetial","1");
sumChildColumnWidth+=65;
lsChildColumns.add(column);
}
}else if(parentid.equals("overtime")){
String[] overtimeChild = {"overtime_nonleave","overtime_4leave","overtimeTotal"};
for(int i=0;i<overtimeChild.length;i++){
String id = overtimeChild[i];
column = new HashMap();
String fieldlabel = "";
column.put("unit", "");
if("overtime_nonleave".equalsIgnoreCase(id)){
fieldlabel = "125805";
}else if("overtime_4leave".equalsIgnoreCase(id)){
fieldlabel = "125804";
}else{
fieldlabel = "523";
column.put("showDetial","1");
String unitType = (KQOvertimeRulesBiz.getMinimumUnit()==3 || KQOvertimeRulesBiz.getMinimumUnit()==5 ||KQOvertimeRulesBiz.getMinimumUnit()==6)?"2":"1";
String unitTypeName = "";
if(Util.null2String(unitType).length()>0){
if(unitType.equals("1")){
unitTypeName=SystemEnv.getHtmlLabelName(1925, user.getLanguage());
}else if(unitType.equals("2")){
unitTypeName=SystemEnv.getHtmlLabelName(391, user.getLanguage());
}else if(unitType.equals("3")){
unitTypeName=SystemEnv.getHtmlLabelName(18083, user.getLanguage());
}
}
column.put("unit", unitTypeName);
}
column.put("title", SystemEnv.getHtmlLabelNames(fieldlabel, user.getLanguage()));
column.put("dataIndex", id);
column.put("key", id);
column.put("rowSpan", 1);
Map<String,Object> mapChildColumnInfo = getChildColumnsInfo(id, user);
int childWidth = 65;
List<Object> childColumns = (List<Object>)mapChildColumnInfo.get("childColumns");
if(childColumns.size()>0) {//跨列width取子列的width
column.put("children", childColumns);
childWidth = Util.getIntValue(Util.null2String(mapChildColumnInfo.get("sumChildColumnWidth")),65);
}
column.put("width", childWidth+"");
sumChildColumnWidth+=childWidth;
lsChildColumns.add(column);
}
}else{
KQReportFieldComInfo kqReportFieldComInfo = new KQReportFieldComInfo();
while (kqReportFieldComInfo.next()){
if(kqReportFieldComInfo.getParentid().equals(parentid)) {
if(!kqReportFieldComInfo.getReportType().equals("month"))continue;
column = new HashMap();
column.put("title", SystemEnv.getHtmlLabelNames(kqReportFieldComInfo.getFieldlabel(), user.getLanguage()));
column.put("unit", KQReportBiz.getUnitType(kqReportFieldComInfo, user));
column.put("width", Util.getIntValue(kqReportFieldComInfo.getWidth()));
column.put("dataIndex", kqReportFieldComInfo.getFieldname());
column.put("key", kqReportFieldComInfo.getFieldname());
column.put("rowSpan", 1);
column.put("colSpan", 1);
column.put("showDetial",kqReportFieldComInfo.getShowDetial());
sumChildColumnWidth+=Util.getIntValue(kqReportFieldComInfo.getWidth());
lsChildColumns.add(column);
}
}
}
returnMap.put("childColumns",lsChildColumns);
returnMap.put("sumChildColumnWidth",sumChildColumnWidth);
return returnMap;
}
private List<Object> getCascadeKeyColumnsInfo(String cascadeKey, User user){
List<Object> lsChildColumns = new ArrayList<>();
if(Util.null2String(cascadeKey).length()==0){
return lsChildColumns;
}
Map<String,Object> column = null;
List<String> lsCascadeKey = Util.splitString2List(cascadeKey,",");
KQReportFieldComInfo kqReportFieldComInfo = new KQReportFieldComInfo();
for(int i=0;i<lsCascadeKey.size();i++){
kqReportFieldComInfo.setTofirstRow();
while (kqReportFieldComInfo.next()) {
if(!kqReportFieldComInfo.getReportType().equals("month"))continue;
if (kqReportFieldComInfo.getFieldname().equals(lsCascadeKey.get(i))){
column = new HashMap();
column.put("title", SystemEnv.getHtmlLabelNames(kqReportFieldComInfo.getFieldlabel(), user.getLanguage()));
column.put("unit", KQReportBiz.getUnitType(kqReportFieldComInfo, user));
column.put("width", Util.getIntValue(kqReportFieldComInfo.getWidth()));
column.put("dataIndex", kqReportFieldComInfo.getFieldname());
column.put("key", kqReportFieldComInfo.getFieldname());
column.put("rowSpan", 1);
column.put("colSpan", 1);
column.put("showDetial",kqReportFieldComInfo.getShowDetial());
column.put("isSystem", kqReportFieldComInfo.getIsSystem());
lsChildColumns.add(column);
}
}
}
return lsChildColumns;
}
/**
*
* @param id
* @param fieldname
* @param scopeid
* @return
*/
public String getCusFieldData(String id,String fieldname,int scopeid){
String fieldVal = "";
RecordSet rs = new RecordSet();
String sql = "select "+fieldname+" from cus_fielddata where id=? and scopeid=? and scope='HrmCustomFieldByInfoType' ";
rs.executeQuery(sql,id,scopeid);
if(rs.next()){
fieldVal = Util.null2String(rs.getString(fieldname));
}
return fieldVal;
}
/**
*
* @param fieldid
* @param selectvalue
* @return
*/
public String getCusSelectName(int fieldid,String selectvalue){
String selectname = "";
if(!"".equals(selectvalue)){
RecordSet rs = new RecordSet();
String sql = " select selectname from cus_selectitem where fieldid=? and selectvalue=? ";
rs.executeQuery(sql,fieldid,selectvalue);
if(rs.next()){
selectname = Util.null2String(rs.getString("selectname"));
}
}
return selectname;
}
/**
*
* @param resourceid
* @param fromDate
* @param toDate
* @return
*/
public int getYbcs(String resourceid,String fromDate,String toDate){
int ybcs = 0;
RecordSet rs = new RecordSet();
//有加班流程且打卡时间在第二天0点-6点30之间才算夜班次数
String jbSql = "select count(1) ybcs from kq_flow_overtime where resourceid =? " +
" and belongdate>=? and belongdate<=? " +
" and totimedb>='00:00' and totimedb<='06:30'";
rs.executeQuery(jbSql,resourceid,fromDate,toDate);
if(rs.next()){
ybcs += Util.getIntValue(rs.getString("ybcs"),0);
}
String ybSql = " select count(1) ybcs from kq_format_detail " +
" where resourceid=? and serialid in(3,4) and attendanceMins>0 " +
" and kqdate>=? and kqdate<=? ";
rs.executeQuery(ybSql,resourceid,fromDate,toDate);
if(rs.next()){
ybcs += Util.getIntValue(rs.getString("ybcs"),0);
}
return ybcs;
}
/**
*
* @param resourceid
* @param fromDate
* @param toDate
* @return
*/
public int getLanchCount(String resourceid, String fromDate, String toDate){
int dinnerCount = 0;
RecordSet rs = new RecordSet();
String sql = "select sum(wuccs) as wuccsAll from uf_zdyzdgsh where xm = "+resourceid+" and rq>='"+fromDate+"' and rq<= '"+toDate+"'";
rs.executeQuery(sql);
if(rs.next()){
dinnerCount = Util.getIntValue(rs.getString("wuccsAll"),0);
}
return dinnerCount;
}
/**
* ()
* @param resourceid
* @param fromDate
* @param toDate
* @return
*/
public int getLanchCountOfNight(String resourceid,String fromDate,String toDate){
int dinnerCount = 0;
RecordSet rs = new RecordSet();
String sql = "select sum(wccshyb) as wccshybAll from uf_zdyzdgsh where xm = "+resourceid+" and rq>='"+fromDate+"' and rq<= '"+toDate+"'";
rs.executeQuery(sql);
if(rs.next()){
dinnerCount = Util.getIntValue(rs.getString("wccshybAll"),0);
}
return dinnerCount;
}
/**
*
* @param resourceid
* @param fromDate
* @param toDate
* @return
*/
public int getDinnerCount(String resourceid,String fromDate,String toDate){
int dinnerCount = 0;
RecordSet rs = new RecordSet();
String sql = "select sum(wccs) as jiabancishu from uf_zdyzdgsh where xm = "+resourceid+" and rq>='"+fromDate+"' and rq<= '"+toDate+"'";
rs.executeQuery(sql);
if(rs.next()){
dinnerCount = Util.getIntValue(rs.getString("jiabancishu"),0);
}
return dinnerCount;
}
/**
* ()
* @param resourceid
* @param fromDate
* @param toDate
* @return
*/
public int getDinnerCountOfNight(String resourceid,String fromDate,String toDate){
int dinnerCount = 0;
RecordSet rs = new RecordSet();
String sql = "select sum(waccshyb) as jiabancishuYb from uf_zdyzdgsh where xm = "+resourceid+" and rq>='"+fromDate+"' and rq<= '"+toDate+"'";
rs.executeQuery(sql);
if(rs.next()){
dinnerCount = Util.getIntValue(rs.getString("jiabancishuYb"),0);
}
return dinnerCount;
}
/**
* ()
* @param resourceid
* @param fromDate
* @param toDate
* @return
*/
public int getYbcsNew(String resourceid,String fromDate,String toDate){
int dinnerCount = 0;
RecordSet rs = new RecordSet();
String sql = "select sum(ybcs) as ybcsAll from uf_zdyzdgsh where xm = "+resourceid+" and rq>='"+fromDate+"' and rq<= '"+toDate+"'";
rs.executeQuery(sql);
if(rs.next()){
dinnerCount = Util.getIntValue(rs.getString("ybcsAll"),0);
}
return dinnerCount;
}
/**
*
* @param resourceid
* @param fromDate
* @param toDate
* @return
*/
public Map<String,Object> getNightShiftInfo(String resourceid,String fromDate,String toDate){
Map<String, Object> ybInfo = new HashMap<>();
RecordSet rs = new RecordSet();
//1.夜班、特殊夜班班次,判断在班次内是否有过零点的打卡记录 记1次2023-9-13下班卡最晚到次日9:00、当日有效出勤>=3.5H;
String ybSql = " select * from kq_format_detail " +
" where resourceid=? and kqdate>=? and kqdate<=? " +
" and serialid in(3,4) and attendanceMins/60>=3.5 and signouttime>='00:00:00' and signouttime<='12:00:00' ";
rs.executeQuery(ybSql,resourceid,fromDate,toDate);
while(rs.next()){
ybInfo.put(Util.null2String(rs.getString("kqdate")),1);
}
//2.白班班次加班情况白班不存在跨0点加班下班卡最晚到次日9:00且有效出勤>=3.5H记1次
// 休息日/法定节假日加班有效出勤时长>=3.5H非工作日跨0点加班必须提外出流程且下班卡过0点记1次
//0913修改不用考虑加班流程只看打卡时间和出勤时长
//String jbSql = " select a.*,b.signindate ,b.signintime ,b.signoutdate ,b.signouttime from kq_flow_overtime a " +
// " left join kq_format_detail b on a.resourceid=b.resourceid and a.belongdate =b.kqdate " +
// " where a.resourceid =? and a.belongdate >=? and a.belongdate <=? " +
// " and (b.signouttime >='00:00:00' and b.signouttime <='09:00:00') and (attendanceMins+duration_min)/60>=3.5 ";
//
String jbsql = " select a.* from kq_format_detail a " +
" left join kq_flow_overtime b on a.resourceid=b.resourceid and a.kqdate =b.belongdate " +
" where a.resourceid=? and kqdate>=? and kqdate<=? " +
" and signouttime >='00:00:00' and signouttime <='12:00:00' and (ifnull(attendanceMins,0)+ifnull(duration_min,0)) /60>=3.5 ";
rs.executeQuery(jbsql,resourceid,fromDate,toDate);
while(rs.next()){
ybInfo.put(Util.null2String(rs.getString("kqdate")),1);
}
return ybInfo;
}
/**
*
* @param userid
* @return
*/
public boolean timingStaff(String userid){
RecordSet rs = new RecordSet();
String sql = " select 1 from cus_fielddata where field112 in(1,2) and id=? ";
rs.executeQuery(sql,userid);
return rs.next();
}
/**
*
* @param userid
* @return
*/
public boolean cleanStaff(String userid){
RecordSet rs = new RecordSet();
String sql = " select 1 from hrmroles a, hrmrolemembers b where a.rolesmark='保洁人员' and a.id=b.roleid and b.resourceid=? ";
rs.executeQuery(sql,userid);
return rs.next();
}
@Override
public BizLogContext getLogContext() {
return null;
}
}

@ -0,0 +1,424 @@
package com.engine.kq.cmd.shiftmanagement;
import com.api.browser.bean.SearchConditionItem;
import com.api.browser.bean.SearchConditionOption;
import com.api.hrm.bean.HrmFieldBean;
import com.api.hrm.util.HrmFieldSearchConditionComInfo;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.hrm.company.SubCompanyComInfo;
import weaver.hrm.moduledetach.ManageDetachComInfo;
import weaver.systeminfo.SystemEnv;
import weaver.systeminfo.systemright.CheckSubCompanyRight;
/**
*
* @author pzy
*
*/
public class GetShiftManagementBaseFormCmd extends AbstractCommonCommand<Map<String, Object>>{
public GetShiftManagementBaseFormCmd(Map<String, Object> params, User user) {
this.user = user;
this.params = params;
}
@Override
public BizLogContext getLogContext() {
// TODO Auto-generated method stub
return null;
}
@Override
public Map<String, Object> execute(CommandContext commandContext) {
Map<String, Object> retmap = new HashMap<String, Object>();
List<Map<String, Object>> grouplist = new ArrayList<Map<String, Object>>();
Map<String, Object> groupitem = null;
List<Object> 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<Object> workSectionList = new ArrayList<>();
Map<String,Object> groupSectionMaps = new HashMap<>();//分组用的map
Map<String,Object> sectionMaps = new HashMap<>();
Map<String,Object> sectionMap = new HashMap<>();
//现在休息时段还是只能设置一个的对于以后可能出现的多个休息时段预留这个map
List<Object> restSectionsList = new ArrayList<>();
Map<String,Object> restSectionsMap = new HashMap<>();
String[] fields = new String[]{"serial,125818,1,1","subcompanyid,141,3,169","shiftonoffworkcount,388563,5,3","punchsettings,388564,4,1",
"rest_shift,536771,4,2",
"isresttimeopen,388565,4,2","restbeigin,388566,3,19","restend,388567,3,19","halfcalrule,513090,5,1","cardRemind,507833,4,2","cardRemOfSignIn,507835,5,1",
"minsBeforeSignIn,510106,1,2","cardRemOfSignOut,507837,5,1","minsAfterSignOut,510108,1,2","remindMode,501471,5,3","remindOnPC,513233,4,2",
"isoffdutyfreecheck,388568,4,2","halfcalpoint,513145,3,19","halfcalpoint2cross,513090,5,1"};
Map<String,String> shiftValMap = new HashMap<>();
if(_id.length() > 0){
String getShiftInfo = "select * from kq_ShiftManagement where (isdelete is null or isdelete <> '1') and id = ?";
rs.executeQuery(getShiftInfo, _id);
if(rs.next()){
for(int i = 0 ; i < fields.length ; i++){
String[] tmpField = Util.null2String(fields[i]).split(",");
String fieldname = tmpField[0];
String fieldvalue = rs.getString(fieldname);
if("shiftonoffworkcount".equalsIgnoreCase(fieldname) ||
"punchsettings".equalsIgnoreCase(fieldname) ||
"cardRemOfSignIn".equalsIgnoreCase(fieldname) ||
"cardRemOfSignOut".equalsIgnoreCase(fieldname) ||
"remindMode".equalsIgnoreCase(fieldname)){
fieldvalue = Util.null2s(fieldvalue, "1");
}else if("isresttimeopen".equalsIgnoreCase(fieldname) ||
"halfcalrule".equalsIgnoreCase(fieldname) ||
"cardRemind".equalsIgnoreCase(fieldname) ||
"minsAfterSignOut".equalsIgnoreCase(fieldname) ||
"remindOnPC".equalsIgnoreCase(fieldname) ||
"isoffdutyfreecheck".equalsIgnoreCase(fieldname) ||
"halfcalpoint".equalsIgnoreCase(fieldname) ||
"halfcalpoint2cross".equalsIgnoreCase(fieldname)||
"rest_shift".equalsIgnoreCase(fieldname)){
fieldvalue = Util.null2s(fieldvalue, "0");
}else if("minsBeforeSignIn".equalsIgnoreCase(fieldname)){
fieldvalue = Util.null2s(fieldvalue, "10");
}else if("subcompanyid".equalsIgnoreCase(fieldname)){
subcompanyid = fieldvalue;
}
shiftValMap.put(fieldname, fieldvalue);
}
}
String getWorkSections = "select * from kq_ShiftOnOffWorkSections where (isdelete is null or isdelete <> '1') and serialid = ? order by record ";
rs.executeQuery(getWorkSections, _id);
while(rs.next()){
String record = rs.getString("record");
if(record.length() == 0) {
continue;
}
String onoffworktype = Util.null2String(rs.getString("onoffworktype"));
String across = Util.null2String(rs.getString("across"));
String times = Util.null2String(rs.getString("times"));
String mins = Util.null2String(rs.getString("mins"));
String mins_next = Util.null2String(rs.getString("mins_next"));
sectionMap = new HashMap<>();
sectionMaps = new HashMap<>();
sectionMap.put("across", across);
sectionMap.put("times", times);
sectionMap.put("mins", mins);
sectionMap.put("mins_next", mins_next);
sectionMaps.put(onoffworktype, sectionMap);
if(groupSectionMaps.get(record) != null){
List<Object> tmpSections = (List<Object>) groupSectionMaps.get(record);
((Map<String,Object>)tmpSections.get(tmpSections.size()-1)).putAll(sectionMaps);
}else{
sectionMaps.put("record", record);
workSectionList.add(sectionMaps);
groupSectionMaps.put(record, workSectionList);
}
}
String getRestSections = "select * from kq_ShiftRestTimeSections where (isdelete is null or isdelete <> '1') and serialid = ? ";
rs.executeQuery(getRestSections, _id);
while(rs.next()){
String resttype = Util.null2String(rs.getString("resttype"));
String across = Util.null2String(rs.getString("across"));
String times = Util.null2String(rs.getString("time"));
restSectionsMap = new HashMap<>();
restSectionsMap.put("resttype", resttype);
restSectionsMap.put("time", times);
restSectionsMap.put("across", across);
restSectionsList.add(restSectionsMap);
if("start".equalsIgnoreCase(resttype)){
shiftValMap.put("restbeigin", times);
}else if("end".equalsIgnoreCase(resttype)){
shiftValMap.put("restend", times);
}
}
isEdit = true;
}
//班次名称 所属机构(开启分权有所属机构) 一天内上下班次数 打卡时段是否开启 排除休息时间是否开启 休息开始时间 休息结束时间 允许下班不打卡
HrmFieldBean hrmFieldBean = null;
HrmFieldSearchConditionComInfo hrmFieldSearchConditionComInfo = new HrmFieldSearchConditionComInfo();
SearchConditionItem searchConditionItem = null;
List<SearchConditionOption> options = new ArrayList<SearchConditionOption>();
groupitem = new HashMap<String, Object>();
itemlist = new ArrayList<Object>();
for (int j = 0; j < fields.length; j++) {
options = new ArrayList<SearchConditionOption>();
String[] tmpField = Util.null2String(fields[j]).split(",");
String fieldname = tmpField[0];
String beanVal = Util.null2String(shiftValMap.get(fieldname));
hrmFieldBean = new HrmFieldBean();
hrmFieldBean.setFieldname(fieldname);
hrmFieldBean.setFieldlabel(tmpField[1]);
hrmFieldBean.setFieldhtmltype(tmpField[2]);
hrmFieldBean.setType(tmpField[3]);
hrmFieldBean.setIsFormField(true);
if("serial".equalsIgnoreCase(tmpField[0]) || "restbeigin".equalsIgnoreCase(tmpField[0]) || "restend".equalsIgnoreCase(tmpField[0])){
hrmFieldBean.setViewAttr(3);
hrmFieldBean.setRules("required|string");
}
if("shiftonoffworkcount".equalsIgnoreCase(tmpField[0]) || "restbeigin".equalsIgnoreCase(tmpField[0]) || "restend".equalsIgnoreCase(tmpField[0])){
hrmFieldBean.setRules("required|string");
if(!isEdit){
if("restbeigin".equalsIgnoreCase(tmpField[0])){
hrmFieldBean.setFieldvalue("12:00");
}
if("restend".equalsIgnoreCase(tmpField[0])){
hrmFieldBean.setFieldvalue("13:00");
}
}
}
// if("color".equalsIgnoreCase(tmpField[0])){
// hrmFieldBean.setTip(SystemEnv.getHtmlLabelName(389509, user.getLanguage()));
// }
if(!isEdit){
if("isresttimeopen".equalsIgnoreCase(tmpField[0])){
hrmFieldBean.setFieldvalue("0");
}
if("isoffdutyfreecheck".equalsIgnoreCase(tmpField[0])){
hrmFieldBean.setFieldvalue("0");
}
if("punchsettings".equalsIgnoreCase(tmpField[0])){
hrmFieldBean.setFieldvalue("1");
}
// if("color".equalsIgnoreCase(tmpField[0])){
// hrmFieldBean.setFieldvalue("#000");
// }
if("cardRemOfSignIn".equals(hrmFieldBean.getFieldname())){
beanVal = "1";
}
if("minsBeforeSignIn".equals(hrmFieldBean.getFieldname())){
beanVal = "10";
}
if("cardRemOfSignOut".equals(hrmFieldBean.getFieldname())){
beanVal = "1";
}
if("minsAfterSignOut".equals(hrmFieldBean.getFieldname())){
beanVal = "0";
}
if("remindMode".equals(hrmFieldBean.getFieldname())){
beanVal = "1";
}
if("halfcalrule".equals(hrmFieldBean.getFieldname())){
hrmFieldBean.setFieldvalue("0");
}
if("halfcalpoint2cross".equals(hrmFieldBean.getFieldname())){
hrmFieldBean.setFieldvalue("0");
}
if("rest_shift".equals(hrmFieldBean.getFieldname())){
hrmFieldBean.setFieldvalue("0");
}
}
if("shiftonoffworkcount".equals(tmpField[0])){
SearchConditionOption SearchConditionOption_1 = new SearchConditionOption("1",SystemEnv.getHtmlLabelName(388569, user.getLanguage()));
SearchConditionOption SearchConditionOption_2 = new SearchConditionOption("2",SystemEnv.getHtmlLabelName(388570, user.getLanguage()));
SearchConditionOption SearchConditionOption_3 = new SearchConditionOption("3",SystemEnv.getHtmlLabelName(388571, user.getLanguage()));
if(isEdit){
if("1".equalsIgnoreCase(beanVal)){
SearchConditionOption_1.setSelected(true);
}else if("2".equalsIgnoreCase(beanVal)){
SearchConditionOption_2.setSelected(true);
}else if("3".equalsIgnoreCase(beanVal)){
SearchConditionOption_3.setSelected(true);
}
}else{
SearchConditionOption_1.setSelected(true);
}
options.add(SearchConditionOption_1);
options.add(SearchConditionOption_2);
options.add(SearchConditionOption_3);
hrmFieldBean.setSelectOption(options);
}
if(isEdit){
hrmFieldBean.setFieldvalue(beanVal);
}
if("subcompanyid".equals(tmpField[0])){
if(hrmdetachable){
hrmFieldBean.setViewAttr(3);
hrmFieldBean.setRules("required|string");
String defaultSubcompanyid = "";
int[] subcomids = newCheck.getSubComByUserRightId(user.getUID(),"KQClass:Management",0);
ManageDetachComInfo detachComInfo = new ManageDetachComInfo();
if(detachComInfo.isUseHrmManageDetach()){
defaultSubcompanyid = detachComInfo.getHrmdftsubcomid();
}else{
rs.executeProc("SystemSet_Select","");
if(rs.next()){
if(subcompanyid.length()==0||subcompanyid.equals("0")){
defaultSubcompanyid = Util.null2String(rs.getString("dftsubcomid"));
}
}
}
boolean hasRight = false;
for (int i = 0; subcomids!=null&& i < subcomids.length; i++) {
if((""+subcomids[i]).equals(defaultSubcompanyid)){
hasRight = true;
break;
}
}
if(!hasRight){
defaultSubcompanyid = "";
}
//表示左侧分部树选择了
if(Util.getIntValue(Util.null2String(subcompanyid)) > 0){
hrmFieldBean.setFieldvalue(subcompanyid);
}else{
hrmFieldBean.setFieldvalue(defaultSubcompanyid);
}
}else{
//不开启分权的话,不显示分部
continue;
}
}
if("punchsettings".equalsIgnoreCase(tmpField[0])){
hrmFieldBean.setFieldvalue("1");
}
searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user);
if("shiftonoffworkcount".equals(tmpField[0])){
// searchConditionItem.setHelpfulTip(SystemEnv.getHtmlLabelName(388574, user.getLanguage()));
}
if("isoffdutyfreecheck".equals(tmpField[0])){
searchConditionItem.setHelpfulTip(SystemEnv.getHtmlLabelName(388573, user.getLanguage()));
}
if(hrmdetachable && "subcompanyid".equals(tmpField[0])){
searchConditionItem.getBrowserConditionParam().getDataParams().put("rightStr", "KQClass:Management");
searchConditionItem.getBrowserConditionParam().getCompleteParams().put("rightStr", "KQClass:Management");
}
if("cardRemOfSignIn".equals(hrmFieldBean.getFieldname())){
List<SearchConditionOption> optionsList = new ArrayList<SearchConditionOption>();
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<SearchConditionOption> optionsList = new ArrayList<SearchConditionOption>();
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<SearchConditionOption> optionsList = new ArrayList<SearchConditionOption>();
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<SearchConditionOption> optionsList = new ArrayList<SearchConditionOption>();
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<SearchConditionOption> optionsList = new ArrayList<SearchConditionOption>();
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;
}
}

@ -0,0 +1,489 @@
package com.engine.kq.cmd.shiftmanagement;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.biz.SimpleBizLogger;
import com.engine.common.constant.BizLogSmallType4Hrm;
import com.engine.common.constant.BizLogType;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.kq.biz.KQConfigComInfo;
import com.engine.kq.biz.KQGroupBiz;
import com.engine.kq.biz.KQGroupComInfo;
import com.engine.kq.biz.KQShiftManagementComInfo;
import com.engine.kq.biz.KQShiftOnOffWorkSectionComInfo;
import com.engine.kq.biz.KQShiftRestTimeSectionComInfo;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import weaver.common.StringUtil;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.Reminder.KQAutoCardTask;
import weaver.hrm.User;
import weaver.hrm.common.database.dialect.DbDialectFactory;
import weaver.hrm.common.database.dialect.IDbDialectSql;
import weaver.systeminfo.SystemEnv;
/**
*
* @author pzy
*
*/
public class SaveShiftManagementBaseFormCmd extends AbstractCommonCommand<Map<String, Object>>{
private SimpleBizLogger logger;
public SaveShiftManagementBaseFormCmd() {
}
public SaveShiftManagementBaseFormCmd(Map<String, Object> 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<BizLogContext> 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<String, Object> execute(CommandContext commandContext) {
Map<String,Object> retmap = new HashMap<String,Object>();
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<String> 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<String,Object> retmap,JSONObject jsonObj) throws Exception{
RecordSetTrans rst = new RecordSetTrans();
rst.setAutoCommit(true);
RecordSet rs = new RecordSet();
String serialid = Util.null2String(jsonObj.get("id"));
String serial = Util.null2String(jsonObj.get("serial"));//班次名称
String subcompanyid = Util.null2o(Util.null2String(jsonObj.get("subcompanyid")));
int rest_shift = StringUtil.parseToInt(jsonObj.getString("rest_shift"),0);//休息班
String shiftOnOffWorkCount = Util.null2o(Util.null2String(jsonObj.get("shiftonoffworkcount")));//一天内上下班次数
String punchSettings = "1";//打卡时段是否开启 1表示开启
String isOffDutyFreeCheck = Util.null2o(Util.null2String(jsonObj.get("isoffdutyfreecheck")));//允许下班不打卡 1表示开启
String isRestTimeOpen = Util.null2o(Util.null2String(jsonObj.get("isresttimeopen")));//排除休息时间是否开启 1表示开启
String worktime = Util.null2o(Util.null2String(jsonObj.get("worktime")));//工作时长
// String color = Util.null2o(Util.null2String(jsonObj.get("color")));//工作时长
String color = "#000";
String cardRemind = Util.null2s(jsonObj.getString("cardRemind"),"0");//是否开启打卡提醒0-不开启、1-开启。默认不开启
String cardRemOfSignIn = Util.null2s(jsonObj.getString("cardRemOfSignIn"),"1");//上班打卡提醒0-不提醒、1-自定义提前提醒分钟数。默认为1
String minsBeforeSignIn = Util.null2s(jsonObj.getString("minsBeforeSignIn"),"10");//自定义提前提醒分钟数。默认10分钟
String cardRemOfSignOut = Util.null2s(jsonObj.getString("cardRemOfSignOut"),"1");//下班打卡提醒0-不提醒、1-自定义延后提醒分钟数。默认为1
String minsAfterSignOut = Util.null2s(jsonObj.getString("minsAfterSignOut"),"0");//自定义延后提醒分钟数。默认0分钟
String remindMode = Util.null2s(jsonObj.getString("remindMode"),"1");//提醒方式1-消息中心提醒、2-邮件提醒、3-短信提醒。默认消息中心提醒
String remindOnPC = Util.null2s(jsonObj.getString("remindOnPC"),"0");//登陆PC端弹窗提醒0-不开启、1-开启
String halfcalrule = Util.null2s(jsonObj.getString("halfcalrule"),"0");//半天计算规则
String halfcalpoint = Util.null2s(jsonObj.getString("halfcalpoint"),"");//半天分界点
String halfcalpoint2cross = Util.null2s(jsonObj.getString("halfcalpoint2cross"),"0");//当日
if(duplicationCheck(serial,serialid)){
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(389019,user.getLanguage()));
return ;
}
String[] works = new String[]{"start","end"};
JSONArray workSections = (JSONArray)jsonObj.get("workSections");
checkRule(retmap,workSections,works);
if(!retmap.isEmpty()){
return ;
}
String mainSql = "update kq_ShiftManagement set serial=?,subcompanyid=?,shiftonoffworkcount=?,punchsettings=?,isoffdutyfreecheck=?,isresttimeopen=?,worktime=?,color=?," +
"cardRemind=? ,cardRemOfSignIn=? ,minsBeforeSignIn=? ,cardRemOfSignOut=? ,minsAfterSignOut=? ,remindMode=? ,remindOnPC=?,halfcalrule=?,halfcalpoint=?,halfcalpoint2cross=?,rest_shift= ? where id = ? ";
boolean isUpdated = rst.executeUpdate(mainSql, serial,subcompanyid,shiftOnOffWorkCount,punchSettings,isOffDutyFreeCheck,isRestTimeOpen,worktime,color,
cardRemind ,cardRemOfSignIn ,minsBeforeSignIn ,cardRemOfSignOut ,minsAfterSignOut ,remindMode ,remindOnPC,halfcalrule,halfcalpoint,halfcalpoint2cross,rest_shift,serialid);
if(isUpdated){
//对于休息时间和工作时间,直接删除后重新创建
String delRestSql = "delete from kq_ShiftRestTimeSections where serialid = ? ";
rs = new RecordSet();
rst.executeUpdate(delRestSql, serialid);
String delWorkSql = "delete from kq_ShiftOnOffWorkSections where serialid = ? ";
rs = new RecordSet();
rst.executeUpdate(delWorkSql, serialid);
//休息时间 resttype:start开始时间,end结束时间
JSONArray restTimeSections = (JSONArray)jsonObj.get("restTimeSections");
//工作时间 across是否跨天1表示跨天;beginMin上班前分钟数开始签到endMin下班后分钟数停止签退;times具体上下班时间;onOffWorkType:start开始时间,end结束时间
String restSql = "insert into kq_ShiftRestTimeSections(serialid,resttype,time,across) values(?,?,?,?)";
int restCount = restTimeSections.size();
rs = new RecordSet();
for(int i = 0 ; i < restCount ; i++){
JSONObject jsonRest = ((JSONObject)restTimeSections.get(i));
String time=Util.null2String(jsonRest.get("time"));
String resttype=Util.null2String(jsonRest.get("resttype"));
String across=Util.null2String(jsonRest.get("across"));
rst.executeUpdate(restSql, serialid,resttype,time,across);
}
rs = new RecordSet();
String workSql = "insert into kq_ShiftOnOffWorkSections(serialid,across,mins,times,onoffworktype,record,mins_next) values(?,?,?,?,?,?,?)";
int workCount = workSections.size();
for(int i = 0 ; i < workCount ; i++){
JSONObject jsonWork = ((JSONObject)workSections.get(i));
String record = Util.null2String(jsonWork.get("record"));
for(int j = 0 ; j < works.length ; j++){
String onOffWorkType=works[j];
JSONObject inWork=(JSONObject)jsonWork.get(onOffWorkType);
String across=Util.null2String(inWork.get("across"));
String mins = Util.null2s(Util.null2String(inWork.get("mins")),"0");
String times=Util.null2String(inWork.get("times"));
String mins_next=Util.null2String(inWork.get("mins_next"));
rst.executeUpdate(workSql, serialid,across,mins,times,onOffWorkType,record,mins_next);
}
}
retmap.put("id", serialid);
retmap.put("status", "1");
retmap.put("message", SystemEnv.getHtmlLabelName(18758, user.getLanguage()));
}else{
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(382661,user.getLanguage()));
}
}
/**
*
* @param retmap
* @param jsonObj
*/
public void add(Map<String,Object> retmap,JSONObject jsonObj) throws Exception{
RecordSetTrans rst = new RecordSetTrans();
rst.setAutoCommit(true);
RecordSet rs = new RecordSet();
String subcompanyid = Util.null2o(Util.null2String(jsonObj.get("subcompanyid")));
int rest_shift = StringUtil.parseToInt(jsonObj.getString("rest_shift"),0);//休息班
String serial = Util.null2String(jsonObj.get("serial"));//班次名称
String shiftOnOffWorkCount = Util.null2o(Util.null2String(jsonObj.get("shiftonoffworkcount")));//一天内上下班次数
String punchSettings = "1";//打卡时段是否开启 1表示开启
String isOffDutyFreeCheck = Util.null2o(Util.null2String(jsonObj.get("isoffdutyfreecheck")));//允许下班不打卡 1表示开启
String isRestTimeOpen = Util.null2o(Util.null2String(jsonObj.get("isresttimeopen")));//排除休息时间是否开启 1表示开启
String worktime = Util.null2o(Util.null2String(jsonObj.get("worktime")));//工作时长
// String color = Util.null2o(Util.null2String(jsonObj.get("color")));//工作时长
String color = "#000";
String uuid = UUID.randomUUID().toString();//uuid供查询使用
String cardRemind = Util.null2s(jsonObj.getString("cardRemind"),"0");//是否开启打卡提醒0-不开启、1-开启。默认不开启
String cardRemOfSignIn = Util.null2s(jsonObj.getString("cardRemOfSignIn"),"1");//上班打卡提醒0-不提醒、1-自定义提前提醒分钟数。默认为1
String minsBeforeSignIn = Util.null2s(jsonObj.getString("minsBeforeSignIn"),"10");//自定义提前提醒分钟数。默认10分钟
String cardRemOfSignOut = Util.null2s(jsonObj.getString("cardRemOfSignOut"),"1");//下班打卡提醒0-不提醒、1-自定义延后提醒分钟数。默认为1
String minsAfterSignOut = Util.null2s(jsonObj.getString("minsAfterSignOut"),"0");//自定义延后提醒分钟数。默认0分钟
String remindMode = Util.null2s(jsonObj.getString("remindMode"),"1");//提醒方式1-消息中心提醒、2-邮件提醒、3-短信提醒。默认消息中心提醒
String remindOnPC = Util.null2s(jsonObj.getString("remindOnPC"),"0");//登陆PC端弹窗提醒0-不开启、1-开启
String halfcalrule = Util.null2s(jsonObj.getString("halfcalrule"),"0");//半天计算规则
String halfcalpoint = Util.null2s(jsonObj.getString("halfcalpoint"),"");//半天分界点
String halfcalpoint2cross = Util.null2s(jsonObj.getString("halfcalpoint2cross"),"0");//当日
if(duplicationCheck(serial,"")){
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(389019,user.getLanguage()));
return ;
}
//工作时间 across是否跨天1表示跨天;beginMin上班前分钟数开始签到endMin下班后分钟数停止签退;times具体上下班时间;onOffWorkType:start开始时间,end结束时间
JSONArray workSections = (JSONArray)jsonObj.get("workSections");
String[] works = new String[]{"start","end"};
checkRule(retmap,workSections,works);
if(!retmap.isEmpty()){
return ;
}
//color改为前台获取
// String color = getRandomColor();
boforeLog(uuid);
String mainSql = "insert into kq_ShiftManagement(serial,subcompanyid,shiftonoffworkcount,punchsettings,isoffdutyfreecheck,isresttimeopen,worktime,uuid,color," +
"cardRemind ,cardRemOfSignIn ,minsBeforeSignIn ,cardRemOfSignOut ,minsAfterSignOut ,remindMode ,remindOnPC,halfcalrule,halfcalpoint,halfcalpoint2cross,rest_shift)"
+ " values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
boolean isUpdated = rst.executeUpdate(mainSql, serial,subcompanyid,shiftOnOffWorkCount,punchSettings,isOffDutyFreeCheck,isRestTimeOpen,worktime,uuid,color,
cardRemind ,cardRemOfSignIn ,minsBeforeSignIn ,cardRemOfSignOut ,minsAfterSignOut ,remindMode ,remindOnPC,halfcalrule,halfcalpoint,halfcalpoint2cross,rest_shift);
if(isUpdated){
int serialid = 0;
String idSql = "select id from kq_ShiftManagement where uuid=? and (isdelete is null or isdelete <> '1') ";
rs = new RecordSet();
rs.executeQuery(idSql,uuid);
if(rs.next()) {
serialid = rs.getInt("id");
}
if(serialid > 0){
//休息时间 resttype:start开始时间,end结束时间
JSONArray restTimeSections = (JSONArray)jsonObj.get("restTimeSections");
String restSql = "insert into kq_ShiftRestTimeSections(serialid,resttype,time,across) values(?,?,?,?)";
int restCount = restTimeSections.size();
rs = new RecordSet();
for(int i = 0 ; i < restCount ; i++){
JSONObject jsonRest = ((JSONObject)restTimeSections.get(i));
String time=Util.null2String(jsonRest.get("time"));
String resttype=Util.null2String(jsonRest.get("resttype"));
String across=Util.null2String(jsonRest.get("across"));
rst.executeUpdate(restSql, serialid,resttype,time,across);
}
rs = new RecordSet();
String workSql = "insert into kq_ShiftOnOffWorkSections(serialid,across,mins,times,onoffworktype,record,mins_next) values(?,?,?,?,?,?,?)";
int workCount = workSections.size();
for(int i = 0 ; i < workCount ; i++){
JSONObject jsonWork = ((JSONObject)workSections.get(i));
String record = Util.null2String(jsonWork.get("record"));
for(int j = 0 ; j < works.length ; j++){
String onOffWorkType=works[j];
JSONObject inWork=(JSONObject)jsonWork.get(onOffWorkType);
String across=Util.null2String(inWork.get("across"));
String mins = Util.null2s(Util.null2String(inWork.get("mins")),"1");
String times=Util.null2String(inWork.get("times"));
String mins_next=Util.null2String(inWork.get("mins_next"));
rst.executeUpdate(workSql, serialid,across,mins,times,onOffWorkType,record,mins_next);
}
}
retmap.put("status", "1");
retmap.put("id", serialid);
retmap.put("message", SystemEnv.getHtmlLabelName(18758, user.getLanguage()));
}else{
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(382661,user.getLanguage()));
}
}else{
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(382661,user.getLanguage()));
}
}
private void checkRule(Map<String, Object> retmap,
JSONArray workSections, String[] works) {
for(int i = 0 ; i < workSections.size() ; i++) {
JSONObject jsonWork = ((JSONObject) workSections.get(i));
for(int j = 0 ; j < works.length ; j++){
String onOffWorkType=works[j];
JSONObject inWork=(JSONObject)jsonWork.get(onOffWorkType);
String mins = Util.null2String(inWork.get("mins"));
if(mins.length() == 0 || Util.getIntValue(mins) == 0){
retmap.put("status", "-1");
retmap.put("message", ""+weaver.systeminfo.SystemEnv.getHtmlLabelName(10005343,weaver.general.ThreadVarLanguage.getLang())+"");
break;
}
}
}
}
/**
*
* @param serial
* @param serialid
* @return
*/
private boolean duplicationCheck(String serial,String serialid){
boolean isDuplicated = false;
RecordSet rs = new RecordSet();
String checkSql = "select 1 from kq_ShiftManagement where serial=? and (isdelete is null or isdelete <> '1') ";
if(serialid.length() > 0){
checkSql += " and id != "+serialid;
}
rs.executeQuery(checkSql, Util.null2s(serial, "").trim());
if(rs.next()){
isDuplicated = true;
}
return isDuplicated;
}
/**
*
* @return
*/
private String getRandomColor(){
RecordSet rs = new RecordSet();
List<String> 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);
}
}

@ -0,0 +1,313 @@
package com.engine.kq.cmd.shiftschedule;
import com.alibaba.fastjson.JSONObject;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.kq.biz.KQGroupComInfo;
import com.engine.kq.biz.KQHolidaySetBiz;
import com.engine.kq.biz.KQShiftManagementComInfo;
import com.engine.kq.cmd.shiftmanagement.toolkit.ShiftManagementToolKit;
import com.engine.kq.log.KQLog;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.resource.ResourceComInfo;
import weaver.systeminfo.SystemEnv;
import java.util.*;
public class GetShiftScheduleCmd extends AbstractCommonCommand<Map<String, Object>> {
public GetShiftScheduleCmd(Map<String, Object> params, User user) {
this.user = user;
this.params = params;
}
@Override
public Map<String, Object> execute(CommandContext commandContext) {
Map<String, Object> retmap = new HashMap<String, Object>();
Map<String, Object> shiftSchedule = new HashMap<String, Object>();
List<Object> lsDatas = null;
List<Object> lsKeyDatas = null;
Map<String, Object> data = null;
RecordSet rs = new RecordSet();
String sql = "";
try{
//必要的权限判断
if(!HrmUserVarify.checkUserRight("HrmKQGroup:Add",user)) {
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage()));
return retmap;
}
int count = 0;
int pageCount = 0;
int isHavePre = 0;
int isHaveNext = 0;
KQGroupComInfo kQGroupComInfo = new KQGroupComInfo();
KQShiftManagementComInfo kQShiftManagementComInfo = new KQShiftManagementComInfo();
ShiftManagementToolKit shiftManagementToolKit = new ShiftManagementToolKit();
ResourceComInfo resourceComInfo = new ResourceComInfo();
DepartmentComInfo departmentComInfo = new DepartmentComInfo();
String status = Util.null2String(params.get("status"));
String groupId = Util.null2String(params.get("groupId"));//考勤组id
String kqMonth = Util.null2String(params.get("kqMonth"));//月份
String viewscope = Util.null2String(params.get("viewscope"));//0总部 1分部 2部门 3人员 4我的下属
int pageIndex = Util.getIntValue(Util.null2String(params.get("pageIndex")), 1);
int pageSize = Util.getIntValue(Util.null2String(params.get("pageSize")), 20);
String year = kqMonth.substring(0,4);
String month = kqMonth.substring(5,7);
String monthBeginDate = DateUtil.getFirstDayOfMonth(kqMonth+"-01");
String monthEndDate = DateUtil.getLastDayOfMonth(kqMonth+"-01");
String serialidStr = Util.null2String(kQGroupComInfo.getSerialids(groupId));
List<String> serialids = new ArrayList<>();
List<Object> lsSerialDatas = new ArrayList<>();
if(serialidStr.length() > 0){
serialids = Util.splitString2List(serialidStr,",");
for(int i=0;i<serialids.size();i++){
data = new HashMap<>();
data.put("id",serialids.get(i));
data.put("name",shiftManagementToolKit.getShiftOnOffWorkSections(serialids.get(i),user.getLanguage()));
data.put("bgColor",kQShiftManagementComInfo.getColor(serialids.get(i)));
lsSerialDatas.add(data);
}
}
lsDatas = new ArrayList<>();
sql = "select id,shiftcyclename,shiftcycleserialids from kq_group_shiftcycle where groupid = ? order by id asc ";
rs.executeQuery(sql,groupId);
while(rs.next()){
data = new HashMap<>();
data.put("name",Util.null2String(rs.getString("shiftcyclename")));//周期名称,
data.put("serial",Util.splitString(Util.null2String(rs.getString("shiftcycleserialids")),","));//周期顺序例7天一周期
lsDatas.add(data);
}
retmap.put("serialInfo", lsDatas);
lsDatas = KQHolidaySetBiz.getGroupHolidaySetList(groupId,year,month);
retmap.put("holidays", lsDatas);
String sqlWhere = " ";
if(viewscope.length()>0){
if(viewscope.equals("1")){//分部
String subCompanyId = Util.null2String(params.get("subCompanyId"));
sqlWhere += " and t.subcompanyid1 in ("+subCompanyId+") ";
}else if(viewscope.equals("2")){//部门
String departmentId = Util.null2String(params.get("departmentId"));
sqlWhere += " and t.departmentid in ("+departmentId+") ";
}else if(viewscope.equals("3")){//人员
String resourceId = Util.null2String(params.get("resourceId"));
sqlWhere += " and t.resourceid in ("+resourceId+") ";
}
}
String isNoAccount = Util.null2String(params.get("isNoAccount"));// 是否显示无账号人员
if (!"1".equals(isNoAccount)) {
sqlWhere += " and t.status in(0,1,2,3) and t.loginid is not null "+(rs.getDBType().equals("oracle")?"":" and t.loginid<>'' ");
}
if(status.length()>0){
if (!status.equals("8") && !status.equals("9")) {
sqlWhere += " and t.status = "+status+ "";
}else if (status.equals("8")) {
sqlWhere += " and (t.status = 0 or t.status = 1 or t.status = 2 or t.status = 3) ";
}
}
if(!Util.null2String(kQGroupComInfo.getExcludecount(groupId)).equals("1")) {
//剔除无需排班人员
String excludeid = Util.null2String(kQGroupComInfo.getExcludeid(groupId));
if (excludeid.length() > 0) {
sqlWhere += " and t.resourceid not in (" + excludeid + ")";
}
}
//二开 2023年06月19日09:37:14 增加分权功能 start
String roleSql = " select a.id from hrmroles a,hrmrolemembers b " +
"where a.id=b.roleid and a.rolesmark='考勤管理员' and resourceid=? ";
rs.executeQuery(roleSql,user.getUID());
if(!user.isAdmin() && !rs.next()){
sqlWhere += " and t.departmentid in( select deptid from hrmdepartmentdefined where kqwy="+user.getUID()+") ";
}
//end
String backFields = " t.resourceid, t.groupid, t.status, t.dsporder,t.lastname,t.subcompanyid1, t.departmentid, t.loginid ";
String sqlFrom = " from (SELECT distinct t.resourceid, t.groupid, t.status, t.dsporder,t.lastname,t.subcompanyid1, t.departmentid, t.loginid FROM ( \n" +
" SELECT a.id AS resourceid, b.groupid, a.status,a.dsporder,a.lastname,a.subcompanyid1, a.departmentid, a.loginid FROM HrmResource a, kq_groupmember b \n" +
" WHERE a.id=b.typevalue and b.type =1 and (b.isdelete is null or b.isdelete <> '1') \n" +
" UNION ALL \n" +
" SELECT a.id AS resourceid, b.groupid, a.status,a.dsporder,a.lastname,a.subcompanyid1, a.departmentid, a.loginid FROM HrmResource a, kq_groupmember b \n" +
" WHERE a.subcompanyid1 = b.typevalue AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto AND b.type=2 and (b.isdelete is null or b.isdelete <> '1') \n" +
" UNION ALL \n" +
" SELECT a.id AS resourceid, b.groupid, a.status,a.dsporder,a.lastname,a.subcompanyid1, a.departmentid, a.loginid FROM HrmResource a, kq_groupmember b \n" +
" WHERE a.departmentid = b.typevalue AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto AND b.type=3 and (b.isdelete is null or b.isdelete <> '1') \n" +
" UNION ALL \n" +
" SELECT a.id AS resourceid, b.groupid, a.status,a.dsporder,a.lastname,a.subcompanyid1, a.departmentid, a.loginid FROM HrmResource a, kq_groupmember b \n" +
" WHERE (a.jobtitle = b.typevalue AND b.type=5 and (b.isdelete is null or b.isdelete <> '1') AND (b.jobtitlelevel=1 OR (b.jobtitlelevel=2 AND a.subcompanyid1 IN(b.jobtitlelevelvalue)) OR (b.jobtitlelevel=3 AND a.departmentid IN(b.jobtitlelevelvalue)))) \n" +
" UNION ALL " +
" SELECT a.id AS resourceid, b.groupid, a.status,a.dsporder,a.lastname,a.subcompanyid1, a.departmentid, a.loginid FROM HrmResource a, kq_groupmember b \n" +
" WHERE b.type=6 AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto and (b.isdelete is null or b.isdelete <> '1')" +
" )t ) t where t.groupid = "+groupId;
String groupBy = " ";
lsKeyDatas = new ArrayList<>();
lsDatas = new ArrayList<>();
// sql = " select b.id, b.kqdate, b.serialid, t.resourceid, t.subcompanyid1, t.departmentid, t.loginid from (\n" +
// " SELECT distinct t.resourceid, t.groupid, t.status, t.dsporder,t.lastname,t.subcompanyid1, t.departmentid, t.loginid FROM ( \n" +
// " SELECT a.id AS resourceid, b.groupid, a.status,a.dsporder,a.lastname,a.subcompanyid1, a.departmentid, a.loginid FROM HrmResource a, kq_groupmember b \n" +
// " WHERE a.id=b.typevalue and b.type =1 and (b.isdelete is null or b.isdelete <> '1') \n" +
// " UNION ALL \n" +
// " SELECT a.id AS resourceid, b.groupid, a.status,a.dsporder,a.lastname,a.subcompanyid1, a.departmentid, a.loginid FROM HrmResource a, kq_groupmember b \n" +
// " WHERE a.subcompanyid1 = b.typevalue AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto AND b.type=2 and (b.isdelete is null or b.isdelete <> '1') \n" +
// " UNION ALL \n" +
// " SELECT a.id AS resourceid, b.groupid, a.status,a.dsporder,a.lastname,a.subcompanyid1, a.departmentid, a.loginid FROM HrmResource a, kq_groupmember b \n" +
// " WHERE a.departmentid = b.typevalue AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto AND b.type=3 and (b.isdelete is null or b.isdelete <> '1') \n" +
// " UNION ALL \n" +
// " SELECT a.id AS resourceid, b.groupid, a.status,a.dsporder,a.lastname,a.subcompanyid1, a.departmentid, a.loginid FROM HrmResource a, kq_groupmember b \n" +
// " WHERE (a.jobtitle = b.typevalue AND b.type=5 and (b.isdelete is null or b.isdelete <> '1') AND (b.jobtitlelevel=1 OR (b.jobtitlelevel=2 AND a.subcompanyid1 IN(b.jobtitlelevelvalue)) OR (b.jobtitlelevel=3 AND a.departmentid IN(b.jobtitlelevelvalue)))) \n" +
// " UNION ALL " +
// " SELECT a.id AS resourceid, b.groupid, a.status,a.dsporder,a.lastname,a.subcompanyid1, a.departmentid, a.loginid FROM HrmResource a, kq_groupmember b \n" +
// " WHERE b.type=6 AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto and (b.isdelete is null or b.isdelete <> '1')" +
// " )t ) t left join kq_shiftschedule b on t.resourceid=b.resourceid and t.groupid = b.groupid and (b.isdelete is null or b.isdelete <> '1') and b.kqdate>=? and b.kqdate<=? where t.groupid=? \n " +
// sqlWhere +
// " order by t.dsporder,t.lastname";
sql = " select count(*) as c from ( select 1 as c "+sqlFrom+sqlWhere+groupBy+") t";
rs.execute(sql);
if (rs.next()){
count = rs.getInt("c");
}
if (count <= 0) {
pageCount = 0;
}
pageCount = count / pageSize + ((count % pageSize > 0) ? 1 : 0);
isHaveNext = (pageIndex + 1 <= pageCount) ? 1 : 0;
isHavePre = (pageIndex - 1 >= 1) ? 1 : 0;
String orderBy = " order by t.dsporder asc, t.lastname asc ";
String descOrderBy = " order by t.dsporder desc, t.lastname desc ";
sql = backFields + sqlFrom + sqlWhere + groupBy;
if (pageIndex > 0 && pageSize > 0) {
if (rs.getDBType().equals("oracle")) {
sql = " select * from (select " + sql+") t "+orderBy;
sql = "select * from ( select row_.*, rownum rownum_ from ( " + sql + " ) row_ where rownum <= "
+ (pageIndex * pageSize) + ") where rownum_ > " + ((pageIndex - 1) * pageSize);
} else if (rs.getDBType().equals("mysql")) {
sql = " select * from (select " + sql+") t "+orderBy;
sql = "select t1.* from (" + sql + ") t1 limit " + ((pageIndex - 1) * pageSize) + "," + pageSize;
}
else if (rs.getDBType().equals("postgresql")) {
sql = " select * from (select " + sql+") t "+orderBy;
sql = "select t1.* from (" + sql + ") t1 limit " +pageSize + " offset " + ((pageIndex - 1) * pageSize);
}
else {
orderBy = " order by dsporder asc, lastname asc ";
descOrderBy = " order by dsporder desc, lastname desc ";
if (pageIndex > 1) {
int topSize = pageSize;
if (pageSize * pageIndex > count) {
topSize = count - (pageSize * (pageIndex - 1));
}
sql = " select top " + topSize + " * from ( select top " + topSize + " * from ( select top "
+ (pageIndex * pageSize) + sql + orderBy+ " ) tbltemp1 " + descOrderBy + ") tbltemp2 " + orderBy;
} else {
sql = " select top " + pageSize + sql+orderBy;
}
}
} else {
sql = " select " + sql;
}
new KQLog().info("GetShiftScheduleCmd:"+sql);
rs.executeQuery(sql);
while(rs.next()){
String resourceid = Util.null2String(rs.getString("resourceid"));
data = new HashMap<>();
data.put("resourceid",resourceid);
data.put("name",resourceComInfo.getLastname(resourceid));
data.put("department",departmentComInfo.getDepartmentname(resourceComInfo.getDepartmentID(resourceid)));
List<Object> shiftScheduleDatas = this.getShiftSchedule(groupId, resourceid, monthBeginDate,monthEndDate);
for(int i=0;shiftScheduleDatas!=null&&i<shiftScheduleDatas.size();i++){
Map<String,Object> shiftScheduleData = (Map<String,Object>)shiftScheduleDatas.get(i);
String id = Util.null2String(shiftScheduleData.get("id"));
String kqdate = Util.null2String(shiftScheduleData.get("kqdate"));
String serialid = Util.null2String(shiftScheduleData.get("serialid"));
if(!serialids.contains(serialid) && !serialid.equals("-1")){
serialids.add(serialid);
Map<String,Object> serialdata = new HashMap<>();
serialdata.put("id",serialid);
serialdata.put("name",shiftManagementToolKit.getShiftOnOffWorkSections(serialid,user.getLanguage()));
serialdata.put("bgColor",kQShiftManagementComInfo.getColor(serialid));
serialdata.put("isDelete",1);
lsSerialDatas.add(serialdata);
}
data.put(kqdate,serialid);
lsKeyDatas.add(resourceid+"|"+kqdate+"|"+id);
}
lsDatas.add(data);
}
retmap.put("pagesize", pageSize);
retmap.put("pageindex", pageIndex);
retmap.put("count", count);
retmap.put("pagecount", pageCount);
retmap.put("ishavepre", isHavePre);
retmap.put("ishavenext", isHaveNext);
retmap.put("datas", lsDatas);
retmap.put("keyDatas", lsKeyDatas);
retmap.put("shiftList", lsSerialDatas);
retmap.put("groupName", kQGroupComInfo.getGroupname(groupId));
retmap.put("today", DateUtil.getCurrentDate());
if(Util.null2String(kQGroupComInfo.getValidity(groupId)).equals("1")){//考勤组设置了有效期
retmap.put("validityFromDate", kQGroupComInfo.getValidityfromdate(groupId));
retmap.put("validityEndDate", kQGroupComInfo.getValidityenddate(groupId));
}
retmap.put("status", "1");
}catch (Exception e) {
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(382661,user.getLanguage()));
writeLog(e);
}
return retmap;
}
private List<Object> getShiftSchedule(String groupid, String resourceid, String monthBeginDate,String monthEndDate){
List<Object> datas = new ArrayList<>();
Map<String,Object> data = null;
String sql = "";
RecordSet rs = new RecordSet();
sql = " select id,kqdate, serialid from kq_shiftschedule where groupid= '"+groupid+"' and resourceid="+resourceid+" " +
" and kqdate>='"+monthBeginDate+"' and kqdate<='"+monthEndDate+"' and (isdelete is null or isdelete <> '1')";
rs.executeQuery(sql);
while(rs.next()){
String id = Util.null2String(rs.getString("id"));
String kqdate = Util.null2String(rs.getString("kqdate"));
String serialid = Util.null2String(rs.getString("serialid"));
data = new HashMap<>();
data.put("id",id);
data.put("kqdate",kqdate);
data.put("serialid",serialid);
datas.add(data);
}
return datas;
}
@Override
public BizLogContext getLogContext() {
return null;
}
}

@ -0,0 +1,119 @@
package com.engine.kq.cmd.shiftschedule;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.kq.biz.KQGroupComInfo;
import com.engine.kq.biz.KQHolidaySetBiz;
import com.engine.kq.biz.KQShiftManagementComInfo;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.resource.ResourceComInfo;
import weaver.systeminfo.SystemEnv;
import java.util.*;
public class GetShiftScheduleTotalCmd extends AbstractCommonCommand<Map<String, Object>> {
public GetShiftScheduleTotalCmd(Map<String, Object> params, User user) {
this.user = user;
this.params = params;
}
@Override
public Map<String, Object> execute(CommandContext commandContext) {
Map<String, Object> retmap = new HashMap<String, Object>();
List<Object> lsColumns = new ArrayList<>();
Map<String, Object> column = null;
List<Object> lsDatas = null;
Map<String, Object> data = null;
String sql = "";
RecordSet rs = new RecordSet();
try{
//必要的权限判断
if(!HrmUserVarify.checkUserRight("HrmKQGroup:Add",user)) {
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage()));
return retmap;
}
Calendar cal = DateUtil.getCalendar();
KQGroupComInfo kQGroupComInfo = new KQGroupComInfo();
KQShiftManagementComInfo kQShiftManagementComInfo = new KQShiftManagementComInfo();
String groupId = Util.null2String(params.get("groupId"));//考勤组id
String kqMonth = Util.null2String(params.get("kqMonth"));//月份
String monthBeginDate = DateUtil.getFirstDayOfMonth(kqMonth+"-01");
String monthEndDate = DateUtil.getLastDayOfMonth(kqMonth+"-01");
boolean hasRestShift = false;
Map<String,Object> mapShiftSchedule = new HashMap<>();
sql = " select kqdate,serialid,count(resourceid) as num from kq_shiftschedule " +
" where (isdelete is null or isdelete <> '1') and kqdate>=? and kqdate<=? and groupid=? " +
" group by kqdate,serialid ";
rs.executeQuery(sql,monthBeginDate,monthEndDate,groupId);
while(rs.next()){
if(Util.null2String(rs.getString("serialid")).equals("-1")){
hasRestShift=true;
}
mapShiftSchedule.put(rs.getString("kqdate")+"|"+rs.getInt("serialid"),rs.getInt("num"));
}
column = new HashMap<String, Object>();
column.put("title", SystemEnv.getHtmlLabelName(389646,user.getLanguage()));
column.put("dataIndex", "serialName");
lsColumns.add(column);
boolean isEnd = false;
for(String date=monthBeginDate; !isEnd;) {
if (date.equals(monthEndDate)) isEnd = true;
column = new HashMap<String, Object>();
column.put("title", date);
column.put("dataIndex", date);
lsColumns.add(column);
cal.setTime(DateUtil.parseToDate(date));
date = DateUtil.getDate(cal.getTime(), 1);
}
List<String> lsSerialId = Util.splitString2List(Util.null2String(kQGroupComInfo.getSerialids(groupId)),",");
if(hasRestShift && !lsSerialId.contains("-1"))lsSerialId.add("-1");//统计休息班
lsDatas = new ArrayList<>();
for(int i=0;lsSerialId!=null&&i<lsSerialId.size();i++){
data = new HashMap<>();
data.put("serialId",lsSerialId.get(i));
if(lsSerialId.get(i).equals("-1")){
data.put("serialName",SystemEnv.getHtmlLabelName(26593,user.getLanguage()));
}else{
data.put("serialName",kQShiftManagementComInfo.getSerial(lsSerialId.get(i)));
}
data.put("bgColor",kQShiftManagementComInfo.getColor(lsSerialId.get(i)));
isEnd = false;
for(String date=monthBeginDate; !isEnd;) {
if (date.equals(monthEndDate)) isEnd = true;
data.put(date,mapShiftSchedule.get(date+"|"+lsSerialId.get(i)));
cal.setTime(DateUtil.parseToDate(date));
date = DateUtil.getDate(cal.getTime(), 1);
}
lsDatas.add(data);
}
retmap.put("columns", lsColumns);
retmap.put("datas", lsDatas);
retmap.put("groupName", kQGroupComInfo.getGroupname(groupId));
retmap.put("status", "1");
}catch (Exception e) {
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(382661,user.getLanguage()));
writeLog(e);
}
return retmap;
}
@Override
public BizLogContext getLogContext() {
return null;
}
}

@ -0,0 +1,309 @@
package com.engine.kq.cmd.shiftschedule;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.biz.SimpleBizLogger;
import com.engine.common.constant.BizLogSmallType4Hrm;
import com.engine.common.constant.BizLogType;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.kq.biz.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import weaver.conn.BatchRecordSet;
import weaver.conn.RecordSet;
import weaver.file.ImageFileManager;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.Reminder.KQAutoCardTask;
import weaver.hrm.User;
import weaver.hrm.resource.ResourceComInfo;
import weaver.systeminfo.SystemEnv;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ImportExcelCmd extends AbstractCommonCommand<Map<String, Object>> {
private String today = weaver.common.DateUtil.getCurrentDate();
private SimpleBizLogger logger;
public ImportExcelCmd(Map<String, Object> params, User user) {
this.user = user;
this.params = params;
this.logger = new SimpleBizLogger();
String groupId = Util.null2String(params.get("groupId"));
BizLogContext bizLogContext = new BizLogContext();
bizLogContext.setLogType(BizLogType.HRM_ENGINE);//模块类型
bizLogContext.setBelongType(BizLogSmallType4Hrm.HRM_ENGINE_Schedule_Set);//所属大类型
bizLogContext.setLogSmallType(BizLogSmallType4Hrm.HRM_ENGINE_Schedule_Set);//当前小类型
bizLogContext.setParams(params);//当前request请求参数
logger.setUser(user);//当前操作人
String mainSql = "select * from kq_group where id = " + groupId + " and (isdelete is null or isdelete <> '1') ";
logger.setMainSql(mainSql, "id");//主表sql
logger.setMainPrimarykey("id");//主日志表唯一key
logger.setMainTargetNameColumn("groupname");
SimpleBizLogger.SubLogInfo subLogInfo1 = logger.getNewSubLogInfo();
String subSql1 = "select * from kq_shiftschedule where groupid = " + groupId + " and (isdelete is null or isdelete <> '1') ";
subLogInfo1.setSubSql(subSql1,"id");
logger.addSubLogInfo(subLogInfo1);
logger.before(bizLogContext);
}
@Override
public Map<String, Object> execute(CommandContext commandContext) {
Map<String, Object> retmap = new HashMap<String, Object>();
RecordSet rs = new RecordSet();
BatchRecordSet bRs = new BatchRecordSet();
String sql = "";
try {
//必要的权限判断
if (!HrmUserVarify.checkUserRight("HrmKQGroup:Add", user)) {
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage()));
return retmap;
}
ResourceComInfo resourceComInfo = new ResourceComInfo();
KQGroupComInfo kqGroupComInfo = new KQGroupComInfo();
KQGroupBiz kqGroupBiz = new KQGroupBiz();
KQShiftManagementComInfo kqShiftManagementComInfo = new KQShiftManagementComInfo();
String groupId = Util.null2String(params.get("groupId"));
String filename = Util.null2String(params.get("filename"));
List lsColumn = null;
List<List<Object>> paramInsert = new ArrayList<List<Object>>();
List<List<Object>> paramUpdate = new ArrayList<List<Object>>();
List<Object> param = null;
List<List<Object>> lsFormatParams = new ArrayList<>();
List<Object> formatParams = null;
List<List<Object>> lscheckSerialParams = new ArrayList<>();
List<Object> checkSerialParams = null;
Map<String,Object> mapShiftSchedule = new HashMap<>();
Map<String,String> mapSerial = new HashMap<>();
Map<String,String> mapGroupMembersWorkCode = new HashMap<>();
Map<String,String> mapGroupMembersLastName = new HashMap<>();
List<String> serialids=Util.splitString2List(kqGroupComInfo.getSerialids(groupId),",");
if(!serialids.contains("-1"))serialids.add("-1");
for(String serialid : serialids){
if(serialid.equals("-1")){
mapSerial.put(SystemEnv.getHtmlLabelName(26593, user.getLanguage()),serialid);
}else{
mapSerial.put(Util.formatMultiLang(kqShiftManagementComInfo.getSerial(serialid),""+user.getLanguage()),serialid);
}
}
Map<String,Object> params = new HashMap<>();
params.put("groupId",groupId);
params.put("isNoAccount","1");
List<String> kqGroupMembers = kqGroupBiz.getGroupMembers(params);
List<String> excludeidList = new ArrayList<>();
if(!Util.null2String(kqGroupComInfo.getExcludecount(groupId)).equals("1")) {
String excludeid = Util.null2String(kqGroupComInfo.getExcludeid(groupId));
if (excludeid.length() > 0) {
excludeidList = Util.splitString2List(excludeid,",");
}
}
for(String resourceid : kqGroupMembers){
// 排除无需考勤人员
if(excludeidList != null && excludeidList.contains(resourceid)) {
continue;
}
String workCode = Util.formatMultiLang(Util.null2String(resourceComInfo.getWorkcode(resourceid)),""+user.getLanguage());
String lastName = Util.formatMultiLang(Util.null2String(resourceComInfo.getLastname(resourceid)),""+user.getLanguage());
if(workCode.length()>0){
mapGroupMembersWorkCode.put(workCode,resourceid);
}else if(lastName.length()>0){
mapGroupMembersLastName.put(lastName,resourceid);
}
}
sql = " delete from kq_shiftschedule where groupid=? and isdelete='1' ";
rs.executeUpdate(sql,groupId);
sql = " select id, resourceid, kqdate from kq_shiftschedule where groupid=? ";
rs.executeQuery(sql,groupId);
while(rs.next()){
mapShiftSchedule.put(rs.getString("kqdate")+"|"+rs.getString("resourceid"),rs.getString("id"));
}
int firstRow = 6;
int firstCol = 3;
ImageFileManager manager = new ImageFileManager();
manager.getImageFileInfoById(Util.getIntValue(filename));
//Workbook workbook = WorkbookFactory.create(manager.getInputStream());
Workbook workbook = new XSSFWorkbook(manager.getInputStream());
for (int idx = 0; idx < workbook.getNumberOfSheets(); idx++) {
Sheet sheet = workbook.getSheetAt(idx);
if(sheet.getSheetName().indexOf("constraintDataSheet")>-1)continue;
Row row = null;
Cell cell = null;
row = sheet.getRow(firstRow);
lsColumn = new ArrayList();
for (int cellIndex = firstCol; cellIndex < row.getLastCellNum(); cellIndex++) {
cell = row.getCell((short) cellIndex);
lsColumn.add(Util.null2String(getCellValue(cell)).trim());
}
firstRow++;
for (int i = firstRow; firstRow<=sheet.getLastRowNum() && i <= sheet.getLastRowNum(); i++) {
row = sheet.getRow(i);
if (row == null) {
continue;
}
String workCode = Util.null2String(row.getCell(1));//编号
String lastName = Util.null2String(row.getCell(2));//姓名
if(workCode.length()==0 && lastName.length()==0){
continue;
}
String resourceId = Util.null2String(mapGroupMembersWorkCode.get(workCode));//人员id
if(resourceId.length()==0){
resourceId = Util.null2String(mapGroupMembersLastName.get(lastName));//人员id
}
if(resourceId.length()==0)continue;
for (int cellIndex = firstCol; cellIndex < row.getLastCellNum(); cellIndex++) {
cell = row.getCell((short) cellIndex);
if (cell == null) continue;
String serialId = "";
String serialName = Util.null2String(getCellValue(cell)).trim();
if(serialName.length()==0)continue;
String kqdate = Util.null2String(lsColumn.get(cellIndex-firstCol));
//if(weaver.common.DateUtil.timeInterval(kqdate,today)>0)continue;//今天之前的无需处理
serialId = Util.null2String(mapSerial.get(serialName));
if(serialId.length()==0)continue;
String id = Util.null2String(mapShiftSchedule.get(kqdate+"|"+resourceId));
if(id.length()>0){
param = new ArrayList<Object>();
param.add(serialId);
param.add(id);
paramUpdate.add(param);
}else{
param = new ArrayList<Object>();
param.add(kqdate);
param.add(serialId);
param.add(resourceId);
param.add(groupId);
paramInsert.add(param);
}
formatParams = new ArrayList<>();
formatParams.add(resourceId);
formatParams.add(kqdate);
lsFormatParams.add(formatParams);
checkSerialParams = new ArrayList<>();
checkSerialParams.add(resourceId);
checkSerialParams.add(kqdate);
checkSerialParams.add(serialId);
lscheckSerialParams.add(checkSerialParams);
}
}
sql = " update kq_shiftschedule set serialid=?, isDelete=0 where id = ? ";
for (int i = 0; paramUpdate != null && i < paramUpdate.size(); i++) {
List<Object> update_params = paramUpdate.get(i);
String serialid = Util.null2String(update_params.get(0));
String id = Util.null2String(update_params.get(1));
rs.executeUpdate(sql, serialid,id);
}
sql = "insert into kq_shiftschedule (kqdate,serialid,resourceid,groupid,isDelete) values(?,?,?,?,0)";
for (int i = 0; paramInsert != null && i < paramInsert.size(); i++) {
List<Object> insert_params = paramInsert.get(i);
String kqdate = Util.null2String(insert_params.get(0));
String serialid = Util.null2String(insert_params.get(1));
String resourceid = Util.null2String(insert_params.get(2));
String groupid = Util.null2String(insert_params.get(3));
rs.executeUpdate(sql, kqdate,serialid,resourceid,groupid);
}
}
//删除之前的排的班次,一天只能有一个班次
sql = " update kq_shiftschedule set isdelete =1 where (isdelete is null or isdelete <> '1') and resourceid = ? and kqdate = ? and groupid != "+groupId;
for (int i = 0; lsFormatParams != null && i < lsFormatParams.size(); i++) {
List<Object> delete_params = lsFormatParams.get(i);
String resourceid = Util.null2String(delete_params.get(0));
String kqdate = Util.null2String(delete_params.get(1));
rs.executeUpdate(sql, resourceid,kqdate);
}
sql = " update kq_shiftschedule set isdelete =1 where (isdelete is null or isdelete <> '1') and resourceid = ? and kqdate = ? and serialid != ? ";
for (int i = 0; lscheckSerialParams != null && i < lscheckSerialParams.size(); i++) {
List<Object> check_params = lscheckSerialParams.get(i);
String resourceid = Util.null2String(check_params.get(0));
String kqdate = Util.null2String(check_params.get(1));
String serialid = Util.null2String(check_params.get(2));
rs.executeUpdate(sql, resourceid,kqdate,serialid);
}
new KQShiftScheduleComInfo().removeCache();
//刷新报表数据
sql = " insert into kq_format_pool (resourceid, kqdate) values (?,?)";
bRs.executeBatchSql(sql, lsFormatParams);
KQGroupComInfo kQGroupComInfo = new KQGroupComInfo();
String auto_checkout = kQGroupComInfo.getAuto_checkout(groupId);
String auto_checkin = kQGroupComInfo.getAuto_checkin(groupId);
if("1".equalsIgnoreCase(auto_checkin) || "1".equalsIgnoreCase(auto_checkout)){
//如果开启了自动打卡,保存考勤组成员之后需要格式化下缓存
KQAutoCardTask kqAutoCardTask = new KQAutoCardTask();
kqAutoCardTask.initAutoCardTask(groupId);
}
retmap.put("status", "1");
} catch (Exception e) {
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(382661, user.getLanguage()));
writeLog(e);
}
return retmap;
}
@Override
public BizLogContext getLogContext() {
return null;
}
@Override
public List<BizLogContext> getLogContexts() {
return logger.getBizLogContexts();
}
/**
* /**
* excel
*
* @param cell
* @return
*/
public String getCellValue(Cell cell) {
String cellValue = "";
if (cell == null)
return "";
switch (cell.getCellType()) {
case BOOLEAN: // 得到Boolean对象的方法
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {// 先看是否是日期格式
SimpleDateFormat sft = new SimpleDateFormat("yyyy-MM-dd");
cellValue = String.valueOf(sft.format(cell.getDateCellValue())); // 读取日期格式
} else {
cellValue = String.valueOf(new Double(cell.getNumericCellValue())); // 读取数字
if (cellValue.endsWith(".0"))
cellValue = cellValue.substring(0, cellValue.indexOf("."));
}
break;
case FORMULA: // 读取公式
cellValue = cell.getCellFormula();
break;
case STRING: // 读取String
cellValue = cell.getStringCellValue();
break;
}
return cellValue;
}
}

@ -0,0 +1,136 @@
package com.engine.kq.entity;
import java.util.List;
import java.util.Map;
/***
*
*/
public class WorkTimeEntity {
private String groupId;//所属考勤组
private String groupName;//所属考勤组
private String kqType;//考勤类型
private String serialId;//班次
private Map<String,Object> shiftRuleInfo;//班次人性化规则
private List<TimeScopeEntity> signTime;//允许打卡时间
private List<TimeScopeEntity> workTime;//工作时间
private List<TimeScopeEntity> restTime;//休息时间
private int workMins;//工作时长
private String isAcross;//是否跨天
private String signstart;//自由工时开始打卡时间
private boolean isExclude;//无需考勤人员
private String calmethod;//自由班制计算方式
private int restShift;
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public String getKQType() {
return kqType;
}
public void setKQType(String kqType) {
this.kqType = kqType;
}
public String getSerialId() {
return serialId;
}
public void setSerialId(String serialId) {
this.serialId = serialId;
}
public Map<String, Object> getShiftRuleInfo() {
return shiftRuleInfo;
}
public void setShiftRuleInfo(Map<String, Object> shiftRuleInfo) {
this.shiftRuleInfo = shiftRuleInfo;
}
public List<TimeScopeEntity> getWorkTime() {
return workTime;
}
public void setWorkTime(List<TimeScopeEntity> workTime) {
this.workTime = workTime;
}
public List<TimeScopeEntity> getRestTime() {
return restTime;
}
public void setRestTime(List<TimeScopeEntity> 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<TimeScopeEntity> getSignTime() {
return signTime;
}
public void setSignTime(List<TimeScopeEntity> signTime) {
this.signTime = signTime;
}
public boolean getIsExclude() {
return isExclude;
}
public void setIsExclude(boolean isExclude) {
this.isExclude = isExclude;
}
public String getCalmethod() {
return calmethod;
}
public void setCalmethod(String calmethod) {
this.calmethod = calmethod;
}
public int getRestShift() {
return restShift;
}
public void setRestShift(int restShift) {
this.restShift = restShift;
}
}

@ -0,0 +1,633 @@
package com.engine.kq.util;
import com.alibaba.fastjson.JSONObject;
import com.engine.kq.biz.KQLeaveRulesBiz;
import com.engine.kq.biz.KQLeaveRulesComInfo;
import com.engine.kq.biz.KQShiftManagementComInfo;
import com.engine.kq.biz.KQWorkTime;
import com.engine.kq.biz.chain.cominfo.ShiftInfoCominfoBean;
import com.engine.kq.biz.chain.duration.NonDayUnitSplitChain;
import com.engine.kq.biz.chain.duration.NonHalfUnitSplitChain;
import com.engine.kq.biz.chain.duration.NonHourUnitSplitChain;
import com.engine.kq.biz.chain.duration.NonWholeUnitSplitChain;
import com.engine.kq.biz.chain.duration.NonWorkDurationChain;
import com.engine.kq.biz.chain.duration.WorkDayUnitSplitChain;
import com.engine.kq.biz.chain.duration.WorkDurationChain;
import com.engine.kq.biz.chain.duration.WorkHalfUnitSplitChain;
import com.engine.kq.biz.chain.duration.WorkHourUnitSplitChain;
import com.engine.kq.biz.chain.duration.WorkWholeUnitSplitChain;
import com.engine.kq.biz.chain.shiftinfo.ShiftInfoBean;
import com.engine.kq.enums.DurationTypeEnum;
import com.engine.kq.log.KQLog;
import com.engine.kq.wfset.bean.SplitBean;
import com.engine.kq.wfset.util.KQFlowUtil;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import weaver.common.StringUtil;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.report.schedulediff.HrmScheduleDiffUtil;
public class KQDurationCalculatorUtil extends BaseBean {
private KQLog kqLog = new KQLog();
private final String resourceid;
private String fromDate;
private String toDate;
private String fromTime;
private String toTime;
private String newLeaveType;
/**
*
* 1-
* 2-
* 3-
* 4-
*/
private String durationrule;
/**
* 1-
* 2-
*/
private String computingMode;
/**
*
*/
private String overtime_type;
private DurationTypeEnum durationTypeEnum;
//外部类的构造函数
private KQDurationCalculatorUtil(DurationParamBuilder build){
this.resourceid = build.resourceid;
this.fromDate = build.fromDate;
this.toDate = build.toDate;
this.fromTime = build.fromTime;
this.toTime = build.toTime;
this.newLeaveType = build.newLeaveType;
this.durationrule = build.durationrule;
this.computingMode = build.computingMode;
this.durationTypeEnum = build.durationTypeEnum;
this.overtime_type = build.overtime_type;
}
/**
*
* @param resourceid
* @param date
* @param containYesterday
* @return
*/
public static ShiftInfoBean getWorkTime(String resourceid, String date,boolean containYesterday){
User user = User.getUser(Util.getIntValue(resourceid), 0);
if(user == null){
return null;
}
return getWorkTime(user, date,containYesterday);
}
public static ShiftInfoBean getWorkTimeNew(String resourceid, String date,boolean containYesterday){
User user = User.getUser(Util.getIntValue(resourceid), 0);
if(user == null){
return null;
}
return getWorkTime(user, date, containYesterday, true, false);
}
/**
*
* @param resourceid
* @param date
* @param containYesterday
* @param isLog
* @return
*/
public static ShiftInfoBean getWorkTime(String resourceid, String date,boolean containYesterday,boolean isLog){
User user = User.getUser(Util.getIntValue(resourceid), 0);
if(user == null){
return null;
}
return getWorkTime(user, date,containYesterday,isLog);
}
public static ShiftInfoCominfoBean getShiftInfoCominfoBean(String resourceid, String date){
KQWorkTime kqWorkTime = new KQWorkTime();
Map<String, Object> kqWorkTimeMap = new HashMap<>();
ShiftInfoCominfoBean shiftInfoCominfoBean = kqWorkTime.getShiftInfoCominfoBean(resourceid, date);
return shiftInfoCominfoBean;
}
/**
* user
* @param user
* @param date
* @param containYesterday
* @param isLog
* @return
*/
public static ShiftInfoBean getWorkTime(User user, String date,boolean containYesterday,boolean isLog){
return getWorkTime(user, date, containYesterday, isLog, true);
}
public static ShiftInfoBean getWorkTime(User user, String date,boolean containYesterday,boolean isLog, boolean isUsedRestShift){
KQWorkTime kqWorkTime = new KQWorkTime();
Map<String, Object> kqWorkTimeMap = new HashMap<>();
kqWorkTimeMap = kqWorkTime.getWorkDuration(""+user.getUID(), date,containYesterday,isLog);
boolean isfree = "1".equalsIgnoreCase(Util.null2String(kqWorkTimeMap.get("isfree")));
if(isfree){
ShiftInfoBean shiftInfoBean = new ShiftInfoBean();
shiftInfoBean.setIsfree(true);
String signStart = Util.null2String(kqWorkTimeMap.get("signStart"));
String workMins = Util.null2String(kqWorkTimeMap.get("workMins"));
shiftInfoBean.setFreeSignStart(signStart);
shiftInfoBean.setFreeWorkMins(workMins);
shiftInfoBean.setSplitDate(date);
if(signStart.length() > 0 && workMins.length() > 0){
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm");
LocalTime signLocalTime = LocalTime.parse(signStart, dateTimeFormatter);
shiftInfoBean.setFreeSignEnd(signLocalTime.plusMinutes(Util.getIntValue(workMins)).format(dateTimeFormatter));
shiftInfoBean.setFreeSignMiddle(signLocalTime.plusMinutes(Util.getIntValue(workMins)/2).format(dateTimeFormatter));
}
return shiftInfoBean;
}else{
if(kqWorkTimeMap.get("shiftInfoBean") != null){
ShiftInfoBean shiftInfoBean = (ShiftInfoBean)kqWorkTimeMap.get("shiftInfoBean");
if(isUsedRestShift) {
int serialid = Util.getIntValue(Util.null2String(shiftInfoBean.getSerialid()), 0);
KQShiftManagementComInfo kQShiftManagementComInfo = new KQShiftManagementComInfo();
int restShift = StringUtil.parseToInt(kQShiftManagementComInfo.getRestShift(String.valueOf(serialid)), 0);
if(restShift == 1) {
return null;
}
}
return shiftInfoBean;
}else{
return null;
}
}
}
/**
* user
* @param user
* @param date
* @param containYesterday
* @return
*/
public static ShiftInfoBean getWorkTime(User user, String date,boolean containYesterday){
return getWorkTime(user, date, containYesterday, true);
}
public static Map<String, Object> getWorkButton(String resourceid, String date, boolean containYesterday){
User user = User.getUser(Util.getIntValue(resourceid), 0);
return getWorkButton(user,date,containYesterday);
}
public static Map<String, Object> getWorkButton(User user, String date, boolean containYesterday){
KQWorkTime kqWorkTime = new KQWorkTime();
Map<String, Object> kqWorkTimeMap = new HashMap<>();
kqWorkTimeMap = kqWorkTime.getWorkButton(""+user.getUID(), date,containYesterday);
return kqWorkTimeMap;
}
/**
*
* @return
*/
public Map<String,Object> getNonWorkDuration(){
Map<String,Object> 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<SplitBean> 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<String,Object> getWorkDuration(){
Map<String,Object> durationMap = new HashMap<>();
try{
if(!isValidate(fromDate,toDate,fromTime,toTime)){
durationMap.put("duration", "0.0");
return durationMap;
}
if(durationTypeEnum != DurationTypeEnum.COMMON_CAL){
kqLog.info("resourceid="+resourceid+",getWorkDuration:"+durationTypeEnum.getDurationType()+":fromDate:"+fromDate+":toDate:"+toDate+":fromTime:"+fromTime+":toTime:"+toTime+":durationrule:"+durationrule+":computingMode:"+computingMode);
}
//如果是加班
if(durationTypeEnum ==DurationTypeEnum.OVERTIME){
return getNonWorkDuration();
}
//时长
double D_Duration = 0.0;
//分钟数
double Min_Duration = 0.0;
SplitBean splitBean = new SplitBean();
splitBean.setFromDate(fromDate);
splitBean.setFromTime(fromTime);
splitBean.setToDate(toDate);
splitBean.setToTime(toTime);
splitBean.setResourceId(resourceid);
splitBean.setFromdatedb(fromDate);
splitBean.setTodatedb(toDate);
splitBean.setFromtimedb(fromTime);
splitBean.setTotimedb(toTime);
splitBean.setDurationrule(durationrule);
splitBean.setDurationTypeEnum(durationTypeEnum);
splitBean.setComputingMode(computingMode);
splitBean.setNewLeaveType(newLeaveType);
if("2".equalsIgnoreCase(computingMode)){
double oneDayHour = KQFlowUtil.getOneDayHour(durationTypeEnum,newLeaveType);
splitBean.setOneDayHour(oneDayHour);
if(durationTypeEnum == DurationTypeEnum.LEAVE){
//只有自然日 请假才有这个排除节假日、休息日的功能
splitBean.setFilterholidays(KQLeaveRulesBiz.getFilterHolidays(splitBean.getNewLeaveType()));
}
}
if(durationTypeEnum ==DurationTypeEnum.LEAVE || durationTypeEnum ==DurationTypeEnum.LEAVEBACK){
if(newLeaveType.length() > 0){
KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo();
String conversion = kqLeaveRulesComInfo.getConversion(newLeaveType);
splitBean.setConversion(conversion);
}
}
List<SplitBean> splitBeans = new ArrayList<>();
WorkDurationChain hourUnitSplitChain = new WorkHourUnitSplitChain(splitBeans);
WorkDurationChain dayUnitSplitChain = new WorkDayUnitSplitChain(splitBeans);
WorkDurationChain halfUnitSplitChain = new WorkHalfUnitSplitChain(splitBeans);
WorkDurationChain wholeUnitSplitChain = new WorkWholeUnitSplitChain(splitBeans);
//设置执行链
hourUnitSplitChain.setDurationChain(dayUnitSplitChain);
dayUnitSplitChain.setDurationChain(halfUnitSplitChain);
halfUnitSplitChain.setDurationChain(wholeUnitSplitChain);
//把初始数据设置进去
hourUnitSplitChain.handleDuration(splitBean);
kqLog.info("getWorkDuration--resourceid="+resourceid+",durationType="+durationTypeEnum.getDurationType()+",splitBeans="+ JSONObject.toJSONString(splitBeans));
//每一天的流程时长都在这里了,搞吧
for(SplitBean sb : splitBeans){
double durations = Util.getDoubleValue(sb.getDuration(), 0.0);
double min_durations = sb.getD_Mins();
D_Duration += durations;
Min_Duration += min_durations;
}
kqLog.info("getWorkDuration--resourceid=" + resourceid + ",durationType=" + durationTypeEnum.getDurationType() + ",D_Duration=" + D_Duration);
durationMap.put("duration", KQDurationCalculatorUtil.getDurationRound(""+D_Duration));
durationMap.put("min_duration", KQDurationCalculatorUtil.getDurationRound(""+Min_Duration));
kqLog.info("getWorkDuration--resourceid=" + resourceid + ",durationType=" + durationTypeEnum.getDurationType() + ",durationMap=" + durationMap.toString());
}catch (Exception e){
e.printStackTrace();
}
return durationMap;
}
/**
*
* @return false
*/
private boolean isValidate(String fromDate,String toDate,String fromTime,String toTime) {
if(fromDate.length() == 0 || toDate.length() == 0){
return false;
}
if(fromTime.length() == 0 || toTime.length() == 0){
return false;
}
DateTimeFormatter fullFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String fromDateTime = fromDate+" "+fromTime+":00";
String toDateTime = toDate+" "+toTime+":00";
LocalDateTime localFromDateTime = LocalDateTime.parse(fromDateTime,fullFormatter);
LocalDateTime localToDateTime = LocalDateTime.parse(toDateTime,fullFormatter);
if(localFromDateTime.isAfter(localToDateTime) || localFromDateTime.isEqual(localToDateTime)){
return false;
}
return true;
}
/**
*
* @param fromDate
* @param fromTime
* @param toDate
* @param toTime
* @param resourceid
* @return
*/
public Map<String,Object> 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<String,Object> 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<String,Object> 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<String,Object> 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<String,Object> 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<String,Object> 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<String,Object> 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);
}
}
}

File diff suppressed because it is too large Load Diff

@ -0,0 +1,148 @@
package com.engine.kq.util;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.Util;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* hansang
*
* @author wangj
* @version 1.00
* @Date 2023/9/12
*/
public class UtilKQHS {
/**
*
* @return
*/
public static boolean isLastYearChildcareLeave(String userid,String searchYear) {
boolean flag = false;
RecordSet rs = new RecordSet();
rs.executeQuery("select csrq from uf_jt where gx = 2 and ry = ? ORDER BY csrq desc limit 1",userid);
String csrq = "";
while (rs.next()){
csrq = Util.null2String(rs.getString("csrq"));
}
if(!"".equals(csrq)){
String year = Util.object2String(Util.getIntValue(csrq.substring(0,4))+3);
if(year.equals(searchYear)){
flag = true;
}
}
return flag;
}
/**
*
* @param userid
* @param searchDate
* @return
*/
public static String getLastDateChildcareLeave(String userid,String searchDate){
RecordSet rs = new RecordSet();
rs.executeQuery("select csrq from uf_jt where gx = 2 and ry = ? ORDER BY csrq desc limit 1",userid);
String date = "";
while (rs.next()){
String csrq = Util.null2String(rs.getString("csrq"));
if("".equals(csrq)){
date = searchDate;
}else{
try {
date = dealDate(csrq);
}catch (ParseException e) {
e.getMessage();
}
}
}
return date;
}
public static String dealDate(String date) throws ParseException {
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
Date dt=sdf.parse(date);
Calendar rightNow = Calendar.getInstance();
rightNow.setTime(dt);
rightNow.add(Calendar.YEAR,+3);//日期减1年
// rightNow.add(Calendar.MONTH,3);//日期加3个月
// rightNow.add(Calendar.DAY_OF_YEAR ,10);//日期加10天
Date dt1=rightNow.getTime();
Calendar calendar = Calendar.getInstance();
calendar.setTime(dt1);
calendar.add(Calendar.DAY_OF_MONTH, -1); //当前时间减去一天,即一天前的时间
// 获取减一天后的日期
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
String months = "";
String days = "";
if(month < 10){
months = "0"+month;
}else{
months = month+"";
}
if(day < 10){
days = "0"+day;
}else{
days = day + "";
}
return year+"-"+months+"-"+days;
}
//比较时间大小
public static boolean compareDate(String start, String end) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date1 = simpleDateFormat.parse(start);
Date date2 = simpleDateFormat.parse(end);
if (date1.getTime() < date2.getTime()) {
return true;
}
} catch (ParseException e) {
throw new RuntimeException(e);
}
return false;
}
// public static void main(String[] args) {
// System.out.println(handleAmount("7.60","7.89"));
// }
public static String handleAmount(String restAmount,String baseAmount){
String[] arr = restAmount.split("\\.");
String restPart0 = arr[0];
String restPart1 = arr[1];
System.out.println("restPart0:"+restPart0);
System.out.println("restPart1:"+restPart1);
double a = 0.00;
double base = Util.getDoubleValue(baseAmount);
if(Util.getIntValue(restPart1) > 50){
a = Util.getIntValue(restPart0) + 1.00;
if(a > base){
a = Util.getIntValue(restPart0) + 0.5;
}
}else{
a = Util.getIntValue(restPart0) + 0.00;
}
return Util.object2String(a);
}
}

@ -0,0 +1,471 @@
package com.engine.kq.wfset.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.engine.kq.biz.KQExitRulesBiz;
import com.engine.kq.biz.KQFormatData;
import com.engine.kq.biz.KQLeaveRulesBiz;
import com.engine.kq.biz.KQOvertimeRulesBiz;
import com.engine.kq.biz.KQTravelRulesBiz;
import com.engine.kq.enums.DurationTypeEnum;
import com.engine.kq.enums.KqSplitFlowTypeEnum;
import com.engine.kq.log.KQLog;
import com.engine.kq.wfset.bean.SplitBean;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.resource.ResourceComInfo;
import weaver.workflow.workflow.WorkflowRequestComInfo;
public class KQFlowUtil {
private KQLog kqLog = new KQLog();
/**
* bean
* @param splitBean
* @param rs1
* @param requestId
* @param rci
* @param workflowId
* @param durationTypeEnum
* @param key
* @param result
* @param datetimeFormatter
* @param uuid
*/
public boolean fillSplitBean(SplitBean splitBean, RecordSet rs1, String requestId,
ResourceComInfo rci, String workflowId, DurationTypeEnum durationTypeEnum, String key,
Map<String, String> result, DateTimeFormatter datetimeFormatter, String uuid){
boolean isFillRight = true;
String concort = "###" ;
int usedetail = Util.getIntValue(key.split(concort)[2], 0);
String tableDetailName= key.split(concort)[1] ;
String tableName= key.split(concort)[0] ;
String prefix = "";
String id = "dataId";
if(usedetail == 1){
prefix = "detail_";
id = "detailId";
}
boolean isLeaveBack = false;
if(durationTypeEnum == DurationTypeEnum.LEAVEBACK){
isLeaveBack = true;
}
boolean isProcessChange = false;
boolean isProcessDrawBack = false;
if(durationTypeEnum == DurationTypeEnum.PROCESSCHANGE){
isProcessChange = true;
String changetype = Util.null2s(rs1.getString("changetype"), "");
if("1".equalsIgnoreCase(changetype)){
//如果是撤销的话,没有开始日期时间和结束日期时间
isProcessDrawBack = true;
}
}
String resourceId = "";
//查询到的requestid
String requestId_rs = "";
String idVal = Util.null2s(rs1.getString(id), "0");
String fromDate = Util.null2s(rs1.getString(prefix+"fromDate"), "");
String toDate = Util.null2s(rs1.getString(prefix+"toDate"), "");
String fromTime = Util.null2s(rs1.getString(prefix+"fromTime"), "");
String toTime = Util.null2s(rs1.getString(prefix+"toTime"), "");
String durationDB = Util.null2s(rs1.getString(prefix+"duration"), "");
if(isLeaveBack || isProcessChange){
resourceId = Util.null2s(rs1.getString("resourceId"), "");
}else{
resourceId = Util.null2s(rs1.getString(prefix+"resourceId"), "");
}
if(Util.getIntValue(requestId,0) <= 0){
requestId_rs = Util.null2s(rs1.getString("requestId"), "0");
}
boolean isVal = checkActionValidate(result, fromDate, toDate, fromTime, toTime, datetimeFormatter);
if(isProcessDrawBack){
result.clear();
result.put("isProcessDrawBack", "1");
isVal = true;
}
if(!isVal){
isFillRight = false;
return isFillRight;
}
if(isLeaveBack){
LocalDateTime localFromDateTime = LocalDateTime.parse(fromDate+" "+fromTime,datetimeFormatter);
LocalDateTime localToDateTime = LocalDateTime.parse(toDate+" "+toTime,datetimeFormatter);
isFillRight = KQFlowLeaveBackUtil.leaveBackCheck(rs1 ,datetimeFormatter,prefix,localFromDateTime,localToDateTime,result);
if(!isFillRight){
return isFillRight;
}
}
if(isProcessChange){
isFillRight = KQFlowProcessChangeUtil.processChangeCheck(rs1 ,requestId_rs,result);
if(!isFillRight){
return isFillRight;
}
}
if(usedetail == 1){
splitBean.setDataId("0");
splitBean.setDetailId(idVal);
splitBean.setTablenamedb(tableDetailName);
}else{
splitBean.setDataId(idVal);
splitBean.setDetailId("0");
splitBean.setTablenamedb(tableName);
}
splitBean.setFromdatedb(fromDate);
splitBean.setFromtimedb(fromTime);
splitBean.setTodatedb(toDate);
splitBean.setTotimedb(toTime);
if(requestId_rs.length() > 0){
WorkflowRequestComInfo workflowRequestComInfo = new WorkflowRequestComInfo();
splitBean.setRequestId(requestId_rs);
splitBean.setWorkflowId(workflowRequestComInfo.getWorkflowId(requestId_rs));
}else{
splitBean.setRequestId(requestId);
splitBean.setWorkflowId(workflowId);
}
splitBean.setUsedetail(""+usedetail);
splitBean.setResourceId(resourceId);
splitBean.setSubcompanyid(Util.null2s(rci.getSubCompanyID(resourceId),"0"));
splitBean.setDepartmentid(Util.null2s(rci.getDepartmentID(resourceId),"0"));
splitBean.setJobtitle(Util.null2s(rci.getJobTitle(resourceId),"0"));
splitBean.setFromDate(fromDate);
splitBean.setFromTime(fromTime);
splitBean.setToDate(toDate);
splitBean.setToTime(toTime);
splitBean.setDurationDB(durationDB);
//默认记录的状态都为0
splitBean.setStatus("0");
splitBean.setDurationTypeEnum(durationTypeEnum);
switch (durationTypeEnum){
case LEAVE:
KQFlowLeaveUtil.bean4Leave(prefix,rs1,splitBean);
break;
case EVECTION:
KQFlowEvectionUtil.bean4Evection(prefix,rs1,splitBean);
break;
case OUT:
KQFlowOutUtil.bean4Out(splitBean);
break;
case OVERTIME:
KQFlowOvertimeUtil.bean4Overtime(prefix,rs1,splitBean);
break;
case LEAVEBACK:
KQFlowLeaveBackUtil.bean4LeaveBack(prefix,rs1,splitBean);
break;
case OTHER:
bean4Other(prefix,rs1,splitBean);
break;
case PROCESSCHANGE:
KQFlowProcessChangeUtil.bean4ProcessChange(prefix,rs1,splitBean);
break;
default:
break;
}
String computingMode = splitBean.getComputingMode();
String newLeaveType = splitBean.getNewLeaveType();
if("2".equalsIgnoreCase(computingMode)){
if(durationTypeEnum == DurationTypeEnum.PROCESSCHANGE){
double oneDayHour = getOneDayHour(splitBean.getDurationTypeEnum(),newLeaveType);
splitBean.setOneDayHour(oneDayHour);
}else{
double oneDayHour = getOneDayHour(durationTypeEnum,newLeaveType);
splitBean.setOneDayHour(oneDayHour);
}
}
return isFillRight;
}
private void bean4Other(String prefix, RecordSet rs1, SplitBean splitBean) {
String minimumUnit = "1";
String computingMode = "1";
splitBean.setDurationrule(minimumUnit);
splitBean.setComputingMode(computingMode);
}
/**
* /
* @param durationTypeEnum
* @param newLeaveType
* @return
*/
public static double getOneDayHour(DurationTypeEnum durationTypeEnum,String newLeaveType){
double oneDayHour = 0.0;
//TODO KQLeaveRulesBiz.getHoursToDay如果单位是小时的时候取不到日折算时长
switch (durationTypeEnum){
case LEAVE:
oneDayHour = Util.getDoubleValue(KQLeaveRulesBiz.getHoursToDay(newLeaveType), 0.0);
break;
case EVECTION:
oneDayHour = Util.getDoubleValue(KQTravelRulesBiz.getHoursToDay(), 0.0);
break;
case OUT:
oneDayHour = Util.getDoubleValue(KQExitRulesBiz.getHoursToDay(), 0.0);
break;
case OVERTIME:
oneDayHour = KQOvertimeRulesBiz.getHoursToDay();
break;
case LEAVEBACK:
oneDayHour = Util.getDoubleValue(KQLeaveRulesBiz.getHoursToDay(newLeaveType), 0.0);
break;
default:
}
return oneDayHour;
}
public boolean checkActionValidate(Map<String,String> result,String fromDate,String toDate,String fromTime,String toTime, DateTimeFormatter datetimeFormatter){
boolean isVal = true;
if(Util.null2String(fromDate,"").length() == 0 ||
Util.null2String(toDate,"").length() == 0 ||
Util.null2String(fromTime,"").length() == 0 ||
Util.null2String(toTime,"").length() == 0){
result.put("status", "-1");
result.put("message", ""+weaver.systeminfo.SystemEnv.getHtmlLabelName(10005411,weaver.general.ThreadVarLanguage.getLang())+"");
isVal = false;
return isVal;
}
if((fromDate+" "+fromTime).length() != 16 || (toDate+" "+toTime).length() != 16){
result.put("status", "-1");
result.put("message", ""+weaver.systeminfo.SystemEnv.getHtmlLabelName(10005412,weaver.general.ThreadVarLanguage.getLang())+""+(fromDate+" "+fromTime)+":"+(toDate+" "+toTime));
isVal = false;
return isVal;
}
LocalDate localFromDate = LocalDate.parse(fromDate);
LocalDate localToDate = LocalDate.parse(toDate);
LocalDateTime localFromDateTime = LocalDateTime.parse(fromDate+" "+fromTime,datetimeFormatter);
LocalDateTime localToDateTime = LocalDateTime.parse(toDate+" "+toTime,datetimeFormatter);
if(localFromDateTime.isAfter(localToDateTime)){
result.put("status", "-1");
result.put("message", ""+weaver.systeminfo.SystemEnv.getHtmlLabelName(511480,weaver.general.ThreadVarLanguage.getLang())+"");
isVal = false;
return isVal;
}
if (localFromDate.isAfter(localToDate)) {
result.put("status", "-1");
result.put("message", ""+weaver.systeminfo.SystemEnv.getHtmlLabelName(10005413,weaver.general.ThreadVarLanguage.getLang())+"");
isVal = false;
return isVal;
}
return isVal;
}
/**
*
* @param splitBeans
* @param flowTypeEnum
* @param rci
* @param result
* @param isForce
* @param requestId
* @param workflowId
* @param isUpgrade
* @throws Exception
*/
public void handleSplitFLowActionData(
List<SplitBean> splitBeans, KqSplitFlowTypeEnum flowTypeEnum,
ResourceComInfo rci, Map<String, String> result, boolean isForce, int requestId,
int workflowId,boolean isUpgrade) throws Exception{
RecordSet rs = new RecordSet();
RecordSet rs1 = new RecordSet();
Map<String,String> custome_map = Maps.newHashMap();
List<String> custome_field = Lists.newArrayList();
if(flowTypeEnum == KqSplitFlowTypeEnum.OVERTIME){
custome_field.add("overtime_type");
}
kqLog.info("splitBeans="+(null!=splitBeans?JSON.toJSON(null!=splitBeans):"is null"));
String batchSql = "insert into "+flowTypeEnum.getTablename()+" ("
+ "requestid,workflowid,dataid,detailid,resourceid,fromdate,fromtime,"
+ "todate,totime,newleavetype,duration,usedetail,durationrule,tablenamedb,fromdatedb,"
+ "fromtimedb,todatedb,totimedb,durationdb,status,belongDate,D_Mins,serialid,"
+ "changeType,subcompanyid,departmentid,jobtitle,companion,iscompanion"+getCustomField(custome_field,"field",null,
custome_map)+")"+
" values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?"+getCustomField(custome_field,"param",null,
custome_map)+") ";
List<List> params = new ArrayList<List>();
List<String> formateList = new ArrayList<>();
for(SplitBean bean : splitBeans){
List<Object> beanParams = new ArrayList<Object>();
beanParams.add(bean.getRequestId());
beanParams.add(bean.getWorkflowId());
beanParams.add(bean.getDataId());
beanParams.add(bean.getDetailId());
beanParams.add(bean.getResourceId());
beanParams.add(bean.getFromDate());
beanParams.add(bean.getFromTime());
beanParams.add(bean.getToDate());
beanParams.add(bean.getToTime());
beanParams.add(bean.getNewLeaveType());
beanParams.add(Util.null2s(bean.getDuration(),"0"));
beanParams.add(bean.getUsedetail());
beanParams.add(bean.getDurationrule());
beanParams.add(bean.getTablenamedb());
beanParams.add(bean.getFromdatedb());
beanParams.add(bean.getFromtimedb());
beanParams.add(bean.getTodatedb());
beanParams.add(bean.getTotimedb());
beanParams.add(bean.getDurationDB());
beanParams.add(bean.getStatus());
beanParams.add(bean.getBelongDate());
beanParams.add(bean.getD_Mins());
beanParams.add(bean.getSerialid());
beanParams.add(bean.getChangeType());
beanParams.add(bean.getSubcompanyid());
beanParams.add(bean.getDepartmentid());
beanParams.add(bean.getJobtitle());
beanParams.add(bean.getCompanion());
beanParams.add(bean.getIscompanion());
if(!custome_field.isEmpty()){
if(flowTypeEnum == KqSplitFlowTypeEnum.OVERTIME){
custome_map.put("overtime_type", bean.getOvertime_type());
}
getCustomField(custome_field, "value",beanParams,custome_map);
}
String format = bean.getResourceId()+"_"+bean.getBelongDate();
formateList.add(format);
params.add(beanParams);
if(flowTypeEnum == KqSplitFlowTypeEnum.EVECTION && false){
//qc898997 已经改成根据每个人的班次来计算了,这里就屏蔽了
KQFlowEvectionUtil kqFlowEvectionUtil = new KQFlowEvectionUtil();
String companion = Util.null2s(bean.getCompanion(), "");
if(companion.length() > 0){
kqFlowEvectionUtil.splitEvectionCompanion(companion,bean,params,rci,formateList);
}
}
}
kqLog.info("params="+ JSONObject.toJSONString(params));
if(!params.isEmpty()){
ReentrantLock lock = new ReentrantLock();
//先根据requestid删除中间表里的数据再做啥插入操作
try {
lock.lock();
String delSql = "delete from "+flowTypeEnum.getTablename()+" where requestid = "+requestId;
boolean isok1 = rs.executeUpdate(delSql);
kqLog.info("isok1="+ isok1);
for(int i = 0 ; i < params.size() ; i++){
List<Object> beanParams = params.get(i);
boolean isOk = rs1.executeUpdate(batchSql, beanParams);
kqLog.info("isOk="+ isOk);
if(!isOk){
delSql = "delete from "+flowTypeEnum.getTablename()+" where requestid = "+requestId;
rs.executeUpdate(delSql);
result.put("status", "-1");
result.put("message", ""+weaver.systeminfo.SystemEnv.getHtmlLabelName(10005408,weaver.general.ThreadVarLanguage.getLang())+":"+flowTypeEnum.getTablename()+""+weaver.systeminfo.SystemEnv.getHtmlLabelName(10005414,weaver.general.ThreadVarLanguage.getLang())+"");
kqLog.info("handleSplitFLowActionData:"+flowTypeEnum.getTablename()+"拆分保存失败:"+params);
return ;
}
}
} finally {
lock.unlock();
}
kqLog.info("handleSplitFLowActionData:formateList:"+formateList+":flowTypeEnum:"+flowTypeEnum);
for(String format: formateList){
kqLog.info("handleSplitFLowActionData:format:"+ JSON.toJSONString(format)+":flowTypeEnum:"+flowTypeEnum);
String[] formats = format.split("_");
if(!isUpgrade){
//考勤设置升级的话 流程数据就不需要格式化考勤了
new KQFormatData().formatKqDate(formats[0],formats[1]);
}
}
if(!isUpgrade){
if(isForce){
if(flowTypeEnum == KqSplitFlowTypeEnum.LEAVE){
//先在这里执行扣减动作
SplitActionUtil.handleLeaveAction(splitBeans,""+requestId);
//然后再把扣减的了数据更新下KQ_ATT_VACATION表
String updateFreezeSql = "update KQ_ATT_VACATION set status=0 where requestId=? and workflowId = ? ";
boolean isUpdate = rs.executeUpdate(updateFreezeSql,requestId,""+workflowId);
if(!isUpdate){
result.put("status", "-1");
result.put("message", (""+weaver.systeminfo.SystemEnv.getHtmlLabelName(82823,weaver.general.ThreadVarLanguage.getLang())+"action"+weaver.systeminfo.SystemEnv.getHtmlLabelName(10005361,weaver.general.ThreadVarLanguage.getLang())+""+updateFreezeSql+"(0,"+requestId+","+workflowId+")"));
kqLog.info("扣减action保存失败"+updateFreezeSql+"(0,"+requestId+","+workflowId+")");
return ;
}
}else if(flowTypeEnum == KqSplitFlowTypeEnum.OVERTIME){
// 强制归档,加班数据第一第二种规则都需要处理
SplitActionUtil.handleOverTimeAction(splitBeans, ""+requestId,true, "");
}
}else{
if(flowTypeEnum == KqSplitFlowTypeEnum.OVERTIME){
//正常归档的时候 单独针对加班规则的第一 第二种模式 生成加班数据
SplitActionUtil.handleOverTimeActionMode2(splitBeans, ""+requestId);
}
}
}else{
if(flowTypeEnum == KqSplitFlowTypeEnum.OVERTIME){
if(!splitBeans.isEmpty()){
for (SplitBean splitBean : splitBeans) {
String sql = "delete from kq_flow_overtime where requestid=? ";
rs.executeUpdate(sql, splitBean.getRequestId());
}
}
SplitActionUtil.handleOverTimeActionMode2(splitBeans, ""+requestId);
}
}
}else{
rs1.writeLog(flowTypeEnum.getTablename()+"生成的params是空");
return ;
}
}
/**
*
* @param custome_field
* @param key
* @param beanParams
* @param custome_map
* @return
*/
public String getCustomField(List<String> custome_field, String key, List<Object> beanParams,
Map<String, String> custome_map) {
String fieldValue = "";
if(!custome_field.isEmpty()){
for(int i = 0 ; i < custome_field.size() ; i++){
String tmp_value = Util.null2String(custome_field.get(i));
if(tmp_value.length() > 0){
if("field".equalsIgnoreCase(key)){
fieldValue += ","+tmp_value;
}else if("param".equalsIgnoreCase(key)){
fieldValue += ",?";
}else if("value".equalsIgnoreCase(key)){
String value = custome_map.get(tmp_value);
beanParams.add(value);
}
}
}
}
return fieldValue;
}
}

@ -0,0 +1,42 @@
package com.engine.leshanvc.cmd;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.User;
import java.util.HashMap;
import java.util.Map;
/**
* @Author weaver_cl
* @Description:
* @Date 2023/2/21
* @Version V1.0
**/
public class EntryWorkflowSaveEventCmd extends AbstractCommonCommand<Map<String, Object>> {
public EntryWorkflowSaveEventCmd(Map<String, Object> params, User user) {
this.user = user;
this.params = params;
}
@Override
public BizLogContext getLogContext() {
return null;
}
@Override
public Map<String, Object> execute(CommandContext commandContext) {
Map<String, Object> apidatas = new HashMap<>(16);
RecordSet rs = new RecordSet();
String tableName = Util.null2String(params.get("tableName"));
String status = Util.null2String(params.get("status"));
String billId = Util.null2String(params.get("billId"));
rs.executeUpdate("update "+tableName+" set rzzt = ? where id = ?",status,billId);
apidatas.put("msg","success");
return apidatas;
}
}

@ -0,0 +1,60 @@
package com.engine.leshanvc.cmd;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.kq.biz.chain.shiftinfo.ShiftInfoBean;
import com.engine.kq.util.KQDurationCalculatorUtil;
import weaver.hrm.User;
import weaver.wechat.util.Utils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* @Author weaver_cl
* @Description:
* @Date 2023/3/3
* @Version V1.0
**/
public class KqWorkflowRangeLimitCmd extends AbstractCommonCommand<Map<String, Object>> {
public KqWorkflowRangeLimitCmd(Map<String, Object> params, User user) {
this.user = user;
this.params = params;
}
@Override
public BizLogContext getLogContext() {
return null;
}
@Override
public Map<String, Object> execute(CommandContext commandContext) {
Map<String, Object> data = new HashMap<>(16);
boolean result = false;
String resourceId = Utils.null2String(params.get("resourceId"));
String fromDate = Utils.null2String(params.get("fromDate"));
String fromTime = Utils.null2String(params.get("fromTime"));
String toDate = Utils.null2String(params.get("toDate"));
String toTime = Utils.null2String(params.get("toTime"));
User user1 = new User();
user1.setUid(Integer.valueOf(resourceId));
ShiftInfoBean shiftInfoBean = KQDurationCalculatorUtil.getWorkTime(user1, fromDate, false, false);
ShiftInfoBean shiftInfoBean1 = KQDurationCalculatorUtil.getWorkTime(user1, toDate, false, false);
if (Objects.nonNull(shiftInfoBean) && Objects.nonNull(shiftInfoBean1)) {
List<String[]> workAcrossTime = shiftInfoBean.getWorkAcrossTime();
List<String[]> workAcrossTime1 = shiftInfoBean1.getWorkAcrossTime();
if (fromTime.compareTo(workAcrossTime.get(0)[0]) >= 0 && fromTime.compareTo(workAcrossTime.get(0)[1]) < 0
&& toTime.compareTo(workAcrossTime1.get(0)[0]) > 0 && toTime.compareTo(workAcrossTime1.get(0)[1]) <= 0) {
result = true;
}
}
data.put("result",result);
return data;
}
}

@ -0,0 +1,56 @@
package com.engine.leshanvc.cmd;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import lombok.SneakyThrows;
import weaver.conn.RecordSet;
import weaver.hrm.User;
import weaver.hrm.resource.ResourceComInfo;
import weaver.wechat.util.Utils;
import java.util.HashMap;
import java.util.Map;
/**
* @Author weaver_cl
* @Description:
* @Date 2023/3/8
* @Version V1.0
**/
public class WorkflowCheckCmd extends AbstractCommonCommand<Map<String, Object>> {
public WorkflowCheckCmd(Map<String, Object> params, User user) {
this.user = user;
this.params = params;
}
@Override
public BizLogContext getLogContext() {
return null;
}
@SneakyThrows
@Override
public Map<String, Object> execute(CommandContext commandContext) {
Map<String, Object> data = new HashMap<>(16);
String workflowId = Utils.null2String(params.get("workflowId"));
String resourceId = Utils.null2String(params.get("resourceId"));
String requestId = Utils.null2String(params.get("requestid"));
RecordSet rs = new RecordSet();
ResourceComInfo resourceComInfo = new ResourceComInfo();
rs.executeQuery("select requestname,creater from workflow_requestbase where workflowid = ? and creater = ? " +
" and requestid != ? and currentnodetype not in (0,3)",workflowId,resourceId,requestId);
if (rs.next()) {
String requestName = Utils.null2String(rs.getString("requestname"));
String creater = Utils.null2String(rs.getString("creater"));
String lastname = resourceComInfo.getLastname(creater);
data.put("result",true);
data.put("requestName",requestName);
data.put("lastname",lastname);
}
return data;
}
}

@ -0,0 +1,42 @@
package com.engine.leshanvc.enums;
/**
* @Author weaver_cl
* @Description:
* @Date 2023/2/13
* @Version V1.0
**/
public enum MessageContentEnum {
ONE(3,3,11),
TWO(11,11,36),
THREE(36,36,60),
FOUR(60,60,80),
FIVE(80,80,12)
;
private int value;
private int min;
private int max;
MessageContentEnum(int value, int min, int max) {
this.value = value;
this.min = min;
this.max = max;
}
public int getValue() {
return value;
}
public int getMin() {
return min;
}
public int getMax() {
return max;
}
}

@ -0,0 +1,22 @@
package com.engine.leshanvc.exception;
/**
* @Author weaver_cl
* @Description:
* @Date 2023/2/21
* @Version V1.0
**/
public class CustomizeRunTimeException extends RuntimeException{
public CustomizeRunTimeException(String message) {
super(message);
}
public CustomizeRunTimeException(Throwable cause) {
super(cause);
}
public CustomizeRunTimeException(String message, Throwable cause) {
super(message, cause);
}
}

@ -0,0 +1,21 @@
package com.engine.leshanvc.service;
import java.util.Map;
/**
* @Author ml
* @Date 2023/3/1 11:13
* @Description This is description of class
* @Since version-1.0
*/
public interface EntryCommitFormModeService {
/**
* @Author ml
* @Date 2023/3/1 11:14
* @Description
* @Param [params]
* @Return java.util.Map<java.lang.String,java.lang.Object>
*/
Map<String,Object> entryCommit(Map<String, Object> params);
}

@ -0,0 +1,19 @@
package com.engine.leshanvc.service;
import java.util.Map;
/**
* @Author weaver_cl
* @Description:
* @Date 2023/2/21
* @Version V1.0
**/
public interface EntryWorkflowSaveEventService {
/**
* uf_rzgl
* @param params
* @return
*/
Map<String,Object> changeStatus(Map<String, Object> params);
}

@ -0,0 +1,19 @@
package com.engine.leshanvc.service;
import java.util.Map;
/**
* @Author weaver_cl
* @Description:
* @Date 2023/3/3
* @Version V1.0
**/
public interface KqWorkflowRangeLimitService {
/**
*
* @param params
* @return
*/
Map<String,Object> rangeLimit(Map<String, Object> params);
}

@ -0,0 +1,19 @@
package com.engine.leshanvc.service;
import java.util.Map;
/**
* @author:dxfeng
* @createTime: 2023/04/19
* @version: 1.0
*/
public interface LeaverWorkflowService {
/**
*
*
* @param params
* @return
*/
Map<String,Object> getEndDate(Map<String, Object> params);
}

@ -0,0 +1,13 @@
package com.engine.leshanvc.service;
import java.util.Map;
/**
* @Author ml
* @Date 2023/3/16 9:22
* @Since version-1.0
*/
public interface LzWorkflowManageService {
Map<String,Object> getHrmInfoByLinSup(Map<String, Object> params);
}

@ -0,0 +1,17 @@
package com.engine.leshanvc.service;
import java.util.Map;
/**
* @author:dxfeng
* @createTime: 2023/04/20
* @version: 1.0
*/
public interface ResourceCardService {
/**
*
*
* @param params
*/
void editResourceCard(Map<String, Object> params);
}

@ -0,0 +1,39 @@
package com.engine.leshanvc.service;
import java.util.Map;
/**
* @Author ml
* @Date 2023/3/29 11:22
* @Description 线
* @Since version-1.0
*/
public interface SyncXcDataService {
/**
* @Author ml
* @Date 2023/3/29 11:22
* @Description 线
* @Param []
* @Return java.util.Map<java.lang.String,java.lang.Object>
*/
Map<String ,Object> syncXcData(Map<String, Object> params);
/**
* @Author ml
* @Date 2023/4/4 17:18
* @Description
* @Param [params]
* @Return java.util.Map<java.lang.String, java.lang.Object>
*/
Map<String, Object> nonOfficeUpload(Map<String, Object> params);
/**
* @Author ml
* @Date 2023/4/6 17:31
* @Description
* @Param [params]
* @Return java.lang.Long
*/
Map<String, Object> saveIDCard(Map<String, Object> params);
}

@ -0,0 +1,19 @@
package com.engine.leshanvc.service;
import java.util.Map;
/**
* @Author weaver_cl
* @Description:
* @Date 2023/3/8
* @Version V1.0
**/
public interface WorkflowCheckService {
/**
*
* @param params
* @return
*/
Map<String,Object> workflowController(Map<String, Object> params);
}

@ -0,0 +1,247 @@
package com.engine.leshanvc.service.impl;
import com.engine.core.impl.Service;
import com.engine.leshanvc.service.EntryCommitFormModeService;
import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.PasswordUtil;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.interfaces.leshanvc.workflow.entity.FieldMapEntity;
import weaver.interfaces.leshanvc.workflow.util.ResourceSyncUtil;
import weaver.soa.workflow.request.Property;
import weaver.systeminfo.SystemEnv;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
/**
* @Author ml
* @Date 2023/3/3 17:46
* @Description This is description of class
* @Since version-1.0
*/
public class EntryCommitFormModeServiceImpl extends Service implements EntryCommitFormModeService {
BaseBean baseBean = new BaseBean();
@Override
public Map<String, Object> entryCommit(Map<String, Object> params) {
Map<String, Object> result = new HashMap<>();
RecordSet rs = new RecordSet();
// 查询字段预处理
List<String> fieldNameList = new ArrayList<>();
String fieldsSql = "select wf_field,ec_type from uf_hs_field_map";
baseBean.writeLog("fieldsSql:" + fieldsSql);
rs.executeQuery(fieldsSql);
while (rs.next()) {
fieldNameList.add(rs.getString("wf_field"));
}
String fieldNames = fieldNameList.stream().collect(Collectors.joining(","));
List<Property> propertyList = new ArrayList<>();
Property[] properties;
String sql = "select " + fieldNames + " from uf_rzgl where id=" + Util.null2String(params.get("id"));
baseBean.writeLog("动态拼接字段查询sql:" + sql);
rs.executeQuery(sql);
if (rs.next()) {
for (String s : fieldNameList) {
Property property = new Property();
property.setName(s);
property.setValue(rs.getString(s));
propertyList.add(property);
}
}
if (propertyList.size() == 0) {
result.put("type", 2);
result.put("msg", "未查询到入职管理表中对应数据");
baseBean.writeLog("未查询到入职管理表中对应数据");
return result;
}
properties = new Property[propertyList.size()];
properties = propertyList.toArray(properties);
// 根据手机号+姓名校验数据存在
String sjhm = null;
String xm = null;
for (Property property : properties) {
if ("sjhm".equals(property.getName())) {
sjhm = property.getValue();
}
if ("xm".equals(property.getName())) {
xm = property.getValue();
}
}
rs.execute("select * from hrmresource where mobile='" + sjhm + "' and lastname='" + xm + "'");
if (rs.next()) {
result.put("type", 2);
result.put("msg", "当前人员已存在,无法重复添加");
baseBean.writeLog("当前人员已存在,无法重复添加");
return result;
}
// 获取人员主表(系统表)字段
String sysSql = "select ec_field,wf_field,ec_type from uf_hs_field_map where ec_type=0";
rs.executeQuery(sysSql);
// 系统字段
Map<String, String> fieldsMap = new HashMap<>();
StringBuilder updateSysFields = new StringBuilder();
while (rs.next()) {
fieldsMap.put(rs.getString("wf_field"), rs.getString("ec_field"));
}
//取系统字段对应字段数据
Map<String, Object> resMap = new HashMap<>();
for (Property p : properties) {
if (fieldsMap.containsKey(p.getName())) {
resMap.put(fieldsMap.get(p.getName()), p.getValue());
baseBean.writeLog("resMap参数值"+fieldsMap.get(p.getName()) + "++" + p.getValue());
updateSysFields.append(fieldsMap.get(p.getName())).append("=").append("'").append(p.getValue()).append("'").append(",");
}
}
baseBean.writeLog("updateSysFields="+updateSysFields);
boolean flag = false;
//人员表数据插入
resMap.put("status","0");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String currentDate = sdf.format(new Date());
resMap.put("companystartdate",currentDate);
boolean canEdit = HrmUserVarify.checkUserRight("HrmResourceEdit:Edit", user);
if (!canEdit) {
result.put("msg", "人员新增失败,当前用户没有权限");
baseBean.writeLog("人员新增失败,当前用户没有权限");
return result;
}
Map<String, Object> retMap = ResourceSyncUtil.addResource(user, resMap);
if (!"1".equals(retMap.get("status"))) {
result.put("type", 2);
result.put("msg", "人员新增失败,请联系管理员");
baseBean.writeLog("人员新增失败,请联系管理员");
return result;
}
//查询拼接
String defId = "";
//查询新增成功的人员id
String queryHrmSql = "select id, workcode from hrmresource h where h.lastname = '" + resMap.get("lastname") + "' and h.mobile = '" + resMap.get("mobile") + "'";
flag = rs.executeQuery(queryHrmSql);
RecordSet recordSet = new RecordSet();
baseBean.writeLog("查询新增人员sql" + queryHrmSql);
if (rs.next()) {
defId = rs.getString("id");
String encrptPassword = "";
String salt = "";
if (org.apache.commons.lang3.StringUtils.isNotBlank(rs.getString("workcode"))) {
String[] encrypts = PasswordUtil.encrypt(rs.getString("workcode"));
encrptPassword = encrypts[0];
salt = encrypts[1];
}
String updateSql = "update hrmresource set "+updateSysFields+" loginid='" + rs.getString("workcode") + "',password='" + encrptPassword + "',salt='" + salt + "',certificatenum='"+Util.null2String(resMap.get("certificatenum"))+"' where id=" + defId;
recordSet.execute(updateSql);
} else {
result.put("type", 2);
result.put("msg", "未查到对应人员Id请联系管理员");
baseBean.writeLog("未查到对应人员Id请联系管理员");
return result;
}
Map<String, String> defMap;
rs.execute("select DISTINCT(ec_type) as ec_type from uf_hs_field_map where ec_type!=0");
List<String> ecTypes = new ArrayList<>();
while (rs.next()) {
ecTypes.add(rs.getString("ec_type"));
}
// 自定义表数据插入
for (String s : ecTypes) {
defMap = getFields(s, properties);
if (defMap != null) {
String defFields = "id, " + defMap.get("defFields");
String defFieldsValue = defId + ", " + defMap.get("defFieldsValue");
String insertSql = "insert into cus_fielddata(" + defFields + ") values (" + defFieldsValue + ")";
flag = rs.execute(insertSql);
if (!flag) {
recordSet.execute("delete from hrmresource where id=" + defId);
recordSet.execute("delete from cus_fielddata where id=" + defId);
result.put("type", 2);
result.put("msg", "自定义字段类型" + s + "数据插入失败,请联系管理员检查字段");
baseBean.writeLog("自定义字段类型" + s + "数据插入失败,请联系管理员检查字段");
return result;
}
}
}
//修改建模表中人员状态
if (flag) {
recordSet.execute("update uf_rzgl set rzzt='3' where xm='" + resMap.get("lastname") + "' and sfzh='" + resMap.get("certificatenum") + "'");
result.put("type", 3);
result.put("msg", "入职提交成功!");
baseBean.writeLog("入职提交成功!");
}
return result;
}
/**
*
* @param type
* @param properties
*/
private Map<String,String> getFields(String type,Property[] properties) {
String ecType = "1";
switch (type){
case "2":
ecType = "-1";
break;
case "3":
ecType = "1";
break;
case "4":
ecType = "3";
break;
default: break;
}
RecordSet rs = new RecordSet();
List<FieldMapEntity> fieldsList = new ArrayList<>();
List<Property> propertyListWf = new ArrayList<>();
Map<String,String> fieldsMapDef = new HashMap<>();
// 自定义表字段
String defSql = "select ec_field,wf_field,ec_type from uf_hs_field_map where ec_type='" + type +"'";
rs.execute(defSql);
while (rs.next()) {
FieldMapEntity fieldMapEntity = new FieldMapEntity();
fieldMapEntity.setEcField(rs.getString("ec_field"));
fieldMapEntity.setWfField(rs.getString("wf_field"));
fieldMapEntity.setEcType(rs.getString("ec_type"));
fieldsList.add(fieldMapEntity);
Property property = new Property();
property.setName(rs.getString("wf_field"));
propertyListWf.add(property);
}
if (fieldsList.size()<1){
return null;
}
// 拼接sql字段
String defFields = fieldsList.stream().map(FieldMapEntity::getEcField).collect(Collectors.joining(","));
defFields = " scope, scopeid," + defFields;
//交集字段和数据
List<Property> propertyListFront = Arrays.asList(properties);
Map<String, Property> frontMap = propertyListFront.stream().collect(Collectors.toMap(Property::getName,(p) -> p));
for (FieldMapEntity f : fieldsList) {
if (frontMap.containsKey(f.getWfField())) {
f.setEcValue(Util.null2String(frontMap.get(f.getWfField()).getValue()));
}
}
String defFieldsValue2 = fieldsList.stream().map(fieldMapEntity -> StringUtils.isBlank(fieldMapEntity.getEcValue()) ? "null" : "'"+fieldMapEntity.getEcValue()+"'").collect(Collectors.joining(","));
System.out.println(defFieldsValue2);
List<Property> propertyListBack = propertyListFront.stream()
.filter(property -> propertyListWf.stream()
.map(Property::getName)
.anyMatch(name -> Objects.equals(property.getName(), name)))
.collect(Collectors.toList());
String defFieldsValue = propertyListBack.stream().map(property -> "".equals(property.getValue()) ? "null" : property.getValue()).collect(Collectors.joining(","));
defFieldsValue2 = " 'HrmCustomFieldByInfoType', " + ecType + "," + defFieldsValue2;
Map<String ,String> resFieldMap = new HashMap<>();
resFieldMap.put("defFields",defFields);
resFieldMap.put("defFieldsValue",defFieldsValue2);
return resFieldMap;
}
}

@ -0,0 +1,21 @@
package com.engine.leshanvc.service.impl;
import com.engine.core.impl.Service;
import com.engine.leshanvc.cmd.EntryWorkflowSaveEventCmd;
import com.engine.leshanvc.service.EntryWorkflowSaveEventService;
import java.util.Map;
/**
* @Author weaver_cl
* @Description:
* @Date 2023/2/21
* @Version V1.0
**/
public class EntryWorkflowSaveEventServiceImpl extends Service implements EntryWorkflowSaveEventService {
@Override
public Map<String, Object> changeStatus(Map<String, Object> params) {
return commandExecutor.execute(new EntryWorkflowSaveEventCmd(params, user));
}
}

@ -0,0 +1,21 @@
package com.engine.leshanvc.service.impl;
import com.engine.core.impl.Service;
import com.engine.leshanvc.cmd.KqWorkflowRangeLimitCmd;
import com.engine.leshanvc.service.KqWorkflowRangeLimitService;
import java.util.Map;
/**
* @Author weaver_cl
* @Description:
* @Date 2023/3/3
* @Version V1.0
**/
public class KqWorkflowRangeLimitServiceImpl extends Service implements KqWorkflowRangeLimitService {
@Override
public Map<String, Object> rangeLimit(Map<String, Object> params) {
return commandExecutor.execute(new KqWorkflowRangeLimitCmd(params, user));
}
}

@ -0,0 +1,92 @@
package com.engine.leshanvc.service.impl;
import com.engine.core.impl.Service;
import com.engine.leshanvc.service.LeaverWorkflowService;
import com.engine.leshanvc.util.HsDateUtil;
import org.apache.commons.lang3.StringUtils;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.Util;
import java.util.HashMap;
import java.util.Map;
/**
* @author:dxfeng
* @createTime: 2023/04/19
* @version: 1.0
*/
public class LeaverWorkflowServiceImpl extends Service implements LeaverWorkflowService {
private static final String DAY_SHIFT_ID = "2";
@Override
public Map<String, Object> getEndDate(Map<String, Object> params) {
Map<String, Object> returnMap = new HashMap<>(16);
String newLeaveType = Util.null2String(params.get("newLeaveType"));
String resourceId = Util.null2String(params.get("resourceId"));
String fromDate = Util.null2String(params.get("fromDate"));
String startTime = "";
String endTime = "";
String viewAttr = "1";
Boolean includeHoliday = null;
if (StringUtils.isBlank(fromDate)) {
fromDate = DateUtil.getCurrentDate();
}
RecordSet rs = new RecordSet();
String sql = "select times,onoffworktype,record from kq_shiftonoffworksections where serialid = ? order by record";
rs.executeQuery(sql, DAY_SHIFT_ID);
while (rs.next()) {
if ("start".equalsIgnoreCase(rs.getString("onoffworktype")) && "0".equals(rs.getString("record"))) {
startTime = rs.getString("times");
} else if ("end".equalsIgnoreCase(rs.getString("onoffworktype"))) {
endTime = rs.getString("times");
}
}
// 根据白名单,判断结束时间是否可以自行调整
sql = "select * from uf_xjlx where qjlx = ? and qjr = ? and sfqy = 1 ";
rs.executeQuery(sql, newLeaveType, resourceId);
if (rs.next()) {
viewAttr = "3";
}
// 根据假期类型,判断是否包含节假日
switch (newLeaveType) {
// 陪产假、婚假、丧假
case "9":
case "32":
case "35":
includeHoliday = true;
break;
// 产假、产假(剖腹产顺延)、产假(多胞胎顺延)
case "8":
case "17":
case "18":
includeHoliday = false;
break;
default:
viewAttr = "3";
break;
}
Integer holidayAmount = HsDateUtil.getHolidayAmount(resourceId, newLeaveType, fromDate);
String endDate;
if (null != includeHoliday && holidayAmount != 0) {
endDate = HsDateUtil.addDay(resourceId, holidayAmount, fromDate, includeHoliday);
} else {
endDate = "";
viewAttr = "3";
}
returnMap.put("endDate", endDate);
returnMap.put("endTime", endTime);
returnMap.put("startDate", fromDate);
returnMap.put("startTime", startTime);
returnMap.put("viewAttr", viewAttr);
return returnMap;
}
}

@ -0,0 +1,269 @@
package com.engine.leshanvc.service.impl;
import com.engine.core.impl.Service;
import com.engine.leshanvc.service.LzWorkflowManageService;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class LzWorkflowManageServiceImpl extends Service implements LzWorkflowManageService {
BaseBean baseBean = new BaseBean();
@Override
public Map<String, Object> getHrmInfoByLinSup(Map<String, Object> params) {
Map<String,Object> data = new HashMap<>();
String lineSup = Util.null2String(params.get("userid"));
List<HrmInfo> hrmInfoList = new ArrayList<>();
RecordSet rs = new RecordSet();
rs.execute("select a.id,b.lastname,b.departmentid,field35,jobtitle,field102,xnfzmc,b.workcode,c.departmentname,d.jobtitlename from cus_fielddata a \n" +
"inner join hrmresource b on a.id=b.id " +
"left join hrmdepartment c ON b.DEPARTMENTID=c.id\n" +
"left join hrmjobtitles d on b.JOBTITLE=d.ID \n" +
"left join uf_xlfz e on a.field102 =e.xnfzbm \n" +
"where scope ='HrmCustomFieldByInfoType' and b.status < 4\n" +
"and scopeid ='-1' and field89='"+lineSup+"'");
while (rs.next()) {
String userId = rs.getString("id");
String bm = rs.getString("departmentid");
String zjj = rs.getString("field35");
String gw = rs.getString("jobtitle");
String xnfz = rs.getString("field102");
String xnfzmc = rs.getString("xnfzmc");
String gh = rs.getString("workcode");
String departmentname = rs.getString("departmentname");
String jobtitlename = rs.getString("jobtitlename");
String dyyljjbxs = getJBTimes(userId);
String dyljjbcexs = getJbCHETimes(bm,zjj,gw);
String sfgpczg = getSfgpczg(bm,zjj,gw);
hrmInfoList.add(new HrmInfo(userId,rs.getString("lastname"),bm,dyyljjbxs,dyljjbcexs,gh,gw,sfgpczg,xnfz,xnfzmc,zjj,departmentname,jobtitlename));
}
data.put("data",hrmInfoList);
return data;
}
/**
*
*/
String getJBTimes(String userId){
RecordSet recordSet = new RecordSet();
recordSet.executeQuery("select sum(cast(duration_min as decimal(18,4)))/60 jbtimes \n" +
"from kq_flow_overtime b\n" +
"where date_format(b.belongdate,'%Y-%m')=date_format(curdate(),'%Y-%m') and b.resourceid=? ",userId);
String jbTimes = "";
if(recordSet.next()){
jbTimes = Util.null2String(recordSet.getString("jbtimes"));
}
return jbTimes;
}
/**
*
*/
String getJbCHETimes(String bm,String zjj,String gw){
RecordSet recordSet = new RecordSet();
recordSet.executeQuery("select a.dyljjbcexs from uf_jbfjsp a where a.bm =? " +
"and a.zjj=? and gw=? " +
"union all select 500 ",bm,zjj,gw);
String dyljjbcexs = "";
if (recordSet.next()) {
dyljjbcexs = Util.null2String(recordSet.getString("dyljjbcexs"));
}
return dyljjbcexs;
}
/**
* PC
*/
public String getSfgpczg(String bm,String zjj,String gw){
String sfgpczg = "";
RecordSet rs = new RecordSet();
rs.executeQuery(" select sfgpczg from uf_jbfjsp " +
" where bm=? and zjj=? and gw=? ",new Object[]{bm,zjj,gw});
if (rs.next()) {
sfgpczg = Util.null2String(rs.getString("sfgpczg"));
}
return sfgpczg;
}
private static class HrmInfo {
/**
* id
*/
private String id;
/**
*
*/
private String lastName;
/**
* id
*/
private String departmentId;
/**
*
*/
private String dyyljjbxs;
/**
*
*/
private String dyljjbcexs;
/**
*
*/
private String gh;
/**
*
*/
private String gw;
/**
* pc
*/
private String sfgpczg;
/**
* 线
*/
private String xnfz;
/**
* 线
*/
private String xnfzmc;
private String zjj;
private String deptName;
private String jobTitleName;
public HrmInfo(String id, String lastName, String departmentId, String dyyljjbxs, String dyljjbcexs, String gh, String gw,String sfgpczg, String xnfz,String xnfzmc, String zjj, String deptName, String jobTitleName) {
this.id = id;
this.lastName = lastName;
this.departmentId = departmentId;
this.dyyljjbxs = dyyljjbxs;
this.dyljjbcexs = dyljjbcexs;
this.gh = gh;
this.gw = gw;
this.sfgpczg = sfgpczg;
this.xnfz = xnfz;
this.xnfzmc = xnfzmc;
this.zjj = zjj;
this.deptName = deptName;
this.jobTitleName = jobTitleName;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getDepartmentId() {
return departmentId;
}
public void setDepartmentId(String departmentId) {
this.departmentId = departmentId;
}
public String getDyyljjbxs() {
return dyyljjbxs;
}
public void setDyyljjbxs(String dyyljjbxs) {
this.dyyljjbxs = dyyljjbxs;
}
public String getDyljjbcexs() {
return dyljjbcexs;
}
public void setDyljjbcexs(String dyljjbcexs) {
this.dyljjbcexs = dyljjbcexs;
}
public String getGh() {
return gh;
}
public void setGh(String gh) {
this.gh = gh;
}
public String getGw() {
return gw;
}
public void setGw(String gw) {
this.gw = gw;
}
public String getSfgpczg() {
return sfgpczg;
}
public void setSfgpczg(String sfgpczg) {
this.sfgpczg = sfgpczg;
}
public String getXnfz() {
return xnfz;
}
public void setXnfz(String xnfz) {
this.xnfz = xnfz;
}
public String getXnfzmc() {
return xnfzmc;
}
public void setXnfzmc(String xnfzmc) {
this.xnfzmc = xnfzmc;
}
public String getZjj() {
return zjj;
}
public void setZjj(String zjj) {
this.zjj = zjj;
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
public String getJobTitleName() {
return jobTitleName;
}
public void setJobTitleName(String jobTitleName) {
this.jobTitleName = jobTitleName;
}
}
}

@ -0,0 +1,105 @@
package com.engine.leshanvc.service.impl;
import com.engine.core.impl.Service;
import com.engine.leshanvc.service.ResourceCardService;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.systeminfo.systemright.CheckUserRight;
import java.util.Map;
/**
* @author:dxfeng
* @createTime: 2023/04/20
* @version: 1.0
*/
public class ResourceCardServiceImpl extends Service implements ResourceCardService {
@Override
public void editResourceCard(Map<String, Object> params) {
String field102 = "";
Integer lineLeaderId = null;
String probationDate = "";
String dimissionDate = "";
RecordSet rs = new RecordSet();
String resourceId = Util.null2String(params.get("id"));
String roleName = Util.null2String(params.get("roleName"));
// 查询线内分组字段的值
String sql = "select field102 from cus_fielddata cf where scope ='HrmCustomFieldByInfoType' and scopeid ='-1' and id = ?";
rs.executeQuery(sql, resourceId);
if (rs.next()) {
field102 = rs.getString("field102");
}
// 查询分组的
sql = "select xc from uf_xlfz where xnfzbm = ?";
rs.executeQuery(sql, field102);
if (rs.next()) {
lineLeaderId = rs.getInt("xc");
}
// 补充线长字段,判断当前线长是否拥有线长角色
sql = "update cus_fielddata set field89 = ? where scope ='HrmCustomFieldByInfoType' and scopeid ='-1' and id = ? ";
rs.executeUpdate(sql, lineLeaderId, resourceId);
sql = "select id from hrmroles where ROLESMARK = ? ";
rs.executeQuery(sql, roleName);
if (rs.next()) {
addResourceRoles(String.valueOf(lineLeaderId), rs.getString("id"));
}
// 查询转正日期、离职日期
sql = "select field18,field82 from cus_fielddata where scope ='HrmCustomFieldByInfoType' and scopeid ='3' and id = ?";
rs.executeQuery(sql, resourceId);
if (rs.next()) {
probationDate = rs.getString("field18");
dimissionDate = rs.getString("field82");
}
// 修改当前人员为正式(转正日期小于等于当前日期)
if (probationDate.length() >0 ) {
if (probationDate.compareTo(DateUtil.getCurrentDate()) <= 0) {
sql = "update hrmresource set status = 1 where id = ?";
rs.executeUpdate(sql, resourceId);
}
}
// 修改当前人员为离职(离职日期小于当前日期)
if (dimissionDate.length() > 0) {
if (dimissionDate.compareTo(DateUtil.getCurrentDate()) <0) {
sql = "update hrmresource set status = 5 where id = ?";
rs.executeUpdate(sql,resourceId);
}
}
}
/**
*
*
* @param resourceId
* @param roleId
*/
private void addResourceRoles(String resourceId, String roleId) {
RecordSet rs = new RecordSet();
// 角色级别:总部
String roleLevel = "2";
CheckUserRight checkUserRight = new CheckUserRight();
if (!"".equals(roleId)) {
boolean isExist = false;
String sql = " select count(id) from HrmRoleMembers where roleid=" + roleId + " and resourceid = " + resourceId + " and resourcetype = 1 ";
rs.executeQuery(sql);
if (rs.next()) {
if (rs.getInt(1) > 0) {
isExist = true;
}
}
if (!isExist) {
sql = " INSERT INTO HrmRoleMembers ( roleid ,resourceid ,rolelevel ,resourcetype) " +
" VALUES ( " + roleId + ", " + resourceId + " , '" + roleLevel + "', '1')";
}
rs.executeUpdate(sql);
}
checkUserRight.removeMemberRoleCache();
checkUserRight.removeRoleRightdetailCache();
}
}

@ -0,0 +1,322 @@
package com.engine.leshanvc.service.impl;
import com.engine.core.impl.Service;
import com.engine.kq.biz.KQGroupMemberComInfo;
import com.engine.kq.biz.KQHolidaySetBiz;
import com.engine.leshanvc.service.SyncXcDataService;
import org.apache.commons.lang3.StringUtils;
import org.apache.tools.ant.util.DateUtils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.PasswordUtil;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.interfaces.leshanvc.workflow.util.ResourceSyncUtil;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
public class SyncXcDataServiceImpl extends Service implements SyncXcDataService {
BaseBean baseBean = new BaseBean();
static String dateFormat = "yyyy-MM-dd";
static SimpleDateFormat format = new SimpleDateFormat(dateFormat);
@Override
public Map<String, Object> syncXcData(Map<String, Object> params) {
Map<String, Object> data = new HashMap<>(16);
baseBean.writeLog("同步线长信息至花名册");
RecordSet recordSet = new RecordSet();
Boolean boo = false;
try {
boo = recordSet.execute("update cus_fielddata a, uf_xlfz b \n" +
"set a.field89=SUBSTRING_INDEX(b.xc,',',1) where a.SCOPEID='-1' and a.SCOPE='HrmCustomFieldByInfoType' and a.field102=b.xnfzbm ");
if (boo) {
data.put("status","success");
data.put("msg","线长信息同步成功!");
}
}catch (Exception e) {
data.put("status","error");
data.put("msg","线长信息同步失败,请联系管理员!");
baseBean.writeLog(e);
}
return data;
}
@Override
public Map<String, Object> nonOfficeUpload(Map<String, Object> params) {
Map<String, Object> result = new HashMap<String, Object>();
try {
String ids = Util.null2String(params.get("ids"));
boolean canEdit = HrmUserVarify.checkUserRight("HrmResourceEdit:Edit", user);
if (!canEdit) {
baseBean.writeLog("人员新增失败,当前用户不具备权限");
result.put("msg", "人员新增失败,当前用户不具备权限");
result.put("status", "error");
return result;
}
String[] idStr = ids.split(",");
for (String s : idStr) {
//------请在下面编写业务逻辑代码------
RecordSet rs = new RecordSet();
rs.executeQuery("select sfzhm,xm,xb,mz,csrq,jtzz,ksyxq,jzyxq,sfrhmc from uf_sfzxxgl where id=?", s);
Map<String, Object> paraMap = new HashMap<>();
String defId = null;
RecordSet recordSet = new RecordSet();
if (rs.next()) {
String xm = Util.null2String("xm");
paraMap.put("certificatenum", Util.null2String(rs.getString("sfzhm")));
paraMap.put("lastname", Util.null2String(rs.getString("xm")));
paraMap.put("sex", Util.null2String(rs.getString("xb")));
paraMap.put("folk", Util.null2String(rs.getString("mz")));
paraMap.put("birthday", Util.null2String(rs.getString("csrq")));
paraMap.put("regresidentplace", Util.null2String(rs.getString("jtzz")));
paraMap.put("status", "0");
paraMap.put("ksyxq", Util.null2String(rs.getString("ksyxq")));
paraMap.put("jzyxq", Util.null2String(rs.getString("jzyxq")));
if (StringUtils.isNotBlank(rs.getString("sfrhmc"))) {
recordSet.executeQuery("select id from hrmresource where CERTIFICATENUM='"+Util.null2String(rs.getString("sfzhm"))+"' and status < 4");
if (recordSet.next()) {
baseBean.writeLog("【"+xm+"】已存在花名册中,系统自动更新数据!!");
String updateHrmSql = "update hrmresource set CERTIFICATENUM='"+paraMap.get("certificatenum")+"', " +
"LASTNAME='"+paraMap.get("lastname")+"',FOLK='"+paraMap.get("folk")+"',BIRTHDAY='"+paraMap.get("birthday")+"', " +
"REGRESIDENTPLACE='"+paraMap.get("regresidentplace")+"',SEX='"+paraMap.get("sex")+"' where id='"+Util.null2String(recordSet.getString("id"))+"'";
String updateCusSql = "update cus_fielddata set field103='"+paraMap.get("ksyxq")+"',field104='"+paraMap.get("jzyxq")+"'" +
" where id='"+Util.null2String(recordSet.getString("id"))+"' and scopeid = 1";
rs.execute(updateHrmSql);
rs.execute(updateCusSql);
result.put("msg", "【"+xm+"】已存在花名册中,系统自动更新数据!!");
result.put("status", "warning");
return result;
}
}
Map<String, Object> retMap = ResourceSyncUtil.addResource(user, paraMap);
if (!"1".equals(retMap.get("status"))) {
baseBean.writeLog("人员新增失败,请联系管理员");
result.put("msg", "人员新增失败,请联系管理员");
result.put("status", "error");
return result;
} else {
defId = retMap.get("id").toString();
BaseBean bb = new BaseBean();
//新增人员自动排考勤组和班次
//考勤组
String kqz = "12";
//平时班次
String bcId = "2";
//周末班次
String zmbc = "15";
bb.writeLog("新增人员id:"+defId+"kqz:"+kqz+"bcId:"+bcId+"zmbc:"+zmbc);
//当前日期
String nowDate = DateUtils.format(new Date(), "yyyy-MM-dd");
//本月最后一天
// String toDate = TimeUtil.getMonthEndDay(nowDate);
String toDate = nowDate.substring(0,4)+"-12-31";
Set<String> all = new HashSet<>();
all.add(nowDate);
List<String> back = days(nowDate,toDate);
all.addAll(back);
all.add(toDate);
//插入考勤组
insertGroupMember(defId,kqz);
bb.writeLog("考勤组插入完成");
RecordSet rsn = new RecordSet();
//默认排班
String sql = "insert into kq_shiftschedule(kqdate,serialid,resourceid,groupid,isdelete)values(?,?,?,?,?)";
for (String date : all) {
boolean holiday = KQHolidaySetBiz.isHoliday(defId, date, true);
bb.writeLog("date:"+date+"holiday:"+holiday);
if (holiday) {
//节假日休息班
rsn.executeUpdate(sql, date, zmbc, defId, kqz, "0");
} else {
rsn.executeUpdate(sql, date, bcId, defId, kqz, "0");
}
}
bb.writeLog("默认排班插入完成");
}
}
String queryHrmSql = "select workcode from hrmresource h where h.id = '" + defId + "'";
rs.executeQuery(queryHrmSql);
String encrptPassword = "";
String salt = "";
if (rs.next()) {
if (StringUtils.isNotBlank(rs.getString("workcode"))) {
String[] encrypts = PasswordUtil.encrypt(rs.getString("workcode"));
encrptPassword = encrypts[0];
salt = encrypts[1];
}
recordSet.execute("update hrmresource set loginid='" + rs.getString("workcode") + "',password='" + encrptPassword + "',salt='" +
salt + "',certificatenum='" + Util.null2String(paraMap.get("certificatenum")) + "',folk='"+paraMap.get("folk")+"'," +
"birthday='"+paraMap.get("birthday")+"',regresidentplace='"+paraMap.get("regresidentplace")+"' where id=" + defId);
} else {
baseBean.writeLog("未查到对应人员Id请联系管理员");
result.put("msg", "未查到对应人员Id请联系管理员");
result.put("status", "error");
return result;
}
// 自定义表cus_fielddata
String insertCusFieldData = "insert cus_fielddata(scope,scopeid,id,field81,field103,field104) " +
"values ('HrmCustomFieldByInfoType','1'," + defId + ",'0','" + paraMap.get("ksyxq") + "','" + paraMap.get("jzyxq") + "')";
rs.execute(insertCusFieldData);
// 更新状态
String updateStatus = "update uf_sfzxxgl set sfrhmc = '1' where id = ?";
rs.executeUpdate(updateStatus, s);
}
} catch (Exception e) {
result.put("msg", "内部错误,请联系管理员");
result.put("status", "error");
}
result.put("status", "success");
result.put("msg", "所选人员上岗成功!");
return result;
}
@Override
public Map<String, Object> saveIDCard(Map<String, Object> params) {
baseBean.writeLog(params);
Map<String, Object> result = new HashMap<String, Object>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
String cardNo = Util.null2String(params.get("cardno"));
String name = Util.null2String(params.get("name"));
String sex = Util.null2String(params.get("sex")).equals("男") ? "0" : "1";
String nation = Util.null2String(params.get("nation"));
String born = null;
String userLifeB = null;
String userLifeE = null;
try {
Date date = df.parse(Util.null2String(params.get("born")));
born = sdf.format(date);
date = df.parse(Util.null2String(params.get("userlifeb")));
userLifeB = sdf.format(date);
date = df.parse(Util.null2String(params.get("userlifee")));
userLifeE = sdf.format(date);
} catch (ParseException e) {
throw new RuntimeException(e);
}
String address = Util.null2String(params.get("address"));
String police = Util.null2String(params.get("police"));
String CardType = Util.null2String(params.get("CardType"));
String photobase64 = Util.null2String(params.get("photobase64"));
String modeUuid = UUID.randomUUID().toString();
int modeDataCreate = user.getUID();
String modeDataCreateDate = sdf.format(new Date());
String modeDataCreateTime = LocalTime.now().format(formatter);
RecordSet rs = new RecordSet();
//身份证录入时,系统需检验
//① 身份证号码相同 且 是否黑名单:否,身份信息可录入,并且提示:该入职员工属于二次入职。
//② 身份证号码相同 且 是否黑名单:是,身份信息不可录入,提示:该入职员工属于黑名单,不允许入职。
//③ 身份证号码不相同 且 是否和名单:否,身份信息可录入。
String msg = "身份证读取录入成功";
boolean isBlack = false;
String checkSql = " select a.certificatenum ,b.field113 from hrmresource a " +
" left join cus_fielddata b on a.id=b.id and b.scopeid =3 where certificatenum=? ";
rs.executeQuery(checkSql,cardNo);
if(rs.next()){
isBlack = Util.getIntValue(rs.getString("field113"))==0;
if(isBlack){
msg = "该入职员工属于黑名单,不允许入职";
}else{
msg = "该入职员工属于二次入职";
}
}
if(!isBlack){
String insertSql = "INSERT INTO uf_sfzxxgl (formmodeid, modedatacreater, modedatacreatertype, " +
"modedatacreatedate, modedatacreatetime, MODEUUID, sfzhm, xm, " +
"xb, mz, csrq, jtzz, ksyxq, jzyxq, sfrhmc, qfjg, zjlx, zjtx) VALUES (50, "+modeDataCreate+", 0, " +
"'"+modeDataCreateDate+"', '"+modeDataCreateTime+"', '"+modeUuid+"', '"+cardNo+"', '"+name+"'," +
sex+", '"+nation+"', '"+born+"', '"+address+"', '"+userLifeB+"', '"+userLifeE+"', 0, '"+police+"', '"+CardType+"', '"+photobase64+"')";
boolean res = rs.execute(insertSql);
if(!res){
msg = "身份证读取录入失败";
}
}
result.put("status","success");
result.put("msg",msg);
return result;
}
/**
*
* @param date1
* @param date2
* @return
*/
public static ArrayList days(String date1, String date2) {
ArrayList L = new ArrayList();
if (date1.equals(date2)) {
System.out.println("两个日期相等!");
return L;
}
String tmp;
if (date1.compareTo(date2) > 0) { // 确保 date1的日期不晚于date2
tmp = date1;
date1 = date2;
date2 = tmp;
}
tmp = format.format(str2Date(date1).getTime() + 3600 * 24 * 1000);
int num = 0;
while (tmp.compareTo(date2) < 0) {
L.add(tmp);
num++;
tmp = format.format(str2Date(tmp).getTime() + 3600 * 24 * 1000);
}
if (num == 0)
System.out.println("两个日期相邻!");
return L;
}
private static Date str2Date(String str) {
if (str == null)
return null;
try {
return format.parse(str);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
/**
*
* @param rzry
* @param groupId
*/
private static void insertGroupMember(String rzry,String groupId){
BaseBean bb = new BaseBean();
RecordSet rsInsert = new RecordSet();
String sql = "insert into kq_groupmember (type,typevalue,groupid) "
+ " values(?,?,?) ";
rsInsert.executeUpdate(sql, 1,rzry,groupId);
bb.writeLog("insertSql:"+sql);
new KQGroupMemberComInfo().removeCache();
}
}

@ -0,0 +1,21 @@
package com.engine.leshanvc.service.impl;
import com.engine.core.impl.Service;
import com.engine.leshanvc.cmd.WorkflowCheckCmd;
import com.engine.leshanvc.service.WorkflowCheckService;
import java.util.Map;
/**
* @Author weaver_cl
* @Description:
* @Date 2023/3/8
* @Version V1.0
**/
public class WorkflowCheckServiceImpl extends Service implements WorkflowCheckService {
@Override
public Map<String, Object> workflowController(Map<String, Object> params) {
return commandExecutor.execute(new WorkflowCheckCmd(params, user));
}
}

@ -0,0 +1,20 @@
package com.engine.leshanvc.util;
/**
* @Author weaver_cl
* @Description:
* @Date 2023/2/21
* @Version V1.0
**/
public class ExceptionUtil {
public static String getRealMessage(Throwable e) {
while (e != null) {
Throwable cause = e.getCause();
if (cause == null) {
return e.getMessage();
}
e = cause;
}
return "";
}
}

@ -0,0 +1,93 @@
package com.engine.leshanvc.util;
import com.engine.kq.biz.KQBalanceOfLeaveBiz;
import com.engine.kq.biz.KQGroupMemberComInfo;
import com.engine.kq.biz.KQHolidaySetComInfo;
import weaver.common.DateUtil;
import weaver.general.Util;
/**
* @author:dxfeng
* @createTime: 2023/04/19
* @version: 1.0
*/
public class HsDateUtil {
/**
*
*
* @param resourceId ID
* @param addDays
* @param startDate
* @param includeHoliday
* @return
*/
public static String addDay(String resourceId, Integer addDays, String startDate, boolean includeHoliday) {
int i = 0;
String tempDate = startDate;
boolean isCurrentDate = false;
while (i < addDays) {
if (isCurrentDate) {
tempDate = DateUtil.addDate(tempDate, 1);
} else {
isCurrentDate = true;
}
boolean holiday = isHoliday(resourceId, tempDate, false);
if (includeHoliday || !holiday) {
i++;
}
}
return tempDate;
}
/**
*
*
* @param resourceId ID
* @param newLeaveType
* @param startDate
* @return
*/
public static Integer getHolidayAmount(String resourceId, String newLeaveType, String startDate) {
String restAmount = KQBalanceOfLeaveBiz.getRestAmount(resourceId, newLeaveType, startDate);
String substring = "0".equals(restAmount) ? restAmount : restAmount.substring(0, restAmount.lastIndexOf('.'));
return Integer.parseInt(substring);
}
/**
* @param resourceId ID
* @param date
* @param containWeekend
* @return
*/
public static boolean isHoliday(String resourceId, String date, boolean containWeekend) {
boolean flag = false;
/*获取考勤组的ID因为考勤组有有效期所以需要传入日期*/
KQGroupMemberComInfo kqGroupMemberComInfo = new KQGroupMemberComInfo();
String groupId = kqGroupMemberComInfo.getKQGroupId(resourceId, date);
int changeType = getChangeType(groupId, date);
/*如果需要包含周末,判断传入的日期是不是周末*/
if (containWeekend && changeType != 2 && (DateUtil.getWeek(date) == 6 || DateUtil.getWeek(date) == 7)) {
flag = true;
}
if (changeType == 1) {
flag = true;
}
return flag;
}
/**
* @param groupId ID
* @param date
* @return
*/
public static int getChangeType(String groupId, String date) {
//默认没有设置过节假日(节假日设置的类型1-公众假日、2-调配工作日、3-调配休息日)
KQHolidaySetComInfo kqHolidaySetComInfo = new KQHolidaySetComInfo();
return Util.getIntValue(kqHolidaySetComInfo.getChangeType(groupId, date), -1);
}
}

@ -0,0 +1,171 @@
package com.engine.leshanvc.util;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.engine.core.exception.ECException;
import com.engine.leshanvc.exception.CustomizeRunTimeException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import weaver.general.BaseBean;
import weaver.hrm.User;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
/**
*
* <p>Copyright: Copyright (c) 2022</p>
* <p>Company: </p>
*
* @author qiantao
* @version 1.0
**/
@Slf4j
public class ResponseResult<T, R> {
private static final long serialVersionUID = 1L;
private final User user;
private final BaseBean baseBean = new BaseBean();
private final Boolean isLog = "true".equals(baseBean.getPropValue("hrmSalary", "log"));
public ResponseResult(User user) {
this.user = user;
}
/**
*
*/
public String run(Function<T, R> f, T t) {
try {
if (isLog) {
log.info("run api , param {}", t);
}
return Ok(f.apply(t));
} catch (CustomizeRunTimeException e) {
log.error("api run fail", e);
return Error(e.getMessage());
} catch (ECException e) {
log.error("api run fail", e);
Throwable cause = e.getCause();
return Error(cause.getMessage());
} catch (Exception e) {
log.error("api run fail", e);
return Error("系统异常!");
}
}
/**
*
*/
public String run(Consumer<T> f, T t) {
try {
if (isLog) {
log.info("run api , param {}", t);
}
f.accept(t);
return Ok();
} catch (CustomizeRunTimeException e) {
log.error("api run fail", e);
return Error(e.getMessage());
} catch (ECException e) {
log.error("api run fail", e);
return Error(ExceptionUtil.getRealMessage(e));
} catch (Exception e) {
log.error("api run fail", e);
return Error("系统异常!", e);
}
}
/**
*
*/
public String run(Supplier<R> f) {
try {
if (isLog) {
log.info("run api");
}
return Ok(f.get());
} catch (CustomizeRunTimeException e) {
log.error("api run fail", e);
return Error(e.getMessage());
} catch (ECException e) {
log.error("api run fail", e);
Throwable cause = e.getCause();
return Error(cause.getMessage());
} catch (Exception e) {
log.error("api run fail", e);
return Error("系统异常!", e);
}
}
private static String getJsonString(Object apidatas) {
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.writeValueAsString(apidatas);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return "";
}
/**
*
*/
private String Ok() {
Map<String, Object> apidatas = new HashMap<>();
apidatas.put("status", true);
return JSONObject.toJSONString(apidatas, SerializerFeature.DisableCircularReferenceDetect);
}
/**
*
*/
private String Ok(R r) {
Map<String, Object> apidatas = new HashMap<>();
apidatas.put("status", true);
apidatas.put("data", r);
String success = getJsonString(apidatas);
if (isLog) {
log.info("run salary api success return {}", success);
}
return success;
}
/**
*
*/
private static String Error(String message) {
Map<String, Object> apidatas = new HashMap<>();
apidatas.put("status", false);
apidatas.put("errormsg", message);
return JSONObject.toJSONString(apidatas, SerializerFeature.DisableCircularReferenceDetect);
}
/**
*
*/
private static String Error(String message, Exception e) {
Map<String, Object> apidatas = new HashMap<>();
apidatas.put("status", false);
apidatas.put("errormsg", message);
apidatas.put("error", e.getMessage());
return JSONObject.toJSONString(apidatas, SerializerFeature.DisableCircularReferenceDetect);
}
}

@ -0,0 +1,42 @@
package com.engine.leshanvc.web;
import com.engine.common.util.ParamUtil;
import com.engine.common.util.ServiceUtil;
import com.engine.leshanvc.service.EntryCommitFormModeService;
import com.engine.leshanvc.service.EntryWorkflowSaveEventService;
import com.engine.leshanvc.service.impl.EntryCommitFormModeServiceImpl;
import com.engine.leshanvc.service.impl.EntryWorkflowSaveEventServiceImpl;
import com.engine.leshanvc.util.ResponseResult;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.Map;
/**
* @Author ml
* @Date 2023/3/1 11:10
* @Description This is description of class
* @Since version-1.0
*/
public class EntryCommitFormModeController {
public EntryCommitFormModeService getService(User user) {
return ServiceUtil.getService(EntryCommitFormModeServiceImpl.class, user);
}
@POST
@Path("/entryCommit")
@Produces(MediaType.APPLICATION_JSON)
public String entryCommit(@Context HttpServletRequest request, @Context HttpServletResponse response) {
User user = HrmUserVarify.getUser(request, response);
return new ResponseResult<Map<String, Object>, Map<String, Object>>(user).run(getService(user)::entryCommit, ParamUtil.request2Map(request));
}
}

@ -0,0 +1,43 @@
package com.engine.leshanvc.web;
import com.engine.common.util.ParamUtil;
import com.engine.common.util.ServiceUtil;
import com.engine.leshanvc.service.EntryWorkflowSaveEventService;
import com.engine.leshanvc.service.impl.EntryWorkflowSaveEventServiceImpl;
import com.engine.leshanvc.util.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.Map;
/**
* @Author weaver_cl
* @Description:
* @Date 2023/2/21
* @Version V1.0
**/
@Slf4j
public class EntryWorkflowSaveEventAction {
public EntryWorkflowSaveEventService getService(User user) {
return ServiceUtil.getService(EntryWorkflowSaveEventServiceImpl.class, user);
}
@POST
@Path("/changeStatus")
@Produces(MediaType.APPLICATION_JSON)
public String changeStatus(@Context HttpServletRequest request, @Context HttpServletResponse response) {
User user = HrmUserVarify.getUser(request, response);
return new ResponseResult< Map<String, Object>, Map<String, Object>>(user).run(getService(user)::changeStatus, ParamUtil.request2Map(request));
}
}

@ -0,0 +1,39 @@
package com.engine.leshanvc.web;
import com.engine.common.util.ParamUtil;
import com.engine.common.util.ServiceUtil;
import com.engine.leshanvc.service.KqWorkflowRangeLimitService;
import com.engine.leshanvc.service.impl.KqWorkflowRangeLimitServiceImpl;
import com.engine.leshanvc.util.ResponseResult;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.Map;
/**
* @Author weaver_cl
* @Description:
* @Date 2023/3/3
* @Version V1.0
**/
public class KqWorkflowRangeLimitAction {
public KqWorkflowRangeLimitService getService(User user) {
return ServiceUtil.getService(KqWorkflowRangeLimitServiceImpl.class,user);
}
@GET
@Path("/rangeLimit")
@Produces(MediaType.APPLICATION_JSON)
public String rangeLimit(@Context HttpServletRequest request, @Context HttpServletResponse response) {
User user = HrmUserVarify.getUser(request, response);
return new ResponseResult< Map<String, Object>, Map<String, Object>>(user).run(getService(user)::rangeLimit, ParamUtil.request2Map(request));
}
}

@ -0,0 +1,38 @@
package com.engine.leshanvc.web;
import com.engine.common.util.ParamUtil;
import com.engine.common.util.ServiceUtil;
import com.engine.leshanvc.service.LeaverWorkflowService;
import com.engine.leshanvc.service.impl.LeaverWorkflowServiceImpl;
import com.engine.leshanvc.util.ResponseResult;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.Map;
/**
* @author:dxfeng
* @createTime: 2023/04/19
* @version: 1.0
*/
public class LeaverWorkflowAction {
public LeaverWorkflowService getService(User user) {
return ServiceUtil.getService(LeaverWorkflowServiceImpl.class, user);
}
@POST
@Path("/getEndDate")
@Produces(MediaType.APPLICATION_JSON)
public String rangeLimit(@Context HttpServletRequest request, @Context HttpServletResponse response) {
User user = HrmUserVarify.getUser(request, response);
return new ResponseResult<Map<String, Object>, Map<String, Object>>(user).run(getService(user)::getEndDate, ParamUtil.request2Map(request));
}
}

@ -0,0 +1,38 @@
package com.engine.leshanvc.web;
import com.engine.common.util.ParamUtil;
import com.engine.common.util.ServiceUtil;
import com.engine.leshanvc.service.LzWorkflowManageService;
import com.engine.leshanvc.service.impl.LzWorkflowManageServiceImpl;
import com.engine.leshanvc.util.ResponseResult;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.Map;
public class LzWorkflowManageAction {
public LzWorkflowManageService getService(User user){
return ServiceUtil.getService(LzWorkflowManageServiceImpl.class,user);
}
/**
* @Author ml
* @Date 2023/3/16 10:44
* @Description 线线
* @Since version-1.0
*/
@GET
@Path("/getHrmInfoByLinSup")
@Produces(MediaType.APPLICATION_JSON)
public String getHrmInfoByLinSup(@Context HttpServletRequest request, @Context HttpServletResponse response) {
User user = HrmUserVarify.getUser(request, response);
return new ResponseResult<Map<String, Object>, Map<String, Object>>(user).run(getService(user)::getHrmInfoByLinSup, ParamUtil.request2Map(request));
}
}

@ -0,0 +1,39 @@
package com.engine.leshanvc.web;
import com.engine.common.util.ParamUtil;
import com.engine.common.util.ServiceUtil;
import com.engine.leshanvc.service.ResourceCardService;
import com.engine.leshanvc.service.impl.ResourceCardServiceImpl;
import com.engine.leshanvc.util.ResponseResult;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.Map;
/**
* @author:dxfeng
* @createTime: 2023/04/20
* @version: 1.0
*/
public class ResourceCardAction {
public ResourceCardService getService(User user) {
return ServiceUtil.getService(ResourceCardServiceImpl.class, user);
}
@POST
@Path("/editResourceCard")
@Produces(MediaType.APPLICATION_JSON)
public String rangeLimit(@Context HttpServletRequest request, @Context HttpServletResponse response) {
User user = HrmUserVarify.getUser(request, response);
return new ResponseResult<Map<String, Object>, Map<String, Object>>(user).run(getService(user)::editResourceCard, ParamUtil.request2Map(request));
}
}

@ -0,0 +1,55 @@
package com.engine.leshanvc.web;
import com.engine.common.util.ParamUtil;
import com.engine.common.util.ServiceUtil;
import com.engine.leshanvc.service.SyncXcDataService;
import com.engine.leshanvc.service.WorkflowCheckService;
import com.engine.leshanvc.service.impl.SyncXcDataServiceImpl;
import com.engine.leshanvc.service.impl.WorkflowCheckServiceImpl;
import com.engine.leshanvc.util.ResponseResult;
import com.engine.organization.util.response.ReturnResult;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.Map;
public class SyncXcDataAction {
public SyncXcDataService getService(User user) {
return ServiceUtil.getService(SyncXcDataServiceImpl.class,user);
}
@GET
@Path("/syncXcData")
@Produces(MediaType.APPLICATION_JSON)
public String workflowController(@Context HttpServletRequest request, @Context HttpServletResponse response) {
User user = HrmUserVarify.getUser(request, response);
return new ResponseResult<Map<String, Object>, Map<String, Object>>(user).run(getService(user)::syncXcData, ParamUtil.request2Map(request));
}
@GET
@Path("/nonOfficeUpload")
@Produces(MediaType.APPLICATION_JSON)
public String nonOfficeUpload(@Context HttpServletRequest request, @Context HttpServletResponse response) {
User user = HrmUserVarify.getUser(request, response);
return new ResponseResult<Map<String, Object>, Map<String, Object>>(user).run(getService(user)::nonOfficeUpload, ParamUtil.request2Map(request));
}
@POST
@Path("/saveIDCard")
@Produces(MediaType.APPLICATION_JSON)
public ReturnResult saveBaseComp(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody Map<String, Object> params) {
try {
User user = HrmUserVarify.getUser(request, response);
return ReturnResult.successed(getService(user).saveIDCard(params));
} catch (Exception e) {
return ReturnResult.exceptionHandle(e);
}
}
}

@ -0,0 +1,39 @@
package com.engine.leshanvc.web;
import com.engine.common.util.ParamUtil;
import com.engine.common.util.ServiceUtil;
import com.engine.leshanvc.service.WorkflowCheckService;
import com.engine.leshanvc.service.impl.WorkflowCheckServiceImpl;
import com.engine.leshanvc.util.ResponseResult;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.Map;
/**
* @Author weaver_cl
* @Description:
* @Date 2023/3/8
* @Version V1.0
**/
public class WorkflowCheckAction {
public WorkflowCheckService getService(User user) {
return ServiceUtil.getService(WorkflowCheckServiceImpl.class,user);
}
@GET
@Path("/controller")
@Produces(MediaType.APPLICATION_JSON)
public String workflowController(@Context HttpServletRequest request, @Context HttpServletResponse response) {
User user = HrmUserVarify.getUser(request, response);
return new ResponseResult< Map<String, Object>, Map<String, Object>>(user).run(getService(user)::workflowController, ParamUtil.request2Map(request));
}
}

@ -0,0 +1,220 @@
package com.engine.workflow.biz.requestForm;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;
import com.engine.workflow.util.FileUtils;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import weaver.general.BaseBean;
import weaver.general.GCONST;
import weaver.general.Util;
/**
* Description: htmlpdf
*
* @author Mcr
*
*/
public class Html2Pdf extends BaseBean{
/**
* 线htmlpdf
*
* @param htmlPath 线
* @param pdfPath pdf
* @param filename
* @param zipPath zip
* @return
*/
public boolean getPdf(String htmlPath,String pdfPath,String filename,String zipPath){
boolean result = true;
boolean isWindows = isWindows();
boolean useLocalServer = isUseLocalServer(isWindows);
if(useLocalServer){//使用本地插件转pdf useLocalServer
String cmd = getToolPath(isWindows) + " --enable-local-file-access " + htmlPath + " " + pdfPath;
long l1 = System.currentTimeMillis();
writeLog("开始导出pdf");
writeLog("执行脚本:" + cmd);
Process p = null;
BufferedInputStream err = null;
BufferedReader errBr = null;
try {
Runtime run = Runtime.getRuntime();
p = run.exec(cmd);//启动另一个进程来执行命令
err = new BufferedInputStream(p.getErrorStream());
errBr = new BufferedReader(new InputStreamReader(err));
String lineStr = "";
while ((lineStr = errBr.readLine()) != null){
writeLog(lineStr);
}
//检查命令是否执行失败。
try {
if (p.waitFor()!=0) {
if(p.exitValue()==1)//p.exitValue()==0表示正常结束1非正常结束
writeLog("执行过程中出现异常");
}
}catch (InterruptedException e){
e.printStackTrace();
}
writeLog("执行成功");
} catch (Exception e) {
result = false;
e.printStackTrace();
}finally {
try {
errBr.close();
err.close();
if (p != null) {
p.destroy();
}
} catch (IOException e) {
e.printStackTrace();
}
}
long l2 = System.currentTimeMillis();
writeLog("开始导出结束,耗时:"+ (l2-l1));
}else{//使用window中转服务转pdf
String windowsServer = getPropValue("form2pdf_e9", "windowsServer");
if(!"".equals(windowsServer)){
File zipFile = new File(zipPath);
try {
String fileString = FileUtils.file2String(zipFile);
String pdfString = callService(fileString, windowsServer, filename);
if(!"".equals(pdfString)){
byte[] string2Byte = FileUtils.string2Byte(pdfString);
result = FileUtils.saveFile(pdfPath, string2Byte);
}else{
result = false;
}
} catch (IOException e) {
e.printStackTrace();
}
}else{
result = false;
writeLog("form2pdf_e9.properties中的windowsServer参数未配置请检查");
}
}
return result;
}
/**
* 使
*
* @param isWindows
* @return
*/
private boolean isUseLocalServer(boolean isWindows){
boolean result = true;
if(!isWindows){//linux系统
if(getConvertType() == 3)
result = false;//使用windows中转服务
}
return result;
}
/**
*
* @return
*/
private int getConvertType(){
int convertType = Util.getIntValue(getPropValue("form2pdf_e9", "convertType"),1);
return convertType;
}
/**
* windows
*
* @return
*/
public boolean isWindows(){
boolean isWindows = true;
Properties properties = System.getProperties();
String os = properties.getProperty("os.name").toLowerCase();
if(os.indexOf("windows") > -1){
isWindows = true;
}else{
isWindows = false;
}
return isWindows;
}
/**
* wkhtmltopdf
* @return
*/
private String getToolPath(boolean isWindows){
String toolPath = GCONST.getRootPath() + "wkhtmltopdf";
if(isWindows){//Windows系统
toolPath = "cmd /c " + toolPath + File.separator + "windows" + File.separator + "bin" + File.separator + "wkhtmltopdf.exe";
}else{//Linux系统
int convertType = getConvertType();
if(convertType == 1){//使用ecology自带插件
toolPath += File.separator + "linux" + File.separator + "bin" + File.separator + "./wkhtmltopdf";
}else if(convertType == 2){//使用自行安装插件
toolPath = Util.null2String(getPropValue("form2pdf_e9", "wkhtml2xPath")) + File.separator + "bin" + File.separator + "./wkhtmltopdf";
}
}
return toolPath;
}
public static void wKConvertLinux(String whktmlExe,String htmlUrl, String pdfFilePath) {
try {
//ProcessBuilder pb = new ProcessBuilder(whktmlExe,"--print-media-type", "--margin-left", "10mm", "--margin-right", "10mm", htmlUrl, pdfFilePath);
ProcessBuilder pb = new ProcessBuilder(whktmlExe, htmlUrl, pdfFilePath);
pb.redirectErrorStream(true);
Process process = pb.start();
BufferedReader errstreamReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = errstreamReader.readLine();
while (line != null) {
line = errstreamReader.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* windows
* @param fileString
* @param windowsServer
* @param filename
* @return
*/
private String callService(String fileString,String windowsServer,String filename){
String result = "";
try {
String endpoint = windowsServer + "/services/PdfService";
Service service = new Service();
Call call = (Call) service.createCall();
call.setTargetEndpointAddress(endpoint);
call.setOperationName("convertPdf");//方法
call.addParameter("fileString", org.apache.axis.encoding.XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.IN);//接口的参数
call.addParameter("filename", org.apache.axis.encoding.XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.IN);
call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);//设置返回类型
result = (String)call.invoke(new Object[]{fileString,filename});
}catch (Exception e) {
writeLog("调用window中转服务【html->pdf】失败");
}
return result;
}
}

@ -0,0 +1,234 @@
package com.engine.workflow.cmd.monitor;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.constant.BizLogOperateType;
import com.engine.common.constant.BizLogSmallType4Workflow;
import com.engine.common.constant.BizLogType;
import com.engine.common.constant.ParamConstant;
import com.engine.common.entity.BizLogContext;
import com.engine.common.util.ParamUtil;
import com.engine.core.interceptor.Command;
import com.engine.workflow.biz.requestForm.RequestRemindBiz;
import com.engine.workflow.constant.RemindTypeEnum;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.workflow.monitor.Monitor;
import weaver.workflow.workflow.WFManager;
import weaver.workflow.workflow.WfForceOver;
import weaver.workflow.workflow.WfFunctionManageUtil;
import com.engine.core.interceptor.CommandContext;
import weaver.workflow.request.RequestCheckAddinRules;
import weaver.workflow.request.RequestManager;
import weaver.workflow.workflow.WorkflowComInfo;
/**
*
* @author luosy 2017/11/17
*
*/
public class DoArchivingCmd extends AbstractCommonCommand<Map<String,Object>> {
private HttpServletRequest request;
private HttpServletResponse response;
private User user;
public DoArchivingCmd(HttpServletRequest request,HttpServletResponse response,User user){
this.request = request;
this.response = response;
this.user = user;
}
public DoArchivingCmd(){
//空参构造器
}
@Override
public Map<String, Object> execute(CommandContext commandContext) {
return this.doArchiving(request, response, user);
}
/**
*
* @param request
* @param response
* @param user
* @return
*/
public Map<String, Object> doArchiving(HttpServletRequest request,HttpServletResponse response,User user){
Map<String, Object> apidatas = new HashMap<String, Object>();
String multiRequestIds = Util.null2String(request.getParameter("multiRequestIds"));
if(multiRequestIds.endsWith(",")) multiRequestIds = multiRequestIds.substring(0,multiRequestIds.length() - 1);
String[] requestids = Util.TokenizerString2(multiRequestIds, ",");
RecordSet rs = new RecordSet();
WfFunctionManageUtil WfFunctionManageUtil = new WfFunctionManageUtil();
Monitor Monitor = new Monitor();
WfForceOver WfForceOver = new WfForceOver();
int success = 0,fail = 0;
if (requestids != null) {
for (int i = 0; i < requestids.length; i++) {
ArrayList requestidsArr = new ArrayList();
int requestid_tmp = Util.getIntValue(requestids[i]);
if(requestid_tmp == -1){
fail++;
continue;
}
if(!WfFunctionManageUtil.haveOtherOperationRight(requestid_tmp)){
continue;
}
boolean isForceOver=false;
rs.execute("select creater,workflowid from workflow_requestbase where requestid = " + requestid_tmp);
rs.next();
String creater = rs.getString(1);
int workflowid_rs = rs.getInt(2);
weaver.workflow.monitor.MonitorDTO dto = Monitor.getMonitorInfo(user.getUID()+"",creater,workflowid_rs+"");
isForceOver = dto.getIsforceover();
if (isForceOver && !WfForceOver.isOver(requestid_tmp)) {
requestidsArr.add(requestids[i]);
WfForceOver.doForceOver(requestidsArr, request, response);
DoRepossessedCmd dor = new DoRepossessedCmd();
Map<String, String> data = dor.getWorkflowInfo(requestids[i]);
if(data.size() > 0){
dor.releaseNumber(Util.getIntValue(data.get("formid")), Util.getIntValue(data.get("workflowid")));
}
success++;
this.doRemind(requestid_tmp,workflowid_rs);
//no.2545225 强制归档需要触发节点附加操作,实现一键审批
try {
RequestManager requestManager = new RequestManager();
requestManager.setUser(user);
requestManager.setWorkflowid(workflowid_rs);
requestManager.setRequestid(requestid_tmp);
WorkflowComInfo wfComInfo = new WorkflowComInfo();
int formid = Util.getIntValue(wfComInfo.getFormId(workflowid_rs+""));
int isbill = Util.getIntValue(wfComInfo.getIsBill(workflowid_rs+""));
String sql2 = "select nodeid from workflow_flownode where workflowid = ? and nodetype = 3";
RecordSet recordSet = new RecordSet();
recordSet.executeQuery(sql2,workflowid_rs);
int nodeid = -1;
if(recordSet.next()) {
nodeid = recordSet.getInt("nodeid");
}
RequestCheckAddinRules requestCheckAddinRules = new RequestCheckAddinRules();
requestCheckAddinRules.resetParameter();
requestCheckAddinRules.setWorkflowid(workflowid_rs);
requestCheckAddinRules.setRequestid(requestid_tmp);
requestCheckAddinRules.setNodeid(nodeid);
requestCheckAddinRules.setObjid(nodeid);
requestCheckAddinRules.setObjtype(1);
requestCheckAddinRules.setIsbill(isbill);
requestCheckAddinRules.setFormid(formid);
requestCheckAddinRules.setIspreadd("0");
requestCheckAddinRules.setRequestManager(requestManager);
requestCheckAddinRules.checkAddinRules();
} catch (Exception e) {
e.printStackTrace();
apidatas.put("api_errormsg", "节点后附加操作执行失败!");
}
}else{
fail++;
}
}
apidatas.put("total", requestids.length);
apidatas.put("success", success);
apidatas.put("fail", fail);
}else{
apidatas.put("api_errormsg", "The parameters passed in are not valid");
}
return apidatas;
}
/**
*
* @param requestId
* @param workflowId
*/
private void doRemind(int requestId,int workflowId){
RequestRemindBiz remindBiz = new RequestRemindBiz(user);
try{
WFManager wfManager = new WFManager();
wfManager.setWfid(workflowId);
wfManager.getWfInfo();
RecordSet rs = new RecordSet();
rs.executeQuery("select remindscope from workflow_base where id = ? ", workflowId);
rs.next();
int remindscope = Util.getIntValue(rs.getString("remindscope"),0);
if (remindscope ==1) {
remindBiz.requestRemind(requestId,workflowId,"", RemindTypeEnum.EMAIL,0);
} else {
String isArchiveNoRemind = wfManager.getIsArchiveNoRemind();
if("1".equals(isArchiveNoRemind)) return; //强制归档不需要提醒
String isSms = wfManager.getIsDefaultSmsRemind();
String isEmail = wfManager.getIsDefaultEmailRemind();
if("1".equals(isEmail) ){
remindBiz.requestRemind(requestId,workflowId,"", RemindTypeEnum.EMAIL,0);
}
if("1".equals(isSms)){
remindBiz.requestRemind(requestId,workflowId, "",RemindTypeEnum.SMS,0);
}
String archiveNoMsgAlert = wfManager.getArchiveNoMsgAlert();
String archiveNoMailAlert = wfManager.getArchiveNoMailAlert();
String messageType = wfManager.getMessageType();
String mailMessageType = wfManager.getMailMessageType();
if("1".equals(mailMessageType) && !"1".equals(archiveNoMailAlert)){
remindBiz.requestRemind(requestId,workflowId,"", RemindTypeEnum.EMAIL,0);
}
if(!"1".equals(archiveNoMsgAlert)){
if("2".equals(messageType)){
remindBiz.requestRemind(requestId,workflowId, "",RemindTypeEnum.SMS,0);
}
if("1".equals(messageType)){
remindBiz.requestRemind(requestId,workflowId,"", RemindTypeEnum.SMS,1);
}
}
}
}catch (Exception e){
}
}
public HttpServletRequest getRequest() {
return request;
}
public User getUser() {
return user;
}
@Override
public BizLogContext getLogContext() {
BizLogContext bizLogContext = new BizLogContext();
BizLogOperateType bizLogOperateType = BizLogOperateType.APPROVE;
bizLogContext.setDateObject(new Date());
bizLogContext.setUserid(user.getUID());
bizLogContext.setUsertype(Util.getIntValue(user.getLogintype()));
bizLogContext.setTargetId("monitor_archiving");
bizLogContext.setTargetName("流程强制归档");
bizLogContext.setLogType(BizLogType.WORKFLOW);
bizLogContext.setLogSmallType(BizLogSmallType4Workflow.WORKFLOW_APPROVE);
bizLogContext.setOperateType(bizLogOperateType);
bizLogContext.setClientIp(Util.null2String(Util.getIpAddr(request)));
bizLogContext.setParams(ParamUtil.request2Map(request));
bizLogContext.setDesc(String.format(user.getLastname() + "进行了流程强制归档操作"));
return bizLogContext;
}
}

@ -0,0 +1,375 @@
package com.engine.workflow.cmd.requestForm;
import com.api.workflow.util.ServiceUtil;
import com.cloudstore.dev.api.util.Util_TableMap;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.constant.BizLogOperateType;
import com.engine.common.constant.BizLogSmallType4Workflow;
import com.engine.common.constant.BizLogType;
import com.engine.common.entity.BizLogContext;
import com.engine.common.util.ParamUtil;
import com.engine.core.interceptor.CommandContext;
import com.engine.workflow.biz.WorkflowTestBiz;
import com.engine.workflow.biz.publicApi.RequestOperateBiz;
import com.engine.workflow.biz.requestForm.RequestRemindBiz;
import com.engine.workflow.biz.requestForm.SubmitErrorMsgBiz;
import com.engine.workflow.biz.requestForm.TestWorkflowCheckBiz;
import com.engine.workflow.biz.requestList.RequestAttentionBiz;
import com.engine.workflow.biz.workflowOvertime.OvertimeBiz;
import com.engine.workflow.constant.RemindTypeEnum;
import com.engine.workflow.constant.requestForm.RequestExecuteType;
import com.engine.workflow.entity.requestForm.RequestOperationResultBean;
import weaver.conn.RecordSet;
import weaver.file.FileUpload;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.systeminfo.SystemEnv;
import weaver.workflow.agent.AgentManager;
import weaver.workflow.msg.MsgPushUtil;
import weaver.workflow.msg.entity.MsgEntity;
import weaver.workflow.request.*;
import weaver.workflow.workflow.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
*
* @author liuzy 2018/5/4
*/
public class FunctionManageCmd extends AbstractCommonCommand<Map<String,Object>>{
private HttpServletRequest request;
private HttpServletResponse response;
public FunctionManageCmd(HttpServletRequest request, HttpServletResponse response, User user){
this.request = request;
this.response = response;
this.user = user;
}
public Map<String,Object> execute(CommandContext commandContext){
Map<String, Object> apidatas = new HashMap<String, Object>();
Map<String, String> resultmap = new HashMap<String, String>();
int logintype = Util.getIntValue(user.getLogintype());
int requestid = Util.getIntValue(request.getParameter("requestid"), 0);
String flag = Util.null2String(request.getParameter("flag"));
WfFunctionManageUtil wffmu = new WfFunctionManageUtil();
ArrayList<String> requestidlist = new ArrayList<String>();
int formid = Util.getIntValue(request.getParameter("formid"), 0);
int requestLogId = Util.getIntValue(request.getParameter("workflowRequestLogId"), 0);
String signdocids = Util.null2String(request.getParameter("signdocids"));
String signworkflowids = Util.null2String(request.getParameter("signworkflowids"));
String remark = Util.null2String(request.getParameter("remark"));
int workflowid = Util.getIntValue(request.getParameter("workflowid"), 0);
int nodeid = -1;
String isnew = new BaseBean().getPropValue("WorkflowOvertimeIsNew" , "isNew");
boolean isnewFlag = "1".equals(isnew);
// 流程暂停
if ("stop".equals(flag)) {
wffmu.setStopOperation(requestid, user);
// this.pushOperationMsg(requestid,user,flag);
if(isnewFlag)
OvertimeBiz.getInstance().cancelOvertimeTask(requestid, nodeid);//取消超时任务
}
// 流程撤销
if ("cancel".equals(flag)) {
wffmu.setCancelOperation(requestid, user);
// this.pushOperationMsg(requestid,user,flag);
if(isnewFlag)
OvertimeBiz.getInstance().cancelOvertimeTask(requestid, nodeid);//取消超时任务
}
// 流程启用
if ("restart".equals(flag)) {
wffmu.setRestartOperation(requestid, user);
// this.pushOperationMsg(requestid,user,flag);
if(isnewFlag)
OvertimeBiz.getInstance().addOvertimeTaskThread(requestid, workflowid, nodeid);//添加超时任务
}
// 强制归档
if ("ov".equals(flag)) {
WfForceOver wfo = new WfForceOver();
String annexdocids = "";
String fromflow = Util.null2String(request.getParameter("fromflow"));
String remarkLocation = Util.null2String(request.getParameter("remarkLocation"));
int agentType = Util.getIntValue(Util.null2String(request.getParameter("agentType")));
int agentorByAgentId = Util.getIntValue(Util.null2String(request.getParameter("agentorByAgentId")));
if (agentType == 1) {//流程代理出去,本人强制归档,需先收回代理
AgentManager agentManager = new AgentManager(user);
agentManager.agentBackRequest(agentorByAgentId, user.getUID(), workflowid + "", requestid);
Date currentDate = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd");
SimpleDateFormat timeForamt = new SimpleDateFormat("HH:mm:ss");
new RecordSet().executeUpdate("update workflow_currentoperator set operatedate = ? , operatetime = ? where userid = ? and requestid = ? and (operatedate is null or operatedate < ' ' ) ",
dateFormat.format(currentDate), timeForamt.format(currentDate), user.getUID(), requestid);
}
if (fromflow.equals("1")) {
FileUpload fu = new FileUpload(request);
remark = Util.null2String(fu.getParameter("remark"));
workflowid = Util.getIntValue(fu.getParameter("workflowid"), -1);
nodeid = Util.getIntValue(fu.getParameter("nodeid"), -1);
// 获取签字意见相关文档,相关流程
signdocids = Util.null2String(fu.getParameter("signdocids"));
signworkflowids = Util.null2String(fu.getParameter("signworkflowids"));
String ismode = Util.null2String(request.getParameter("ismode"));
if (!ismode.equals("1")) {
RequestAnnexUpload rau = new RequestAnnexUpload();
rau.setRequest(fu);
rau.setUser(user);
annexdocids = rau.AnnexUpload();
} else {
String hasSign = "0";// 模板中是否设置了签字
RecordSet rs = new RecordSet();
rs.executeSql("select * from workflow_modeview where formid=" + formid + " and nodeid=" + nodeid + " and fieldid=-4");
if (rs.next())
hasSign = "1";
if ("1".equals(hasSign)) {// 模板中设置了签字
annexdocids = Util.null2String(fu.getParameter("qianzi"));
} else {// 模板中没有设置签字,按普通方式上传签字意见的附件
RequestAnnexUpload rau = new RequestAnnexUpload();
rau.setRequest(fu);
rau.setUser(user);
annexdocids = rau.AnnexUpload();
}
}
WFManager wfManager = new WFManager();
wfManager.setWfid(workflowid);
try {
wfManager.getWfInfo();
} catch (Exception e) {
e.printStackTrace();
}
String isShowChart = Util.null2s(wfManager.getIsShowChart().trim(),"0");
apidatas.put("isShowChart", isShowChart);
}
wfo.setRemark(remark);
wfo.setAnnexdocids(annexdocids);
wfo.setSigndocids(signdocids);
wfo.setSignworkflowids(signworkflowids);
wfo.setRequestLogId(requestLogId);
wfo.setRemarkLocation(remarkLocation);
WFUrgerManager wfum = new WFUrgerManager();
if (wffmu.haveOtherOperationRight(requestid) && !wfo.isOver(requestid) && (wfo.isNodeOperator(requestid, user.getUID()) || wfum.getMonitorViewRight(requestid, user.getUID()))) {
requestidlist.add("" + requestid);
wfo.doForceOver(requestidlist, request, response, user);
apidatas.put("success",1);
if(isnewFlag)
OvertimeBiz.getInstance().cancelOvertimeTask(requestid, nodeid);//取消超时任务
//no.2545225 强制归档需要触发节点附加操作,实现一键审批
try {
RequestManager requestManager = new RequestManager();
requestManager.setUser(user);
requestManager.setWorkflowid(workflowid);
requestManager.setRequestid(requestid);
WorkflowComInfo wfComInfo = new WorkflowComInfo();
int tempformid = Util.getIntValue(wfComInfo.getFormId(workflowid+""));
int tempisbill = Util.getIntValue(wfComInfo.getIsBill(workflowid+""));
String sql2 = "select nodeid from workflow_flownode where workflowid = ? and nodetype = 3";
RecordSet recordSet = new RecordSet();
recordSet.executeQuery(sql2,workflowid);
int tempnodeid = -1;
if(recordSet.next()) {
tempnodeid = recordSet.getInt("nodeid");
}
RequestCheckAddinRules requestCheckAddinRules = new RequestCheckAddinRules();
requestCheckAddinRules.resetParameter();
requestCheckAddinRules.setWorkflowid(workflowid);
requestCheckAddinRules.setRequestid(requestid);
requestCheckAddinRules.setNodeid(tempnodeid);
requestCheckAddinRules.setObjid(tempnodeid);
requestCheckAddinRules.setObjtype(1);
requestCheckAddinRules.setIsbill(tempisbill);
requestCheckAddinRules.setFormid(tempformid);
requestCheckAddinRules.setIspreadd("0");
requestCheckAddinRules.setRequestManager(requestManager);
requestCheckAddinRules.checkAddinRules();
} catch (Exception e) {
e.printStackTrace();
}
}else{
apidatas.put("success",0);
}
//判断是否属于流程测试
TestWorkflowCheckBiz testBiz = new TestWorkflowCheckBiz();
boolean belongTest = testBiz.judgeBelongTest(request, false);
if(belongTest) {
RecordSet rs = new RecordSet();
rs.executeQuery("select nodeid from workflow_flownode where workflowid = ? and nodetype = 3",workflowid);
rs.next();
WorkflowTestBiz.setWorkflowTestInfo(flag, requestid, nodeid, "", null,rs.getInt("nodeid"));
}
this.doArchiveRemind(workflowid,requestid);
new weaver.cpt.util.CptWfUtil().releaseFrozenCptnum(requestid+""); //清除资产冻结
}
// 强制收回
if ("rb".equals(flag)) {
WfForceDrawBack wfdb = new WfForceDrawBack();
RequestForceDrawBack requestForceDrawBack = new RequestForceDrawBack();
RequestOperationResultBean resultBean = new RequestOperationResultBean();
if (wffmu.haveOtherOperationRight(requestid) && wfdb.isHavePurview(requestid, user.getUID(), logintype, -1, -1)) {
requestidlist.add("" + requestid);
// WfForceDrawBack.doForceDrawBack(requestidsArr, request,
// response, -1, -1);
// 使用新的收回方式
String sessionkey = workflowid + "_" + nodeid + "_" + user.getUID() + "_" + System.currentTimeMillis();
int result = requestForceDrawBack.foreceDrawBack(user, requestid, false, -1, -1);
if (!requestForceDrawBack.isAddInOperateSuccess()) {//强制收回附加操作执行失败,返回错误信息
String message = requestForceDrawBack.getMessage();
String messagecontent = requestForceDrawBack.getMessageContent();
if("".equals(message) || requestid <= 0) {
message = "1";
}
resultBean.setMessageInfo(SubmitErrorMsgBiz.getMsgInfo(request,user,message,messagecontent));
resultBean.setType(RequestExecuteType.FAILD);
Util_TableMap.setObjVal(Util.null2String(sessionkey), resultBean);
apidatas.put("success",false);
apidatas.put("msg",SystemEnv.getHtmlLabelNames("506175,83071",user.getLanguage()));
return apidatas;
}
if (result == RequestForceDrawBack.OLDDATA) {
wfdb.doForceDrawBack(requestidlist, request, response, -1, -1);
}
RequestOperateBiz.drawBackSpecialTreatment(formid, workflowid);
/*E9打印登录超时报错(QC:527424)*/
if(user == null) {
try {
response.sendRedirect(weaver.general.GCONST.getContextPath()+"/wui/index.html");
return null;
} catch (IOException e) {
e.printStackTrace();
}
}
//判断是否可以跳转到新的页面
boolean reqRoute = ServiceUtil.isReqRoute(String.valueOf(requestid),user);
apidatas.put("reqRoute", reqRoute);
apidatas.put("success",result == RequestForceDrawBack.SUCCESS);
if(result == RequestForceDrawBack.SUCCESS){
apidatas.put("msg",SystemEnv.getHtmlLabelName(83585,user.getLanguage()));
}else if(result == RequestForceDrawBack.FAIL){
apidatas.put("msg",SystemEnv.getHtmlLabelName(389102,user.getLanguage()));
}else if(result == RequestForceDrawBack.NORIGHT){
apidatas.put("msg",SystemEnv.getHtmlLabelName(18567,user.getLanguage()));
}
apidatas.put("sessionkey", sessionkey);
}else {
apidatas.put("success",false);
apidatas.put("msg",SystemEnv.getHtmlLabelName(18567,user.getLanguage()));
}
}
//自动取消 流程关注
new RequestAttentionBiz().cancelAttention(requestid,flag);
return apidatas;
}
@Override
public BizLogContext getLogContext() {
String targetName = "";
String flag = Util.null2String(request.getParameter("flag"));
if ("stop".equals(flag)) {
targetName = "流程暂停";
} else if ("cancel".equals(flag)) {
targetName = "流程撤销";
} else if ("restart".equals(flag)) {
targetName = "流程启用";
} else if ("ov".equals(flag)) {
targetName = "强制归档";
} else if ("rb".equals(flag)) {
targetName = "强制收回";
}
BizLogContext bizLogContext = new BizLogContext();
BizLogOperateType bizLogOperateType = BizLogOperateType.APPROVE;
bizLogContext.setDateObject(new Date());
bizLogContext.setUserid(user.getUID());
bizLogContext.setUsertype(Util.getIntValue(user.getLogintype()));
bizLogContext.setTargetId("request_functionlink_" + flag);
bizLogContext.setTargetName(targetName);
bizLogContext.setLogType(BizLogType.WORKFLOW);
bizLogContext.setLogSmallType(BizLogSmallType4Workflow.WORKFLOW_APPROVE);
bizLogContext.setOperateType(bizLogOperateType);
bizLogContext.setClientIp(Util.null2String(Util.getIpAddr(request)));
bizLogContext.setParams(ParamUtil.request2Map(request));
bizLogContext.setDesc(String.format(user.getLastname() + "进行了"+targetName+"操作"));
return bizLogContext;
}
/**
*
* @param requestId
* @param user
* @param flag
*/
private boolean pushOperationMsg(int requestId,User user,String flag){
RequestOperationMsgManager romm = new RequestOperationMsgManager();
List<MsgEntity> requestMsgEntity = romm.getOperateMsgByReqId(String.valueOf(requestId),user,flag);
new MsgPushUtil().pushMsg(requestMsgEntity);
return true;
}
private void doArchiveRemind(int workflowid,int requestid){
String src = Util.null2String(request.getParameter("src"));
String remindTypes = Util.null2String(request.getParameter("remindTypes")); //表单上提醒方式
RequestRemindBiz requestRemindBiz = new RequestRemindBiz(user);
//默认提醒
WFManager wfManager = new WFManager();
try{
wfManager.setWfid(workflowid);
wfManager.getWfInfo();
}catch (Exception e){}
if("-1".equals(remindTypes)){ //老数据
int messageType = Util.getIntValue(Util.null2String(request.getParameter("messageType")),-1); // 老短信提醒
int mailMessageType = Util.getIntValue(Util.null2String(request.getParameter("chatsType")),-1); // 老邮件提醒
if(messageType >=1) requestRemindBiz.requestRemind(requestid,workflowid,src, RemindTypeEnum.SMS,messageType);
//历史数据可能只有短信提醒,但是其实也开启了邮件提醒
int _mailMessageType = Util.getIntValue(wfManager.getMailMessageType(),-1);
if(mailMessageType == 1 || _mailMessageType == 1) requestRemindBiz.requestRemind(requestid,workflowid,src,RemindTypeEnum.EMAIL,0);
Set<String> remindType = new HashSet<>();
if(messageType >=1) {
requestRemindBiz.requestRemind(requestid,workflowid,src,RemindTypeEnum.SMS,messageType);
}
if(mailMessageType == 1 || _mailMessageType == 1) {
requestRemindBiz.requestRemind(requestid,workflowid,src,RemindTypeEnum.EMAIL,0);
}
}else{
String isSmsRemind = remindTypes.indexOf(RemindTypeEnum.SMS.getCode()) > -1 ? "1" : "0";
String isEmailRemind = remindTypes.indexOf(RemindTypeEnum.EMAIL.getCode()) > -1 ? "1" : "0";
if("1".equals(isSmsRemind)) requestRemindBiz.requestRemind(requestid,workflowid,src,RemindTypeEnum.SMS,0);
if("1".equals(isEmailRemind)) requestRemindBiz.requestRemind(requestid,workflowid,src,RemindTypeEnum.EMAIL,0);
}
requestRemindBiz.requestEmailApproveRemind(String.valueOf(workflowid),String.valueOf(requestid),src);
}
public HttpServletRequest getRequest() {
return request;
}
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save