超发二开代码

This commit is contained in:
shilei 2025-09-29 10:43:32 +08:00
parent ce8e509ded
commit e7dee32fec
81 changed files with 46091 additions and 0 deletions

View File

@ -0,0 +1,24 @@
# 法大大 接口url
fadada_url=http://172.18.3.51:8072
# 法大大 对接 appid
fadada_appid=100003
# 法大大 对接 secret
fadada_secret=Sq3xcgWquEA56XU3hY4AGKsj
#
#
#
#
#
#
#
#

View File

@ -0,0 +1,59 @@
# \u75C5\u5047 7 \u5E74\u5047 2 \u4EA7\u5047 8 \u966A\u4EA7\u5047 9 \u5A5A\u5047 10 \u4E27\u5047 11 \u5DE5\u4F24\u5047 13 \u63A2\u4EB2\u5047 14 \u8C03\u4F11\u5047 15
halfday_leave_ids=7,2,9,10,11,14,15
# \u54FA\u4E73\u5047 \u5047\u671F\u7C7B\u578Bid 12
breastfeed_leave_id=12
# \u4E8B\u5047 \u5047\u671F\u7C7B\u578Bid
leaveabsencetype=6
# \u75C5\u5047 \u5047\u671F\u7C7B\u578Bid
sickleavetype=7
# \u5E74\u5047 \u5047\u671F\u7C7B\u578Bid
annualleavetype=2
# \u966A\u4EA7\u5047 \u5047\u671F\u7C7B\u578Bid
paternityleavetype=9
# \u5A5A\u5047 \u5047\u671F\u7C7B\u578Bid
marriageleavetype=10
# \u4E27\u5047 \u5047\u671F\u7C7B\u578Bid
bereavementleavetype=11
# \u63A2\u4EB2\u5047 \u5047\u671F\u7C7B\u578Bid
homeleavetype=14
# \u8C03\u4F11\u5047 \u5047\u671F\u7C7B\u578Bid
compensatory_leave_id=15
# \u4EA7\u5047 \u5047\u671F\u7C7B\u578Bid
maternity_leave_id=8
# \u5DE5\u4F24\u5047 \u5047\u671F\u7C7B\u578Bid
injuryLeave_leave_id=13
# \u7247\u533A \u4EBA\u5458\u5361\u7247\u81EA\u5B9A\u4E49\u5B57\u6BB5
area_fieldid=field137
# \u5C97\u4F4D\u540D\u79F0 \u4EBA\u5458\u5361\u7247\u81EA\u5B9A\u4E49\u5B57\u6BB5
position_fieldid=field128
# \u4F11\u606F\u73ED\u6B21 id
rest_serial_id=191
rest2_serial_id=2
# \u96C6\u56E2\u603B\u90E8\u884C\u653F\u73ED\u6B21 \u8003\u52E4\u7EC4id
the_top_groupid=209
# \u8F6C\u6B63\u65E5\u671F \u5DE5\u4F5C\u4FE1\u606F \u81EA\u5B9A\u4E49\u5B57\u6BB5id
zzrq_fieldid=field14
# \u79BB\u804C\u65E5\u671F \u5DE5\u4F5C\u4FE1\u606F \u81EA\u5B9A\u4E49\u5B57\u6BB5id
lzrq_fieldid=field49

View File

@ -0,0 +1,52 @@
# \uFFFD\uFFFD\u0221\uFFFD\uFFFD\uFFFD\u0432\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u03E2 \uFFFD\u04FF\uFFFDurl
get_all_dept_url=http://222.212.88.118:8989/api/v2/department/get/
# \uFFFD\uFFFD\u0221\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u0531\uFFFD\uFFFD\u03E2 \uFFFD\u04FF\uFFFDurl
get_all_user_url=http://222.212.88.118:8989/api/v2/employee/get/
# \uFFFD\u04FF\uFFFD\u01BE\u05A4 key
key=56b2gxturpnypuumxq4bpwhrj1_82cpu0nqwrslzkgzp
# \uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u00B2\uFFFD\uFFFD\uFFFD \uFFFD\u04FF\uFFFDurl
add_update_dept_url=http://222.212.88.118:8989/api/v2/department/update/
# \u027E\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD \uFFFD\u04FF\uFFFDurl
delete_dept_url=http://222.212.88.118:8989/api/v2/department/delete/
# \uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u0531 \uFFFD\u04FF\uFFFDurl
add_update_user_url=http://222.212.88.118:8989/api/v2/employee/update/
# \uFFFD\uFFFD\u0531\uFFFD\uFFFD\u05B0 \uFFFD\u04FF\uFFFDurl
leave_user_url=http://222.212.88.118:8989/api/v2/employee/leave/
# \u027E\uFFFD\uFFFD\uFFFD\uFFFD\u0531 \uFFFD\u04FF\uFFFDurl
#delete_user_url=http://222.212.88.118:8989/api/v2/employee/delete/
# \uFFFD\uFFFD\u0221\uFFFD\uFFFD\uFFFD\u06BC\uFFFD\u00BC \uFFFD\u04FF\uFFFDurl
get_kqinfo_url=http://222.212.88.118:8989/api/v2/transaction/get/
# \uFFFD\u043F\u063F\uFFFD\uFFFD\u06BB\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD \u0123\uFFFD\uFFFDid
zkkqjkqsj_formmodeid=38
# \uFFFD\uFFFD\uFFFD\u06BF\uFFFD\uFFFD\uFFFD \uFFFD\u0536\uFFFD\uFFFD\uFFFD\uFFFD\u05B6\uFFFDid
kq_fieldid=field38
# \uFFFD\uFFFD\uFFFD\uFFFD
kq_number=2000
# \uFFFD\uFFFD\u0531\uFFFD\uFFFD\uFFFD\uFFFD\u05B0\uFFFD\uFFFD\u03E2 \uFFFD\uFFFD\uFFFD\u0331\uFFFD\uFFFD\uFFFD
newuser_table=formtable_main_118
# \uFFFD\uFFFD\u05B0\u0237\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD \uFFFD\uFFFD\uFFFD\uFFFD
deleteuser_table=formtable_main_72
# HR\u036C\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u043F\u063F\uFFFD\uFFFD\u06BB\uFFFD\uFFFD\uFFFD\u00BC\uFFFD\uFFFD \u0123\uFFFD\uFFFDid
hrtozkkqj_formmodeid=103
lzyy_fieldid=8900
sfhl_fieldid=field150
restore_user_url=http://222.212.88.118:8989/api/v2/employee/restore/
zksfhf_fieldid=field151

View File

@ -0,0 +1,323 @@
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@page import="weaver.general.Util"%>
<%@ page import="weaver.conn.RecordSet" %>
<%@ page import="weaver.general.TimeUtil" %>
<%@ page import="com.alibaba.fastjson.JSONObject" %>
<%@ page import="java.util.*" %>
<%@ page import="com.alibaba.fastjson.JSONArray" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="java.text.ParseException" %>
<%@ page import="org.apache.http.client.methods.CloseableHttpResponse" %>
<%@ page import="org.apache.http.impl.client.CloseableHttpClient" %>
<%@ page import="org.apache.http.impl.client.HttpClients" %>
<%@ page import="org.apache.http.client.methods.HttpPost" %>
<%@ page import="org.apache.http.entity.StringEntity" %>
<%@ page import="org.apache.http.HttpEntity" %>
<%@ page import="org.apache.http.util.EntityUtils" %>
<%@ page import="java.io.IOException" %>
<%@ page import="com.fdd.utils.HttpUtil" %>
<%@ page import="com.fdd.dto.BaseDTO" %>
<%@ page import="com.fdd.utils.SignTypeEnum" %>
<%@ page import="com.fdd.utils.SignUtil" %>
<%@ page import="java.sql.Timestamp" %>
<%@ page import="java.text.DateFormat" %>
<%@ page import="weaver.file.Prop" %>
<%@ page import="java.net.URLEncoder" %>
<%@ page import="java.io.UnsupportedEncodingException" %>
<%@ page import="sun.misc.BASE64Encoder" %>
<%@ page import="com.alibaba.fastjson.JSON" %>
<%@ page import="java.security.MessageDigest" %>
<%@ page import="java.security.NoSuchAlgorithmException" %>
<jsp:useBean id="rs" class="weaver.conn.RecordSet" scope="page" />
<%
int sum = 0;
String type = Util.null2String(request.getParameter("type"));
String account = Util.null2String(request.getParameter("account"));
String adminAccountId = "";
String companyName = "";
String data = registerAccount(type,account,adminAccountId,companyName);
sum++;
%>
<%!
RecordSet rst = new RecordSet();
/**
* 项目部署后向项目经理申请对接Api的APPID
*/
private String APPID = rst.getPropValue("hrm_fadada", "fadada_appid");
/**
* 项目部署后向项目经理申请对接Api的APPSECRET
*/
private String APPSECRET = rst.getPropValue("hrm_fadada", "fadada_secret");
/**
* 项目部署后,对外访问的域名
*/
private String FDDHOST = rst.getPropValue("hrm_fadada", "fadada_url");
/**
* 注册账号
*/
public String registerAccount(String type, String account, String adminAccountId, String companyName) {
Map<String, Object> map = new HashMap<String, Object>();// 业务参数都放在这里
map.put("type", type);
map.put("account", account);
map.put("adminAccountId", adminAccountId);
map.put("companyName", companyName);
String rep = request("/account/register", map, "POST");
rst.writeLog("[ApiUtil.registerAccount]:注册账号接口返回参数:" + rep);
JSONObject jsonObject = JSONObject.parseObject(rep);
String data = jsonObject.getString("data");
return data;
}
/**
* 实名认证状态查询
* @param type 类型 1 为个人2为企业。
*/
public String personCertificationStatus(String type, String customerId) {
Map<String, Object> map = new HashMap<String, Object>();// 业务参数都放在这里
map.put("customerId", customerId);
String rep = "";
if ("1".equals(type)) {
rep = request("/certification/person/get-status", map, "POST");
} else if ("2".equals(type)) {
rep = request("/certification/company/get-status", map, "POST");
}
rst.writeLog("[ApiUtil.personCertificationStatus]实名认证状态查询接口返回参数:" + rep);
return rep;
}
/**
* @param url
* @param map
*/
public String request(String url, Map<String, Object> map, String type) {
String response = "";
try {
rst.writeLog("[ApiUtil.request]:接口传入业务参数:" + map.toString());
Map<String, Object> params = getParams(map);
rst.writeLog("[ApiUtil.request]:接口传入共通参数:" + params);
if ("POST".equals(type)) {
response = HttpUtil.postUrlAsJson(FDDHOST + url, params, "UTF-8");
} else if ("GET".equals(type)) {
response = getGetUrl(FDDHOST + url, params, "UTF-8");
}
} catch (Exception e) {
rst.writeLog("[ApiUtil.request]:错误信息:" + e.getMessage());
}
return response;
}
public Map<String, Object> getParams(Map<String, Object> map) {
Map<String, Object> params = null;
try {
String timestamp = getTimeStamp();// 获取时间戳
BaseDTO baseDTO = new BaseDTO();
baseDTO.setSignType(SignTypeEnum.SHA256.getValue());
baseDTO.setTimestamp(timestamp);
baseDTO.setAppId(APPID);
baseDTO.setAppSecret(APPSECRET);
String bizContent = bizContent(map);// 把所有业务参数
String sign = getSign(baseDTO.getAppId(), baseDTO.getAppSecret(), baseDTO.getSignType(),
baseDTO.getTimestamp(), bizContent);// 生成签名
params = new HashMap<String, Object>(8);
params.put("appId", APPID);
params.put("signType", SignTypeEnum.SHA256.getValue());
params.put("sign", sign);
params.put("timestamp", timestamp);
params.put("bizContent", bizContent);
} catch (Exception e) {
rst.writeLog("[ApiUtil.getParams]:错误信息:" + e.getMessage());
}
return params;
}
/**
* 根据数据获取签名
*
* @param appId
* @param appKey
* @param signType
* @param timestamp
* @param bizContent
* @return java.lang.String
* @author zhangq2@fadada.com
* @date 2019/1/2
*/
public static String getSign(String appId, String appKey, String signType, String timestamp, String bizContent)
throws Exception {
// 可以优化
Map<String, Object> map = new HashMap<String, Object>(10);
map.put("appId", appId);
map.put("signType", signType);
map.put("timestamp", timestamp);
map.put("bizContent", bizContent);
List<String> list = new ArrayList<String>(map.keySet());
Collections.sort(list);
StringBuilder builder = new StringBuilder();
for (String key : list) {
Object value = map.get(key);
if (null != value && !"".equals(value)) {
builder.append(key).append("=").append(value).append("&");
}
}
String content = builder.substring(0, builder.length() - 1);
String sign = "";
switch (SignTypeEnum.valueOf(signType)) {
case SHA256:
String sha256 = CryptTool.sha256(CryptTool.sha256(content) + appKey);
sign = CryptTool.encryptBASE64(sha256.getBytes("UTF-8"));
break;
case SHA1:
String sha1 = CryptTool.sha1(CryptTool.sha1(content) + appKey);
sign = CryptTool.encryptBASE64(sha1.getBytes("UTF-8"));
break;
case MD5:
String md5 = CryptTool.md5(CryptTool.md5(content) + appKey);
sign = CryptTool.encryptBASE64(md5.getBytes("UTF-8"));
break;
default:
break;
}
return sign.trim();
}
/**
* 获取时间戳
*
* @return
*/
public String getTimeStamp() {
Timestamp ts = new Timestamp(System.currentTimeMillis());
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(ts);
}
/**
* 获取手动签署地址
*/
public String getGetUrl(String url, Map<String, Object> params, String encode) {
StringBuffer buf = new StringBuffer(url);
if (params != null) {
// 地址增加?或者&
String flag = (url.indexOf('?') == -1) ? "?" : "&";
// 添加参数
for (String name : params.keySet()) {
buf.append(flag);
buf.append(name);
buf.append("=");
try {
String param = params.get(name).toString();
if (param == null) {
param = "";
}
buf.append(URLEncoder.encode(param, encode));
} catch (UnsupportedEncodingException e) {
}
flag = "&";
}
}
return buf.toString();
}
/**
* 将字符串转为base-64编码
* @param s
* @return
*/
public static String toBase64(String s) {
if (s == null) {
return s;
}
try {
BASE64Encoder base64Encoder = new BASE64Encoder();
return base64Encoder.encode(s.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return s;
}
}
/**
* 利用java原生的摘要实现SHA256加密
* @param str 加密后的报文
* @return
*/
public static String String2SHA256StrJava(String str){
MessageDigest messageDigest;
String encodeStr = "";
try {
messageDigest = MessageDigest.getInstance("SHA-256");
messageDigest.update(str.getBytes("UTF-8"));
encodeStr = byte2Hex(messageDigest.digest());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return encodeStr;
}
/**
* 将byte转为16进制
* @param bytes
* @return
*/
private static String byte2Hex(byte[] bytes){
StringBuffer stringBuffer = new StringBuffer();
String temp = null;
for (int i=0;i<bytes.length;i++){
temp = Integer.toHexString(bytes[i] & 0xFF);
if (temp.length()==1){
//1得到一位的进行补0操作
stringBuffer.append("0");
}
stringBuffer.append(temp);
}
return stringBuffer.toString();
}
/**
* 生成biz_content
*
* @param object
* @return
*/
public static String bizContent(Object object) {
String bizcont = "";
try {
// 将对象转为JSON字符串
String jsonObject = JSON.toJSONString(object);
// 将JSON字符串内特殊字符进行编码
String encodedObject = URLEncoder.encode(jsonObject, "UTF-8");
// 将编码后的JSON字符串进行base64加密
bizcont = toBase64(encodedObject);
} catch (Exception e) {
e.printStackTrace();
System.out.println("[SignUtil.bizContent]错误信息:" + e.getMessage());
}
return bizcont;
}
%>
<HEAD>
</HEAD>
<BODY>
<h1>Congratulation Mode 666666 !</h1>
<h1> sum <%=sum%> </h1>
<h1> data <%=data%> </h1>
</BODY>

View File

@ -0,0 +1,226 @@
<%@ page import="weaver.general.Util" %>
<%@ page import="java.math.BigDecimal" %>
<%@ page contentType="text/html; charset=UTF-8" %>
<jsp:useBean id="rs" class="weaver.conn.RecordSet" scope="page" />
<jsp:useBean id="bb" class="weaver.general.BaseBean" />
<%
int nodeid = Util.getIntValue(request.getParameter("nodeid"));//流程的节点id
bb.writeLog("========== 加班申请流程 nodeid ============"+ nodeid);
String sql = "select isstart from workflow_nodebase where id = " + nodeid;
rs.execute(sql);
rs.next();
int isstart = Util.getIntValue(rs.getString("isstart"));//判断是否是流程创建节点 1是 0
%>
<script type="text/javascript">
jQuery(document).ready(function(){
//计算日期相差天数
function calculateDaysBetweenDates(date1, date2) {
// 获取两个日期对象的时间戳
let time1 = new Date(date1).getTime();
let time2 = new Date(date2).getTime();
// 计算相差的毫秒数
let diff = Math.abs(time1 - time2);
// 将毫秒数转换为天数
let days = Math.floor(diff / (1000 * 60 * 60 * 24));
return days;
}
//时间比较yyyy-MM-dd
function compareTime(date1,date2) {
var standardDate1 = new Date(date1.getFullYear(), date1.getMonth(), date1.getDate());
var standardDate2 = new Date(date2.getFullYear(), date2.getMonth(), date2.getDate());
// 比较两个日期
if (standardDate1 >= standardDate2) {
return 1;
} else if (standardDate1 < standardDate2) {
return 0;
}
}
//加班人
let jbrs_id = WfForm.convertFieldNameToId("JBRD");
//加班日期
let jbrq_id = WfForm.convertFieldNameToId("JBRQ");
//加班开始时间
let jbqssj_id = WfForm.convertFieldNameToId("JBQSSJ");
//加班结束时间
let jbjssj_id = WfForm.convertFieldNameToId("JBJSSJ");
//明细1 姓名
let xm_mxid = WfForm.convertFieldNameToId("xm", "detail_1");
//明细1 加班开始日期
let jbksrq_mxid = WfForm.convertFieldNameToId("jbksrq", "detail_1");
//明细1 加班结束日期
let jbjsrq_mxid = WfForm.convertFieldNameToId("jbjsrq", "detail_1");
//明细1 加班开始时间
let jbkssj_mxid = WfForm.convertFieldNameToId("jbkssj", "detail_1");
//明细1 加班结束时间
let jbjssj_mxid = WfForm.convertFieldNameToId("jbjssj", "detail_1");
//姓名 值变化时
WfForm.bindDetailFieldChangeEvent(xm_mxid,function(id,rowIndex,value){
if(value){
//加班日期
let jbrq = WfForm.getFieldValue(jbrq_id);
//加班开始时间
let jbqssj = WfForm.getFieldValue(jbqssj_id);
//加班结束时间
let jbjssj = WfForm.getFieldValue(jbjssj_id);
//加班开始日期
WfForm.changeFieldValue(jbksrq_mxid+"_"+rowIndex,{value:jbrq});
//加班结束日期
WfForm.changeFieldValue(jbjsrq_mxid+"_"+rowIndex,{value:jbrq});
//加班开始时间
WfForm.changeFieldValue(jbkssj_mxid+"_"+rowIndex,{value:jbqssj});
//加班结束时间
WfForm.changeFieldValue(jbjssj_mxid+"_"+rowIndex,{value:jbjssj});
//触发字段联动
WfForm.triggerFieldAllLinkage("field15632_"+rowIndex);
}
});
WfForm.registerAction(WfForm.ACTION_ADDROW+"1", function(index){
// 姓名
let xm = WfForm.getFieldValue(xm_mxid+'_'+index);
if(xm != '' && xm !== undefined){
//加班日期
let jbrq = WfForm.getFieldValue(jbrq_id);
//加班开始时间
let jbqssj = WfForm.getFieldValue(jbqssj_id);
//加班结束时间
let jbjssj = WfForm.getFieldValue(jbjssj_id);
//加班开始日期
WfForm.changeFieldValue(jbksrq_mxid+"_"+index,{value:jbrq});
//加班结束日期
WfForm.changeFieldValue(jbjsrq_mxid+"_"+index,{value:jbrq});
//加班开始时间
WfForm.changeFieldValue(jbkssj_mxid+"_"+index,{value:jbqssj});
//加班结束时间
WfForm.changeFieldValue(jbjssj_mxid+"_"+index,{value:jbjssj});
//触发字段联动
WfForm.triggerFieldAllLinkage("field15632_"+rowIndex);
}
});
//加班人 值变化时
WfForm.bindFieldChangeEvent(jbrs_id, function(obj,id,value){
//加班日期
let jbrq = WfForm.getFieldValue(jbrq_id);
//加班开始时间
let jbqssj = WfForm.getFieldValue(jbqssj_id);
//加班结束时间
let jbjssj = WfForm.getFieldValue(jbjssj_id);
//加班人 有值
if(value){
//先清空明细1
WfForm.delDetailRow("detail_1", "all");
let jbrs = value.split(',');
// 加班日期、加班开始时间、加班结束时间 都有值,新增明细 1
if((jbrq!=null && jbrq!='' && jbrq !==undefined) && (jbqssj!=null && jbqssj!='' && jbqssj !==undefined) && (jbjssj!=null && jbjssj!='' && jbjssj !==undefined)){
for(var i=0;i<jbrs.length;i++) {
var jbr = jbrs[i];
WfForm.addDetailRow("detail_1",{field15634:{value:jbrq},field15636:{value:jbrq},field15635:{value:jbqssj},field15637:{value:jbjssj},
field15632:{value:jbr,specialobj:[{id:jbr,name:jbr}]}});
//触发字段联动
WfForm.triggerFieldAllLinkage("field15632_"+i);
}
}
}
});
//加班日期 值变化时
WfForm.bindFieldChangeEvent(jbrq_id, function(obj,id,value){
//加班人
let jbr = WfForm.getFieldValue(jbr_id);
//加班开始时间
let jbqssj = WfForm.getFieldValue(jbqssj_id);
//加班结束时间
let jbjssj = WfForm.getFieldValue(jbjssj_id);
//加班日期 有值
if(value){
}
});
//加班开始时间 值变化时
WfForm.bindFieldChangeEvent(jbqssj_id, function(obj,id,value){
//加班日期
let jbrq = WfForm.getFieldValue(jbrq_id);
//加班人
let jbr = WfForm.getFieldValue(jbr_id);
//加班结束时间
let jbjssj = WfForm.getFieldValue(jbjssj_id);
//加班开始时间 有值
if(value){
}
});
//加班结束时间 值变化时
WfForm.bindFieldChangeEvent(jbjssj_id, function(obj,id,value){
//加班日期
let jbrq = WfForm.getFieldValue(jbrq_id);
//加班人
let jbr = WfForm.getFieldValue(jbr_id);
//加班开始时间
let jbqssj = WfForm.getFieldValue(jbqssj_id);
//加班结束时间 有值
if(value){
}
});
// ============================= 请假申请流程 ================================
// 开始日期
let ksrq_id = WfForm.convertFieldNameToId("KSRQ");
// 结束日期
let jsrq_id = WfForm.convertFieldNameToId("JSRQ");
// 在点击保存或点击提交按钮时,判断 提交时间 不能晚于请假时间
WfForm.registerCheckEvent(WfForm.OPER_SAVE+","+WfForm.OPER_SUBMIT,function(callback){
let ksrq = WfForm.getFieldValue(ksrq_id);
let jsrq = WfForm.getFieldValue(jsrq_id);
let ksrq_date = new Date(ksrq);
let jsrq_date = new Date(jsrq);
let currentDate = new Date();
// 当前日期 > 开始日期
if(currentDate > ksrq_date){
// 当前日期 > 结束日期
if(currentDate > jsrq_date){
window.weaJs.alert('提交时间不能晚于请假时间!');
return;
}else{
callback();
}
}else {
callback();
}
});
// =============================== 加班申请流程 ===========================================
// 次月不可提交上月的加班单
WfForm.registerCheckEvent(WfForm.OPER_SAVE+","+WfForm.OPER_SUBMIT,function(callback){
let ksrq = WfForm.getFieldValue(ksrq_id);
let jsrq = WfForm.getFieldValue(jsrq_id);
let ksrq_date = new Date(ksrq);
let jsrq_date = new Date(jsrq);
let currentDate = new Date();
// 当前日期 > 开始日期
if(currentDate > ksrq_date){
// 当前日期 > 结束日期
if(currentDate > jsrq_date){
window.weaJs.alert('提交时间不能晚于请假时间!');
return;
}else{
callback();
}
}else {
callback();
}
});
});
</script>

View File

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

View File

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

View File

@ -0,0 +1,44 @@
<%@ page import="weaver.general.Util" %>
<%@ page contentType="text/html; charset=UTF-8" %>
<jsp:useBean id="rs" class="weaver.conn.RecordSet" scope="page" />
<jsp:useBean id="bb" class="weaver.general.BaseBean" />
<%
int nodeid = Util.getIntValue(request.getParameter("nodeid"));//流程的节点id
bb.writeLog("========== 请假流程 nodeid ============"+ nodeid);
String sql = "select isstart from workflow_nodebase where id = " + nodeid;
rs.execute(sql);
rs.next();
int isstart = Util.getIntValue(rs.getString("isstart"));//判断是否是流程创建节点 1是 0
%>
<script type="text/javascript">
jQuery(document).ready(function(){
//请假类型
let qjlx_id = WfForm.convertFieldNameToId("newLeaveType");
//假期余额
let jqye_id = WfForm.convertFieldNameToId("vacationInfo");
let qjlx = WfForm.getFieldValue(qjlx_id);
// 调休假,隐藏 假期余额
if(qjlx == '15'){
WfForm.changeFieldAttr(jqye_id, 4);
}
//请假类型 值变化时
WfForm.bindFieldChangeEvent(qjlx_id,function(id,rowIndex,value){
if(value){
// 调休假,隐藏 假期余额
if(value == '15'){
WfForm.changeFieldAttr(jqye_id, 4);
}
}
});
});
</script>

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,39 @@
<%@ page import="com.alibaba.fastjson.JSONObject" %>
<%@ page import="com.alibaba.fastjson.JSONArray" %>
<%@ page import="weaver.general.Util" %>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<jsp:useBean id="rs" class="weaver.conn.RecordSet" scope="page" />
<%
int sum = 0;
JSONObject json = new JSONObject();
JSONArray array = new JSONArray();
rs.executeQuery("select top 10 * from uf_kqjysdkjl");
while(rs.next()){
JSONObject jsonObject = new JSONObject();
String modedatacreatedate = Util.null2String(rs.getString("modedatacreatedate"));
String modedatacreatetime = Util.null2String(rs.getString("modedatacreatetime"));
jsonObject.put("modedatacreatedate",modedatacreatedate);
jsonObject.put("modedatacreatetime",modedatacreatetime);
array.add(jsonObject);
}
json.put("key",array);
%>
<BODY>
<h1>Congratulation Mode 666666 !</h1>
<h1> sum <%=sum%> </h1>
<h1> json <%=json%> </h1>
</BODY>

View File

@ -0,0 +1,103 @@
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@page import="weaver.general.Util"%>
<%@ page import="java.math.BigDecimal" %>
<jsp:useBean id="rs" class="weaver.conn.RecordSet" scope="page" />
<jsp:useBean id="rs1" class="weaver.conn.RecordSet" scope="page" />
<jsp:useBean id="rss" class="weaver.conn.RecordSet" scope="page" />
<jsp:useBean id="rst" class="weaver.conn.RecordSet" scope="page" />
<%
int sub_sum = 0;
int dept_sum = 0;
String lsh = "1";
rs.executeQuery("select * from hrmsubcompany where canceled is null order by showOrderOfTree");
while(rs.next()){
String mxid = Util.null2String(rs.getString("id"));
String newlsh = "";
if(lsh.length() == 1){
newlsh = "LY000"+lsh;
}
if(lsh.length() == 2){
newlsh = "LY00"+lsh;
}
if(lsh.length() == 3){
newlsh = "LY0"+lsh;
}
if(lsh.length() == 4){
newlsh = "LY"+lsh;
}
boolean bool = rst.executeUpdate("update hrmsubcompany set subcompanycode=? where id = ?",newlsh,mxid);
if(bool){
lsh = floatAdd(lsh,"1");
sub_sum++;
}
String lshh = "1";
rs1.executeQuery("select * from hrmdepartment where canceled is null and subcompanyid1=? order by showOrderOfTree",mxid);
while(rs1.next()){
String deptid = Util.null2String(rs1.getString("id"));
String newlshh = "";
if(lshh.length() == 1){
newlshh = newlsh+"000"+lshh;
}
if(lshh.length() == 2){
newlshh = newlsh+"00"+lshh;
}
if(lshh.length() == 3){
newlshh = newlsh+"0"+lshh;
}
if(lshh.length() == 4){
newlshh = newlsh+lshh;
}
boolean booll = rss.executeUpdate("update hrmdepartment set departmentcode=? where id = ?",newlshh,deptid);
if(booll){
lshh = floatAdd(lshh,"1");
dept_sum++;
}
}
}
%>
<%!
/**
* 方法描述 : 对两个字符串进行金额的相加
* @param a
* @param b
* @return
* String
*/
public static String floatAdd(String a, String b) {
a=a.equals("")?"0":a;
b=b.equals("")?"0":b;
BigDecimal bg1 = new BigDecimal(a);
BigDecimal bg2 = new BigDecimal(b);
BigDecimal bd = bg1.add(bg2);
return bd.toString();
}
%>
<HEAD>
</HEAD>
<BODY>
<h1>Congratulation Mode 666666 !</h1>
<h1> 分部的 <%=sub_sum%> </h1>
<h1> 部门的 <%=dept_sum%> </h1>
</BODY>

View File

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

View File

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

View File

@ -0,0 +1,92 @@
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@page import="weaver.general.Util"%>
<%@ page import="java.math.BigDecimal" %>
<jsp:useBean id="rs" class="weaver.conn.RecordSet" scope="page" />
<jsp:useBean id="rst" class="weaver.conn.RecordSet" scope="page" />
<%
int detail_sum = 0;
int total_sum = 0;
String resourceId = Util.null2String(request.getParameter("userid"));
String fromDate = Util.null2String(request.getParameter("fromdate"));
String toDate = Util.null2String(request.getParameter("todate"));
rs.executeQuery("select * from kq_format_detail where resourceid = ? and kqdate >= ? and kqdate <= ?",resourceId,fromDate,toDate);
while(rs.next()){
//数据ID
String mxid = Util.null2o(rs.getString("id"));
//出勤时长
String attendanceMins = Util.null2o(rs.getString("attendanceMins"));
//迟到时长
String belatemins = Util.null2o(rs.getString("belatemins"));
//严重迟到时长
String graveBeLateMins = Util.null2o(rs.getString("graveBeLateMins"));
//早退时长
String leaveearlymins = Util.null2o(rs.getString("leaveearlymins"));
//严重早退时长
String graveLeaveEarlyMins = Util.null2o(rs.getString("graveLeaveEarlyMins"));
String attendancemins = floatAdd(attendanceMins,floatAdd(floatAdd(belatemins,graveBeLateMins),floatAdd(leaveearlymins,graveLeaveEarlyMins)));
boolean bool = rst.executeUpdate("update kq_format_detail set attendanceMins=? where id = ?",attendancemins,mxid);
if(bool){
detail_sum ++;
}
}
rs.executeQuery("select * from kq_format_total where resourceid = ? and kqdate >= ? and kqdate <= ?",resourceId,fromDate,toDate);
while(rs.next()){
//数据ID
String mxid = Util.null2o(rs.getString("id"));
//出勤时长
String attendanceMins = Util.null2o(rs.getString("attendanceMins"));
//迟到时长
String belatemins = Util.null2o(rs.getString("belatemins"));
//严重迟到时长
String graveBeLateMins = Util.null2o(rs.getString("graveBeLateMins"));
//早退时长
String leaveearlymins = Util.null2o(rs.getString("leaveearlymins"));
//严重早退时长
String graveLeaveEarlyMins = Util.null2o(rs.getString("graveLeaveEarlyMins"));
String attendancemins = floatAdd(attendanceMins,floatAdd(floatAdd(belatemins,graveBeLateMins),floatAdd(leaveearlymins,graveLeaveEarlyMins)));
boolean bool = rst.executeUpdate("update kq_format_total set attendanceMins=? where id = ?",attendancemins,mxid);
if(bool){
total_sum ++;
}
}
%>
<%!
/**
* 方法描述 : 对两个字符串进行金额的相加
* @param a
* @param b
* @return
* String
*/
public static String floatAdd(String a, String b) {
a=a.equals("")?"0":a;
b=b.equals("")?"0":b;
BigDecimal bg1 = new BigDecimal(a);
BigDecimal bg2 = new BigDecimal(b);
BigDecimal bd = bg1.add(bg2);
return bd.toString();
}
%>
<HEAD>
</HEAD>
<BODY>
<h1>Congratulation Mode 666666 !</h1>
<h1> 分部的 <%=sub_sum%> </h1>
<h1> 部门的 <%=dept_sum%> </h1>
</BODY>

View File

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

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,16 @@
package com.api.lingyue;
import com.engine.lingyue.web.SynOtherKqInfoAction;
import javax.ws.rs.Path;
/**
* @Title
* @Author wangchaofa
* @CreateDate 2024/7/17
* @Version 1.0
* @Description
*/
@Path("/lingyue/syn")
public class SynOtherKqInfoApi extends SynOtherKqInfoAction {
}

View File

@ -0,0 +1,231 @@
package com.engine.hrm.cmd.organization;
import com.api.hrm.util.ServiceUtil;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.biz.SimpleBizLogger;
import com.engine.common.constant.BizLogOperateAuditType;
import com.engine.common.constant.BizLogSmallType4Hrm;
import com.engine.common.constant.BizLogType;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.hrm.cmd.matrix.biz.MatrixMaintComInfo;
import com.engine.hrm.entity.RuleCodeType;
import com.engine.hrm.util.CodeRuleManager;
import com.engine.hrm.util.HrmOrganizationUtil;
import com.engine.hrm.util.face.HrmFaceCheckManager;
import com.lingyue.util.KqUtil;
import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.hrm.common.DbFunctionUtil;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.definedfield.HrmDeptFieldManagerE9;
import weaver.interfaces.email.CoreMailAPI;
import weaver.interfaces.hrm.HrmServiceManager;
import weaver.matrix.MatrixUtil;
import weaver.rtx.OrganisationCom;
import weaver.rtx.OrganisationComRunnable;
import weaver.systeminfo.SystemEnv;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class AddDepartmentCmd extends AbstractCommonCommand<Map<String, Object>>{
private SimpleBizLogger logger;
public AddDepartmentCmd(Map<String, Object> params, User user) {
this.user = user;
this.params = params;
String departmentname = Util.fromScreen((String)params.get("departmentname"),user.getLanguage());
this.logger = new SimpleBizLogger();
BizLogContext bizLogContext = new BizLogContext();
bizLogContext.setLogType(BizLogType.HRM_ENGINE);//模块类型
bizLogContext.setBelongType(BizLogSmallType4Hrm.HRM_ENGINE_ORGANIZATION);
bizLogContext.setLogSmallType(BizLogSmallType4Hrm.HRM_ENGINE_ORGANIZATION_DPEARTMENT);//当前小类型
bizLogContext.setOperateAuditType(BizLogOperateAuditType.WARNING);//警告
bizLogContext.setParams(params);//当前request请求参数
logger.setUser(user);//当前操作人
String mainSql = "select * from HrmDepartment where 1=2 ";
logger.setMainSql(mainSql,"id");//主表sql
logger.setMainPrimarykey("id");//主日志表唯一key
logger.setMainTargetNameColumn("departmentname");//当前targetName对应的列对应日志中的对象名
logger.before(bizLogContext);
}
@Override
public Map<String, Object> execute(CommandContext commandContext) {
Map<String, Object> retmap = new HashMap<String, Object>();
RecordSet rs = new RecordSet();
try {
if (!HrmUserVarify.checkUserRight("HrmDepartmentAdd:Add", user)) {
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage()));
return retmap;
}
DepartmentComInfo DepartmentComInfo = new DepartmentComInfo();
//OrganisationCom OrganisationCom = new OrganisationCom();
HrmServiceManager HrmServiceManager = new HrmServiceManager();
String departmentmark = Util.fromScreen((String)params.get("departmentmark"),user.getLanguage());
String departmentname = Util.fromScreen((String)params.get("departmentname"),user.getLanguage());
String subcompanyid1 = Util.fromScreen((String)params.get("subcompanyid1"),user.getLanguage());
int supdepid = Util.getIntValue((String)params.get("supdepid"),0);
String showorder = Util.fromScreen(Util.null2s((String)params.get("showorder"),"0"),user.getLanguage());
if(Util.getIntValue(subcompanyid1,0)<=0){
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(382647, user.getLanguage()));
return retmap;
}
String allsupdepid = "0";
String departmentcode = Util.fromScreen((String)params.get("departmentcode"),user.getLanguage());
int coadjutant=Util.getIntValue((String)params.get("coadjutant"),0);
/*
* Added by Charoes Huang
* 判断是否10级部门
*/
int supdepartmentid = supdepid;
if(supdepartmentid > 0){
Map<String, String> supMap = new HashMap<String, String>();
supMap.put(""+supdepid, "1");
int supdepidtemp = Util.getIntValue(DepartmentComInfo.getDepartmentsupdepid(""+supdepid), 0);
while(supdepidtemp>0){
if(supMap.get(""+supdepidtemp)==null){
supMap.put(""+supdepidtemp, "1");
supdepidtemp = Util.getIntValue(DepartmentComInfo.getDepartmentsupdepid(""+supdepidtemp), 0);
}else{
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(382650,user.getLanguage()));
return retmap;
}
}
if(HrmOrganizationUtil.ifDeptLevelEquals10(supdepartmentid)){
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(382650, user.getLanguage()));
return retmap;
}
}
// 如果编码为空 自动生成编码
departmentcode = CodeRuleManager.getCodeRuleManager().generateRuleCode(RuleCodeType.DEPARTMENT, subcompanyid1, departmentcode);
if(!"".equals(departmentcode)){
String sql2="select id from hrmdepartment where departmentcode = '" + departmentcode + "' ";
rs.executeSql(sql2);
if(rs.next()){
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(382653, user.getLanguage()));
return retmap;
}
}
char separator = Util.getSeparator() ;
if(supdepid > 0){//当选择了上级部门的时候需要更改当前部门的上级分部
subcompanyid1 = DepartmentComInfo.getSubcompanyid1(supdepid+"");
}
String para = departmentmark + separator + departmentname + separator +
supdepid+separator+allsupdepid+separator+subcompanyid1 + separator+ showorder+separator+coadjutant;
rs.executeProc("HrmDepartment_Insert",para);
int flag=rs.getFlag();
if(flag==2){
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(382655, user.getLanguage()));
return retmap;
}else if(flag==3){
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(382657, user.getLanguage()));
return retmap;
}
int id=0;
if(rs.next()){
id = rs.getInt(1);
}
weaver.hrm.company.OrgOperationUtil OrgOperationUtil = new weaver.hrm.company.OrgOperationUtil();
OrgOperationUtil.updateDepartmentLevel(""+id,"0");
String sql3="update hrmdepartment set departmentcode = '" + departmentcode + "' ";
sql3 += ","+ DbFunctionUtil.getInsertUpdateSetSql(rs.getDBType(),user.getUID()) ;
sql3+=" where id = "+id;
rs.executeSql(sql3);
HrmDeptFieldManagerE9 hrmDeptFieldManager = new HrmDeptFieldManagerE9(5);
hrmDeptFieldManager.editCustomData(params,id);
DepartmentComInfo.removeCompanyCache();
rs.executeSql("update orgchartstate set needupdate=1");
//add by wjy
//同步RTX端部门信息
//OrganisationCom.addDepartment(id);//执行速度过慢改为另起线程执行
new Thread(new OrganisationComRunnable("department", "add", String.valueOf(id))).start();
//同步到CoreMail邮件系统开始
if(supdepid == 0) {
CoreMailAPI.synOrg(""+id, departmentname, "parent_org_unit_id=com_"+subcompanyid1+"&org_unit_name="+departmentname, "0");
//testapi.synOrg(""+id, departmentname, "com_"+subcompanyid1, "0");
} else {
CoreMailAPI.synOrg(""+id, departmentname, "parent_org_unit_id="+supdepid+"&org_unit_name="+departmentname, "0");
//testapi.synOrg(""+id, departmentname, ""+supdepid, "0");
}
//同步到CoreMail邮件系统结束
//OA与第三方接口单条数据同步方法开始
HrmServiceManager.SynInstantDepartment(""+id,"1");
//OA与第三方接口单条数据同步方法结束
HrmFaceCheckManager.sync(id+"",HrmFaceCheckManager.getOptInsert(),this.getClass().getName(),HrmFaceCheckManager.getOaDepartment());
//同步部门数据到矩阵
MatrixUtil.updateDepartmentData(""+id);
//同步矩阵维护范围
MatrixMaintComInfo maintComInfo = new MatrixMaintComInfo();
maintComInfo.removeCache();
//初始化应用分权
new weaver.hrm.appdetach.AppDetachComInfo().initSubDepAppData();
// 同步部门数据到中控考勤机
KqUtil.synAddOrUpdateDeptInfo(""+id);
String mainSql = "select a.* from HrmDepartment a left join HrmDepartmentdefined b on a.id=b.deptid where a.id in(" + id + ")";
String tableColumns = new ServiceUtil().getTableColumns("select * from HrmDepartmentdefined", "b", "id");
if (!tableColumns.equals("")) {
mainSql = "select a.*," + tableColumns + " from HrmDepartment a left join HrmDepartmentdefined b on a.id=b.deptid where a.id in(" + id + ")";
}
logger.setMainSql(mainSql, "id");//主表sql
retmap.put("id", id);
retmap.put("status", "1");
retmap.put("message", SystemEnv.getHtmlLabelName(18758, user.getLanguage()));
} catch (Exception e) {
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(382661,user.getLanguage()));
writeLog(e);
}
return retmap;
}
@Override
public BizLogContext getLogContext() {
return null;
}
@Override
public List<BizLogContext> getLogContexts() {
return logger.getBizLogContexts();
}
}

View File

@ -0,0 +1,245 @@
package com.engine.hrm.cmd.organization;
import com.api.hrm.util.ServiceUtil;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.biz.SimpleBizLogger;
import com.engine.common.constant.BizLogOperateAuditType;
import com.engine.common.constant.BizLogSmallType4Hrm;
import com.engine.common.constant.BizLogType;
import com.engine.common.constant.ParamConstant;
import com.engine.common.entity.BizLogContext;
import com.engine.common.service.ThemeService;
import com.engine.common.service.impl.ThemeServiceImpl;
import com.engine.core.interceptor.CommandContext;
import com.engine.hrm.cmd.matrix.biz.MatrixMaintComInfo;
import com.engine.hrm.entity.RuleCodeType;
import com.engine.hrm.util.CodeRuleManager;
import com.engine.hrm.util.HrmOrganizationUtil;
import com.engine.hrm.util.face.HrmFaceCheckManager;
import com.lingyue.util.KqUtil;
import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.hrm.common.DbFunctionUtil;
import weaver.hrm.company.SubCompanyComInfo;
import weaver.hrm.definedfield.HrmDeptFieldManagerE9;
import weaver.interfaces.email.CoreMailAPI;
import weaver.interfaces.hrm.HrmServiceManager;
import weaver.matrix.MatrixUtil;
import weaver.rtx.OrganisationCom;
import weaver.rtx.OrganisationComRunnable;
import weaver.systeminfo.SystemEnv;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class AddSubCompanyCmd extends AbstractCommonCommand<Map<String, Object>> {
private SimpleBizLogger logger;
public AddSubCompanyCmd(Map<String, Object> params, User user) {
this.user = user;
this.params = params;
String subcompanyname = Util.fromScreen((String) params.get("subcompanyname"), user.getLanguage());
this.logger = new SimpleBizLogger();
BizLogContext bizLogContext = new BizLogContext();
bizLogContext.setLogType(BizLogType.HRM_ENGINE);//模块类型
bizLogContext.setBelongType(BizLogSmallType4Hrm.HRM_ENGINE_ORGANIZATION);
bizLogContext.setLogSmallType(BizLogSmallType4Hrm.HRM_ENGINE_ORGANIZATION_SUBCOMPANY);//当前小类型
bizLogContext.setOperateAuditType(BizLogOperateAuditType.WARNING);//警告
bizLogContext.setParams(params);//当前request请求参数
logger.setUser(user);//当前操作人
String mainSql = "select * from HrmSubCompany where 1=2 ";
logger.setMainSql(mainSql, "id");//主表sql
logger.setMainPrimarykey("id");//主日志表唯一key
logger.setMainTargetNameColumn("subcompanyname");//当前targetName对应的列对应日志中的对象名
logger.before(bizLogContext);
}
@Override
public Map<String, Object> execute(CommandContext commandContext) {
Map<String, Object> retmap = new HashMap<String, Object>();
try {
String sql = "";
RecordSet rs = null;
if (!HrmUserVarify.checkUserRight("HrmSubCompanyEdit:Edit", user)) {
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage()));
return retmap;
}
SubCompanyComInfo SubCompanyComInfo = new SubCompanyComInfo();
//OrganisationCom OrganisationCom = new OrganisationCom();
HrmServiceManager HrmServiceManager = new HrmServiceManager();
int companyid = 1;
int supsubcomid = Util.getIntValue((String) params.get("supsubcomid"), 0);
String subcompanycode = Util.fromScreen((String) params.get("subcompanycode"), user.getLanguage());
String subcompanyname = Util.fromScreen((String) params.get("subcompanyname"), user.getLanguage());
String subcompanydesc = Util.fromScreen((String) params.get("subcompanydesc"), user.getLanguage());
String url = Util.null2String((String) params.get("url"));
float showorder = Util.getFloatValue((String) params.get("showorder"), 0.00f);
int limitUsers = Util.getIntValue(Util.fromScreen((String) params.get("limitUsers"), user.getLanguage()), 0);
limitUsers = limitUsers < 0 ? 0 : limitUsers;
if (supsubcomid > 0) {
Map<String, String> supMap = new HashMap<String, String>();
supMap.put(""+supsubcomid, "1");
int supsubcomidtemp = Util.getIntValue(SubCompanyComInfo.getSupsubcomid(""+supsubcomid), 0);
while(supsubcomidtemp>0){
if(supMap.get(""+supsubcomidtemp)==null){
supMap.put(""+supsubcomidtemp, "1");
supsubcomidtemp = Util.getIntValue(SubCompanyComInfo.getSupsubcomid(""+supsubcomidtemp), 0);
}else{
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(382649,user.getLanguage()));
return retmap;
}
}
if (HrmOrganizationUtil.ifSubComLevelEquals10(supsubcomid)) {
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(382649, user.getLanguage()));
return retmap;
}
}
// 如果编码为空 自动生成编码
subcompanycode = CodeRuleManager.getCodeRuleManager().generateRuleCode(RuleCodeType.SUBCOMPANY, subcompanycode);
if (!"".equals(subcompanycode)) {
sql = "select id from HrmSubCompany where subcompanycode = '" + subcompanycode + "'";
rs = new RecordSet();
rs.executeSql(sql);
if (rs.next()) {
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(382651, user.getLanguage()));
return retmap;
}
}
char separator = Util.getSeparator();
String para = subcompanyname + separator + subcompanydesc + separator + companyid + separator + supsubcomid + separator + url + separator + showorder;
rs = new RecordSet();
rs.executeProc("HrmSubCompany_Insert", para);
int flag = rs.getFlag();
int id = 0;
if (rs.next()) {
id = rs.getInt(1);
}
if (flag == 2) {
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(382654, user.getLanguage()));
return retmap;
}
if (flag == 3) {
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(382656, user.getLanguage()));
return retmap;
}
sql = "update HrmSubCompany set subcompanycode = '" + subcompanycode + "'";
if (user.getUID() == 1){
sql += ", limitUsers = " + limitUsers;
}
sql += ","+ DbFunctionUtil.getInsertUpdateSetSql(rs.getDBType(),user.getUID()) ;
sql += " where id = " + id;
rs.executeSql(sql);
HrmDeptFieldManagerE9 hrmDeptFieldManager = new HrmDeptFieldManagerE9(4);
hrmDeptFieldManager.editCustomData(params,id);
// 更新机构权限数据新增加的分部默认继承上级分部的所有机构权限
para = String.valueOf(id) + separator + String.valueOf(supsubcomid);
rs = new RecordSet();
rs.executeProc("HrmRoleSRT_AddByNewSc", para);
//新增分部統一调用门户接口创建门户菜单
ThemeService themService = new ThemeServiceImpl();
themService.createSubCompanyMenu(id,supsubcomid);
// // 更新左侧菜单新增的分部继承上级分部的左侧菜单
// String strWhere = " where resourcetype=2 and resourceid=" + supsubcomid;
// if (supsubcomid == 0)
// strWhere = " where resourcetype=1 and resourceid=1 ";
// String strSql = "insert into leftmenuconfig (userid,infoid,visible,viewindex,resourceid,resourcetype,locked,lockedbyid,usecustomname,customname,customname_e) select distinct userid,infoid,visible,viewindex," + id + ",2,locked,lockedbyid,usecustomname,customname,customname_e from leftmenuconfig " + strWhere;
// rs = new RecordSet();
// rs.executeSql(strSql);
//
// // 更新顶部菜单新增的分部继承上级分部的顶部菜单
// strWhere = " where resourcetype=2 and resourceid=" + supsubcomid;
// if (supsubcomid == 0)
// strWhere = " where resourcetype=1 and resourceid=1 ";
// strSql = "insert into mainmenuconfig (userid,infoid,visible,viewindex,resourceid,resourcetype,locked,lockedbyid,usecustomname,customname,customname_e) select distinct userid,infoid,visible,viewindex," + id + ",2,locked,lockedbyid,usecustomname,customname,customname_e from mainmenuconfig " + strWhere;
// rs = new RecordSet();
// rs.executeSql(strSql);
SubCompanyComInfo.removeCompanyCache();
rs = new RecordSet();
rs.executeSql("update orgchartstate set needupdate=1");
weaver.hrm.company.OrgOperationUtil OrgOperationUtil = new weaver.hrm.company.OrgOperationUtil();
OrgOperationUtil.updateSubcompanyLevel("" + id, "0");
//OrganisationCom.addSubCompany(id);//执行速度过慢改成另起现成执行
new Thread(new OrganisationComRunnable("subcompany", "add", String.valueOf(id))).start();
// 同步到CoreMail邮件系统开始
if (supsubcomid > 0) {
CoreMailAPI.synOrg("com_" + id, subcompanyname, "parent_org_unit_id=com_" + supsubcomid + "&org_unit_name=" + subcompanyname, "0");
// testapi.synOrg("com_"+id, subcompanyname, "com_"+supsubcomid, "0");
} else {
CoreMailAPI.synOrg("com_" + id, subcompanyname, "org_unit_name=" + subcompanyname, "0");
// testapi.synOrg("com_"+id, subcompanyname, "", "0");
}
// 同步到CoreMail邮件系统结束
// OA与第三方接口单条数据同步方法开始
HrmServiceManager.SynInstantSubCompany("" + id, "1");
// OA与第三方接口单条数据同步方法结束
HrmFaceCheckManager.sync(id+"",HrmFaceCheckManager.getOptInsert(),"HRM_AddSubCompanyCmd",HrmFaceCheckManager.getOaSubcompany());
// 同步分部数据到矩阵
MatrixUtil.updateSubcompayData("" + id);
//同步矩阵维护范围
MatrixMaintComInfo maintComInfo = new MatrixMaintComInfo();
maintComInfo.removeCache();
// 初始化应用分权
new weaver.hrm.appdetach.AppDetachComInfo().initSubDepAppData();
// 同步分部数据到中控考勤机
KqUtil.synAddOrUpdateSubComInfo(""+id);
String mainSql = "select a.* from HrmSubCompany a left join hrmsubcompanydefined b on a.id=b.subcomid where a.id in(" + id + ") ";
String tableColumns = new ServiceUtil().getTableColumns("select * from hrmsubcompanydefined", "b", "id");
if (!tableColumns.equals("")) {
mainSql = "select a.*," + tableColumns + " from HrmSubCompany a left join hrmsubcompanydefined b on a.id=b.subcomid where a.id in(" + id + ") ";
}
logger.setMainSql(mainSql, "id");//主表sql
retmap.put("id", id);
retmap.put("status", "1");
retmap.put("message", SystemEnv.getHtmlLabelName(18758, user.getLanguage()));
} catch (Exception e) {
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(382661,user.getLanguage()));
writeLog(e);
}
return retmap;
}
@Override
public BizLogContext getLogContext() {
return null;
}
@Override
public List<BizLogContext> getLogContexts() {
return logger.getBizLogContexts();
}
}

View File

@ -0,0 +1,175 @@
package com.engine.hrm.cmd.organization;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.biz.SimpleBizLogger;
import com.engine.common.constant.BizLogOperateAuditType;
import com.engine.common.constant.BizLogSmallType4Hrm;
import com.engine.common.constant.BizLogType;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.hrm.util.face.HrmFaceCheckManager;
import com.lingyue.util.KqUtil;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.hrm.common.DbFunctionUtil;
import weaver.hrm.company.DepartmentComInfo;
import weaver.interfaces.email.CoreMailAPI;
import weaver.interfaces.hrm.HrmServiceManager;
import weaver.matrix.MatrixUtil;
import weaver.rtx.OrganisationCom;
import weaver.systeminfo.SystemEnv;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CancelDepartmentCmd extends AbstractCommonCommand<Map<String, Object>>{
private SimpleBizLogger logger;
public CancelDepartmentCmd(Map<String, Object> params, User user) {
this.user = user;
this.params = params;
this.logger = new SimpleBizLogger();
String id = Util.null2String(params.get("id"));
BizLogContext bizLogContext = new BizLogContext();
bizLogContext.setLogType(BizLogType.HRM_ENGINE);//模块类型
bizLogContext.setBelongType(BizLogSmallType4Hrm.HRM_ENGINE_ORGANIZATION);
bizLogContext.setLogSmallType(BizLogSmallType4Hrm.HRM_ENGINE_ORGANIZATION_DPEARTMENT);//当前小类型
bizLogContext.setOperateAuditType(BizLogOperateAuditType.WARNING);//警告
bizLogContext.setParams(params);//当前request请求参数
logger.setUser(user);//当前操作人
String mainSql = "select * from Hrmdepartment where id in("+id+")";
logger.setMainSql(mainSql,"id");//主表sql
logger.setMainPrimarykey("id");//主日志表唯一key
logger.setMainTargetNameColumn("departmentname");//当前targetName对应的列对应日志中的对象名
logger.before(bizLogContext);
}
@Override
public Map<String, Object> execute(CommandContext commandContext) {
Map<String, Object> retmap = new HashMap<String, Object>();
try {
if(!HrmUserVarify.checkUserRight("HrmDepartmentAdd:Add", user)){
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage()));
return retmap;
}
String ids = Util.null2String((String)params.get("id"));
String[] arrIds = Util.splitString(ids, ",");
if(arrIds.length>1){
for(int i=0; i<arrIds.length;i++){
int id = Util.getIntValue(arrIds[i]);
this.cancel(id);
}
}else{
int id = Util.getIntValue(ids);
retmap = this.cancel(id);
if(!retmap.isEmpty()){
return retmap;
}
}
retmap.put("status", "1");
retmap.put("message", SystemEnv.getHtmlLabelName(22155, user.getLanguage()));
} catch (Exception e) {
writeLog(e);
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(22155, user.getLanguage()));
}
return retmap;
}
private Map<String, Object> cancel(int id) throws Exception {
Map<String, Object> retmap = new HashMap<String, Object>();
try {
if(!HrmUserVarify.checkUserRight("HrmDepartmentEdit:Edit", user)){
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage()));
return retmap;
}
RecordSet rs = new RecordSet();
DepartmentComInfo DepartmentComInfo = new DepartmentComInfo();
OrganisationCom OrganisationCom = new OrganisationCom();
HrmServiceManager HrmServiceManager = new HrmServiceManager();
String deptorsubname = "";
String sqlname = "";
String supdepid = "";
String subcompanyid1 = "";
sqlname = "select departmentname, supdepid, subcompanyid1 from hrmdepartment where id = "+id;
rs.executeSql(sqlname);
if(rs.next()) {
deptorsubname = rs.getString("departmentname");
supdepid = Util.null2String(rs.getString("supdepid"));
subcompanyid1 = Util.null2String(rs.getString("subcompanyid1"));
}
String sqlstr = "select id from hrmresource where status in (0,1,2,3)"
+ " and EXISTS (select 1 from hrmdepartment b where hrmresource.departmentid=b.id and b.id = "
+ id +")";
rs.executeSql(sqlstr);
if (rs.next()) {
//部门下有在职的人员
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(82293, user.getLanguage()));
return retmap;
}
sqlstr = " select id from hrmdepartment where (canceled = '0' or canceled is null) and id in (select id from hrmdepartment where supdepid = "
+ id + ")";
rs.executeSql(sqlstr);
if (rs.next()) {
//部门存在下级部门
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(82294, user.getLanguage()));
return retmap;
}
// 同步 删除 中控考勤机 部门数据
KqUtil.synDeleteDeptInfo(""+id);
rs.executeSql("update hrmdepartment set canceled = '1', "+ DbFunctionUtil.getUpdateSetSql(rs.getDBType(),user.getUID())+" where id ="+ id);
DepartmentComInfo.removeCompanyCache();
OrganisationCom.deleteDepartment(id);//部门封存时同步到RTX
//部门封存时同步到邮件系统
if("0".equals(supdepid)) {
CoreMailAPI.synOrg(""+id, deptorsubname, "parent_org_unit_id=com_"+subcompanyid1+"&org_unit_name="+deptorsubname, "1");
//testapi.synOrg(""+deptorsupid, deptorsubname, "com_"+subcompanyid1, "1");
} else {
CoreMailAPI.synOrg(""+id, deptorsubname, "parent_org_unit_id="+supdepid+"&org_unit_name="+deptorsubname, "1");
//testapi.synOrg(""+deptorsupid, deptorsubname, ""+supdepid, "1");
}
//OA与第三方接口单条数据同步方法开始
HrmServiceManager.SynInstantDepartment(""+id,"3");
//OA与第三方接口单条数据同步方法结束
HrmFaceCheckManager.sync(id+"",HrmFaceCheckManager.getOptUpdate(),this.getClass().getName(),HrmFaceCheckManager.getOaDepartment());
//同步部门数据到矩阵
MatrixUtil.updateDepartmentData(""+id);
} catch (Exception e) {
writeLog(e);
throw e;
}
return retmap;
}
@Override
public BizLogContext getLogContext() {
return null;
}
@Override
public List<BizLogContext> getLogContexts() {
return logger.getBizLogContexts();
}
}

View File

@ -0,0 +1,165 @@
package com.engine.hrm.cmd.organization;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.biz.SimpleBizLogger;
import com.engine.common.constant.BizLogOperateAuditType;
import com.engine.common.constant.BizLogSmallType4Hrm;
import com.engine.common.constant.BizLogType;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.hrm.util.face.HrmFaceCheckManager;
import com.lingyue.util.KqUtil;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.hrm.common.DbFunctionUtil;
import weaver.hrm.company.SubCompanyComInfo;
import weaver.interfaces.email.CoreMailAPI;
import weaver.interfaces.hrm.HrmServiceManager;
import weaver.matrix.MatrixUtil;
import weaver.rtx.OrganisationCom;
import weaver.systeminfo.SystemEnv;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CancelSubCompanyCmd extends AbstractCommonCommand<Map<String, Object>>{
private SimpleBizLogger logger;
public CancelSubCompanyCmd(Map<String, Object> params, User user) {
this.user = user;
this.params = params;
this.logger = new SimpleBizLogger();
String id = Util.null2String(params.get("id"));
BizLogContext bizLogContext = new BizLogContext();
bizLogContext.setLogType(BizLogType.HRM_ENGINE);//模块类型
bizLogContext.setBelongType(BizLogSmallType4Hrm.HRM_ENGINE_ORGANIZATION);
bizLogContext.setLogSmallType(BizLogSmallType4Hrm.HRM_ENGINE_ORGANIZATION_SUBCOMPANY);//当前小类型
bizLogContext.setOperateAuditType(BizLogOperateAuditType.WARNING);//警告
bizLogContext.setParams(params);//当前request请求参数
logger.setUser(user);//当前操作人
String mainSql = "select * from HrmSubCompany where id in("+id+")";
logger.setMainSql(mainSql,"id");//主表sql
logger.setMainPrimarykey("id");//主日志表唯一key
logger.setMainTargetNameColumn("subcompanyname");//当前targetName对应的列对应日志中的对象名
logger.before(bizLogContext);
}
@Override
public Map<String, Object> execute(CommandContext commandContext) {
Map<String, Object> retmap = new HashMap<String, Object>();
try {
if(!HrmUserVarify.checkUserRight("HrmSubCompanyEdit:Edit", user)){
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage()));
return retmap;
}
String ids = Util.null2String((String)params.get("id"));
String[] arrIds = Util.splitString(ids, ",");
if(arrIds.length>1){
for(int i=0; i<arrIds.length;i++){
int id = Util.getIntValue(arrIds[i]);
this.cancel(id);
}
}else{
int id = Util.getIntValue(ids);
retmap = this.cancel(id);
if(!retmap.isEmpty()){
return retmap;
}
}
retmap.put("status", "1");
retmap.put("message", SystemEnv.getHtmlLabelName(22155, user.getLanguage()));
} catch (Exception e) {
writeLog(e);
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(382661, user.getLanguage()));
}
return retmap;
}
private Map<String, Object> cancel(int id) throws Exception {
Map<String, Object> retmap = new HashMap<String, Object>();
try {
RecordSet rs = new RecordSet();
SubCompanyComInfo SubCompanyComInfo = new SubCompanyComInfo();
OrganisationCom OrganisationCom = new OrganisationCom();
HrmServiceManager HrmServiceManager = new HrmServiceManager();
int supsubcomid = 0;
String deptorsubname = "";
String sqlname = "";
sqlname = "select subcompanyname, supsubcomid from HrmSubCompany where id = "+id;
rs.executeSql(sqlname);
if(rs.next()) {
deptorsubname = rs.getString("subcompanyname");
supsubcomid = Util.getIntValue(rs.getString("supsubcomid"), 0);
}
String sqlstr = "select id from hrmdepartment where (canceled = '0' or canceled is null) "
+ " and exists (select 1 from hrmsubcompany b where hrmdepartment.subcompanyid1 = b.id and b.id ="+ id+ ")";
rs.executeSql(sqlstr);
if (rs.next()) {
//分部下存在部门
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(82296, user.getLanguage()));
return retmap;
}
sqlstr = " select id from hrmsubcompany where (canceled = '0' or canceled is null) and id in (select id from hrmsubcompany where supsubcomid ="+ id + ")";
rs.executeSql(sqlstr);
if (rs.next()) {
//分部下存在下级分部
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(82295, user.getLanguage()));
return retmap;
}
// 同步 删除 中控考勤机 部门数据
KqUtil.synDeleteSubComInfo(""+id);
rs.executeSql("update HrmSubCompany set canceled = '1' , "+ DbFunctionUtil.getUpdateSetSql(rs.getDBType(),user.getUID())+" where id ="+ id);
SubCompanyComInfo.removeCompanyCache();
OrganisationCom.deleteSubCompany(id);//分部封存时同步到RTX
//分部封存时同步到CoreMail邮件系统
if(supsubcomid == 0) {
CoreMailAPI.synOrg("com_"+id, deptorsubname, "org_unit_name="+deptorsubname, "1");
//testapi.synOrg("com_"+deptorsupid, deptorsubname, "", "1");
} else {
CoreMailAPI.synOrg("com_"+id, deptorsubname, "parent_org_unit_id=com_"+supsubcomid+"&org_unit_name="+deptorsubname, "1");
//testapi.synOrg("com_"+deptorsupid, deptorsubname, "com_"+supsubcomid, "1");
}
//OA与第三方接口单条数据同步方法开始
HrmServiceManager.SynInstantSubCompany(""+id,"3");
//OA与第三方接口单条数据同步方法结束
HrmFaceCheckManager.sync(id+"",HrmFaceCheckManager.getOptUpdate(),"HRM_CancelSubCompanyCmd",HrmFaceCheckManager.getOaSubcompany());
//同步分部数据到矩阵
MatrixUtil.updateSubcompayData(""+id);
} catch (Exception e) {
writeLog(e);
throw e;
}
return retmap;
}
@Override
public BizLogContext getLogContext() {
return null;
}
@Override
public List<BizLogContext> getLogContexts() {
return logger.getBizLogContexts();
}
}

View File

@ -0,0 +1,182 @@
package com.engine.hrm.cmd.organization;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.biz.SimpleBizLogger;
import com.engine.common.constant.BizLogOperateAuditType;
import com.engine.common.constant.BizLogSmallType4Hrm;
import com.engine.common.constant.BizLogType;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.hrm.util.face.HrmFaceCheckManager;
import com.lingyue.util.KqUtil;
import weaver.conn.RecordSet;
import org.apache.commons.lang3.StringUtils;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.hrm.company.DepartmentComInfo;
import weaver.integration.framework.data.record.SimpleRecordData;
import weaver.interfaces.email.CoreMailAPI;
import weaver.interfaces.hrm.HrmServiceManager;
import weaver.matrix.MatrixUtil;
import weaver.rtx.OrganisationCom;
import weaver.systeminfo.SystemEnv;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DelDepartmentCmd extends AbstractCommonCommand<Map<String, Object>>{
private SimpleBizLogger logger;
public DelDepartmentCmd(Map<String, Object> params, User user) {
this.user = user;
this.params = params;
this.logger = new SimpleBizLogger();
String id = Util.null2String(params.get("id"));
BizLogContext bizLogContext = new BizLogContext();
bizLogContext.setLogType(BizLogType.HRM_ENGINE);//模块类型
bizLogContext.setBelongType(BizLogSmallType4Hrm.HRM_ENGINE_ORGANIZATION);
bizLogContext.setLogSmallType(BizLogSmallType4Hrm.HRM_ENGINE_ORGANIZATION_DPEARTMENT);//当前小类型
bizLogContext.setOperateAuditType(BizLogOperateAuditType.WARNING);//警告
bizLogContext.setParams(params);//当前request请求参数
logger.setUser(user);//当前操作人
String mainSql = "select * from Hrmdepartment where id in("+id+")";
logger.setMainSql(mainSql,"id");//主表sql
logger.setMainPrimarykey("id");//主日志表唯一key
logger.setMainTargetNameColumn("departmentname");//当前targetName对应的列对应日志中的对象名
logger.before(bizLogContext);
}
@Override
public Map<String, Object> execute(CommandContext commandContext) {
Map<String, Object> retmap = new HashMap<String, Object>();
try {
if(!HrmUserVarify.checkUserRight("HrmDepartmentEdit:Delete", user)){
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage()));
return retmap;
}
String ids = Util.null2String((String)params.get("id"));
retmap = checkCanDelelte(ids) ;
if(!retmap.isEmpty()){
return retmap;
}
String[] arrIds = Util.splitString(ids, ",");
if(arrIds.length>1){
for(int i=0; i<arrIds.length;i++){
int id = Util.getIntValue(arrIds[i]);
this.del(id);
}
}else{
int id = Util.getIntValue(ids);
retmap = this.del(id);
if(!retmap.isEmpty()){
return retmap;
}
}
retmap.put("status", "1");
retmap.put("message", SystemEnv.getHtmlLabelName(22155, user.getLanguage()));
} catch (Exception e) {
writeLog(e);
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(22155, user.getLanguage()));
}
return retmap;
}
private Map<String, Object> checkCanDelelte(String id)throws Exception{
if(StringUtils.isBlank(id)) throw new Exception("删除部门错误id为空") ;
Map<String, Object> retmap = new HashMap<String, Object>();
RecordSet rs = new RecordSet();
String sql = "select count(id) from HrmResource where departmentid in ("+id+")";
rs.execute(sql) ;
rs.next();
if(rs.getInt(1)>0){
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(33594,user.getLanguage()));
return retmap;
}
return retmap;
}
private Map<String, Object> del(int id) throws Exception {
Map<String, Object> retmap = new HashMap<String, Object>();
try {
String sql = "";
RecordSet rs = new RecordSet();;
DepartmentComInfo DepartmentComInfo = new DepartmentComInfo();
OrganisationCom OrganisationCom = new OrganisationCom();
HrmServiceManager HrmServiceManager = new HrmServiceManager();
String departmentname = "";
int supdepid = 0;
String subcompanyid1 = "";
rs.executeSql("select departmentname, supdepid, subcompanyid1 from HrmDepartment where id = " + id);
if(rs.next()) {
departmentname = Util.null2String(rs.getString("departmentname"));
supdepid = Util.getIntValue(rs.getString("supdepid"), 0);
subcompanyid1 = Util.null2String(rs.getString("subcompanyid1"));
}
String para = ""+id;
// 同步 删除 中控考勤机 部门数据
KqUtil.synDeleteDeptInfo(""+id);
SimpleRecordData recordData = HrmFaceCheckManager.syncQuery(id+"",HrmFaceCheckManager.getOptDelete(),HrmFaceCheckManager.getOaDepartment());
rs.executeProc("HrmDepartment_Delete",para);
rs.executeUpdate("delete from HrmDepartmentDefined WHERE deptid= " +id);
//add by wjy
//同步RTX端部门信息
OrganisationCom.deleteDepartment(id);
//同步到CoreMail邮件系统开始
if(supdepid == 0) {
CoreMailAPI.synOrg(""+id, departmentname, "parent_org_unit_id=com_"+subcompanyid1+"&org_unit_name="+departmentname, "1");
//testapi.synOrg(""+id, departmentname, "com_"+subcompanyid1, "1");
} else {
CoreMailAPI.synOrg(""+id, departmentname, "parent_org_unit_id="+supdepid+"&org_unit_name="+departmentname, "1");
//testapi.synOrg(""+id, departmentname, ""+supdepid, "1");
}
//同步到CoreMail邮件系统结束
//OA与第三方接口单条数据同步方法开始
HrmServiceManager.SynInstantDepartment(""+id,"3");
//OA与第三方接口单条数据同步方法结束
HrmFaceCheckManager.sync(id+"",HrmFaceCheckManager.getOptDelete(),this.getClass().getName(),HrmFaceCheckManager.getOaDepartment(),recordData);
DepartmentComInfo.removeCompanyCache();
rs.executeSql("update orgchartstate set needupdate=1");
//同步部门数据到矩阵
MatrixUtil.updateDepartmentData(""+id);
} catch (Exception e) {
writeLog(e);
throw e;
}
return retmap;
}
@Override
public BizLogContext getLogContext() {
return null;
}
@Override
public List<BizLogContext> getLogContexts() {
return logger.getBizLogContexts();
}
}

View File

@ -0,0 +1,205 @@
package com.engine.hrm.cmd.organization;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.biz.SimpleBizLogger;
import com.engine.common.constant.BizLogOperateAuditType;
import com.engine.common.constant.BizLogSmallType4Hrm;
import com.engine.common.constant.BizLogType;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.hrm.util.face.HrmFaceCheckManager;
import com.lingyue.util.KqUtil;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.hrm.company.SubCompanyComInfo;
import weaver.integration.framework.data.record.SimpleRecordData;
import weaver.interfaces.email.CoreMailAPI;
import weaver.interfaces.hrm.HrmServiceManager;
import weaver.matrix.MatrixUtil;
import weaver.rtx.OrganisationCom;
import weaver.systeminfo.SystemEnv;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DelSubCompanyCmd extends AbstractCommonCommand<Map<String, Object>>{
private SimpleBizLogger logger;
public DelSubCompanyCmd(Map<String, Object> params, User user) {
this.user = user;
this.params = params;
this.logger = new SimpleBizLogger();
String id = Util.null2String(params.get("id"));
BizLogContext bizLogContext = new BizLogContext();
bizLogContext.setLogType(BizLogType.HRM_ENGINE);//模块类型
bizLogContext.setBelongType(BizLogSmallType4Hrm.HRM_ENGINE_ORGANIZATION);
bizLogContext.setLogSmallType(BizLogSmallType4Hrm.HRM_ENGINE_ORGANIZATION_SUBCOMPANY);//当前小类型
bizLogContext.setOperateAuditType(BizLogOperateAuditType.WARNING);//警告
bizLogContext.setParams(params);//当前request请求参数
logger.setUser(user);//当前操作人
String mainSql = "select * from HrmSubCompany where id in("+id+")";
logger.setMainSql(mainSql,"id");//主表sql
logger.setMainPrimarykey("id");//主日志表唯一key
logger.setMainTargetNameColumn("subcompanyname");//当前targetName对应的列对应日志中的对象名
logger.before(bizLogContext);
}
@Override
public Map<String, Object> execute(CommandContext commandContext) {
Map<String, Object> retmap = new HashMap<String, Object>();
try {
if(!HrmUserVarify.checkUserRight("HrmSubCompanyEdit:Delete", user)){
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage()));
return retmap;
}
String ids = Util.null2String((String)params.get("id"));
String[] arrIds = Util.splitString(ids, ",");
if(arrIds.length>1){
for(int i=0; i<arrIds.length;i++){
int id = Util.getIntValue(arrIds[i]);
this.del(id);
}
}else{
int id = Util.getIntValue(ids);
retmap = this.del(id);
if(!retmap.isEmpty()){
return retmap;
}
}
retmap.put("status", "1");
retmap.put("message", SystemEnv.getHtmlLabelName(22155, user.getLanguage()));
} catch (Exception e) {
writeLog(e);
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(22155, user.getLanguage()));
}
return retmap;
}
private Map<String, Object> del(int id) throws Exception {
Map<String, Object> retmap = new HashMap<String, Object>();
try {
String sql = "";
RecordSet rs = new RecordSet();;
SubCompanyComInfo SubCompanyComInfo = new SubCompanyComInfo();
OrganisationCom OrganisationCom = new OrganisationCom();
HrmServiceManager HrmServiceManager = new HrmServiceManager();
String subcompanyname = "";
int supsubcomid = 0;
rs.executeSql("select subcompanyname, supsubcomid from HrmSubCompany where id = " + id);
if(rs.next()) {
subcompanyname = Util.null2String(rs.getString("subcompanyname"));
supsubcomid = Util.getIntValue(rs.getString("supsubcomid"), 0);
}
String para = ""+id;
SimpleRecordData recordData = HrmFaceCheckManager.syncQuery(id+"",HrmFaceCheckManager.getOptDelete(),HrmFaceCheckManager.getOaSubcompany()) ;
// 同步 删除 中控考勤机 部门数据
KqUtil.synDeleteSubComInfo(""+id);
rs.executeProc("HrmSubCompany_Delete",para);
rs.executeUpdate("delete from HrmSubCompanyDefined WHERE SUBCOMID= " +id);
rs.executeUpdate("delete from mainmenuconfig where resourcetype=2 and resourceid="+id);
rs.executeUpdate("delete from leftmenuconfig where resourcetype=2 and resourceid="+id);
//更新分级管理数据至默认分部
rs.executeSql("select detachable,dftsubcomid from SystemSet");
String detachable = "";
String dftsubcomid = "";
if(rs.next()){
detachable = Util.null2String(rs.getString("detachable"));
dftsubcomid = Util.null2String(rs.getString("dftsubcomid"));
}
if(detachable.equals("1")&&!dftsubcomid.equals("")&&!dftsubcomid.equals("0")){
//RecordSet.executeProc("SystemSet_DftSCUpdate",""+dftsubcomid);
RecordSet rsupdate = new RecordSet();
String updatesql = " update HrmRoles set subcompanyid="+dftsubcomid+" "+
" where subcompanyid is null or subcompanyid=0 or subcompanyid=-1 " +
" or subcompanyid not in (select id from hrmsubcompany) ";
rsupdate.executeSql(updatesql);
updatesql =" update HrmContractTemplet set subcompanyid="+dftsubcomid+" "+
" where subcompanyid is null or subcompanyid=0 or subcompanyid=-1 " +
" or subcompanyid not in (select id from hrmsubcompany) ";
rsupdate.executeSql(updatesql);
updatesql =" update HrmContractType set subcompanyid="+dftsubcomid+" "+
" where subcompanyid is null or subcompanyid=0 or subcompanyid=-1 " +
" or subcompanyid not in (select id from hrmsubcompany) ";
rsupdate.executeSql(updatesql);
updatesql =" update HrmCareerApply set subCompanyId="+dftsubcomid+" "+
" where subCompanyId is null or subCompanyId=0 or subCompanyId=-1 " +
" or subCompanyId not in (select id from hrmsubcompany) ";
rsupdate.executeSql(updatesql);
}
//add by wjy
//同步RTX端的分部信息.
rs.executeSql("select count(id) from HrmDepartment where (canceled = '0' or canceled is null) and subcompanyid1 ="+id);
if(rs.next()){
if(rs.getInt(1)>0){
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(81683,user.getLanguage()));
return retmap;
}else{
OrganisationCom.deleteSubCompany(id);
//同步到CoreMail邮件系统开始
if(supsubcomid > 0) {
CoreMailAPI.synOrg("com_"+id, subcompanyname, "parent_org_unit_id=com_"+supsubcomid+"&org_unit_name="+subcompanyname, "1");
//testapi.synOrg("com_"+id, subcompanyname, "com_"+supsubcomid, "1");
} else {
CoreMailAPI.synOrg("com_"+id, subcompanyname, "org_unit_name="+subcompanyname, "1");
//testapi.synOrg("com_"+id, subcompanyname, "", "1");
}
//同步到CoreMail邮件系统结束
//OA与第三方接口单条数据同步方法开始
HrmServiceManager.SynInstantSubCompany(""+id,"3");
//OA与第三方接口单条数据同步方法结束
HrmFaceCheckManager.sync(id+"",HrmFaceCheckManager.getOptDelete(),"HRM_DelSubCompanyCmd",HrmFaceCheckManager.getOaSubcompany(),recordData);
}
}
SubCompanyComInfo.removeCompanyCache();
sql="update hrmsubcompany set supsubcomid=0 where supsubcomid="+id;
rs.executeSql(sql);
SubCompanyComInfo.removeCompanyCache();
rs.executeSql("update orgchartstate set needupdate=1");
//同步分部数据到矩阵
MatrixUtil.updateSubcompayData(""+id);
} catch (Exception e) {
writeLog(e);
throw e;
}
return retmap;
}
@Override
public BizLogContext getLogContext() {
return null;
}
@Override
public List<BizLogContext> getLogContexts() {
return logger.getBizLogContexts();
}
}

View File

@ -0,0 +1,282 @@
package com.engine.hrm.cmd.organization;
import com.api.hrm.util.ServiceUtil;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.biz.SimpleBizLogger;
import com.engine.common.constant.BizLogOperateAuditType;
import com.engine.common.constant.BizLogSmallType4Hrm;
import com.engine.common.constant.BizLogType;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.hrm.entity.RuleCodeType;
import com.engine.hrm.util.CodeRuleManager;
import com.engine.hrm.util.HrmOrganizationUtil;
import com.lingyue.util.KqUtil;
import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.Util;
import com.engine.hrm.util.face.HrmFaceCheckManager;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.hrm.common.DbFunctionUtil;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.definedfield.HrmDeptFieldManagerE9;
import weaver.hrm.definedfield.HrmFieldComInfo;
import weaver.hrm.resource.ResourceComInfo;
import weaver.interfaces.email.CoreMailAPI;
import weaver.interfaces.hrm.HrmServiceManager;
import weaver.matrix.MatrixUtil;
import weaver.rtx.OrganisationCom;
import weaver.rtx.OrganisationComRunnable;
import weaver.systeminfo.SystemEnv;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class EditDepartmentCmd extends AbstractCommonCommand<Map<String, Object>> {
private SimpleBizLogger logger;
public EditDepartmentCmd(Map<String, Object> params, User user) {
this.user = user;
this.params = params;
this.logger = new SimpleBizLogger();
String id = Util.null2String(params.get("id"));
BizLogContext bizLogContext = new BizLogContext();
bizLogContext.setLogType(BizLogType.HRM_ENGINE);//模块类型
bizLogContext.setBelongType(BizLogSmallType4Hrm.HRM_ENGINE_ORGANIZATION);
bizLogContext.setLogSmallType(BizLogSmallType4Hrm.HRM_ENGINE_ORGANIZATION_DPEARTMENT);//当前小类型
bizLogContext.setOperateAuditType(BizLogOperateAuditType.WARNING);//警告
bizLogContext.setParams(params);//当前request请求参数
logger.setUser(user);//当前操作人
String mainSql = "select a.* from HrmDepartment a left join HrmDepartmentdefined b on a.id=b.deptid where a.id in(" + id + ") ";
String tableColumns = new ServiceUtil().getTableColumns("select * from HrmDepartmentdefined", "b", "id");
if (!tableColumns.equals("")) {
mainSql = "select a.*," + tableColumns + " from HrmDepartment a left join HrmDepartmentdefined b on a.id=b.deptid where a.id in(" + id + ")";
}
logger.setMainSql(mainSql,"id");//主表sql
logger.setMainPrimarykey("id");//主日志表唯一key
logger.setMainTargetNameColumn("departmentname");//当前targetName对应的列对应日志中的对象名
logger.before(bizLogContext);
}
@Override
public Map<String, Object> execute(CommandContext commandContext) {
Map<String, Object> retmap = new HashMap<String, Object>();
try {
String sql = "";
RecordSet rs = null;
RecordSet rs1 = null;
if (!HrmUserVarify.checkUserRight("HrmDepartmentEdit:Edit", user)) {
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage()));
return retmap;
}
DepartmentComInfo DepartmentComInfo = new DepartmentComInfo();
ResourceComInfo ResourceComInfo = new ResourceComInfo();
//OrganisationCom OrganisationCom = new OrganisationCom();
HrmServiceManager HrmServiceManager = new HrmServiceManager();
int id = Util.getIntValue((String) params.get("id"), 0);
String departmentmark = Util.fromScreen((String) params.get("departmentmark"), user.getLanguage());
String departmentname = Util.fromScreen((String) params.get("departmentname"), user.getLanguage());
String subcompanyid1 = Util.fromScreen((String) params.get("subcompanyid1"), user.getLanguage());
int supdepid = Util.getIntValue((String) params.get("supdepid"), 0);
String showorder = Util.fromScreen(Util.null2s((String) params.get("showorder"), "0"), user.getLanguage());
if (Util.getIntValue(subcompanyid1, 0) <= 0) {
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(382658,user.getLanguage()));
return retmap;
}
int supdepartmentid = supdepid;
if (supdepid > 0) {
if(supdepid==id){
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(382650,user.getLanguage()));
return retmap;
}else{
Map<String, String> supMap = new HashMap<String, String>();
supMap.put(""+id, "1");
supMap.put(""+supdepid, "1");
int supdepidtemp = Util.getIntValue(DepartmentComInfo.getDepartmentsupdepid(""+supdepid), 0);
while(supdepidtemp>0){
if(supMap.get(""+supdepidtemp)==null){
supMap.put(""+supdepidtemp, "1");
supdepidtemp = Util.getIntValue(DepartmentComInfo.getDepartmentsupdepid(""+supdepidtemp), 0);
}else{
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(382650,user.getLanguage()));
return retmap;
}
}
}
if (HrmOrganizationUtil.ifDeptLevelEquals10(supdepid)) {
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(382650,user.getLanguage()));
return retmap;
}
}
String allsupdepid = "0";
String departmentcode = Util.fromScreen((String) params.get("departmentcode"), user.getLanguage());
// 如果编码为空 自动生成编码
// departmentcode = CodeRuleManager.getCodeRuleManager().generateRuleCode(RuleCodeType.DEPARTMENT, subcompanyid1, departmentcode);
if (StringUtils.isNotEmpty(departmentcode)) {
CodeRuleManager.getCodeRuleManager().checkReservedIfDel(RuleCodeType.DEPARTMENT.getValue(), departmentcode);
}
int coadjutant = Util.getIntValue((String) params.get("coadjutant"), 0);
HrmFieldComInfo hrmFieldComInfo = new HrmFieldComInfo();
sql = "select * from HrmDepartment where id=" + id;
rs = new RecordSet();
rs.executeSql(sql);
while (rs.next()) {
if (!hrmFieldComInfo.getIsused("73").equals("1"))
departmentmark = rs.getString("departmentmark");
if (!hrmFieldComInfo.getIsused("74").equals("1"))
departmentname = rs.getString("departmentname");
if (!hrmFieldComInfo.getIsused("75").equals("1"))
subcompanyid1 = rs.getString("subcompanyid1");
if (!hrmFieldComInfo.getIsused("76").equals("1"))
supdepid = rs.getInt("supdepid");
if (!hrmFieldComInfo.getIsused("77").equals("1"))
coadjutant = rs.getInt("coadjutant");
if (!hrmFieldComInfo.getIsused("78").equals("1"))
showorder = rs.getString("showorder");
if (!hrmFieldComInfo.getIsused("80").equals("1"))
departmentcode = rs.getString("departmentcode");
}
if(supdepid > 0){
supdepartmentid = supdepid;
}
if (!"".equals(departmentcode)) {
sql = "select id from hrmdepartment where departmentcode = '" + departmentcode + "' and id !=" + id;
rs = new RecordSet();
rs.executeSql(sql);
if (rs.next()) {
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(382653,user.getLanguage()));
return retmap;
}
}
char separator = Util.getSeparator();
if (supdepartmentid > 0) {//当选择了上级部门的时候需要更改当前部门的上级分部
subcompanyid1 = DepartmentComInfo.getSubcompanyid1(supdepartmentid + "");
}
String para = "" + id + separator + departmentmark + separator + departmentname + separator + supdepartmentid + separator + allsupdepid + separator + subcompanyid1 + separator + showorder + separator + coadjutant;
rs = new RecordSet();
rs.executeProc("HrmDepartment_Update", para);
int flag = rs.getFlag();
if (flag == 2) {
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(382655,user.getLanguage()));
return retmap;
}
if (flag == 3) {
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(382657,user.getLanguage()));
return retmap;
}
weaver.hrm.company.OrgOperationUtil OrgOperationUtil = new weaver.hrm.company.OrgOperationUtil();
OrgOperationUtil.updateDepartmentLevel("" + id, "0");
HrmDeptFieldManagerE9 hrmDeptFieldManager = new HrmDeptFieldManagerE9(5);
hrmDeptFieldManager.editCustomData(params,id);
sql = "update hrmdepartment set departmentcode = '" + departmentcode + "' ";
sql += ","+ DbFunctionUtil.getUpdateSetSql(rs.getDBType(),user.getUID()) ;
sql += " where id = " + id;
rs = new RecordSet();
rs.executeSql(sql);
ArrayList departmentlist = new ArrayList();
departmentlist = DepartmentComInfo.getAllChildDeptByDepId(departmentlist, id + "");
departmentlist.add(id + "");
for (int i = 0; i < departmentlist.size(); i++) {
String listdepartmenttemp = (String) departmentlist.get(i);
rs = new RecordSet();
rs.execute("update HrmDepartment set subcompanyid1=" + subcompanyid1 + " where id=" + listdepartmenttemp);
//TD16048改为逐条修改
rs = new RecordSet();
rs.execute("select id, subcompanyid1,managerid,seclevel,managerstr from hrmresource where departmentid=" + listdepartmenttemp);
while (rs.next()) {
int resourceid_tmp = Util.getIntValue(rs.getString(1), 0);
int oldsubcompanyid1 = Util.getIntValue(rs.getString(2), 0);
int oldmanagerid = Util.getIntValue(rs.getString(3), 0);
int seclevel = Util.getIntValue(rs.getString(4), 0);
String oldmanagerstr = Util.null2String(rs.getString(5));
rs1 = new RecordSet();
rs1.execute("update hrmresource set subcompanyid1=" + subcompanyid1 + " where id=" + resourceid_tmp);
para = "" + resourceid_tmp + separator + listdepartmenttemp + separator + subcompanyid1 + separator + oldmanagerid + separator + seclevel + separator + oldmanagerstr + separator + listdepartmenttemp + separator + oldsubcompanyid1 + separator + oldmanagerid + separator + seclevel + separator + oldmanagerstr + separator + "1";
rs1 = new RecordSet();
rs1.executeProc("HrmResourceShare", para);
}
//add by wjy
//同步RTX端部门信息
//OrganisationCom.editDepartment(Util.getIntValue(listdepartmenttemp));//执行速度过慢改成另起现成执行
new Thread(new OrganisationComRunnable("department", "edit", String.valueOf(listdepartmenttemp))).start();
}
DepartmentComInfo.removeCompanyCache();
ResourceComInfo.removeResourceCache();
rs = new RecordSet();
rs.executeSql("update orgchartstate set needupdate=1");
//同步到CoreMail邮件系统开始
if (supdepid == 0) {
CoreMailAPI.synOrg("" + id, departmentname, "parent_org_unit_id=com_" + subcompanyid1 + "&org_unit_name=" + departmentname, "0");
//testapi.synOrg(""+id, departmentname, "com_"+subcompanyid1, "0");
} else {
CoreMailAPI.synOrg("" + id, departmentname, "parent_org_unit_id=" + supdepid + "&org_unit_name=" + departmentname, "0");
//testapi.synOrg(""+id, departmentname, ""+supdepid, "0");
}
//同步到CoreMail邮件系统结束
//OA与第三方接口单条数据同步方法开始
HrmServiceManager.SynInstantDepartment("" + id, "2");
//OA与第三方接口单条数据同步方法结束
HrmFaceCheckManager.sync(id+"",HrmFaceCheckManager.getOptUpdate(),this.getClass().getName(),HrmFaceCheckManager.getOaDepartment());
//同步部门数据到矩阵
MatrixUtil.updateDepartmentData("" + id);
// 同步部门数据到中控考勤机
KqUtil.synAddOrUpdateDeptInfo(""+id);
retmap.put("status", "1");
retmap.put("message", SystemEnv.getHtmlLabelName(18758, user.getLanguage()));
} catch (Exception e) {
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(382661,user.getLanguage()));
writeLog(e);
}
return retmap;
}
@Override
public BizLogContext getLogContext() {
return null;
}
@Override
public List<BizLogContext> getLogContexts() {
return logger.getBizLogContexts();
}
}

View File

@ -0,0 +1,223 @@
package com.engine.hrm.cmd.organization;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.api.hrm.util.ServiceUtil;
import com.engine.common.biz.SimpleBizLogger;
import com.engine.common.constant.*;
import com.engine.hrm.entity.RuleCodeType;
import com.engine.hrm.util.CodeRuleManager;
import com.engine.hrm.util.face.HrmFaceCheckManager;
import com.lingyue.util.KqUtil;
import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.hrm.common.DbFunctionUtil;
import weaver.hrm.company.OrgOperationUtil;
import weaver.hrm.company.SubCompanyComInfo;
import weaver.hrm.definedfield.HrmDeptFieldManagerE9;
import weaver.hrm.definedfield.HrmFieldComInfo;
import weaver.interfaces.email.CoreMailAPI;
import weaver.interfaces.hrm.HrmServiceManager;
import weaver.matrix.MatrixUtil;
import weaver.rtx.OrganisationCom;
import weaver.systeminfo.SystemEnv;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.hrm.util.HrmOrganizationUtil;
public class EditSubCompanyCmd extends AbstractCommonCommand<Map<String, Object>>{
private SimpleBizLogger logger;
public EditSubCompanyCmd(Map<String, Object> params, User user) {
this.user = user;
this.params = params;
this.logger = new SimpleBizLogger();
String id = Util.null2String(params.get("id"));
BizLogContext bizLogContext = new BizLogContext();
bizLogContext.setLogType(BizLogType.HRM_ENGINE);//模块类型
bizLogContext.setBelongType(BizLogSmallType4Hrm.HRM_ENGINE_ORGANIZATION);
bizLogContext.setLogSmallType(BizLogSmallType4Hrm.HRM_ENGINE_ORGANIZATION_SUBCOMPANY);//当前小类型
bizLogContext.setOperateAuditType(BizLogOperateAuditType.WARNING);//警告
bizLogContext.setParams(params);//当前request请求参数
logger.setUser(user);//当前操作人
String mainSql = "select a.* from HrmSubCompany a left join hrmsubcompanydefined b on a.id=b.subcomid where a.id in(" + id + ")";
String tableColumns = new ServiceUtil().getTableColumns("select * from hrmsubcompanydefined", "b", "id");
if (!tableColumns.equals("")) {
mainSql = "select a.*," + tableColumns + " from HrmSubCompany a left join hrmsubcompanydefined b on a.id=b.subcomid where a.id in(" + id + ")";
}
logger.setMainSql(mainSql, "id");//主表sql
logger.setMainPrimarykey("id");//主日志表唯一key
logger.setMainTargetNameColumn("subcompanyname");//当前targetName对应的列对应日志中的对象名
logger.before(bizLogContext);
}
@Override
public Map<String, Object> execute(CommandContext commandContext) {
Map<String, Object> retmap = new HashMap<String, Object>();
try {
String sql = "";
RecordSet rs = null;
if(!HrmUserVarify.checkUserRight("HrmSubCompanyEdit:Edit", user)){
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage()));
return retmap;
}
SubCompanyComInfo SubCompanyComInfo = new SubCompanyComInfo();
OrgOperationUtil OrgOperationUtil = new OrgOperationUtil();
OrganisationCom OrganisationCom = new OrganisationCom();
HrmServiceManager HrmServiceManager = new HrmServiceManager();
int companyid = 1;
int id = Util.getIntValue((String)params.get("id"));
int supsubcomid=Util.getIntValue((String)params.get("supsubcomid"),0);
String subcompanycode = Util.fromScreen((String)params.get("subcompanycode"),user.getLanguage());
String subcompanyname = Util.fromScreen((String)params.get("subcompanyname"),user.getLanguage());
String subcompanydesc = Util.fromScreen((String)params.get("subcompanydesc"),user.getLanguage());
String url=Util.null2String((String)params.get("url"));
String showorder = Util.fromScreen(Util.null2s((String) params.get("showorder"), "0"), user.getLanguage());
int limitUsers = Util.getIntValue(Util.fromScreen((String)params.get("limitUsers"),user.getLanguage()), 0);
limitUsers = limitUsers < 0 ? 0 : limitUsers;
if(supsubcomid > 0){
if(supsubcomid==id){
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(382649,user.getLanguage()));
return retmap;
}else{
Map<String, String> supMap = new HashMap<String, String>();
supMap.put(""+id, "1");
supMap.put(""+supsubcomid, "1");
int supsubcomidtemp = Util.getIntValue(SubCompanyComInfo.getSupsubcomid(""+supsubcomid), 0);
while(supsubcomidtemp>0){
if(supMap.get(""+supsubcomidtemp)==null){
supMap.put(""+supsubcomidtemp, "1");
supsubcomidtemp = Util.getIntValue(SubCompanyComInfo.getSupsubcomid(""+supsubcomidtemp), 0);
}else{
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(382649,user.getLanguage()));
return retmap;
}
}
}
if(HrmOrganizationUtil.ifSubComLevelEquals10(supsubcomid)){
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(382649,user.getLanguage()));
return retmap;
}
}
// 如果编码为空 自动生成编码
// subcompanycode = CodeRuleManager.getCodeRuleManager().generateRuleCode(RuleCodeType.SUBCOMPANY, subcompanycode);
if (StringUtils.isNotEmpty(subcompanycode)) {
CodeRuleManager.getCodeRuleManager().checkReservedIfDel(RuleCodeType.SUBCOMPANY.getValue(), subcompanycode);
}
if(!"".equals(subcompanycode)){
sql = "select id from HrmSubCompany where subcompanycode = '" + subcompanycode + "' and id !="+id;
rs = new RecordSet();
rs.executeSql(sql);
if(rs.next()){
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(382651,user.getLanguage()));
return retmap;
}
}
char separator = Util.getSeparator() ;
HrmFieldComInfo hrmFieldComInfo = new HrmFieldComInfo();
sql = "select * from HrmSubCompany where id="+id;
rs = new RecordSet();
rs.executeSql(sql);
while(rs.next()){
if(!hrmFieldComInfo.getIsused("67").equals("1"))subcompanyname = rs.getString("subcompanyname");
if(!hrmFieldComInfo.getIsused("68").equals("1"))subcompanydesc = rs.getString("subcompanydesc");
if(!hrmFieldComInfo.getIsused("69").equals("1"))supsubcomid = rs.getInt("supsubcomid");
if(!hrmFieldComInfo.getIsused("70").equals("1"))url = rs.getString("url");
if(!hrmFieldComInfo.getIsused("71").equals("1"))showorder = rs.getString("showorder");
if(!hrmFieldComInfo.getIsused("72").equals("1"))subcompanycode = rs.getString("subcompanycode");
if(!hrmFieldComInfo.getIsused("84").equals("1"))limitUsers = rs.getInt("limitUsers");
}
String para = ""+id + separator + subcompanyname + separator + subcompanydesc + separator + companyid+ separator + supsubcomid+ separator + url+ separator + showorder;
rs = new RecordSet();
rs.executeProc("HrmSubCompany_Update",para);
int flag=rs.getFlag();
sql="update HrmSubCompany set subcompanycode = '" + subcompanycode + "'";
if(user.getUID() == 1) sql += ", limitUsers = "+limitUsers;
sql += ","+ DbFunctionUtil.getUpdateSetSql(rs.getDBType(),user.getUID()) ;
sql+=" where id = "+id;
rs = new RecordSet();
rs.executeSql(sql);
HrmDeptFieldManagerE9 hrmDeptFieldManager = new HrmDeptFieldManagerE9(4);
hrmDeptFieldManager.editCustomData(params,id);
if(flag==2){
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(382654,user.getLanguage()));
return retmap;
}
if(flag==3){
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(382656,user.getLanguage()));
return retmap;
}
SubCompanyComInfo.removeCompanyCache();
rs = new RecordSet();
rs.executeSql("update orgchartstate set needupdate=1");
OrgOperationUtil.updateSubcompanyLevel(""+id,"0");
OrganisationCom.editSubCompany(id);
//同步到CoreMail邮件系统开始
if(supsubcomid > 0) {
CoreMailAPI.synOrg("com_"+id, subcompanyname, "parent_org_unit_id=com_"+supsubcomid+"&org_unit_name="+subcompanyname, "0");
} else {
CoreMailAPI.synOrg("com_"+id, subcompanyname, "org_unit_name="+subcompanyname, "0");
}
//同步到CoreMail邮件系统结束
//OA与第三方接口单条数据同步方法开始
HrmServiceManager.SynInstantSubCompany(""+id,"2");
//OA与第三方接口单条数据同步方法结束
HrmFaceCheckManager.sync(id+"",HrmFaceCheckManager.getOptUpdate(),"HRM_EditSubCompanyCmd",HrmFaceCheckManager.getOaSubcompany());
//同步分部数据到矩阵
MatrixUtil.updateSubcompayData(""+id);
// 同步分部数据到中控考勤机
KqUtil.synAddOrUpdateSubComInfo(""+id);
retmap.put("status", "1");
retmap.put("message", SystemEnv.getHtmlLabelName(18758, user.getLanguage()));
} catch (Exception e) {
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(382661,user.getLanguage()));
writeLog(e);
}
return retmap;
}
@Override
public BizLogContext getLogContext() {
return null;
}
@Override
public List<BizLogContext> getLogContexts() {
return logger.getBizLogContexts();
}
}

View File

@ -0,0 +1,497 @@
package com.engine.kq.bean;
import com.engine.kq.biz.KQLeaveRulesComInfo;
import com.engine.kq.biz.KQLeaveRulesDetailComInfo;
import com.engine.kq.biz.KQSettingsComInfo;
import com.engine.kq.biz.KQUsageHistoryBiz;
import com.engine.kq.entity.KQUsageHistoryEntity;
import com.engine.kq.jucailin.util.KQDateUtil;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.file.Prop;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.resource.ResourceComInfo;
import weaver.systeminfo.SystemEnv;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
/**
* 假期余额--用于Excel导入
*/
public class KQBalanceOfLeave extends BaseBean {
/**
* 人员ID
*/
private String resourceId;
/**
* 编号
*/
private String workcode ;
/**
* 人员姓名
*/
private String lastName;
/**
* 假期类型ID
*/
private String leaveRulesId;
/**
* 所属年份
*/
private String belongYear;
/**
* (混合模式下为法定年假)假期余额基数
*/
private double baseAmount = 0.00;
/**
* (混合模式下为法定年假)已使用的假期余额
*/
private double usedAmount = 0.00;
/**
* (混合模式下为法定年假)额外的假期余额
*/
private double extraAmount = 0.00;
/**
* (仅混合模式下使用为福利年假)假期余额基数
*/
private double baseAmount2 = 0.00;
/**
* (仅混合模式下使用为福利年假)已使用的假期余额
*/
private double usedAmount2 = 0.00;
/**
* (仅混合模式下使用为福利年假)额外的假期余额
*/
private double extraAmount2 = 0.00;
/**
* 用户语言
*/
private int userlanguage = 7;
/**
* 导入Excel的操作者
*/
private String operator;
/**
* 失效日期
*/
private String expirationDate;
/**
* 验证模板数据有效性--用于Excel导入
*
* @return
*/
public String valExcelData() {
KQSettingsComInfo kqSettingsComInfo = new KQSettingsComInfo();
String allow_negative = Util.null2String(kqSettingsComInfo.getMain_val("allow_negative"),"0");
String errorInfo = "";
if (!isExist(resourceId, lastName)) {
errorInfo = SystemEnv.getHtmlLabelName(389985, userlanguage);//ID和姓名不匹配
return errorInfo;
}
if (!"1".equals(allow_negative) && this.baseAmount < 0) {
errorInfo = "基数不能为负数";
return errorInfo;
}
if (!"1".equals(allow_negative) && this.extraAmount < 0) {
errorInfo = "额外不能为负数";
return errorInfo;
}
if (this.usedAmount < 0) {
errorInfo = ""+ SystemEnv.getHtmlLabelName(10005288,weaver.general.ThreadVarLanguage.getLang())+"";
return errorInfo;
}
double _totalAmount = this.baseAmount+this.extraAmount;
if (!"1".equals(allow_negative) && _totalAmount < this.usedAmount) {
errorInfo = ""+ SystemEnv.getHtmlLabelName(508124,weaver.general.ThreadVarLanguage.getLang())+"";
return errorInfo;
}
if (!"1".equals(allow_negative) && this.baseAmount2 < 0) {
errorInfo = "福利基数不能为负数";
return errorInfo;
}
if (!"1".equals(allow_negative) && this.extraAmount2 < 0) {
errorInfo = "福利额外不能为负数";
return errorInfo;
}
if (this.usedAmount2 < 0) {
errorInfo = "福利已休不能大于总数";
return errorInfo;
}
double _totalAmount2 = this.baseAmount2+this.extraAmount2;
if (!"1".equals(allow_negative) && _totalAmount2 < this.usedAmount2) {
errorInfo = ""+ SystemEnv.getHtmlLabelName(508124,weaver.general.ThreadVarLanguage.getLang())+"";
return errorInfo;
}
return errorInfo;
}
/**
* 保存数据
*
* @return
*/
public String save() {
String resultStr = "false";
try {
/*获取当前日期,当前时间*/
Calendar today = Calendar.getInstance();
String currentDate = Util.add0(today.get(Calendar.YEAR), 4) + "-" +
Util.add0(today.get(Calendar.MONTH) + 1, 2) + "-" +
Util.add0(today.get(Calendar.DAY_OF_MONTH), 2);
String currentTime = Util.add0(today.get(Calendar.HOUR_OF_DAY), 2) + ":" +
Util.add0(today.get(Calendar.MINUTE), 2) + ":" +
Util.add0(today.get(Calendar.SECOND), 2);
/********************************************************************************************************/
/*获取人员的相关信息*/
ResourceComInfo resourceComInfo = new ResourceComInfo();
/*分部ID*/
String subcompanyId = resourceComInfo.getSubCompanyID(this.resourceId);
//部门ID
String departmentId = resourceComInfo.getDepartmentID(this.resourceId);
/*入职日期*/
String companyStartDate = resourceComInfo.getCompanyStartDate(this.resourceId);
/********************************************************************************************************/
/*获取假期类型的相关设置*/
KQLeaveRulesComInfo rulesComInfo = new KQLeaveRulesComInfo();
/*请假最小单位*/
String minimumUnit = rulesComInfo.getMinimumUnit(this.leaveRulesId);
/********************************************************************************************************/
/*获取假期规则(一个假期类型下可能存在多个假期规则)的相关设置*/
KQLeaveRulesDetailComInfo detailComInfo = new KQLeaveRulesDetailComInfo();
/*请假时长计算方式1-按工作日计算请假时长、2-按自然日计算请假时长*/
int distributionMode = Util.getIntValue(detailComInfo.getDistributionMode(this.leaveRulesId, subcompanyId, departmentId, this.resourceId), 1);
/*有效期规则0-永久有效、1-按自然年1月1日-12月31日、2-按入职日期起12个月、3-自定义次年失效日期*/
int validityRule = validityRule = Util.getIntValue(detailComInfo.getValidityRule(this.leaveRulesId, subcompanyId, departmentId, this.resourceId), 0);
/*失效日期--月当有效期规则选择4-自定义次年失效日期时有效)*/
String expirationMonth = detailComInfo.getExpirationMonth(this.leaveRulesId, subcompanyId ,departmentId, this.resourceId);
/*失效日期--日当有效期规则选择4-自定义次年失效日期时有效)*/
String expirationDay = detailComInfo.getExpirationDay(this.leaveRulesId, subcompanyId, departmentId, this.resourceId);
/*允许延长有效期0-不允许、1-允许*/
int extensionEnable = Util.getIntValue(detailComInfo.getExtensionEnable(this.leaveRulesId, subcompanyId, departmentId, this.resourceId), 0);
/*允许超过有效期天数*/
int extendedDays = Util.getIntValue(detailComInfo.getExtendedDays(this.leaveRulesId, subcompanyId, departmentId, this.resourceId), 0);
/********************************************************************************************************/
/*员工假期余额变更记录*/
String insertOrUpdate = "";
KQUsageHistoryEntity usageHistoryEntity = new KQUsageHistoryEntity();//员工假期余额变更记录实体类
List<KQUsageHistoryEntity> usageHistoryEntityList = new ArrayList<KQUsageHistoryEntity>();//员工假期余额变更记录集合
/********************************************************************************************************/
double oldBaseAmount = 0.00;
double oldUsedAmount = 0.00;
double oldExtraAmount = 0.00;
double oldBaseAmount2 = 0.00;
double oldUsedAmount2 = 0.00;
double oldExtraAmount2 = 0.00;
double newBaseAmount = 0.00;
double newUsedAmount = 0.00;
double newExtraAmount = 0.00;
double newBaseAmount2 = 0.00;
double newUsedAmount2 = 0.00;
double newExtraAmount2 = 0.00;
int status = 0;
String expirationDate = "";
/*计算有效期 start*/
if (validityRule == 0) {
/*不限制有效期,默认永久有效*/
status = 0;
} else if (validityRule == 1) {
/*按自然年1月1日-12月31日*/
if (extensionEnable == 1) {
/*允许延长有效期*/
expirationDate = DateUtil.addDate(this.belongYear + "-12-31", extendedDays);
if (Util.dayDiff(expirationDate, currentDate) > 1) {
status = 1;
}
} else {
expirationDate = this.belongYear + "-12-31";
if (Util.dayDiff(expirationDate, currentDate) > 1) {
status = 1;
}
}
} else if (validityRule == 2) {
/*按入职日期起12个月*/
if (companyStartDate.equals("")) {
status = 1;
} else if (extensionEnable == 1) {
/*允许延长有效期*/
expirationDate = DateUtil.addDate((Util.getIntValue(this.belongYear) + 1) + companyStartDate.substring(4), extendedDays);
if (Util.dayDiff(expirationDate, currentDate) > 1) {
status = 1;
}
} else {
expirationDate = (Util.getIntValue(this.belongYear) + 1) + companyStartDate.substring(4);
if (Util.dayDiff(expirationDate, currentDate) > 1) {
status = 1;
}
}
} else if (validityRule == 3) {
/*自定义次年失效日期*/
if (extensionEnable == 1) {
/*允许延长有效期*/
expirationDate = DateUtil.addDate((Util.getIntValue(this.belongYear) + 1) + "-" + expirationMonth + "-" + expirationDay, extendedDays);
if (Util.dayDiff(expirationDate, currentDate) > 1) {
status = 1;
}
} else {
expirationDate = (Util.getIntValue(this.belongYear) + 1) + "-" + expirationMonth + "-" + expirationDay;
if (Util.dayDiff(expirationDate, currentDate) > 1) {
status = 1;
}
}
}
String nianjiaId = Prop.getInstance().getPropValue("lingyue_nianjia","nianjiaid");
if (nianjiaId.equals(leaveRulesId)){
expirationDate = this.expirationDate;
}
/*计算有效期 end*/
newBaseAmount = this.baseAmount;
newExtraAmount = this.extraAmount;
newUsedAmount = this.usedAmount;
if (distributionMode == 6) {
newBaseAmount2 = this.baseAmount2;
newExtraAmount2 = this.extraAmount2;
newUsedAmount2 = this.usedAmount2;
}
Timestamp date = KQDateUtil.getUpdateTimeStamp();
boolean flag = true;//记录SQL操作是否成功
String searchSql = "select * from kq_BalanceOfLeave where leaveRulesId=? and resourceId=? and belongYear=?";
String updateSql = "update kq_BalanceOfLeave set baseAmount=?,extraAmount=?,usedAmount=?,baseAmount2=?,extraAmount2=?,usedAmount2=?,status=?,expirationDate=?,update_time=? where leaveRulesId=? and resourceId=? and belongYear=? ";
String insertSql = "insert into kq_BalanceOfLeave(baseAmount,extraAmount,usedAmount,baseAmount2,extraAmount2,usedAmount2,status,expirationDate,leaveRulesId,resourceId,belongYear,create_time,update_time,creator) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?) ";
RecordSet recordSet = new RecordSet();
if (recordSet.getDBType().equals("postgresql")) {
updateSql = "update kq_BalanceOfLeave set baseAmount=?,extraAmount=?,usedAmount=?,baseAmount2=?,extraAmount2=?,usedAmount2=?,status=?,expirationDate=?,update_time=?::timestamp where leaveRulesId=? and resourceId=? and belongYear=? ";
insertSql = "insert into kq_BalanceOfLeave(baseAmount,extraAmount,usedAmount,baseAmount2,extraAmount2,usedAmount2,status,expirationDate,leaveRulesId,resourceId,belongYear,create_time,update_time,creator) values(?,?,?,?,?,?,?,?,?,?,?,?::timestamp,?::timestamp,?) ";
}
recordSet.executeQuery(searchSql, this.leaveRulesId, this.resourceId, this.belongYear);
if (recordSet.next()) {
oldBaseAmount = Util.getDoubleValue(recordSet.getString("baseAmount"), 0.00);
oldExtraAmount = Util.getDoubleValue(recordSet.getString("extraAmount"), 0.00);
oldUsedAmount = Util.getDoubleValue(recordSet.getString("usedAmount"), 0.00);
if (distributionMode == 6) {
oldBaseAmount2 = Util.getDoubleValue(recordSet.getString("baseAmount2"), 0.00);
oldExtraAmount2 = Util.getDoubleValue(recordSet.getString("extraAmount2"), 0.00);
oldUsedAmount2 = Util.getDoubleValue(recordSet.getString("usedAmount2"), 0.00);
}
/*更新员工假期余额 start*/
flag = recordSet.executeUpdate(updateSql, String.format("%.2f", newBaseAmount), String.format("%.2f", newExtraAmount), String.format("%.2f", newUsedAmount), String.format("%.2f", newBaseAmount2), String.format("%.2f", newExtraAmount2), String.format("%.2f", newUsedAmount2), status, expirationDate,date, this.leaveRulesId, this.resourceId, this.belongYear);
resultStr = String.valueOf(flag);
if (!flag) {
resultStr = "false";
return resultStr;
}
/*更新员工假期余额 end*/
insertOrUpdate = "update";
} else {
/*新增员工假期余额 start*/
flag = recordSet.executeUpdate(insertSql, String.format("%.2f", newBaseAmount), String.format("%.2f", newExtraAmount), String.format("%.2f", newUsedAmount), String.format("%.2f", newBaseAmount2), String.format("%.2f", newExtraAmount2), String.format("%.2f", newUsedAmount2), status, expirationDate, this.leaveRulesId, this.resourceId, this.belongYear,date,date,Util.getIntValue(resourceId));
resultStr = String.valueOf(flag);
if (!flag) {
return resultStr;
}
/*新增员工假期余额 end*/
insertOrUpdate = "insert";
}
/*员工假期余额变更记录 start*/
usageHistoryEntity = new KQUsageHistoryEntity();
usageHistoryEntity.setLeaveRulesId(this.leaveRulesId);
usageHistoryEntity.setRelatedId(this.resourceId);
usageHistoryEntity.setWfRequestId("");
usageHistoryEntity.setOperator(this.operator);
usageHistoryEntity.setOperateDate(currentDate);
usageHistoryEntity.setOperateTime(currentTime);
usageHistoryEntity.setOperateType("7");
usageHistoryEntity.setBelongYear(this.belongYear);
usageHistoryEntity.setOldBaseAmount(String.format("%.2f", oldBaseAmount));
usageHistoryEntity.setNewBaseAmount(String.format("%.2f", newBaseAmount));
usageHistoryEntity.setOldExtraAmount(String.format("%.2f", oldExtraAmount));
usageHistoryEntity.setNewExtraAmount(String.format("%.2f", newExtraAmount));
usageHistoryEntity.setOldUsedAmount(String.format("%.2f", oldUsedAmount));
usageHistoryEntity.setNewUsedAmount(String.format("%.2f", newUsedAmount));
usageHistoryEntity.setOldBaseAmount2(String.format("%.2f", oldBaseAmount2));
usageHistoryEntity.setNewBaseAmount2(String.format("%.2f", newBaseAmount2));
usageHistoryEntity.setOldExtraAmount2(String.format("%.2f", oldExtraAmount2));
usageHistoryEntity.setNewExtraAmount2(String.format("%.2f", newExtraAmount2));
usageHistoryEntity.setOldUsedAmount2(String.format("%.2f", oldUsedAmount2));
usageHistoryEntity.setNewUsedAmount2(String.format("%.2f", newUsedAmount2));
usageHistoryEntity.setOldMinimumUnit(minimumUnit);
usageHistoryEntity.setNewMinimumUnit(minimumUnit);
usageHistoryEntity.setInsertOrUpdate(insertOrUpdate);
usageHistoryEntityList.add(usageHistoryEntity);
KQUsageHistoryBiz usageHistoryBiz = new KQUsageHistoryBiz();
flag = usageHistoryBiz.save(usageHistoryEntityList);
resultStr = String.valueOf(flag);
if (!flag) {
return resultStr;
}
/*员工假期余额变更记录 end*/
} catch (Exception e) {
writeLog(e);
}
return resultStr;
}
/**
* 判断ID和姓名是否匹配系统中是否存在此人员
*
* @param resourceId
* @param lastName
* @return
*/
private boolean isExist(String resourceId, String lastName) {
String sql = "select 1 from HrmResource where id=? ";
RecordSet recordSet = new RecordSet();
recordSet.executeQuery(sql, resourceId);
if (recordSet.next()) {
return true;
} else {
return false;
}
}
public String getResourceId() {
return resourceId;
}
public void setResourceId(String resourceId) {
this.resourceId = resourceId;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLeaveRulesId() {
return leaveRulesId;
}
public void setLeaveRulesId(String leaveRulesId) {
this.leaveRulesId = leaveRulesId;
}
public String getBelongYear() {
return belongYear;
}
public void setBelongYear(String belongYear) {
this.belongYear = belongYear;
}
public double getBaseAmount() {
return baseAmount;
}
public void setBaseAmount(double baseAmount) {
this.baseAmount = baseAmount;
}
public double getUsedAmount() {
return usedAmount;
}
public void setUsedAmount(double usedAmount) {
this.usedAmount = usedAmount;
}
public double getExtraAmount() {
return extraAmount;
}
public void setExtraAmount(double extraAmount) {
this.extraAmount = extraAmount;
}
public double getBaseAmount2() {
return baseAmount2;
}
public void setBaseAmount2(double baseAmount2) {
this.baseAmount2 = baseAmount2;
}
public double getUsedAmount2() {
return usedAmount2;
}
public void setUsedAmount2(double usedAmount2) {
this.usedAmount2 = usedAmount2;
}
public double getExtraAmount2() {
return extraAmount2;
}
public void setExtraAmount2(double extraAmount2) {
this.extraAmount2 = extraAmount2;
}
public void setUserLanguage(String languageId) {
this.userlanguage = Util.getIntValue(languageId, 7);
}
public String getOperator() {
return operator;
}
public void setOperator(String operator) {
this.operator = operator;
}
public String getWorkcode() {
return workcode;
}
public void setWorkcode(String workcode) {
this.workcode = workcode;
}
public String getExpirationDate() {
return expirationDate;
}
public void setExpirationDate(String expirationDate) {
this.expirationDate = expirationDate;
}
}

View File

@ -0,0 +1,46 @@
package com.engine.kq.bean;
/**
* 排班制考勤组----排班设置权限数据存储在建模表中
*/
public class KQChildrenBean {
private String id;
private String birthday;
private String title;
private String resourceid;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getResourceid() {
return resourceid;
}
public void setResourceid(String resourceid) {
this.resourceid = resourceid;
}
}

View File

@ -0,0 +1,74 @@
package com.engine.kq.bean;
/**
* 排班制考勤组----排班设置权限数据存储在建模表中
*/
public class KqLockAttenda {
private String LOCK_COM;
private String LOCK_SUBCOM;
private String LOCK_DEPT;
private String LOCK_RESOURCE;
private String LOCK_FROMDATE;
private String LOCK_TODATE;
private String LOCK_LOCK;
public String getLOCK_COM() {
return LOCK_COM;
}
public void setLOCK_COM(String LOCK_COM) {
this.LOCK_COM = LOCK_COM;
}
public String getLOCK_SUBCOM() {
return LOCK_SUBCOM;
}
public void setLOCK_SUBCOM(String LOCK_SUBCOM) {
this.LOCK_SUBCOM = LOCK_SUBCOM;
}
public String getLOCK_DEPT() {
return LOCK_DEPT;
}
public void setLOCK_DEPT(String LOCK_DEPT) {
this.LOCK_DEPT = LOCK_DEPT;
}
public String getLOCK_RESOURCE() {
return LOCK_RESOURCE;
}
public void setLOCK_RESOURCE(String LOCK_RESOURCE) {
this.LOCK_RESOURCE = LOCK_RESOURCE;
}
public String getLOCK_FROMDATE() {
return LOCK_FROMDATE;
}
public void setLOCK_FROMDATE(String LOCK_FROMDATE) {
this.LOCK_FROMDATE = LOCK_FROMDATE;
}
public String getLOCK_TODATE() {
return LOCK_TODATE;
}
public void setLOCK_TODATE(String LOCK_TODATE) {
this.LOCK_TODATE = LOCK_TODATE;
}
public String getLOCK_LOCK() {
return LOCK_LOCK;
}
public void setLOCK_LOCK(String LOCK_LOCK) {
this.LOCK_LOCK = LOCK_LOCK;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,81 @@
package com.engine.kq.biz;
import weaver.cache.CacheBase;
import weaver.cache.CacheColumn;
import weaver.cache.CacheColumnType;
import weaver.cache.PKColumn;
/**
* 假期规则缓存类
*/
public class KQChildrenComInfo extends CacheBase {
/**
* 数据来源
*/
protected static String TABLE_NAME = "hrmfamilyinfo";
/**
* sql中的where信息不要以where开始
*/
protected static String TABLE_WHERE = " WhetherChildren=1 ";
/**
* sql中的order by信息不要以order by开始
*/
protected static String TABLE_ORDER = " id ";
/**
* 主键
*/
@PKColumn(type = CacheColumnType.NUMBER)
protected static String PK_NAME = "id";
/**
* 出生日期
*/
@CacheColumn(name = "birthday")
protected static int birthday;
/**
* 姓名
*/
@CacheColumn(name = "member")
protected static int member;
/**
* 家长id
*/
@CacheColumn(name = "resourceid")
protected static int resourceid;
public String getId(){
return (String)getRowValue(PK_INDEX);
}
public String getChildrenName() {
return (String)getRowValue(member);
}
public String getChildrenName(String key){
return (String) getValue(member,key);
}
public String getBirthday() {
return (String)getRowValue(birthday);
}
public String getBirthday(String key){
return (String) getValue(birthday,key);
}
public String getResourceid() {
return (String)getRowValue(resourceid);
}
public String getResourceid(String key){
return (String) getValue(resourceid,key);
}
@Override
public void removeCache() {
super.removeCache();
}
}

View File

@ -0,0 +1,339 @@
package com.engine.kq.biz;
import com.engine.kq.entity.TimeScopeEntity;
import com.engine.kq.entity.WorkTimeEntity;
import com.engine.kq.log.KQLog;
import weaver.common.DateUtil;
import weaver.conn.BatchRecordSet;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 考勤数据格式化
*/
public class KQFormatBiz extends BaseBean {
private String today = DateUtil.getCurrentDate();
protected KQLog kqLog = new KQLog();
/**
* 考勤报表格式化
*
* @param lsFormatParams
*/
public void format(List<List<Object>> lsFormatParams) {
format(lsFormatParams, -1);
}
/**
* 考勤报表格式化
* @param lsFormatParams
* @param formatType -1: 其他; 11:右键重新计算考勤数据; 12: 考勤自动和手动同步;13:钉钉同步或者导入; 14:云桥考勤同步 15: 考勤导入;16:排班更新
*/
public void format(List<List<Object>> lsFormatParams, int formatType) {
BatchRecordSet bRs = new BatchRecordSet();
String sql = "";
List<Object> params = null;
try {
for(List<Object> list : lsFormatParams) {
list.add(formatType);
}
if (KQSettingsBiz.getKqformatthread()) {
sql = " insert into kq_format_pool (resourceid, kqdate, formattype) values (?,?,?)";
if (KQSettingsBiz.getKqformatAccurate()){
sql = " insert into kq_format_pool (resourceid, kqdate, exectime,formattype) values (?,?,?,?)";
lsFormatParams = processFormatParams(lsFormatParams);
}
bRs.executeBatchSqlNew(sql, lsFormatParams);
} else {
String resourceid = "";
String kqdate = "";
for (int i = 0; lsFormatParams != null && i < lsFormatParams.size(); i++) {
params = lsFormatParams.get(i);
resourceid = Util.null2String(params.get(0));
kqdate = Util.null2String(params.get(1));
new KQFormatData().formatKqDateByLock(resourceid, kqdate,formatType);
}
}
} catch (Exception e) {
writeLog(" KQFormatData.formatKqDate lsFormatParams >>>>>>>>>" + e);
}
}
public void formatDateByKQDate(String kqdate) {
String sql = "";
RecordSet rs = new RecordSet();
List<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 =? and kqdate = ? ";//删除非工作日数据
rs.executeUpdate(sql, resourceid, kqdate);
sql = " delete from kq_format_total where resourceid =? and kqdate = ? ";//删除非工作日数据
rs.executeUpdate(sql, resourceid, kqdate);
} catch (Exception e) {
writeLog(e);
kqLog.info(e);
}
}
public void clearFormatPool() {
RecordSet rs = new RecordSet();
String sql = "";
try {
//删除三天前的数据格式化数据
if (rs.getDBType().equals("sqlserver")) {
sql = " delete from kq_format_pool where status = 1 and datediff(day,created,getdate()) > 1";
} else if (rs.getDBType().equals("mysql")) {
sql = " delete from kq_format_pool where status = 1 and datediff(now(),created) > 1";
}
else if (rs.getDBType().equals("postgresql")) {
sql = " delete from kq_format_pool where status = 1 and datediff(now(),created) > 1";
}
else if (rs.getOrgindbtype().equals("st")) {
sql = " delete from kq_format_pool where status = 1 and to_number(trunc(sysdate) - trunc(created)) > 1";
} else {
sql = " delete from kq_format_pool where status = 1 and trunc(sysdate) - trunc(created) > 1";
}
rs.executeUpdate(sql);
} catch (Exception e) {
writeLog(e);
}
}
public Map<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;
}
kqLog.writeLog("currentFullTime"+currentFullTime+"wroktime:"+endTime+"needCalForgotCheckMins:"+needCalForgotCheckMins);
}
}
return needCalForgotCheckMins;
}
public boolean needCal(String workDate, String workTime,String isneedcal){
boolean needCalForgotCheckMins = true;
boolean isneedformat = "1".equals(isneedcal);
if (isneedformat) {
workTime = new KQTimesArrayComInfo().turn48to24Time(workTime);
if (workDate.length() > 0 && workTime.length() > 0) {
String currentFullTime = DateUtil.getFullDate();
String endTime = workDate + " " + workTime;
if (DateUtil.timeInterval(currentFullTime, endTime) > 0) {
//当前时间之后的状态无效计算
needCalForgotCheckMins = false;
}
}
}
return needCalForgotCheckMins;
}
private List<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));
String formattype = "";
if(formatParams.size() > 2) {
formattype = Util.null2String(formatParams.get(2));
}
formatParams = new ArrayList<>();
formatParams.add(resourceId);
formatParams.add(kqDate);
formatParams.add(new java.sql.Timestamp(DateUtil.getCalendar(DateUtil.getFullDate()).getTimeInMillis()));
formatParams.add(formattype);
lsFormatParamsTmp.add(formatParams);
String nextDate = DateUtil.addDate(kqDate, 1);//下一天日期
WorkTimeEntity workTime = kqWorkTime.getWorkTime(resourceId, kqDate);
List<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()));
formatParams.add(formattype);
lsFormatParamsTmp.add(formatParams);
formatParams = new ArrayList<>();
formatParams.add(resourceId);
formatParams.add(kqDate);
formatParams.add(new java.sql.Timestamp(DateUtil.getCalendar(workEndDateTime).getTimeInMillis()));
formatParams.add(formattype);
lsFormatParamsTmp.add(formatParams);
}
}else{
formatParams = new ArrayList<>();
formatParams.add(resourceId);
formatParams.add(kqDate);
formatParams.add(formattype);
lsFormatParamsTmp.add(formatParams);
}
}
}catch (Exception e) {
StringWriter errorsWriter = new StringWriter();
e.printStackTrace(new PrintWriter(errorsWriter));
kqLog.info(errorsWriter.toString());
}
return lsFormatParamsTmp;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,562 @@
package com.engine.kq.biz;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.engine.kq.biz.chain.shiftinfo.ShiftInfoBean;
import com.engine.kq.cmd.attendanceButton.ButtonStatusEnum;
import com.engine.kq.entity.KQShiftRuleEntity;
import com.engine.kq.entity.TimeScopeEntity;
import com.engine.kq.entity.TimeSignScopeEntity;
import com.engine.kq.entity.WorkTimeEntity;
import com.engine.kq.log.KQLog;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import java.util.*;
/**
* 格式化数据 人性化规则
*/
public class KQFormatShiftRule extends BaseBean {
private KQLog kqLog = new KQLog();
public KQShiftRuleEntity doShiftRule(WorkTimeEntity workTime, KQShiftRuleEntity kqShiftRuleEntity) {
Map<String, Object> shiftRuleInfo = workTime.getShiftRuleInfo();
//人性化处理
if (shiftRuleInfo != null && shiftRuleInfo.size() > 0) {
Map<String, Object> ruleDetail = (Map<String, Object>) shiftRuleInfo.get("ruleDetail");
//允许迟到分钟数
boolean usepermitlateminutes = Util.null2String(shiftRuleInfo.get("permitlatestatus")).equals("1");
int permitlateminutes = Util.getIntValue(Util.null2String(shiftRuleInfo.get("permitlateminutes")), 0);
boolean enableexcludelate = Util.null2String(shiftRuleInfo.get("enableexcludelate")).equals("1");
//允许早退分钟数
boolean usepermitleaveearlyminutes = Util.null2String(shiftRuleInfo.get("permitleaveearlystatus")).equals("1");
int permitleaveearlyminutes = Util.getIntValue(Util.null2String(shiftRuleInfo.get("permitleaveearlyminutes")), 0);
boolean enableexcludeleaveearly = Util.null2String(shiftRuleInfo.get("enableexcludeleaveearly")).equals("1");
//严重迟到分钟数
boolean useseriouslateminutes = Util.null2String(shiftRuleInfo.get("seriouslatestatus")).equals("1");
int seriouslateminutes = Util.getIntValue(Util.null2String(shiftRuleInfo.get("seriouslateminutes")), 0);
//严重早退分钟数
boolean useseriousleaveearlyminutes = Util.null2String(shiftRuleInfo.get("seriousleaveearlystatus")).equals("1");
int seriousleaveearlyminutes = Util.getIntValue(Util.null2String(shiftRuleInfo.get("seriousleaveearlyminutes")), 0);
//迟到多少钟数算旷工
boolean uselateabsentminutes = Util.null2String(shiftRuleInfo.get("lateabsentstatus")).equals("1");
int lateabsentminutes = Util.getIntValue(Util.null2String(shiftRuleInfo.get("lateabsentminutes")), 0);
//早退多少钟数算旷工
boolean useleaveearlyabsentminutes = Util.null2String(shiftRuleInfo.get("leaveearlyabsentstatus")).equals("1");
int leaveearlyabsentminutes = Util.getIntValue(Util.null2String(shiftRuleInfo.get("leaveearlyabsentminutes")), 0);
//允许下班不打卡
boolean isoffdutyfreecheck = Util.null2String(shiftRuleInfo.get("isoffdutyfreecheck")).equals("1");
String userId = kqShiftRuleEntity.getUserId();
String kqDate = kqShiftRuleEntity.getKqDate();
int beLateMins = kqShiftRuleEntity.getBelatemins();
int graveBeLateMins = 0;
int leaveEarlyMins = kqShiftRuleEntity.getLeaveearlymins();
int graveLeaveEarlyMins = 0;
int absenteeismMins = kqShiftRuleEntity.getAbsenteeismmins();
int forgotcheckMins = kqShiftRuleEntity.getForgotcheckmins();
int forgotBeginWorkCheckMins = kqShiftRuleEntity.getForgotBeginWorkCheckMins();
int earlyInMins = kqShiftRuleEntity.getEarlyInMins();
int lateOutMins = kqShiftRuleEntity.getLateOutMins();
String nosign_is_absent = kqShiftRuleEntity.getNosign_is_absent();
String early_one_mins = kqShiftRuleEntity.getEarly_one_mins();
String signInTime = kqShiftRuleEntity.getSignInTime();
String signOutTime = kqShiftRuleEntity.getSignOutTime();
List<Object> earlyinearlyout = null;//早到早走规则
List<Object> lateinlateout = null;//晚到晚走规则
List<Object> lateoutlatein = null;//晚走晚到规则
//这里个性化没法处理流程数据逻辑改为在前面直接虚拟改掉了上下班时间
if (ruleDetail != null && ruleDetail.size() > 0 && false) {//处理人性化设置其他规则
earlyinearlyout = (List<Object>) ruleDetail.get("earlyinearlyout");
lateinlateout = (List<Object>) ruleDetail.get("lateinlateout");
lateoutlatein = (List<Object>) ruleDetail.get("lateoutlatein");
if (earlyinearlyout != null && earlyinearlyout.size() > 0 && leaveEarlyMins > 0) {
for (int i = 0; earlyInMins > 0 && i < earlyinearlyout.size(); i++) {
Map<String, Object> rule = (Map<String, Object>) earlyinearlyout.get(i);
if (Util.null2String(rule.get("enable")).equals("1")) {
int advancetime = new Double((Util.getDoubleValue(Util.null2String(rule.get("advancetime"))))).intValue();//早到时间
int postponetime = new Double((Util.getDoubleValue(Util.null2String(rule.get("postponetime"))))).intValue();//允许早走时间
if (Util.null2String(rule.get("enablesame")).equals("1")) {
if (earlyInMins > postponetime) {
leaveEarlyMins -= postponetime;
if (leaveEarlyMins < 0) leaveEarlyMins = 0;
} else {
leaveEarlyMins -= earlyInMins;
if (leaveEarlyMins < 0) leaveEarlyMins = 0;
}
break;
} else {
if (earlyInMins >= advancetime) {
leaveEarlyMins -= postponetime;
if (leaveEarlyMins < 0) leaveEarlyMins = 0;
break;
}
}
}
}
}
if (lateinlateout != null && lateinlateout.size() > 0 && beLateMins > 0) {
for (int i = 0; lateOutMins > 0 && i < lateinlateout.size(); i++) {
Map<String, Object> rule = (Map<String, Object>) lateinlateout.get(i);
if (Util.null2String(rule.get("enable")).equals("1")) {
int advancetime = new Double((Util.getDoubleValue(Util.null2String(rule.get("advancetime"))))).intValue();//晚到时间
int postponetime = new Double((Util.getDoubleValue(Util.null2String(rule.get("postponetime"))))).intValue();//需要晚走时间
if (Util.null2String(rule.get("enablesame")).equals("1")) {
if (lateOutMins > postponetime) {
beLateMins -= postponetime;
if (beLateMins < 0) beLateMins = 0;
} else {
beLateMins -= lateOutMins;
if (beLateMins < 0) beLateMins = 0;
}
break;
} else {
if (lateOutMins >= postponetime) {
beLateMins -= advancetime;
if (beLateMins < 0) beLateMins = 0;
break;
}
}
}
}
}
if (lateoutlatein != null && lateoutlatein.size() > 0 && beLateMins > 0) {
int preDayLateOutMins = getPreDayLateOutMins(userId, kqDate);
for (int i = 0; preDayLateOutMins > 0 && i < lateoutlatein.size(); i++) {
Map<String, Object> rule = (Map<String, Object>) lateoutlatein.get(i);
if (Util.null2String(rule.get("enable")).equals("1")) {
int advancetime = new Double((Util.getDoubleValue(Util.null2String(rule.get("advancetime"))))).intValue();//晚走时间
int postponetime = new Double((Util.getDoubleValue(Util.null2String(rule.get("postponetime"))))).intValue();//允许晚到时间
if (Util.null2String(rule.get("enablesame")).equals("1")) {
if (preDayLateOutMins > postponetime) {
beLateMins -= postponetime;
if (beLateMins < 0) beLateMins = 0;
} else {
beLateMins -= preDayLateOutMins;
if (beLateMins < 0) beLateMins = 0;
}
break;
} else {
if (preDayLateOutMins >= advancetime) {
beLateMins -= postponetime;
if (beLateMins < 0) beLateMins = 0;
break;
}
}
}
}
}
}
if (beLateMins > 0) {//迟到人性化设置
if (usepermitlateminutes) {//允许迟到分钟数
if (permitlateminutes >= beLateMins) {
beLateMins = 0;
} else if (enableexcludelate) {
beLateMins = beLateMins - permitlateminutes;
}
}
if (uselateabsentminutes && beLateMins >= lateabsentminutes) {//旷工
absenteeismMins += beLateMins;
beLateMins = 0;
kqShiftRuleEntity.setOn_absenteeismMins(absenteeismMins);
kqShiftRuleEntity.setAMAbsent(true);
//leaveEarlyMins = 0;
if ("1".equals(nosign_is_absent)) {
/**
* 在漏签算实际出勤的情况才需要清空漏签时长forgotcheckMins原由如下比如09:00--18:00这是11:00打上班卡下班卡没有打卡
* 情况1没有开启迟到或者早退算旷工的情况正常应该显示迟到120分钟 漏签这时候实际出勤应该是0
* 情况2开启了迟到60分钟算旷工之后应该显示旷工120分钟 漏签这时候实际出勤应该是0而如果清空漏签时长forgotcheckMins 那么就有实际出勤时长了因为实际出勤=应出勤-迟到-早退-旷工-请假-漏签时长
* 所以在漏签算实际出勤的时候才需要清空也就原标准逻辑反之不需要清空
*
*/
forgotcheckMins = 0;
} else {
kqShiftRuleEntity.setNosign_ishandle("1");
}
} else if (useseriouslateminutes && beLateMins >= seriouslateminutes) {//严重迟到
graveBeLateMins += beLateMins;
//TODO 这有个问题严重迟到了还要不要算迟到这两个是同时存在的吗
beLateMins = 0;
}
}
if (leaveEarlyMins > 0) {//早退人性化设置
if (usepermitleaveearlyminutes) {//允许早退分钟数
if (permitleaveearlyminutes >= leaveEarlyMins) {
leaveEarlyMins = 0;
} else if (enableexcludeleaveearly) {
leaveEarlyMins = leaveEarlyMins - permitleaveearlyminutes;
}
}
if (useleaveearlyabsentminutes && leaveEarlyMins >= leaveearlyabsentminutes) {//旷工
absenteeismMins += leaveEarlyMins;
//beLateMins = 0;
leaveEarlyMins = 0;
kqShiftRuleEntity.setOff_absenteeismMins(absenteeismMins);
kqShiftRuleEntity.setPMAbsent(true);
if ("1".equals(nosign_is_absent)) {
/**
* 在漏签算实际出勤的情况才需要清空漏签时长forgotcheckMins原由如下比如09:00--18:00这是11:00打上班卡下班卡没有打卡
* 情况1没有开启迟到或者早退算旷工的情况正常应该显示迟到120分钟 漏签这时候实际出勤应该是0
* 情况2开启了迟到60分钟算旷工之后应该显示旷工120分钟 漏签这时候实际出勤应该是0而如果清空漏签时长forgotcheckMins 那么就有实际出勤时长了因为实际出勤=应出勤-迟到-早退-旷工-请假-漏签时长
* 所以在漏签算实际出勤的时候才需要清空也就原标准逻辑反之不需要清空
*
*/
forgotcheckMins = 0;
forgotBeginWorkCheckMins = 0;
} else {
kqShiftRuleEntity.setNosign_ishandle("2");
}
} else if (useseriousleaveearlyminutes && leaveEarlyMins >= seriousleaveearlyminutes) {//严重早退
graveLeaveEarlyMins += leaveEarlyMins;
//TODO 这有个问题严重早退了还要不要算早退这两个是同时存在的吗
leaveEarlyMins = 0;
}
}
//允许下班不打卡
if (isoffdutyfreecheck) {
forgotcheckMins = 0;
}
/**
* 含泪加上
* 晚到晚走导致的早退1分钟特殊处理下
* 2024-02-28 上班时间是:2024-02-28 08:30:00,签到时间是:2024-02-28 08:34:26,晚到5分钟, 开启了晚到晚走,相对时间
* 所以2024-02-28的上班时间和下班时间变化了,上班时间变成了:2024-02-28 08:35,下班时间变成了:2024-02-28 17:35
* 现在签到是08:34:26签退是17:34:48导致早退1分钟
*/
if("1".equals(early_one_mins)){
if (ruleDetail != null && ruleDetail.size() > 0) {//处理人性化设置其他规则
earlyinearlyout = (List<Object>) ruleDetail.get("earlyinearlyout");
lateinlateout = (List<Object>) ruleDetail.get("lateinlateout");
}
String signInTime_Sec = (signInTime != null && signInTime.length() == 8) ? signInTime.substring(6, 8) : "";
String signOutTime_Sec = (signOutTime != null && signOutTime.length() == 8) ? signOutTime.substring(6, 8) : "";
writeLog("signInTime="+signInTime+",signInTime_Sec="+signInTime_Sec+",signOutTime="+signOutTime+",signOutTime_Sec="+signOutTime_Sec+",leaveEarlyMins="+leaveEarlyMins);
// writeLog("leaveEarlyMins="+leaveEarlyMins+",lateinlateout="+JSONObject.toJSONString(lateinlateout));
if (((lateinlateout != null && lateinlateout.size() > 0)||(earlyinearlyout != null && earlyinearlyout.size() > 0))
&& leaveEarlyMins == 1) {
if (signInTime_Sec.compareTo(signOutTime_Sec) <= 0) {
leaveEarlyMins = 0;
}
}
}
// writeLog("leaveEarlyMins="+leaveEarlyMins+",early_one_mins="+early_one_mins);
kqShiftRuleEntity.setBelatemins(beLateMins);
kqShiftRuleEntity.setGravebelatemins(graveBeLateMins);
kqShiftRuleEntity.setLeaveearlymins(leaveEarlyMins);
kqShiftRuleEntity.setGraveleaveearlymins(graveLeaveEarlyMins);
kqShiftRuleEntity.setAbsenteeismmins(absenteeismMins);
kqShiftRuleEntity.setForgotcheckmins(forgotcheckMins);
kqShiftRuleEntity.setForgotBeginWorkCheckMins(forgotBeginWorkCheckMins);
}
return kqShiftRuleEntity;
}
public int getEarlyInMins(String userId, String kqDate) {
return getEarlyInMins(userId,kqDate,0);
}
public int getEarlyInMins(String userId, String kqDate,int signoutOnlyoff) {
int earlyInMins = 0;
boolean oneSign = false;
String preDate = DateUtil.addDate(kqDate, -1);//上一天日期
String nextDate = DateUtil.addDate(kqDate, 1);//下一天日期
KQWorkTime kqWorkTime = new KQWorkTime();
WorkTimeEntity workTime = kqWorkTime.getWorkTime(userId, kqDate);
List<TimeScopeEntity> lsSignTime = new ArrayList<>();
List<TimeScopeEntity> lsWorkTime = new ArrayList<>();
if (workTime != null) {
lsSignTime = workTime.getSignTime();//允许打卡时间
lsWorkTime = workTime.getWorkTime();//工作时间
oneSign = lsWorkTime != null && lsWorkTime.size() == 1;
}
if (oneSign) {
KQTimesArrayComInfo kqTimesArrayComInfo = new KQTimesArrayComInfo();
TimeScopeEntity signTimeScope = lsSignTime.get(0);
TimeScopeEntity workTimeScope = lsWorkTime.get(0);
int workBeginIdx = kqTimesArrayComInfo.getArrayindexByTimes(workTimeScope.getBeginTime());
List<Object> lsCheckInfo = new KQFormatSignData().getSignInfo(userId, signTimeScope, workTimeScope, kqDate, preDate, nextDate, kqTimesArrayComInfo
,Lists.newArrayList(), "",0,0,signoutOnlyoff);
for (int j = 0; lsCheckInfo != null && j < lsCheckInfo.size(); j++) {
Map<String, Object> checkInfo = (Map<String, Object>) lsCheckInfo.get(j);
String signDate = Util.null2String(checkInfo.get("signDate"));
String signTime = Util.null2String(checkInfo.get("signTime"));
String deduct_signintime = Util.null2String(checkInfo.get("deduct_signintime"));
if (checkInfo.get("signType").equals("1")) {//签到
//有签到但是没有signTime是因为开启了流程抵扣打卡
if (null == signTime || signTime.length() < 5) {
continue;
} else {
writeLog("signDate:" + signDate + ",signTime=" + signTime + ",checkInfo=" + checkInfo.toString());
}
String signMinTime = signTime.substring(0, 5) + ":00";
boolean signInWorkBeginTime = false;
if (signTime.compareTo(signMinTime) > 0) {
//如果签到时间是带秒的且是迟到那么签到时间多一秒和多一分钟是一样的
signInWorkBeginTime = true;
}
String signInTime = signTime;
int signInTimeIndx = kqTimesArrayComInfo.getArrayindexByTimes(signInTime);
String flow_signInTime = "";
if (deduct_signintime.length() > 0) {
if (signTime.length() > 0) {
if (deduct_signintime.compareTo(signTime) < 0) {
flow_signInTime = deduct_signintime;
}
} else {
flow_signInTime = deduct_signintime;
}
}
if (flow_signInTime.length() > 0) {
signInTimeIndx = kqTimesArrayComInfo.getArrayindexByTimes(flow_signInTime);
}
if (kqDate.compareTo(signDate) < 0) signInTimeIndx += 1440;
if (signInWorkBeginTime) {
signInTimeIndx = signInTimeIndx + 1;
}
if (workBeginIdx > signInTimeIndx) {
earlyInMins = workBeginIdx - signInTimeIndx;
}
}
}
}
return earlyInMins;
}
public int getLateOutMins(String userId, String kqDate) {
return getLateOutMins(userId,kqDate,0);
}
public int getLateOutMins(String userId, String kqDate,int signoutOnlyoff) {
int lateOutMins = 0;
boolean oneSign = false;
String preDate = DateUtil.addDate(kqDate, -1);//上一天日期
String nextDate = DateUtil.addDate(kqDate, 1);//下一天日期
KQWorkTime kqWorkTime = new KQWorkTime();
WorkTimeEntity workTime = kqWorkTime.getWorkTime(userId, kqDate);
List<TimeScopeEntity> lsSignTime = new ArrayList<>();
List<TimeScopeEntity> lsWorkTime = new ArrayList<>();
if (workTime != null) {
lsSignTime = workTime.getSignTime();//允许打卡时间
lsWorkTime = workTime.getWorkTime();//工作时间
oneSign = lsWorkTime != null && lsWorkTime.size() == 1;
}
if (oneSign) {
KQTimesArrayComInfo kqTimesArrayComInfo = new KQTimesArrayComInfo();
TimeScopeEntity signTimeScope = lsSignTime.get(0);
TimeScopeEntity workTimeScope = lsWorkTime.get(0);
int workEndIdx = kqTimesArrayComInfo.getArrayindexByTimes(workTimeScope.getEndTime());
List<Object> lsCheckInfo = new KQFormatSignData().getSignInfo(userId, signTimeScope, workTimeScope, kqDate, preDate, nextDate, kqTimesArrayComInfo
,Lists.newArrayList(), "",0,0,signoutOnlyoff);
for (int j = 0; lsCheckInfo != null && j < lsCheckInfo.size(); j++) {
Map<String, Object> checkInfo = (Map<String, Object>) lsCheckInfo.get(j);
String signDate = Util.null2String(checkInfo.get("signDate"));
String signTime = Util.null2String(checkInfo.get("signTime"));
String deduct_signofftime = Util.null2String(checkInfo.get("deduct_signofftime"));
if (checkInfo.get("signType").equals("2")) {//签退
String signOutTime = signTime;
int signInTimeOutdx = kqTimesArrayComInfo.getArrayindexByTimes(signOutTime);
String flow_signOutTime = signOutTime;
if (deduct_signofftime.length() > 0) {
if (signTime.length() > 0) {
if (deduct_signofftime.compareTo(signTime) > 0) {
flow_signOutTime = deduct_signofftime;
}
} else {
flow_signOutTime = deduct_signofftime;
}
}
if (flow_signOutTime.length() > 0) {
signInTimeOutdx = kqTimesArrayComInfo.getArrayindexByTimes(flow_signOutTime);
}
if (kqDate.compareTo(signDate) < 0) signInTimeOutdx += 1440;
if (signInTimeOutdx > workEndIdx) {
lateOutMins = signInTimeOutdx - workEndIdx;
}
}
}
}
return lateOutMins;
}
public int getPreDayLateOutMins(String userId, String kqDate) {
return getPreDayLateOutMins(userId, kqDate, Lists.newArrayList());
}
public int getPreDayLateOutMins(String userId, String kqDate, List<String> logList) {
return getPreDayLateOutMins(userId, kqDate,logList,0);
}
/**
* 前一天晚走分钟数
*/
public int getPreDayLateOutMins(String userId, String kqDate, List<String> logList,int signoutOnlyoff) {
int preDayLateOutMins = 0;
boolean oneSign = false;
KQWorkTime kqWorkTime = new KQWorkTime();
//前一天是非工作日往前取到工作日
String tmpKQPreDate = DateUtil.addDate(kqDate, -1);
for (int i = 0; i < 31; i++) {
WorkTimeEntity workTime = kqWorkTime.getWorkTime(userId, tmpKQPreDate);
if (workTime.getWorkMins() > 0) {
kqDate = DateUtil.addDate(tmpKQPreDate, 1);
break;
}
tmpKQPreDate = DateUtil.addDate(tmpKQPreDate, -1);
}
String kqPreDate = DateUtil.addDate(kqDate, -1);
;
String kqPrePreDate = DateUtil.addDate(kqDate, -2);
WorkTimeEntity workTime = kqWorkTime.getWorkTime(userId, kqPreDate);
List<TimeScopeEntity> lsSignTime = new ArrayList<>();
List<TimeScopeEntity> lsWorkTime = new ArrayList<>();
if (workTime != null) {
lsSignTime = workTime.getSignTime();//允许打卡时间
lsWorkTime = workTime.getWorkTime();//工作时间
oneSign = lsWorkTime != null && lsWorkTime.size() == 1;
}
if (oneSign) {
KQTimesArrayComInfo kqTimesArrayComInfo = new KQTimesArrayComInfo();
TimeScopeEntity signTimeScope = lsSignTime.get(0);
TimeScopeEntity workTimeScope = lsWorkTime.get(0);
String signBeginDateTime = signTimeScope.getBeginTimeAcross() ? kqPrePreDate : kqPreDate;
signBeginDateTime += " " + kqTimesArrayComInfo.turn48to24Time(signTimeScope.getBeginTime()) + ":00";
String signEndDateTime = signTimeScope.getEndTimeAcross() ? kqDate : kqPreDate;
signEndDateTime += " " + kqTimesArrayComInfo.turn48to24Time(signTimeScope.getEndTime()) + ":00";
String workBeginDateTime = workTimeScope.getBeginTimeAcross() ? kqPrePreDate : kqPreDate;
workBeginDateTime += " " + kqTimesArrayComInfo.turn48to24Time(workTimeScope.getBeginTime()) + ":00";
String workEndDateTime = workTimeScope.getEndTimeAcross() ? kqDate : kqPreDate;
workEndDateTime += " " + kqTimesArrayComInfo.turn48to24Time(workTimeScope.getEndTime()) + ":00";
Map<String, String> shifRuleMap = Maps.newHashMap();
String shif_workEndTime = "";
getPre_ShiftRuleInfo(kqPreDate, workTime, lsSignTime, lsWorkTime, userId, shifRuleMap, logList);
if (!shifRuleMap.isEmpty()) {
if (shifRuleMap.containsKey("shift_endworktime")) {
String shift_endworktime = Util.null2String(shifRuleMap.get("shift_endworktime"));
if (shift_endworktime.length() > 0) {
shif_workEndTime = Util.null2String(shift_endworktime);
}
}
}
List<Object> lsCheckInfo = new KQFormatSignData().getSignInfo(userId, signTimeScope, workTimeScope, kqPreDate, kqPrePreDate, kqDate, kqTimesArrayComInfo
,Lists.newArrayList(), "",0,0,signoutOnlyoff);
Map<String, Object> checkInfo = null;
if (lsCheckInfo.size() == 2) {
for (int i = 0; i < lsCheckInfo.size(); i++) {
checkInfo = (Map<String, Object>) lsCheckInfo.get(i);
String signType = Util.null2String(checkInfo.get("signType"));
if ("2".equalsIgnoreCase(signType)) {
break;
}
}
String signDate = Util.null2String(checkInfo.get("signDate"));
String signTime = Util.null2String(checkInfo.get("signTime"));
String workEndTime = Util.null2String(workTimeScope.getEndTime());
int workEndIdx = kqTimesArrayComInfo.getArrayindexByTimes(workEndTime);
if (shif_workEndTime.length() > 0) {
workEndIdx = kqTimesArrayComInfo.getArrayindexByTimes(shif_workEndTime);
}
if (!kqPreDate.equals(signDate)) { //跨天
signTime = kqTimesArrayComInfo.turn24to48Time(signTime);
}
int signOutTimeIdx = kqTimesArrayComInfo.getArrayindexByTimes(signTime);
if (signOutTimeIdx > workEndIdx) {
preDayLateOutMins = signOutTimeIdx - workEndIdx;
logList.add("签退时间是:" + (signDate + " " + kqTimesArrayComInfo.turn48to24Time(signTime)) + ",晚走了" + preDayLateOutMins + "分钟");
}
} else if (!lsCheckInfo.isEmpty()) {
for (int i = 0; i < lsCheckInfo.size(); i++) {
Map<String, Object> checkInfoMap = (Map<String, Object>) lsCheckInfo.get(i);
String signType = Util.null2String(checkInfoMap.get("signType"));
if ("2".equalsIgnoreCase(signType)) {
String signDate = Util.null2String(checkInfoMap.get("signDate"));
String signTime = Util.null2String(checkInfoMap.get("signTime"));
String workEndTime = Util.null2String(workTimeScope.getEndTime());
int workEndIdx = kqTimesArrayComInfo.getArrayindexByTimes(workEndTime);
if (shif_workEndTime.length() > 0) {
workEndIdx = kqTimesArrayComInfo.getArrayindexByTimes(shif_workEndTime);
}
if (!kqPreDate.equals(signDate)) { //跨天
signTime = kqTimesArrayComInfo.turn24to48Time(signTime);
}
int signOutTimeIdx = kqTimesArrayComInfo.getArrayindexByTimes(signTime);
if (signOutTimeIdx > workEndIdx) {
preDayLateOutMins = signOutTimeIdx - workEndIdx;
logList.add(",签退时间是:" + (signDate + " " + signTime) + ",晚走了" + preDayLateOutMins + "分钟");
}
}
}
}
}
return preDayLateOutMins;
}
/**
* 获取前一天的弹性时间
*
* @param kqPreDate
* @param workTime
* @param lsSignTime
* @param lsWorkTime
* @param userId
* @param logList
*/
public void getPre_ShiftRuleInfo(String kqPreDate, WorkTimeEntity workTime,
List<TimeScopeEntity> lsSignTime, List<TimeScopeEntity> lsWorkTime, String userId,
Map<String, String> shifRuleMap, List<String> logList) {
ShiftInfoBean shiftInfoBean = new ShiftInfoBean();
shiftInfoBean.setSplitDate(kqPreDate);
shiftInfoBean.setShiftRuleMap(workTime.getShiftRuleInfo());
shiftInfoBean.setSignTime(lsSignTime);
shiftInfoBean.setWorkTime(lsWorkTime);
KQShiftRuleInfoBiz.getShiftRuleInfo(shiftInfoBean, userId, shifRuleMap, false, logList);
}
/**
* 获取班次设置里面的上下班不打卡数据
*
* @param i
* @param serialId
*/
public Map<String, String> getModel_ShiftRule(int i, String serialId) {
RecordSet rs = new RecordSet();
HashMap<String, String> sectionMap = new HashMap<>();
String getStartWorkSections = "select * from kq_ShiftOnOffWorkSections where SERIALID=? and record=? ";
rs.executeQuery(getStartWorkSections, serialId, i);
while (rs.next()) {
String onoffworktype = Util.null2String(rs.getString("onoffworktype"));
String clockinnot = Util.null2s(Util.null2String(rs.getString("clockinnot")), "0");
sectionMap.put(onoffworktype, clockinnot);
}
return sectionMap;
}
}

View File

@ -0,0 +1,758 @@
package com.engine.kq.biz;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.engine.kq.cmd.attendanceButton.ButtonStatusEnum;
import com.engine.kq.entity.TimeScopeEntity;
import com.engine.kq.entity.TimeSignScopeEntity;
import com.engine.kq.log.KQLog;
import com.engine.kq.util.UtilKQ;
import com.engine.kq.wfset.util.KQSignUtil;
import com.google.common.collect.Lists;
import java.io.PrintWriter;
import java.io.StringWriter;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import java.util.*;
/**
* 获取班次打卡数据
*/
public class KQFormatSignData extends BaseBean {
private KQLog kqLog = new KQLog();
public List<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(), "");
}
public List<Object> getSignInfo(String userId, TimeScopeEntity signTimeScope,
TimeScopeEntity workTimeScope, String kqDate, String preDate,
String nextDate, KQTimesArrayComInfo kqTimesArrayComInfo, ArrayList<String> hostIps, String uuid) {
return getSignInfo(userId, signTimeScope, workTimeScope, kqDate, preDate, nextDate, kqTimesArrayComInfo, hostIps, uuid, 0, 0);
}
public List<Object> getSignInfo(String userId, TimeScopeEntity signTimeScope,
TimeScopeEntity workTimeScope, String kqDate, String preDate,
String nextDate, KQTimesArrayComInfo kqTimesArrayComInfo, ArrayList<String> hostIps, String uuid, int shiftCount, int shiftI) {
return getSignInfo(userId, signTimeScope, workTimeScope, kqDate, preDate, nextDate, kqTimesArrayComInfo, hostIps, uuid, shiftCount, shiftI, 0);
}
/***
* 获取班次打卡数据
* @param userId
* @param signTimeScope
* @param workTimeScope
* @param kqDate
* @param preDate
* @param nextDate
* @param kqTimesArrayComInfo
* @return
*/
public List<Object> getSignInfo(String userId, TimeScopeEntity signTimeScope,
TimeScopeEntity workTimeScope, String kqDate, String preDate,
String nextDate, KQTimesArrayComInfo kqTimesArrayComInfo, ArrayList<String> hostIps, String uuid, int shiftCount, int shiftI, int signoutOnlyoff) {
kqLog.info("in getSignInfo ::userId" + userId + "kqDate==" + kqDate + ":hostIps:" + hostIps + ":uuid::" + uuid + " in ");
List<Object> lsCheckInfo = new ArrayList<>();
String count4NoonStartDateTime = "";
String count4NoonEndDateTime = "";
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);
kqLog.info("in getSignInfo ::userId" + userId + "kqDate==" + kqDate + ":hostIps:" + hostIps + ":uuid::" + uuid + "::signTimeScope::" + JSON.toJSONString(signTimeScope));
List<Map<String, String>> sqlConditions = getCanSignInfo(signTimeScope, kqDate, preDate, nextDate, kqTimesArrayComInfo, workTimeScope, shiftCount, shiftI, signoutOnlyoff);
base_sql = signSignSql(rs);
new KQLog().info("sqlConditions:(userId:" + userId + ":base_sql" + base_sql + ":::userId" + userId + "kqDate==" + kqDate + ":hostIps:" + hostIps + ":uuid::" + uuid + "::flow_deduct_card_map::" + flow_deduct_card_map + "::sqlConditions::" + JSONObject.toJSONString(sqlConditions));
if (sqlConditions != null && !sqlConditions.isEmpty()) {
if (shiftCount == 2) {
String fieldName = "";
if (shiftI == 0) {
fieldName = "signEndDateTime";
} else if (shiftI == 1) {
fieldName = "signBeginDateTime";
}
Map<String, String> sqlMap = sqlConditions.get(0);
count4NoonStartDateTime = Util.null2String(sqlMap.get(fieldName));
if (count4NoonStartDateTime.length() == 19) {
count4NoonStartDateTime = count4NoonStartDateTime.substring(0, 17) + "00";
}
sqlMap = sqlConditions.get(0);
count4NoonEndDateTime = Util.null2String(sqlMap.get(fieldName));
if (sqlConditions.size() >= 2) {
sqlMap = sqlConditions.get(1);
count4NoonEndDateTime = Util.null2String(sqlMap.get(fieldName));
}
}
boolean hasSignIn = false;
for (Map<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"));
String signoutOnlyoff_flag = Util.null2String(sqlMap.get("signoutOnlyoff"));
if (type.length() > 0) {
if ("signoff".equalsIgnoreCase(type)) {
orderSql = " order by signdate desc, signtime desc ";
} else if ("signin".equalsIgnoreCase(type)) {
orderSql = " order by signdate asc, signtime asc ";
}
if ("oracle".equalsIgnoreCase(dbtype)) {
sql = "select * from (" + base_sql + " " + orderSql + ") a where rownum=1";
} else if ("mysql".equalsIgnoreCase(dbtype)) {
sql = "select * from (" + base_sql + " " + orderSql + ") a limit 0,1";
} else if ("postgresql".equalsIgnoreCase(dbtype)) {
sql = "select * from (" + base_sql + " " + orderSql + ") a limit 1 offset 0";
} else if ("sqlserver".equalsIgnoreCase(dbtype)) {
sql = "select top 1 * from (" + base_sql + ") a " + " " + orderSql;
} else {
sql = "select * from (" + base_sql + " " + orderSql + ") a where rownum=1";
}
} else {
orderSql = " order by signdate asc, signtime asc ";
sql = base_sql + " " + orderSql;
}
rs.executeQuery(sql, userId, signBeginDateTime, signEndDateTime);
new KQLog().info("getSignInfo:(userId:" + userId + ":signBeginDateTime:" +
signBeginDateTime + ":signEndDateTime:" + signEndDateTime + "):sql" + sql + ":counts:" + rs.getCounts() + ":::userId" + userId + "kqDate==" + kqDate + ":hostIps:" + hostIps + ":uuid::" + uuid + "::flow_deduct_card_map::" + flow_deduct_card_map);
while (rs.next()) {
String signId = Util.null2String(rs.getString("id"));
String signdate = Util.null2String(rs.getString("signdate"));
String signtime = Util.null2String(rs.getString("signtime"));
checkInfo = new HashMap<>();
checkInfo.put("signId", signId);//签到签退标识
checkInfo.put("signDate", signdate);//签到签退日期
checkInfo.put("signTime", signtime);//签到签退时间
String signDateTime = signdate + " " + signtime;
idx++;
if (type.length() > 0) {
if ("signin".equalsIgnoreCase(type)) {
checkInfo.put("signType", "1");
if (workBeginDateTime.length() > 0) {
checkInfo.put("signStatus", UtilKQ.getSignStatus("1", signDateTime, workBeginDateTime));
}
if (!Util.null2String(checkInfo.get("signStatus")).equalsIgnoreCase(ButtonStatusEnum.NORMAL.getStatusCode())) {
if (flow_deduct_card_map.containsKey("signin")) {
String deduct_signintime = Util.null2String(flow_deduct_card_map.get("signin"));
if (deduct_signintime.length() > 0) {
signDateTime = signdate + " " + deduct_signintime;
checkInfo.put("deduct_signintime", deduct_signintime);//流程抵扣作为打卡时间
checkInfo.put("signStatus", UtilKQ.getSignStatus("1", signDateTime, workBeginDateTime));
}
}
}
lsCheckInfo.add(checkInfo);
} else {
checkInfo.put("signType", "2");
if (workEndDateTime.length() > 0) {
checkInfo.put("signStatus", UtilKQ.getSignStatus("2", signDateTime, workEndDateTime));
}
if (!Util.null2String(checkInfo.get("signStatus")).equalsIgnoreCase(ButtonStatusEnum.NORMAL.getStatusCode())) {
if (flow_deduct_card_map.containsKey("signoff")) {
String deduct_signofftime = Util.null2String(flow_deduct_card_map.get("signoff"));
if (deduct_signofftime.length() > 0) {
signDateTime = signdate + " " + deduct_signofftime;
checkInfo.put("deduct_signofftime", deduct_signofftime);//流程抵扣作为打卡时间
checkInfo.put("signStatus", UtilKQ.getSignStatus("2", signDateTime, workEndDateTime));
}
}
}
lsCheckInfo.add(checkInfo);
}
} else {
if (signoutOnlyoff_flag.length()>0) {
if("signin".equals(signoutOnlyoff_flag) && idx == 1){
checkInfo.put("signType", "1");
if (workBeginDateTime.length() > 0) {
checkInfo.put("signStatus", UtilKQ.getSignStatus("1", signDateTime, workBeginDateTime));
}
if (!Util.null2String(checkInfo.get("signStatus")).equalsIgnoreCase(ButtonStatusEnum.NORMAL.getStatusCode())) {
if (flow_deduct_card_map.containsKey("signin")) {
String deduct_signintime = Util.null2String(flow_deduct_card_map.get("signin"));
if (deduct_signintime.length() > 0) {
signDateTime = signdate + " " + deduct_signintime;
checkInfo.put("deduct_signintime", deduct_signintime);//流程抵扣作为打卡时间
checkInfo.put("signStatus", UtilKQ.getSignStatus("1", signDateTime, workBeginDateTime));
}
}
}
lsCheckInfo.add(checkInfo);
hasSignIn = true;
}
if("signoff".equals(signoutOnlyoff_flag)){
if ((hasSignIn && idx == rs.getCounts() && idx > 1) || (!hasSignIn && idx == rs.getCounts())) {//第一条可能是签到卡需要处理下否则可能会导致一条上班卡同时识别为上班卡和下班卡
checkInfo.put("signType", "2");
if (workEndDateTime.length() > 0) {
checkInfo.put("signStatus", UtilKQ.getSignStatus("2", signDateTime, workEndDateTime));
}
if (!Util.null2String(checkInfo.get("signStatus")).equalsIgnoreCase(ButtonStatusEnum.NORMAL.getStatusCode())) {
if (flow_deduct_card_map.containsKey("signoff")) {
String deduct_signofftime = Util.null2String(flow_deduct_card_map.get("signoff"));
if (deduct_signofftime.length() > 0) {
signDateTime = signdate + " " + deduct_signofftime;
checkInfo.put("deduct_signofftime", deduct_signofftime);//流程抵扣作为打卡时间
checkInfo.put("signStatus", UtilKQ.getSignStatus("2", signDateTime, workEndDateTime));
}
}
}
lsCheckInfo.add(checkInfo);
}
}
} else {
if (idx == 1) {//第一条算签到
checkInfo.put("signType", "1");
if (workBeginDateTime.length() > 0) {
checkInfo.put("signStatus", UtilKQ.getSignStatus("1", signDateTime, workBeginDateTime));
}
if (!Util.null2String(checkInfo.get("signStatus")).equalsIgnoreCase(ButtonStatusEnum.NORMAL.getStatusCode())) {
if (flow_deduct_card_map.containsKey("signin")) {
String deduct_signintime = Util.null2String(flow_deduct_card_map.get("signin"));
if (deduct_signintime.length() > 0) {
signDateTime = signdate + " " + deduct_signintime;
checkInfo.put("deduct_signintime", deduct_signintime);//流程抵扣作为打卡时间
checkInfo.put("signStatus", UtilKQ.getSignStatus("1", signDateTime, workBeginDateTime));
}
}
}
lsCheckInfo.add(checkInfo);
hasSignIn = true;
} else if (idx == rs.getCounts()) {//最后一条算签退
checkInfo.put("signType", "2");
if (workEndDateTime.length() > 0) {
checkInfo.put("signStatus", UtilKQ.getSignStatus("2", signDateTime, workEndDateTime));
}
if (!Util.null2String(checkInfo.get("signStatus")).equalsIgnoreCase(ButtonStatusEnum.NORMAL.getStatusCode())) {
if (flow_deduct_card_map.containsKey("signoff")) {
String deduct_signofftime = Util.null2String(flow_deduct_card_map.get("signoff"));
if (deduct_signofftime.length() > 0) {
signDateTime = signdate + " " + deduct_signofftime;
checkInfo.put("deduct_signofftime", deduct_signofftime);//流程抵扣作为打卡时间
checkInfo.put("signStatus", UtilKQ.getSignStatus("2", signDateTime, workEndDateTime));
}
}
}
lsCheckInfo.add(checkInfo);
}
}
}
}
}
}
//如果签到签退不成对流程抵扣异常存在那么需要判断下是不是可以补足
if (lsCheckInfo.size() < 2 && !flow_deduct_card_map.isEmpty()) {
if (lsCheckInfo.isEmpty()) {
if (flow_deduct_card_map.containsKey("signin")) {
String deduct_signintime = Util.null2String(flow_deduct_card_map.get("signin"));
if (deduct_signintime.length() > 0) {
checkInfo = new HashMap<>();
String[] workBeginDateTimes = workBeginDateTime.split(" ");
String tmp_workBeginDate = workBeginDateTimes[0];
String tmp_workBeginTime = workBeginDateTimes[1];
checkInfo.put("signType", "1");
checkInfo.put("signDate", tmp_workBeginDate);//签到签退日期
checkInfo.put("signTime", "");//签到签退时间
checkInfo.put("deduct_signintime", tmp_workBeginTime);//流程抵扣作为打卡时间
checkInfo.put("signStatus", ButtonStatusEnum.NORMAL.getStatusCode());
lsCheckInfo.add(checkInfo);
}
}
if (flow_deduct_card_map.containsKey("signoff")) {
String deduct_signofftime = Util.null2String(flow_deduct_card_map.get("signoff"));
if (deduct_signofftime.length() > 0) {
checkInfo = new HashMap<>();
String[] workEndDateTimes = workEndDateTime.split(" ");
String tmp_workEndDate = workEndDateTimes[0];
String tmp_workEndTime = workEndDateTimes[1];
checkInfo.put("signType", "2");
checkInfo.put("signDate", tmp_workEndDate);//签到签退日期
checkInfo.put("signTime", "");//签到签退时间
checkInfo.put("deduct_signofftime", tmp_workEndTime);//流程抵扣作为打卡时间
checkInfo.put("signStatus", ButtonStatusEnum.NORMAL.getStatusCode());
lsCheckInfo.add(checkInfo);
}
}
} else {
Map<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);
}
}
}
}
}
}
// 上午的签退取中间时段的第一次打卡
if (shiftCount == 2 && shiftI == 0) {
String noonSignTimeSql = KQSignUtil.buildSignSql(count4NoonStartDateTime, count4NoonEndDateTime);
String baseSql = "select * from hrmschedulesign where 1=1 and isInCom='1' and userid=" + userId + " ";
String sql = baseSql;
sql += " and " + noonSignTimeSql + " order by signdate, signtime";
rs.executeQuery(sql);
if (rs.next()) {
String signId = Util.null2String(rs.getString("id"));
String signDate = Util.null2String(rs.getString("signdate"));
String signTime = Util.null2String(rs.getString("signtime"));
String signDateTime = signDate + " " + signTime;
for (int j = 0; lsCheckInfo != null && j < lsCheckInfo.size(); j++) {
Map<String, Object> checkInfoInner = (Map<String, Object>) lsCheckInfo.get(j);
if (checkInfoInner.get("signType").equals("2")) {//签退
String signDateInner = Util.null2String(checkInfoInner.get("signDate"));
String signTimeInner = Util.null2String(checkInfoInner.get("signTime"));
String deduct_signofftime = Util.null2String(checkInfoInner.get("deduct_signofftime"));
if (!"".equals(signTimeInner)) {
String signDateTimeInner = signDateInner + " " + signTimeInner;
if (signDateTime.compareTo(signDateTimeInner) < 0) {
checkInfoInner.put("signId", signId);//签到签退标识
checkInfoInner.put("signType", "2");
checkInfoInner.put("signDate", signDateInner);//签到签退日期
checkInfoInner.put("signTime", signTime);//签到签退时间
checkInfoInner.put("deduct_signofftime", deduct_signofftime);//流程抵扣作为打卡时间
checkInfoInner.put("signStatus", ButtonStatusEnum.NORMAL.getStatusCode());
}
}
}
}
}
} else if (shiftCount == 2 && shiftI == 1) { // 下午的签到取中间时段的第二次打卡
String noonSignTimeSql = KQSignUtil.buildSignSql(count4NoonStartDateTime, count4NoonEndDateTime);
String baseSql = "select * from hrmschedulesign where 1=1 and isInCom='1' and userid=" + userId + " ";
String sql = baseSql;
sql += " and " + noonSignTimeSql + " order by signdate, signtime";
rs.executeQuery(sql);
int count = 0;
int counts = rs.getCounts();
if (counts == 1) {
lsCheckInfo.clear();
}
while (rs.next()) {
if (count == 0) {
count++;
continue;
}
String signId = Util.null2String(rs.getString("id"));
String signTime = Util.null2String(rs.getString("signtime"));
for (int j = 0; lsCheckInfo != null && j < lsCheckInfo.size(); j++) {
Map<String, Object> checkInfoInner = (Map<String, Object>) lsCheckInfo.get(j);
if (checkInfoInner.get("signType").equals("1")) {//签退
String signDateInner = Util.null2String(checkInfoInner.get("signDate"));
String signTimeInner = Util.null2String(checkInfoInner.get("signTime"));
String deduct_signofftime = Util.null2String(checkInfoInner.get("deduct_signofftime"));
checkInfoInner.put("signId", signId);//签到签退标识
checkInfoInner.put("signType", "1");
checkInfoInner.put("signDate", signDateInner);//签到签退日期
checkInfoInner.put("signTime", signTime);//签到签退时间
checkInfoInner.put("deduct_signofftime", deduct_signofftime);//流程抵扣作为打卡时间
checkInfoInner.put("signStatus", ButtonStatusEnum.NORMAL.getStatusCode());
}
}
break;
}
}
} catch (Exception e) {
kqLog.info("报表错:getSignInfo:");
StringWriter errorsWriter = new StringWriter();
e.printStackTrace(new PrintWriter(errorsWriter));
kqLog.info(errorsWriter.toString());
}
//writeLog(sql,userId +"=="+ signBeginDateTime+"=="+signEndDateTime);
return lsCheckInfo;
}
/**
* 根据上下班时间获取到是否有流程抵扣打卡的数据
*
* @param userId
* @param kqDate
* @param workBeginDateTime
* @param workEndDateTime
*/
public Map<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,int signoutOnlyoff) {
return getCanSignInfo(signTimeScope, kqDate, preDate, nextDate, kqTimesArrayComInfo, workTimeScope, 0, 0, signoutOnlyoff);
}
public List<Map<String, String>> getCanSignInfo(TimeScopeEntity signTimeScope, String kqDate, String preDate, String nextDate, KQTimesArrayComInfo kqTimesArrayComInfo, TimeScopeEntity workTimeScope) {
return getCanSignInfo(signTimeScope, kqDate, preDate, nextDate, kqTimesArrayComInfo, workTimeScope, 0, 0);
}
public List<Map<String, String>> getCanSignInfo(TimeScopeEntity signTimeScope, String kqDate, String preDate, String nextDate, KQTimesArrayComInfo kqTimesArrayComInfo, TimeScopeEntity workTimeScope, int shiftCount, int shiftI) {
return getCanSignInfo(signTimeScope, kqDate, preDate, nextDate, kqTimesArrayComInfo, workTimeScope, shiftCount, shiftI, 0);
}
public List<Map<String, String>> getCanSignInfo(TimeScopeEntity signTimeScope, String kqDate, String preDate, String nextDate, KQTimesArrayComInfo kqTimesArrayComInfo, TimeScopeEntity workTimeScope, int shiftCount, int shiftI, int signoutOnlyoff) {
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;
// if (workTimeScope != null && workTimeScope.getEndTimeAcross() && signTimeScope.getEndTimeAcross() ) {
// if(workTimeScope.getEndTime().compareTo(signTimeScope.getEndTime())>=0){
// signEndDateTime = DateUtil.addDate(kqDate, 2);//下下一天日期;
// }
// }
signEndDateTime += " " + kqTimesArrayComInfo.turn48to24Time(signTimeScope.getEndTime()) + ":59";
if (timeSignScopeEntity == null) {
//没有设置 签到最晚时间和签退最早时间比如是09:00-18:00打卡范围是08:00---19:00
if (signoutOnlyoff == 1 && workTimeScope != null) {//开启了下班后只能签退的按钮那么考勤格式化的打卡数据查询范围也搞一下
String signBeginDateEndTime = "";
String signEndDateStartTime = "";
String workEndTime = workTimeScope.getEndTime();
boolean workEndTimeAcross = workTimeScope.getEndTimeAcross();
String workEndTimeNew = kqTimesArrayComInfo.getTimesByArrayindex(kqTimesArrayComInfo.getArrayindexByTimes(workEndTime) - 1);//17:59
signBeginDateEndTime = workEndTimeAcross ? nextDate : kqDate;
signBeginDateEndTime += " " + kqTimesArrayComInfo.turn48to24Time(workEndTimeNew) + ":59";//17:59:59
conditionMap = new HashMap<>();
conditionMap.put("signBeginDateTime", signBeginDateTime);//08:00:00
conditionMap.put("signEndDateTime", signBeginDateEndTime);//17:59:59
// conditionMap.put("type", "signin");
conditionMap.put("signoutOnlyoff", "signin");
sqlConditions.add(conditionMap);
conditionMap = new HashMap<>();
conditionMap.put("signBeginDateTime", signBeginDateTime);//08:00:00这里为什么从上班开始打卡时间起算因为存在上班有打卡连续打卡的情况那么需要将除上班卡之后的打卡都识别为下班卡
conditionMap.put("signEndDateTime", signEndDateTime);//19:00:59
//这里不能传type=signoff否则上班打卡可能会同时识别为上班卡和下班卡
conditionMap.put("signoutOnlyoff", "signoff");
sqlConditions.add(conditionMap);
} else {//走标准原逻辑
conditionMap = new HashMap<>();
conditionMap.put("signBeginDateTime", signBeginDateTime);
conditionMap.put("signEndDateTime", signEndDateTime);
sqlConditions.add(conditionMap);
}
} else {
String beginTimeEnd = timeSignScopeEntity.getBeginTimeEnd();
boolean beginTimeEndAcross = timeSignScopeEntity.isBeginTimeEndAcross();
String endTimeStart = timeSignScopeEntity.getEndTimeStart();
boolean endTimeStartAcross = timeSignScopeEntity.isEndTimeStartAcross();
if (beginTimeEnd.length() > 0) {
//如果设置了 上班结束时间
if (endTimeStart.length() > 0) {
//设置了下班开始时间
String signBeginDateEndTime = "";
String signEndDateStartTime = "";
signBeginDateEndTime = beginTimeEndAcross ? nextDate : kqDate;
signBeginDateEndTime += " " + kqTimesArrayComInfo.turn48to24Time(beginTimeEnd) + ":59";
//张总表示设了打卡归属以设置的为准这个开关相当于不起作用代码含泪注释
// if(signoutOnlyoff == 1 && workTimeScope != null){//开启了下班后只能签退的按钮那么考勤格式化的打卡数据查询范围也搞一下
// String workEndTime = workTimeScope.getEndTime();
// boolean workEndTimeAcross = workTimeScope.getEndTimeAcross();
// signBeginDateEndTime = workEndTimeAcross ? nextDate : kqDate;
// signBeginDateEndTime+=" "+kqTimesArrayComInfo.turn48to24Time(workEndTime)+":59";
// conditionMap = new HashMap<>();
// conditionMap.put("signBeginDateTime", signBeginDateTime);
// conditionMap.put("signEndDateTime", signBeginDateEndTime);
// conditionMap.put("type", "signin");
// sqlConditions.add(conditionMap);
//
// conditionMap = new HashMap<>();
// conditionMap.put("signBeginDateTime", signBeginDateEndTime);
// conditionMap.put("signEndDateTime", signEndDateTime);
// conditionMap.put("type", "signoff");
// sqlConditions.add(conditionMap);
//
// }else{
conditionMap = new HashMap<>();
conditionMap.put("signBeginDateTime", signBeginDateTime);
conditionMap.put("signEndDateTime", signBeginDateEndTime);
conditionMap.put("type", "signin");
sqlConditions.add(conditionMap);
signEndDateStartTime = endTimeStartAcross ? nextDate : kqDate;
signEndDateStartTime += " " + kqTimesArrayComInfo.turn48to24Time(endTimeStart) + ":00";
conditionMap = new HashMap<>();
conditionMap.put("signBeginDateTime", signEndDateStartTime);
conditionMap.put("signEndDateTime", signEndDateTime);
conditionMap.put("type", "signoff");
sqlConditions.add(conditionMap);
// }
} else {
//没有设置下班开始时间
String signBeginDateEndTime = "";
String signEndDateStartTime = "";
signBeginDateEndTime = beginTimeEndAcross ? nextDate : kqDate;
signBeginDateEndTime += " " + kqTimesArrayComInfo.turn48to24Time(beginTimeEnd) + ":59";
conditionMap = new HashMap<>();
conditionMap.put("signBeginDateTime", signBeginDateTime);
conditionMap.put("signEndDateTime", signBeginDateEndTime);
conditionMap.put("type", "signin");
sqlConditions.add(conditionMap);
//如果设置了上班结束时间相当于下班开始时间也被限定了
String endTimeByBeginTime = kqTimesArrayComInfo.getTimesByArrayindex(kqTimesArrayComInfo.getArrayindexByTimes(beginTimeEnd) + 1);
signEndDateStartTime = beginTimeEndAcross ? nextDate : kqDate;
signEndDateStartTime += " " + kqTimesArrayComInfo.turn48to24Time(endTimeByBeginTime) + ":00";
conditionMap = new HashMap<>();
conditionMap.put("signBeginDateTime", signEndDateStartTime);
conditionMap.put("signEndDateTime", signEndDateTime);
conditionMap.put("type", "signoff");
sqlConditions.add(conditionMap);
}
} else if (endTimeStart.length() > 0) {
//如果没有设置上班结束时间设置了下班开始时间
String signBeginDateEndTime = "";
String signEndDateStartTime = "";
//如果设置了下班开始时间相当于上班结束时间也被限定了
String BeginTimeByendTime = kqTimesArrayComInfo.getTimesByArrayindex(kqTimesArrayComInfo.getArrayindexByTimes(endTimeStart) - 1);
signBeginDateEndTime = endTimeStartAcross ? nextDate : kqDate;
signBeginDateEndTime += " " + kqTimesArrayComInfo.turn48to24Time(BeginTimeByendTime) + ":59";
conditionMap = new HashMap<>();
conditionMap.put("signBeginDateTime", signBeginDateTime);
conditionMap.put("signEndDateTime", signBeginDateEndTime);
conditionMap.put("type", "signin");
sqlConditions.add(conditionMap);
signEndDateStartTime = endTimeStartAcross ? nextDate : kqDate;
signEndDateStartTime += " " + kqTimesArrayComInfo.turn48to24Time(endTimeStart) + ":00";
conditionMap = new HashMap<>();
conditionMap.put("signBeginDateTime", signEndDateStartTime);
conditionMap.put("signEndDateTime", signEndDateTime);
conditionMap.put("type", "signoff");
sqlConditions.add(conditionMap);
}
}
return sqlConditions;
}
public String signSignSql(RecordSet rs) {
String sql = "";
if (rs.getDBType().equals("oracle")) {
sql = " select id,signdate,signtime from hrmschedulesign where isincom=1 and userid = ? and signdate||' '||signtime >= ? and signdate||' '||signtime <= ? " +
" ";
} else if ("sqlserver".equals(rs.getDBType())) {
sql = " select id,signdate,signtime from hrmschedulesign where isincom=1 and userid = ? and signdate + ' ' + signtime >= ? and signdate + ' ' + signtime <= ? " +
" ";
} else {
sql = " select id,signdate,signtime from hrmschedulesign where isincom=1 and userid = ? and concat(signdate,' ',signtime) >= ? and concat(signdate,' ',signtime) <= ? " +
" ";
}
return sql;
}
public List<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;
}
}

View File

@ -0,0 +1,714 @@
package com.engine.kq.biz;
import com.engine.kq.entity.KQGroupEntity;
import com.engine.kq.log.KQLog;
import com.google.common.collect.Lists;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.IpUtils;
import weaver.general.Util;
import weaver.hrm.common.database.dialect.DbDialectFactory;
import weaver.hrm.common.database.dialect.IDbDialectSql;
import java.util.*;
public class KQGroupBiz extends BaseBean {
private static final double EARTH_RADIUS = 6378137;// 地球半径
public static final String GROUPMEMBER_VALIDATE_FROMDATE="2000-01-01";
public static final String GROUPMEMBER_VALIDATE_TODATE="2999-12-31";
public String getGroupMemberSql() {
return getGroupMemberSql("");
}
public String getGroupMemberSql(String groupId) {
Map<String,Object> params = new HashMap<>();
params.put("groupId",groupId);
return this.getGroupMemberSql(params);
}
public String getGroupMemberSql(Map<String,Object> params) {
String sql = "";
try {
String groupId = Util.null2String(params.get("groupId"));
String isNoAccount = Util.null2String(params.get("isNoAccount"));
if(Util.null2String(groupId).length()>0){
sql = " SELECT distinct resourceid, groupid FROM ( " +
" SELECT a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b " +
" WHERE a.id=b.typevalue and b.type =1 and (b.isdelete is null or b.isdelete <> '1') " +
" UNION ALL " +
" SELECT a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b " +
" WHERE a.subcompanyid1 = b.typevalue AND b.type=2 AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto and (b.isdelete is null or b.isdelete <> '1') " +
" UNION ALL " +
" SELECT a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b " +
" WHERE a.departmentid = b.typevalue AND b.type=3 AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto and (b.isdelete is null or b.isdelete <> '1') " +
" UNION ALL " +
" SELECT a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b " +
" WHERE a.jobtitle = b.typevalue AND b.type=5 " +
" AND (b.jobtitlelevel=1 OR (b.jobtitlelevel=2 AND a.subcompanyid1 IN(b.jobtitlelevelvalue)) OR (b.jobtitlelevel=3 AND a.departmentid IN(b.jobtitlelevelvalue))) " +
" and (b.isdelete is null or b.isdelete <> '1') " +
" UNION ALL " +
" SELECT a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b " +
" WHERE b.type=6 AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto and (b.isdelete is null or b.isdelete <> '1') ) t" +
" where 1=1 ";
if(!Util.null2String(isNoAccount).equals("1")){
sql += " and t.status in (0,1,2,3) ";
}
sql += " and t.groupid = "+groupId;
}else{
sql = " SELECT distinct resourceid, groupid FROM ( " +
" SELECT a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b,kq_group c " +
" WHERE a.id=b.typevalue and b.type =1 and (b.isdelete is null or b.isdelete <> '1') and (c.isdelete is null or c.isdelete <> '1') and c.id=b.groupid " +
" UNION ALL " +
" SELECT a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b,kq_group c " +
" WHERE a.subcompanyid1 = b.typevalue AND b.type=2 AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto and (b.isdelete is null or b.isdelete <> '1') and (c.isdelete is null or c.isdelete <> '1') and c.id=b.groupid " +
" UNION ALL " +
" SELECT a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b,kq_group c " +
" WHERE a.departmentid = b.typevalue AND b.type=3 AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto and (b.isdelete is null or b.isdelete <> '1') and (c.isdelete is null or c.isdelete <> '1') and c.id=b.groupid " +
" UNION ALL " +
" SELECT a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b,kq_group c " +
" WHERE a.jobtitle = b.typevalue AND b.type=5 " +
" AND (b.jobtitlelevel=1 OR (b.jobtitlelevel=2 AND a.subcompanyid1 IN(b.jobtitlelevelvalue)) OR (b.jobtitlelevel=3 AND a.departmentid IN(b.jobtitlelevelvalue))) " +
" and (b.isdelete is null or b.isdelete <> '1') and (c.isdelete is null or c.isdelete <> '1') and c.id=b.groupid " +
" UNION ALL " +
" SELECT a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b,kq_group c " +
" WHERE b.type=6 AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto and (b.isdelete is null or b.isdelete <> '1') and (c.isdelete is null or c.isdelete <> '1') and c.id=b.groupid ) t" +
" where 1=1 ";
if(!Util.null2String(isNoAccount).equals("1")){
sql += " and t.status in (0,1,2,3) ";
}
}
} catch (Exception e) {
writeLog(e);
}
return sql;
}
public List<String> getGroupMembers(String groupId) {
Map<String,Object> params = new HashMap<>();
params.put("groupId",groupId);
return this.getGroupMembers(params);
}
public List<String> getGroupMembers(Map<String,Object> params) {
RecordSet rs = new RecordSet();
List<String> members = new ArrayList<>();
try {
String sql = this.getGroupMemberSql(params);
rs.executeQuery(sql);
while (rs.next()) {
members.add(rs.getString("resourceid"));
}
} catch (Exception e) {
writeLog(e);
}
return members;
}
//根据传入的班次id然后判断是否有考勤组引用这个班次
public boolean serialIdIsUesed(String serialid) {
boolean serialIdUesed = false;
RecordSet rs = new RecordSet();
String sql = "";
IDbDialectSql dialectSql = DbDialectFactory.get(rs.getDBType()) ;
String isDeleteField = dialectSql.isNull("isdelete",0) ;
try {
sql = " select count(1) " +
" from (select distinct serialid from kq_fixedschedulce where serialid in ( ? ) and ("+isDeleteField+" !=1 ) "+
" union " +
" select distinct serialid from kq_shiftschedule where serialid in ( ? ) and ("+isDeleteField+" !=1 ) ) t";
rs.executeQuery(sql,serialid,serialid);
if (rs.next()){
if(rs.getInt(1)>0){
serialIdUesed = true;
}
}
if(!serialIdUesed){
if(rs.getDBType().equals("oracle")||rs.getDBType().equals("postgresql")) {
sql = " select count(1) from kq_group where ((','||serialids||',') like '%," + serialid + ",%' or (','||shiftcycleserialids||',') like '%," + serialid + ",%') and (isdelete is null or isdelete <> '1')";
}else if(rs.getDBType().equals("mysql")){
String serialidsConcatContion = dialectSql.concatStr("','","serialids","','") ;
String shiftcycleSerialidsConcatConditon = dialectSql.concatStr("','","shiftcycleserialids","','") ;
String groupIsDeleteCondition = dialectSql.isNull("isdelete",0) ;
String likeValue = "%,"+serialid+",%" ;
sql = String.format(" select count(1) from kq_group where ((%s) like '%s' or (%s) like '%s') and (%s!=1)",
serialidsConcatContion,likeValue,
shiftcycleSerialidsConcatConditon,likeValue,
groupIsDeleteCondition) ;
}else{
sql = " select count(1) from kq_group where (','+serialids+',' like '%," + serialid + ",%' or ','+shiftcycleserialids+',' like '%," + serialid + ",%') and (isdelete is null or isdelete <> '1')";
}
rs.executeQuery(sql);
if (rs.next()){
if(rs.getInt(1)>0){
serialIdUesed = true;
}
}
}
} catch (Exception e) {
writeLog(e);
}
return serialIdUesed;
}
/**
* 根据传入的班次id引用此班次的考勤组
* @param serialid
* @return
*/
public List<String> getGroupIdByUesedSerialId(String serialid) {
RecordSet rs = new RecordSet();
List<String> groupList = Lists.newArrayList();
String sql = "";
IDbDialectSql dialectSql = DbDialectFactory.get(rs.getDBType()) ;
String isDeleteField = dialectSql.isNull("isdelete",0) ;
try {
sql = " select serialid,groupid " +
" from (select distinct serialid,groupid from kq_fixedschedulce where serialid in ( ? ) and ("+isDeleteField+" !=1 ) "+
" union " +
" select distinct serialid,groupid from kq_shiftschedule where serialid in ( ? ) and ("+isDeleteField+" !=1 ) ) t";
rs.executeQuery(sql,serialid,serialid);
while (rs.next()){
String tmp_groupId = rs.getString("groupid");
if(!groupList.contains(tmp_groupId)){
groupList.add(tmp_groupId);
}
}
if(rs.getDBType().equals("oracle")||rs.getDBType().equals("postgresql")) {
sql = " select id from kq_group where ((','||serialids||',') like '%," + serialid + ",%' or (','||shiftcycleserialids||',') like '%," + serialid + ",%') and (isdelete is null or isdelete <> '1')";
}else if(rs.getDBType().equals("mysql")){
String serialidsConcatContion = dialectSql.concatStr("','","serialids","','") ;
String shiftcycleSerialidsConcatConditon = dialectSql.concatStr("','","shiftcycleserialids","','") ;
String groupIsDeleteCondition = dialectSql.isNull("isdelete",0) ;
String likeValue = "%,"+serialid+",%" ;
sql = String.format(" select id from kq_group where ((%s) like '%s' or (%s) like '%s') and (%s!=1)",
serialidsConcatContion,likeValue,
shiftcycleSerialidsConcatConditon,likeValue,
groupIsDeleteCondition) ;
}else{
sql = " select id from kq_group where (','+serialids+',' like '%," + serialid + ",%' or ','+shiftcycleserialids+',' like '%," + serialid + ",%') and (isdelete is null or isdelete <> '1')";
}
rs.executeQuery(sql);
while (rs.next()){
String tmp_groupId = rs.getString("id");
if(!groupList.contains(tmp_groupId)){
groupList.add(tmp_groupId);
}
}
} catch (Exception e) {
writeLog(e);
}
return groupList;
}
public Map<String,Object> getLocationWifiInfo(String userid,String showWifiList) {
Map<String,Object> result = new HashMap<>();
Map<String,Object> locationInfo = new HashMap<>();
Map<String,Object> wifiInfo = new HashMap<>();
KQGroupComInfo kqGroupComInfo = new KQGroupComInfo();
KQGroupMemberComInfo kqGroupMemberComInfo = new KQGroupMemberComInfo();
KQLoactionComInfo kqLoactionComInfo = new KQLoactionComInfo();
String groupid = Util.null2String(kqGroupMemberComInfo.getKQGroupId(userid));
List<Object> datas = null;
Map<String, Object> data = null;
if(groupid.length()>0){
datas = new ArrayList();
while(kqLoactionComInfo.next()){
if(!kqLoactionComInfo.getGroupid().equals(groupid))continue;
data = new HashMap<>();
data.put("id",kqLoactionComInfo.getId());
data.put("locationname",Util.null2String(kqLoactionComInfo.getLocationname()));
data.put("longitude",Util.null2String(kqLoactionComInfo.getLongitude()));
data.put("latitude",Util.null2String(kqLoactionComInfo.getLatitude()));
data.put("address",Util.null2String(kqLoactionComInfo.getAddress()));
data.put("checkscope",Util.null2String(kqLoactionComInfo.getCheckscope()));
data.put("groupid",Util.null2String(kqLoactionComInfo.getGroupid()));
datas.add(data);
}
locationInfo.put("locationcheck",Util.null2String(kqGroupComInfo.getLocationcheck(groupid)).equals("1"));
locationInfo.put("locationcheckscope",Util.null2String(kqGroupComInfo.getLocationcheckscope(groupid)));
locationInfo.put("locations",datas);
datas = new ArrayList();
if("1".equalsIgnoreCase(showWifiList)){
KQWifiComInfo kqWifiComInfo = new KQWifiComInfo();
while(kqWifiComInfo.next()){
if(!kqWifiComInfo.getGroupid().equals(groupid))continue;
data = new HashMap<>();
data.put("id",kqWifiComInfo.getId());
data.put("wifiname",Util.null2String(kqWifiComInfo.getWifiname()));
data.put("mac",Util.null2String(kqWifiComInfo.getMac()));
data.put("groupid",Util.null2String(kqWifiComInfo.getGroupid()));
datas.add(data);
}
}
wifiInfo.put("wificheck",Util.null2String(kqGroupComInfo.getWificheck(groupid)).equals("1"));
wifiInfo.put("wifis",datas);
result.put("locationInfo",locationInfo);
result.put("wifiInfo",wifiInfo);
result.put("status","1");
String show_position = "show_position";
KQSettingsComInfo kqSettingsComInfo = new KQSettingsComInfo();
String positioncheck = Util.null2String(kqSettingsComInfo.getMain_val(show_position),"0");
result.put("positioncheck",positioncheck);
}
return result;
}
/**
* 用户考勤地点 WIFI限制信息
* @param userid
* @return
*/
public Map<String,Object> getLocationWifiInfo(String userid) {
return getLocationWifiInfo(userid,"1");
}
/**
*判断办公地点范围
* @return
*/
public Map<String,Object> checkLocationScope(String userId, String longitude, String latitude){
Map<String, Object> retmap = new HashMap<>();
Map<String, Object> loactionInfo = null;
try {
boolean inScope = false;
KQGroupMemberComInfo kqGroupMemberComInfo = new KQGroupMemberComInfo();
KQGroupEntity kqGroupEntity = kqGroupMemberComInfo.getUserKQGroupInfo(userId);
KQLoactionComInfo kqLoactionComInfo = new KQLoactionComInfo();
Map<String, Object> locationTrueInfo = new HashMap<>();
double distance = EARTH_RADIUS;
if (kqGroupEntity != null && kqGroupEntity.getLocationcheck().equals("1")) {
while (kqLoactionComInfo.next()) {
if (Util.null2String(kqLoactionComInfo.getGroupid()).equals(kqGroupEntity.getId())) {
double lng1 = Util.getDoubleValue(longitude);//经度
double lat1 = Util.getDoubleValue(latitude);//纬度
double lng2 = Util.getDoubleValue(kqLoactionComInfo.getLongitude());//经度
double lat2 = Util.getDoubleValue(kqLoactionComInfo.getLatitude());//纬度
int checkscope = Util.getIntValue(kqLoactionComInfo.getCheckscope());//有效范围
double geo_distance = geo_distance(lng1, lat1, lng2, lat2);
if (distance > geo_distance) {
distance = geo_distance;
locationTrueInfo.put("lng2", lng2);
locationTrueInfo.put("lat2", lat2);
locationTrueInfo.put("checkscope", checkscope);
locationTrueInfo.put("geo_distance", geo_distance);
// locationTrueInfo = lng2 + "#" + lat2 + "#" + checkscope + "#" + geo_distance;
}
if (geo_distance < checkscope) {
inScope = true;
loactionInfo = new HashMap<>();
loactionInfo.put("locationname", kqLoactionComInfo.getLocationname());
loactionInfo.put("longitude", kqLoactionComInfo.getLongitude());
loactionInfo.put("latitude", kqLoactionComInfo.getLatitude());
loactionInfo.put("address", kqLoactionComInfo.getAddress());
loactionInfo.put("id", kqLoactionComInfo.getId());
loactionInfo.put("longitudefromoa", lng2);
loactionInfo.put("latitudefromoa", lat2);
loactionInfo.put("lengthfromoa", checkscope);
loactionInfo.put("lengthfromem", geo_distance);
break;
}
}
}
} else {//未开启开关
inScope = true;
}
retmap.put("needCheck", kqGroupEntity != null ? Util.null2String(kqGroupEntity.getLocationcheck()) : "0");//是否开启办公地点验证
retmap.put("inScope", inScope);//是否在考勤范围内
retmap.put("locationshowaddress", kqGroupEntity != null ? Util.null2String(kqGroupEntity.getLocationshowaddress()) : "0");//有效识别半径内显示同一地址
if (!inScope && locationTrueInfo != null && !locationTrueInfo.isEmpty()) {
if(loactionInfo == null) {
loactionInfo = new HashMap<>();
}
loactionInfo.put("longitudefromoa", Util.null2String(locationTrueInfo.get("lng2")));
loactionInfo.put("latitudefromoa", Util.null2String(locationTrueInfo.get("lat2")));
loactionInfo.put("lengthfromoa", Util.null2String(locationTrueInfo.get("checkscope")));
loactionInfo.put("lengthfromem", Util.null2String(locationTrueInfo.get("geo_distance")));
}
}catch (Exception e) {
writeLog(e);
}
retmap.put("loactionInfo", loactionInfo);//考勤范围相关信息
return retmap;
}
/**
* 计算两个经度纬度(WGS-84)之间的距离
* @param lng1 坐标1经度
* @param lat1 坐标1纬度EARTH_RADIUS
* @param lng2 坐标2经度
* @param lat2 坐标2纬度
* @return 2个坐标之间距离,单位:
*/
private double geo_distance(double lng1, double lat1, double lng2, double lat2) {
double radLat1 = Math.toRadians(lat1);
double radLat2 = Math.toRadians(lat2);
double a = Math.abs(radLat1 - radLat2);
double b = Math.abs(Math.toRadians(lng1) - Math.toRadians(lng2));
double distance = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
distance = distance * EARTH_RADIUS;
distance = Math.round(distance * 10000) / 10000;
return distance;
}
/**
*判断Wifi范围
* @return
*/
public Map<String,Object> checkWifiScope(String userId, String wifiName, String mac){
Map<String,Object> retmap = new HashMap<>();
Map<String,Object> wifiInfo = null;
boolean inScope = false;
KQGroupMemberComInfo kqGroupMemberComInfo = new KQGroupMemberComInfo();
KQGroupEntity kqGroupEntity = kqGroupMemberComInfo.getUserKQGroupInfo(userId);
KQWifiComInfo kqWifiComInfo = new KQWifiComInfo();
if(kqGroupEntity.getWificheck().equals("1")){
try{
List<String> lst = new ArrayList<>(Arrays.asList(mac.split(":")));
for(int i = 0; i < lst.size(); i++){
String s = lst.get(i);
if(s.length() == 1)
lst.set(i, "0" + s);
}
mac = String.join(":", lst);
}catch (Exception ex){
ex.printStackTrace();
}
while(kqWifiComInfo.next()){
if(Util.null2String(kqWifiComInfo.getGroupid()).equals(kqGroupEntity.getId())){
if(Util.null2String(kqWifiComInfo.getWifiname().toLowerCase()).equals(wifiName.toLowerCase())){
String wifi_cominfo_mac = Util.null2String(kqWifiComInfo.getMac().toLowerCase());
String param_mac = mac.toLowerCase();
int last_wifi_mac_index = wifi_cominfo_mac.lastIndexOf(":");
int param_mac_index = param_mac.lastIndexOf(":");
if(last_wifi_mac_index > 0 && param_mac_index > 0){
wifi_cominfo_mac = wifi_cominfo_mac.substring(0,last_wifi_mac_index);
param_mac = param_mac.substring(0,param_mac_index);
}
if(wifi_cominfo_mac.equals(param_mac)){
inScope = true;
wifiInfo = new HashMap<>();
wifiInfo.put("wifiname",kqWifiComInfo.getWifiname());
wifiInfo.put("mac",kqWifiComInfo.getMac());
break;
}
}
}
}
}else{//未开启开关
inScope = true;
}
retmap.put("needCheck",Util.null2String(kqGroupEntity.getWificheck()));//是否开启wifi验证
retmap.put("inScope",inScope);//是否在考勤范围内
retmap.put("wifiInfo",wifiInfo);//考勤范围相关信息
return retmap;
}
/**
* 校验ipv4和v6范围
* @param userId
* @param clientAddress
* @param ismobile
* @return
*/
public boolean getIsInScopeV4V6(String userId, String clientAddress,String ismobile) {
boolean isInScope = false;
clientAddress = Util.null2String(clientAddress).trim();
if (clientAddress.length() == 0) {
return isInScope;
}
RecordSet rs = new RecordSet();
KQGroupComInfo kqGroupComInfo = new KQGroupComInfo();
KQGroupMemberComInfo kqGroupMemberComInfo = new KQGroupMemberComInfo();
String groupid = Util.null2String(kqGroupMemberComInfo.getKQGroupId(userId));
String signIpScope = Util.null2String(kqGroupComInfo.getIpscope(groupid)).trim();//格式10.*.*.*;10.16.0.12;10.16.0.13-10.16.0.18
String signIpscope_v4_em = Util.null2String(kqGroupComInfo.getIpscope_v4_em(groupid)).trim();
String signIpscope_v4_pc = Util.null2String(kqGroupComInfo.getIpscope_v4_pc(groupid)).trim();
String signIpscope_v6_em = Util.null2String(kqGroupComInfo.getIpscope_v6_em(groupid)).trim();
String signIpscope_v6_pc = Util.null2String(kqGroupComInfo.getIpscope_v6_pc(groupid)).trim();
if (signIpscope_v4_em.length() == 0 && signIpscope_v4_pc.length() == 0
&& signIpscope_v6_em.length() == 0 && signIpscope_v6_pc.length() == 0) {
return true;
}
new KQLog().info("getIsInScopeV4V6:ismobile:"+ismobile+":signIpscope_v4_em:"+signIpscope_v4_em+":signIpscope_v6_em:"+signIpscope_v6_em
+":signIpscope_v4_pc:"+signIpscope_v4_pc+":signIpscope_v6_pc:"+signIpscope_v6_pc);
if("1".equalsIgnoreCase(ismobile)){
if(signIpscope_v4_em.length() > 0){
return checkIps(signIpscope_v4_em,clientAddress,"IPv4");
}else if(signIpscope_v6_em.length() > 0){
return checkIps(signIpscope_v6_em,clientAddress,"IPv6");
}else{
return true;
}
}else{
if(signIpscope_v4_pc.length() > 0){
return checkIps(signIpscope_v4_pc,clientAddress,"IPv4");
}else if(signIpscope_v6_pc.length() > 0){
return checkIps(signIpscope_v6_pc,clientAddress,"IPv6");
}else{
return true;
}
}
}
private boolean checkIps(String signIpScope, String clientAddress,String ipType) {
boolean isInScope = false;
List signIpScopeList = Util.TokenizerString(signIpScope, ";");
String signIpScopeSingle = "";
for (int i = 0; i < signIpScopeList.size(); i++) {
signIpScopeSingle = Util.null2String((String) signIpScopeList.get(i));
signIpScopeSingle = signIpScopeSingle.trim();
if("IPv4".equalsIgnoreCase(ipType)){
isInScope = checkIpV4(signIpScopeSingle,clientAddress);
if(isInScope){
break;
}
}else if("IPv6".equalsIgnoreCase(ipType)){
isInScope = checkIpV6(signIpScopeSingle,clientAddress);
if(isInScope){
break;
}
}
}
return isInScope;
}
private boolean checkIpV6(String signIpScopeSingle, String clientAddress) {
boolean isInScope = false;
if (signIpScopeSingle.indexOf("-") > -1) {
String signIpFrom = signIpScopeSingle.substring(0, signIpScopeSingle.indexOf("-"));
signIpFrom = Util.null2String(signIpFrom).trim();
String signIpTo = "";
if (!signIpScopeSingle.endsWith("-")) {
signIpTo = signIpScopeSingle.substring(signIpScopeSingle.indexOf("-") + 1);
}
signIpTo = Util.null2String(signIpTo).trim();
String tempClientAddress = IpUtils.parseAbbreviationToFullIPv6(clientAddress);
signIpFrom = addToThreeFigure(signIpFrom, "signIpFrom");
signIpTo = addToThreeFigure(signIpTo, "signIpTo");
signIpFrom = IpUtils.parseAbbreviationToFullIPv6(signIpFrom);
signIpTo = IpUtils.parseAbbreviationToFullIPv6(signIpTo);
if (signIpFrom.equals("") && signIpTo.equals("")) {
isInScope = true;
}
if (signIpFrom.equals("") && !signIpTo.equals("")) {
if (tempClientAddress.compareTo(signIpTo) <= 0) {
isInScope = true;
}
}
if (!signIpFrom.equals("") && signIpTo.equals("")) {
if (tempClientAddress.compareTo(signIpFrom) >= 0) {
isInScope = true;
}
}
if (!signIpFrom.equals("") && !signIpTo.equals("")) {
if (tempClientAddress.compareTo(signIpFrom) >= 0 && tempClientAddress.compareTo(signIpTo) <= 0) {
isInScope = true;
}
}
} else {
String tempClientAddress = IpUtils.parseAbbreviationToFullIPv6(clientAddress);
if (tempClientAddress.equals(signIpScopeSingle)) {
isInScope = true;
}
}
return isInScope;
}
public boolean checkIpV4(String signIpScopeSingle,String clientAddress) {
boolean isInScope = false;
if (signIpScopeSingle.indexOf("*") > -1) {//如果单个ip范围的格式为10.*.*.*
List signIpScopeSingleList = Util.TokenizerString(signIpScopeSingle, ".");
List clientAddressList = Util.TokenizerString(clientAddress, ".");
if (signIpScopeSingleList.size() == 4
&& clientAddressList.size() == 4
&& ("*".equals((String) signIpScopeSingleList.get(0))
|| Util.null2String((String) clientAddressList.get(0)).equals((String) signIpScopeSingleList.get(0)))
&& ("*".equals((String) signIpScopeSingleList.get(1))
|| Util.null2String((String) clientAddressList.get(1)).equals((String) signIpScopeSingleList.get(1)))
&& ("*".equals((String) signIpScopeSingleList.get(2))
|| Util.null2String((String) clientAddressList.get(2)).equals((String) signIpScopeSingleList.get(2)))
&& ("*".equals((String) signIpScopeSingleList.get(3))
|| Util.null2String((String) clientAddressList.get(3)).equals((String) signIpScopeSingleList.get(2)))
) {
isInScope = true;
}
} else if (signIpScopeSingle.indexOf("-") > -1) {//如果单个ip范围的格式为10.16.0.13-10.16.0.18
String signIpFrom = signIpScopeSingle.substring(0, signIpScopeSingle.indexOf("-"));
signIpFrom = Util.null2String(signIpFrom).trim();
String signIpTo = "";
if (!signIpScopeSingle.endsWith("-")) {
signIpTo = signIpScopeSingle.substring(signIpScopeSingle.indexOf("-") + 1);
}
signIpTo = Util.null2String(signIpTo).trim();
String tempClientAddress = addToThreeFigure(clientAddress, "clientAddress");
signIpFrom = addToThreeFigure(signIpFrom, "signIpFrom");
signIpTo = addToThreeFigure(signIpTo, "signIpTo");
if (signIpFrom.equals("") && signIpTo.equals("")) {
isInScope = true;
}
if (signIpFrom.equals("") && !signIpTo.equals("")) {
if (tempClientAddress.compareTo(signIpTo) <= 0) {
isInScope = true;
}
}
if (!signIpFrom.equals("") && signIpTo.equals("")) {
if (tempClientAddress.compareTo(signIpFrom) >= 0) {
isInScope = true;
}
}
if (!signIpFrom.equals("") && !signIpTo.equals("")) {
if (tempClientAddress.compareTo(signIpFrom) >= 0 && tempClientAddress.compareTo(signIpTo) <= 0) {
isInScope = true;
}
}
} else {//否则单个ip范围的格式为10.16.0.12
if (clientAddress.equals(signIpScopeSingle)) {
isInScope = true;
}
}
return isInScope;
}
/**
* 校验ip范围
* @param clientAddress
* @return
*/
public boolean getIsInScope(String userId, String clientAddress) {
boolean isInScope = false;
clientAddress = Util.null2String(clientAddress).trim();
if (clientAddress.length() == 0) {
return isInScope;
}
RecordSet rs = new RecordSet();
KQGroupComInfo kqGroupComInfo = new KQGroupComInfo();
KQGroupMemberComInfo kqGroupMemberComInfo = new KQGroupMemberComInfo();
String groupid = Util.null2String(kqGroupMemberComInfo.getKQGroupId(userId));
String signIpScope = Util.null2String(kqGroupComInfo.getIpscope(groupid)).trim();//格式10.*.*.*;10.16.0.12;10.16.0.13-10.16.0.18
if (signIpScope.length() == 0) {
return true;
}
List signIpScopeList = Util.TokenizerString(signIpScope, ";");
String signIpScopeSingle = "";
for (int i = 0; i < signIpScopeList.size(); i++) {
signIpScopeSingle = Util.null2String((String) signIpScopeList.get(i));
signIpScopeSingle = signIpScopeSingle.trim();
if (signIpScopeSingle.indexOf("*") > -1) {//如果单个ip范围的格式为10.*.*.*
List signIpScopeSingleList = Util.TokenizerString(signIpScopeSingle, ".");
List clientAddressList = Util.TokenizerString(clientAddress, ".");
if (signIpScopeSingleList.size() == 4
&& clientAddressList.size() == 4
&& ("*".equals((String) signIpScopeSingleList.get(0))
|| Util.null2String((String) clientAddressList.get(0)).equals((String) signIpScopeSingleList.get(0)))
&& ("*".equals((String) signIpScopeSingleList.get(1))
|| Util.null2String((String) clientAddressList.get(1)).equals((String) signIpScopeSingleList.get(1)))
&& ("*".equals((String) signIpScopeSingleList.get(2))
|| Util.null2String((String) clientAddressList.get(2)).equals((String) signIpScopeSingleList.get(2)))
&& ("*".equals((String) signIpScopeSingleList.get(3))
|| Util.null2String((String) clientAddressList.get(3)).equals((String) signIpScopeSingleList.get(2)))
) {
isInScope = true;
break;
}
} else if (signIpScopeSingle.indexOf("-") > -1) {//如果单个ip范围的格式为10.16.0.13-10.16.0.18
String signIpFrom = signIpScopeSingle.substring(0, signIpScopeSingle.indexOf("-"));
signIpFrom = Util.null2String(signIpFrom).trim();
String signIpTo = "";
if (!signIpScopeSingle.endsWith("-")) {
signIpTo = signIpScopeSingle.substring(signIpScopeSingle.indexOf("-") + 1);
}
signIpTo = Util.null2String(signIpTo).trim();
String tempClientAddress = addToThreeFigure(clientAddress, "clientAddress");
signIpFrom = addToThreeFigure(signIpFrom, "signIpFrom");
signIpTo = addToThreeFigure(signIpTo, "signIpTo");
if (signIpFrom.equals("") && signIpTo.equals("")) {
isInScope = true;
break;
}
if (signIpFrom.equals("") && !signIpTo.equals("")) {
if (tempClientAddress.compareTo(signIpTo) <= 0) {
isInScope = true;
break;
}
}
if (!signIpFrom.equals("") && signIpTo.equals("")) {
if (tempClientAddress.compareTo(signIpFrom) >= 0) {
isInScope = true;
break;
}
}
if (!signIpFrom.equals("") && !signIpTo.equals("")) {
if (tempClientAddress.compareTo(signIpFrom) >= 0 && tempClientAddress.compareTo(signIpTo) <= 0) {
isInScope = true;
break;
}
}
} else {//否则单个ip范围的格式为10.16.0.12
if (clientAddress.equals(signIpScopeSingle)) {
isInScope = true;
break;
}
}
}
return isInScope;
}
/**
* 将IP地址填充为3位数
* "192.168.0.25"填充为3位数后为"192.168.000.025"
* @return String 填充为3位数后的IP地址
*/
private String addToThreeFigure(String IPAddress, String IPType) {
if (IPAddress == null || IPAddress.trim().equals("") || IPType == null || IPType.trim().equals("")) {
return "";
}
String returnString = "";
List IPAddressList = Util.TokenizerString(IPAddress, ".");
String IPAddressPart = "";
for (int i = 0; i < IPAddressList.size(); i++) {
IPAddressPart = Util.null2String(IPAddressList.get(i));
if (IPType.equals("signIpTo")) {
returnString += "." + Util.add0(Util.getIntValue(IPAddressPart, 255), 3);
} else {
returnString += "." + Util.add0(Util.getIntValue(IPAddressPart, 0), 3);
}
}
if (!returnString.equals("")) {
returnString = returnString.substring(1);
}
return returnString;
}
}

View File

@ -0,0 +1,466 @@
package com.engine.kq.biz;
import weaver.cache.CacheBase;
import weaver.cache.CacheColumn;
import weaver.cache.CacheColumnType;
import weaver.cache.PKColumn;
public class KQGroupComInfo extends CacheBase{
protected static String TABLE_NAME = "kq_group";
/** sql中的where信息不要以where开始 */
protected static String TABLE_WHERE = null;
/** sql中的order by信息不要以order by开始 */
protected static String TABLE_ORDER = "id";
@PKColumn(type = CacheColumnType.NUMBER)
protected static String PK_NAME = "id";
@CacheColumn(name = "groupname")
protected static int groupname;
@CacheColumn(name = "excludeid")
protected static int excludeid;
@CacheColumn(name = "excludecount")
protected static int excludecount;
@CacheColumn(name = "subcompanyid")
protected static int subcompanyid;
@CacheColumn(name = "kqtype")
protected static int kqtype;
@CacheColumn(name = "serialids")
protected static int serialids;
@CacheColumn(name = "weekday")
protected static int weekday;
@CacheColumn(name = "signstart")
protected static int signstart;
@CacheColumn(name = "workhour")
protected static int workhour;
@CacheColumn(name = "isdelete")
protected static int isdelete;
@CacheColumn(name = "signintype")
protected static int signintype;
@CacheColumn(name = "ipscope")
protected static int ipscope;
@CacheColumn(name = "locationcheck")
protected static int locationcheck;
@CacheColumn(name = "locationcheckscope")
protected static int locationcheckscope;
@CacheColumn(name = "wificheck")
protected static int wificheck;
@CacheColumn(name = "outsidesign")
protected static int outsidesign;
@CacheColumn(name = "outsignapprove")
protected static int outsignapprove;
@CacheColumn(name = "validity")
protected static int validity;
@CacheColumn(name = "validityfromdate")
protected static int validityfromdate;
@CacheColumn(name = "validityenddate")
protected static int validityenddate;
@CacheColumn(name = "locationfacecheck")
protected static int locationfacecheck;
@CacheColumn(name = "locationfacechecktype")
protected static int locationfacechecktype;
@CacheColumn(name = "locationshowaddress")
protected static int locationshowaddress;
@CacheColumn(name = "wififacecheck")
protected static int wififacecheck;
@CacheColumn(name = "wififacechecktype")
protected static int wififacechecktype;
@CacheColumn(name = "ipscope_v4_pc")
protected static int ipscope_v4_pc;
@CacheColumn(name = "ipscope_v4_em")
protected static int ipscope_v4_em;
@CacheColumn(name = "ipscope_v6_pc")
protected static int ipscope_v6_pc;
@CacheColumn(name = "ipscope_v6_em")
protected static int ipscope_v6_em;
@CacheColumn(name = "auto_checkin")
protected static int auto_checkin;
@CacheColumn(name = "auto_checkin_before")
protected static int auto_checkin_before;
@CacheColumn(name = "auto_checkin_after")
protected static int auto_checkin_after;
@CacheColumn(name = "auto_checkout")
protected static int auto_checkout;
@CacheColumn(name = "auto_checkout_before")
protected static int auto_checkout_before;
@CacheColumn(name = "auto_checkout_after")
protected static int auto_checkout_after;
@CacheColumn(name = "calmethod")
protected static int calmethod;
@CacheColumn(name = "isPhotoPunchEnabled")
protected static int isPhotoPunchEnabled;
/**
* 启用员工自我排班
*/
@CacheColumn(name = "self_shift")
protected static int self_shift;
/**
* 0表示默认统一设置1表示按照班次设置
*/
@CacheColumn(name = "overtime_type")
protected static int overtime_type;
@CacheColumn(name = "abnormalremind")
protected static int abnormalremind;
public String getId() {
return (String) getRowValue(PK_INDEX);
}
public String getGroupname() {
return (String) getRowValue(groupname);
}
public String getGroupname(String key) {
return (String) getValue(groupname, key);
}
public String getExcludeid() {
return (String) getRowValue(excludeid);
}
public String getExcludeid(String key) {
return (String) getValue(excludeid, key);
}
public String getExcludecount() {
return (String) getRowValue(excludecount);
}
public String getExcludecount(String key) {
return (String) getValue(excludecount, key);
}
public String getSubcompanyid() {
return (String) getRowValue(subcompanyid);
}
public String getSubcompanyid(String key) {
return (String) getValue(subcompanyid, key);
}
public String getKqtype() {
return (String) getRowValue(kqtype);
}
public String getKqtype(String key) {
return (String) getValue(kqtype, key);
}
public String getSerialids() {
return (String) getRowValue(serialids);
}
public String getSerialids(String key) {
return (String) getValue(serialids, key);
}
public String getWeekday() {
return (String) getRowValue(weekday);
}
public String getWeekday(String key) {
return (String) getValue(weekday, key);
}
public String getSignstart() {
return (String) getRowValue(signstart);
}
public String getSignstart(String key) {
return (String) getValue(signstart, key);
}
public String getWorkhour() {
return (String) getRowValue(workhour);
}
public String getWorkhour(String key) {
return (String) getValue(workhour, key);
}
public String getIsdelete() {
return (String) getRowValue(isdelete);
}
public String getIsdelete(String key) {
return (String) getValue(isdelete, key);
}
public String getSignintype() {
return (String) getRowValue(signintype);
}
public String getSignintype(String key) {
return (String) getValue(signintype, key);
}
public String getIpscope() {
return (String) getRowValue(ipscope);
}
public String getIpscope(String key) {
return (String) getValue(ipscope, key);
}
public String getLocationcheck() {
return (String) getRowValue(locationcheck);
}
public String getLocationcheck(String key) {
return (String) getValue(locationcheck, key);
}
public String getLocationcheckscope() {
return (String) getRowValue(locationcheckscope);
}
public String getLocationcheckscope(String key) {
return (String) getValue(locationcheckscope, key);
}
public String getWificheck() {
return (String) getRowValue(wificheck);
}
public String getWificheck(String key) {
return (String) getValue(wificheck, key);
}
public String getOutsidesign() {
return (String) getRowValue(outsidesign);
}
public String getOutsidesign(String key) {
return (String) getValue(outsidesign, key);
}
public String getOutsignApprove() {
return (String) getRowValue(outsignapprove);
}
public String getOutsignApprove(String key) {
return (String) getValue(outsignapprove, key);
}
public String getValidity() {
return (String) getRowValue(validity);
}
public String getValidity(String key) {
return (String) getValue(validity, key);
}
public String getValidityfromdate() {
return (String) getRowValue(validityfromdate);
}
public String getValidityfromdate(String key) {
return (String) getValue(validityfromdate, key);
}
public String getValidityenddate() {
return (String) getRowValue(validityenddate);
}
public String getValidityenddate(String key) {
return (String) getValue(validityenddate, key);
}
public String getLocationfacecheck() {
return (String) getRowValue(locationfacecheck);
}
public String getLocationfacecheck(String key) {
return (String) getValue(locationfacecheck, key);
}
public String getLocationfacechecktype() {
return (String) getRowValue(locationfacechecktype);
}
public String getLocationfacechecktype(String key) {
return (String) getValue(locationfacechecktype, key);
}
public String getLocationshowaddress() {
return (String) getRowValue(locationshowaddress);
}
public String getLocationshowaddress(String key) {
return (String) getValue(locationshowaddress, key);
}
public String getWififacecheck() {
return (String) getRowValue(wififacecheck);
}
public String getWififacecheck(String key) {
return (String) getValue(wififacecheck, key);
}
public String getWififacechecktype() {
return (String) getRowValue(wififacechecktype);
}
public String getWififacechecktype(String key) {
return (String) getValue(wififacechecktype, key);
}
public String getIpscope_v4_pc() {
return (String) getRowValue(ipscope_v4_pc);
}
public String getIpscope_v4_pc(String key) {
return (String) getValue(ipscope_v4_pc, key);
}
public String getIpscope_v4_em() {
return (String) getRowValue(ipscope_v4_em);
}
public String getIpscope_v4_em(String key) {
return (String) getValue(ipscope_v4_em, key);
}
public String getIpscope_v6_pc() {
return (String) getRowValue(ipscope_v6_pc);
}
public String getIpscope_v6_pc(String key) {
return (String) getValue(ipscope_v6_pc, key);
}
public String getIpscope_v6_em() {
return (String) getRowValue(ipscope_v6_em);
}
public String getIpscope_v6_em(String key) {
return (String) getValue(ipscope_v6_em, key);
}
public String getAuto_checkin() {
return (String) getRowValue(auto_checkin);
}
public String getAuto_checkin(String key) {
return (String) getValue(auto_checkin, key);
}
public String getAuto_checkin_before() {
return (String) getRowValue(auto_checkin_before);
}
public String getAuto_checkin_before(String key) {
return (String) getValue(auto_checkin_before, key);
}
public String getAuto_checkin_after() {
return (String) getRowValue(auto_checkin_after);
}
public String getAuto_checkin_after(String key) {
return (String) getValue(auto_checkin_after, key);
}
public String getAuto_checkout() {
return (String) getRowValue(auto_checkout);
}
public String getAuto_checkout(String key) {
return (String) getValue(auto_checkout, key);
}
public String getAuto_checkout_before() {
return (String) getRowValue(auto_checkout_before);
}
public String getAuto_checkout_before(String key) {
return (String) getValue(auto_checkout_before, key);
}
public String getAuto_checkout_after() {
return (String) getRowValue(auto_checkout_after);
}
public String getAuto_checkout_after(String key) {
return (String) getValue(auto_checkout_after, key);
}
public String getOvertime_type() {
return (String) getRowValue(overtime_type);
}
public String getOvertime_type(String key) {
return (String) getValue(overtime_type, key);
}
public String getCalmethod() {
return (String) getRowValue(calmethod);
}
public String getCalmethod(String key) {
return (String) getValue(calmethod, key);
}
public String getSelf_shift() {
return (String) getRowValue(self_shift);
}
public String getSelf_shift(String key) {
return (String) getValue(self_shift, key);
}
public String getIsPhotoPunchEnabled() {
return (String) getRowValue(isPhotoPunchEnabled);
}
public String getIsPhotoPunchEnabled(String key) {
return (String) getValue(isPhotoPunchEnabled, key);
}
public String getAbnormalremind() {
return (String)getRowValue(abnormalremind);
}
public String getAbnormalremind(String key) {
return (String)getValue(abnormalremind,key);
}
}

View File

@ -0,0 +1,981 @@
package com.engine.kq.biz;
import com.engine.kq.entity.KQGroupEntity;
import com.engine.kq.log.KQLog;
import weaver.cache.*;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.StaticObj;
import weaver.general.Util;
import weaver.hrm.resource.ResourceComInfo;
import java.io.Serializable;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
public class KQGroupMemberComInfo extends CacheBase implements Serializable {
/*
* 需要关注 : 如果完全在 initCache 自己定义数据初始化 这个字段可以不定义
*/
protected static String TABLE_NAME = "";
/*
* 需要关注 : 如果完全在 initCache 自己定义数据初始化或者不需要指定固定的条件 这个字段可以不定义
* sql中的where信息不要以where开始
*/
protected static String TABLE_WHERE = null;
/*
* 需要关注 : 如果完全在 initCache 自己定义数据初始化或者不需要指定顺序 这个字段可以不定义 sql中的order
* by信息不要以order by开始
*
*/
protected static String TABLE_ORDER = null;
@PKColumn(type = CacheColumnType.NUMBER)
protected static String PK_NAME = "id";
@CacheColumn
protected static int group;
private KQLog kqLog = new KQLog();
private boolean isFormat = false;
@Override
protected boolean autoInitIfNotFound() {
return false;
}
private StaticObj staticobj = null;
@Override
public CacheItem initCache(String key) {
if (key == null || "".equals(key.trim())) {
return null;
}
RecordSet rs = new RecordSet();
String sql = "";
kqLog = new KQLog();
ConcurrentHashMap<String, List> resourceKQGroups = new ConcurrentHashMap<>();
//考勤组优先级
try {
ResourceComInfo resourceComInfo = new ResourceComInfo();
String subcompanyid = Util.null2String(resourceComInfo.getSubCompanyID(key));//分部
String departmentid = Util.null2String(resourceComInfo.getDepartmentID(key));//部门
String jobtitle = Util.null2String(resourceComInfo.getJobTitle(key));//岗位
//人员
sql = " SELECT distinct a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b, kq_group c " +
" WHERE a.id=b.typevalue and b.type =1 and b.groupid=c.id and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1')" +
" and a.id = "+key+
" order by b.groupid desc ";
rs.executeQuery(sql);
while (rs.next()) {
setMemberGroup(resourceKQGroups, rs.getString("resourceid"), rs.getString("groupid"));
}
//部门
if(departmentid.length()>0) {
sql = " SELECT distinct a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b , kq_group c" +
" WHERE a.departmentid = b.typevalue AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto AND b.type=3 " +
" and b.groupid=c.id and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1') " +
" and a.departmentid = " + departmentid +
" and a.id="+key+
" order by b.groupid desc";
rs.executeQuery(sql);
while (rs.next()) {
setMemberGroup(resourceKQGroups, rs.getString("resourceid"), rs.getString("groupid"));
}
}
//分部
if(subcompanyid.length()>0) {
sql = " SELECT distinct a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b, kq_group c " +
" WHERE a.subcompanyid1 = b.typevalue AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto AND b.type=2 " +
" and b.groupid=c.id and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1') " +
" and a.subcompanyid1 = " + subcompanyid +
" and a.id="+key+
" order by b.groupid desc ";
rs.executeQuery(sql);
while (rs.next()) {
setMemberGroup(resourceKQGroups, rs.getString("resourceid"), rs.getString("groupid"));
}
}
//岗位
if(jobtitle.length()>0) {
sql = " SELECT distinct a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b, kq_group c " +
" WHERE a.jobtitle = b.typevalue AND b.type=5 " +
" AND (b.jobtitlelevel=1 OR (b.jobtitlelevel=2 AND a.subcompanyid1 IN(b.jobtitlelevelvalue)) OR (b.jobtitlelevel=3 AND a.departmentid IN(b.jobtitlelevelvalue))) " +
" and b.groupid=c.id and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1') " +
" and a.jobtitle = " + jobtitle +
" and a.id="+key+
" order by b.groupid desc ";
rs.executeQuery(sql);
while (rs.next()) {
setMemberGroup(resourceKQGroups, rs.getString("resourceid"), rs.getString("groupid"));
}
}
//所有人
sql = " SELECT distinct a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b, kq_group c " +
" WHERE (b.type=6 AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto) and b.groupid=c.id " +
" and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1') " +
" and a.id = "+key+
" order by b.groupid desc ";
rs.executeQuery(sql);
while (rs.next()) {
setMemberGroup(resourceKQGroups, rs.getString("resourceid"), rs.getString("groupid"));
}
if(resourceKQGroups.size()>0){
CacheItem cacheItem = createCacheItem();
Iterator<Map.Entry<String, List>> iterator = resourceKQGroups.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, List> entry = iterator.next();
String id = entry.getKey();
List value = entry.getValue();
cacheItem.set(PK_INDEX, id);
cacheItem.set(group, value);
modifyCacheItem(key, cacheItem);
}
return cacheItem;
}
} catch (Exception e) {
kqLog.info(e);
}
return null;
}
private void getHasValidateGroupInfo() {
RecordSet rs = new RecordSet();
String backFields = " b.groupid, b.typevalue, b.validatefrom as validatefrom, b.validateto as validateto,b.seclevel as groupseclevel,b.seclevelto as groupseclevelto ";
String sqlWhere = " and ((validatefrom <>'"+KQGroupBiz.GROUPMEMBER_VALIDATE_FROMDATE+"') or (validateto <>'"+KQGroupBiz.GROUPMEMBER_VALIDATE_TODATE+"'))";
//人员
String sql = " SELECT "+backFields+" FROM HrmResource a, kq_groupmember b, kq_group c " +
" WHERE a.id=b.typevalue and b.type =1 and b.groupid=c.id and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1')" +
sqlWhere + " order by b.groupid desc ";
rs.executeQuery(sql);
// rs.writeLog("sql:::::::::"+sql);
List<String> userGroupList = null;
while (rs.next()) {
String param = "type#1#"+rs.getString("typevalue");
String groupId = rs.getString("groupid");
String validatefrom = Util.null2String(rs.getString("validatefrom"), KQGroupBiz.GROUPMEMBER_VALIDATE_FROMDATE);
String validateto = Util.null2String(rs.getString("validateto"), KQGroupBiz.GROUPMEMBER_VALIDATE_TODATE);
String valueParam = groupId+"#"+validatefrom+"#"+validateto;
if(staticobj.getObject("User&GroupMember") == null) {
userGroupList = new ArrayList<>();
} else {
userGroupList = (List<String>)staticobj.getRecordFromObj("User&GroupMember",param);
if(userGroupList == null) {
userGroupList = new ArrayList<>();
}
}
if(!userGroupList.contains(valueParam)) {
userGroupList.add(valueParam);
staticobj.putRecordToObj("User&GroupMember",param,userGroupList);
}
// rs.writeLog("userGroupList:::::::::"+JSON.toJSONString(userGroupList));
}
//部门
sql = " SELECT "+backFields+" FROM HrmResource a, kq_groupmember b , kq_group c" +
" WHERE a.departmentid = b.typevalue AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto AND b.type=3 " +
" and b.groupid=c.id and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1') " +
sqlWhere +
" order by b.groupid desc";
rs.executeQuery(sql);
List<String> departGroupList = null;
while (rs.next()) {
String param = "type#3#"+rs.getString("typevalue");
String groupId = rs.getString("groupid");
String validatefrom = Util.null2String(rs.getString("validatefrom"), KQGroupBiz.GROUPMEMBER_VALIDATE_FROMDATE);
String validateto = Util.null2String(rs.getString("validateto"), KQGroupBiz.GROUPMEMBER_VALIDATE_TODATE);
String groupseclevel = Util.null2String(rs.getString("groupseclevel"));
String groupseclevelto = Util.null2String(rs.getString("groupseclevelto"));
String valueParam = groupId+"#"+validatefrom+"#"+validateto+"#"+groupseclevel+"#"+groupseclevelto;
if(staticobj.getObject("Department&GroupMember") == null) {
departGroupList = new ArrayList<>();
} else {
departGroupList = (List<String>)staticobj.getRecordFromObj("Department&GroupMember",param);
if(departGroupList == null) {
departGroupList = new ArrayList<>();
}
}
if(!departGroupList.contains(valueParam)) {
departGroupList.add(valueParam);
staticobj.putRecordToObj("Department&GroupMember",param,departGroupList);
}
}
//分部
sql = " SELECT "+backFields+" FROM HrmResource a, kq_groupmember b, kq_group c " +
" WHERE a.subcompanyid1 = b.typevalue AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto AND b.type=2 " +
" and b.groupid=c.id and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1') " +
sqlWhere +
" order by b.groupid desc ";
rs.executeQuery(sql);
List<String> subCompanyGroupList = null;
while (rs.next()) {
String param = "type#2#"+rs.getString("typevalue");
String groupId = rs.getString("groupid");
String validatefrom = Util.null2String(rs.getString("validatefrom"), KQGroupBiz.GROUPMEMBER_VALIDATE_FROMDATE);
String validateto = Util.null2String(rs.getString("validateto"), KQGroupBiz.GROUPMEMBER_VALIDATE_TODATE);
String groupseclevel = Util.null2String(rs.getString("groupseclevel"));
String groupseclevelto = Util.null2String(rs.getString("groupseclevelto"));
String valueParam = groupId+"#"+validatefrom+"#"+validateto+"#"+groupseclevel+"#"+groupseclevelto;
if(staticobj.getObject("SubCompany&GroupMember") == null) {
subCompanyGroupList = new ArrayList<>();
} else {
subCompanyGroupList = (List<String>)staticobj.getRecordFromObj("SubCompany&GroupMember",param);
if(subCompanyGroupList == null) {
subCompanyGroupList = new ArrayList<>();
}
}
if(!subCompanyGroupList.contains(valueParam)) {
subCompanyGroupList.add(valueParam);
staticobj.putRecordToObj("SubCompany&GroupMember",param,subCompanyGroupList);
}
}
//岗位
sql = " SELECT "+backFields+" FROM HrmResource a, kq_groupmember b, kq_group c " +
" WHERE a.jobtitle = b.typevalue AND b.type=5 " +
" AND (b.jobtitlelevel=1 OR (b.jobtitlelevel=2 AND a.subcompanyid1 IN(b.jobtitlelevelvalue)) OR (b.jobtitlelevel=3 AND a.departmentid IN(b.jobtitlelevelvalue))) " +
" and b.groupid=c.id and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1') " +
sqlWhere +
" order by b.groupid desc ";
rs.executeQuery(sql);
List<String> jobtitleGroupList = null;
while (rs.next()) {
String param = "type#5#"+rs.getString("typevalue");
String groupId = rs.getString("groupid");
String validatefrom = Util.null2String(rs.getString("validatefrom"), KQGroupBiz.GROUPMEMBER_VALIDATE_FROMDATE);
String validateto = Util.null2String(rs.getString("validateto"), KQGroupBiz.GROUPMEMBER_VALIDATE_TODATE);
String groupseclevel = Util.null2String(rs.getString("groupseclevel"));
String groupseclevelto = Util.null2String(rs.getString("groupseclevelto"));
String valueParam = groupId+"#"+validatefrom+"#"+validateto+"#"+groupseclevel+"#"+groupseclevelto;
if(staticobj.getObject("Jobtitle&GroupMember") == null) {
jobtitleGroupList = new ArrayList<>();
} else {
jobtitleGroupList = (List<String>)staticobj.getRecordFromObj("Jobtitle&GroupMember",param);
if(jobtitleGroupList == null) {
jobtitleGroupList = new ArrayList<>();
}
}
if(!jobtitleGroupList.contains(valueParam)) {
jobtitleGroupList.add(valueParam);
staticobj.putRecordToObj("Jobtitle&GroupMember",param,jobtitleGroupList);
}
}
//所有人
sql = " SELECT "+backFields+" FROM HrmResource a, kq_groupmember b, kq_group c " +
" WHERE (b.type=6 AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto) and b.groupid=c.id " +
" and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1') " +
sqlWhere +
" order by b.groupid desc ";
rs.executeQuery(sql);
rs.executeQuery(sql);
List<String> allGroupList = null;
while (rs.next()) {
String param = "type#6#"+rs.getString("typevalue");
String groupId = rs.getString("groupid");
String validatefrom = Util.null2String(rs.getString("validatefrom"), KQGroupBiz.GROUPMEMBER_VALIDATE_FROMDATE);
String validateto = Util.null2String(rs.getString("validateto"), KQGroupBiz.GROUPMEMBER_VALIDATE_TODATE);
String groupseclevel = Util.null2String(rs.getString("groupseclevel"));
String groupseclevelto = Util.null2String(rs.getString("groupseclevelto"));
String valueParam = groupId+"#"+validatefrom+"#"+validateto+"#"+groupseclevel+"#"+groupseclevelto;
if(staticobj.getObject("All&GroupMember") == null) {
allGroupList = new ArrayList<>();
} else {
allGroupList = (List<String>)staticobj.getRecordFromObj("All&GroupMember",param);
if(allGroupList == null) {
allGroupList = new ArrayList<>();
}
}
if(!allGroupList.contains(valueParam)) {
allGroupList.add(valueParam);
staticobj.putRecordToObj("All&GroupMember",param,allGroupList);
}
}
}
@Override
public CacheMap initCache() {
// writeLog("KQGroupMemberComInfo::::::in:::::::2222::::::");
staticobj = StaticObj.getInstance();
staticobj.removeObject("User&GroupMember");
staticobj.removeObject("Department&GroupMember");
staticobj.removeObject("SubCompany&GroupMember");
staticobj.removeObject("Jobtitle&GroupMember");
staticobj.removeObject("All&GroupMember");
getHasValidateGroupInfo();
CacheMap localData = createCacheMap();
RecordSet rs = new RecordSet();
String sql = "";
kqLog = new KQLog();
ConcurrentHashMap<String, List> resourceKQGroups = new ConcurrentHashMap<>();
//考勤组优先级
try {
//人员
sql = " SELECT distinct a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b, kq_group c " +
" WHERE a.id=b.typevalue and b.type =1 and b.groupid=c.id and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1') order by b.groupid desc ";
rs.executeQuery(sql);
while (rs.next()) {
setMemberGroup(resourceKQGroups, rs.getString("resourceid"), rs.getString("groupid"));
}
//部门
sql = " SELECT distinct a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b , kq_group c" +
" WHERE a.departmentid = b.typevalue AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto AND b.type=3 " +
" and b.groupid=c.id and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1') order by b.groupid desc";
rs.executeQuery(sql);
while (rs.next()) {
setMemberGroup(resourceKQGroups, rs.getString("resourceid"), rs.getString("groupid"));
}
//分部
sql = " SELECT distinct a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b, kq_group c " +
" WHERE a.subcompanyid1 = b.typevalue AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto AND b.type=2 " +
" and b.groupid=c.id and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1') order by b.groupid desc ";
rs.executeQuery(sql);
while (rs.next()) {
setMemberGroup(resourceKQGroups, rs.getString("resourceid"), rs.getString("groupid"));
}
//岗位
sql = " SELECT distinct a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b, kq_group c " +
" WHERE a.jobtitle = b.typevalue AND b.type=5 " +
" AND (b.jobtitlelevel=1 OR (b.jobtitlelevel=2 AND a.subcompanyid1 IN(b.jobtitlelevelvalue)) OR (b.jobtitlelevel=3 AND a.departmentid IN(b.jobtitlelevelvalue))) " +
" and b.groupid=c.id and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1') order by b.groupid desc ";
rs.executeQuery(sql);
while (rs.next()) {
setMemberGroup(resourceKQGroups, rs.getString("resourceid"), rs.getString("groupid"));
}
//所有人
sql = " SELECT distinct a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b, kq_group c " +
" WHERE (b.type=6 AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto) and b.groupid=c.id " +
" and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1') order by b.groupid desc ";
rs.executeQuery(sql);
while (rs.next()) {
setMemberGroup(resourceKQGroups, rs.getString("resourceid"), rs.getString("groupid"));
}
if(resourceKQGroups.size()>0) {
Iterator<Map.Entry<String, List>> iterator = resourceKQGroups.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, List> entry = iterator.next();
String id = entry.getKey();
List value = entry.getValue();
CacheItem cacheItem = createCacheItem();
cacheItem.set(PK_INDEX, id);
cacheItem.set(group, value);
modifyCacheItem(id, cacheItem);
localData.put(id, cacheItem);
}
}
} catch (Exception e) {
kqLog.writeLog(e);
}
return localData;
}
private void setMemberGroup(ConcurrentHashMap resourceKQGroups, String resourceid, String groupid) {
try {
List<Object> kqGroups = null;
if (resourceKQGroups.get(resourceid) == null) {
kqGroups = new ArrayList<>();
} else {
kqGroups = (List<Object>) resourceKQGroups.get(resourceid);
}
kqGroups.add(groupid);
resourceKQGroups.put(resourceid, kqGroups);
} catch (Exception e) {
kqLog.info(e);
}
}
public String getKQGroupId(String userId) {
String workDate = DateUtil.getCurrentDate();
return getKQGroupId(userId, workDate);
}
/**
* 根据user获取考勤组id
*
* @param userId
* @return
*/
public String getKQGroupId(String userId, String workDate) {
return getKQGroupId(userId, workDate, true);
}
/**
* 是否在考勤组的有效期范围内
* @param tmpGroupId
* @param workDate
* @return
*/
private boolean isInKqGroupValidate(String tmpGroupId, String workDate) {
boolean flag = true;
KQGroupComInfo kqGroupComInfo = new KQGroupComInfo();
String kqtype = kqGroupComInfo.getKqtype(tmpGroupId);
String validity = kqGroupComInfo.getValidity(tmpGroupId);
String validityfromdate = kqGroupComInfo.getValidityfromdate(tmpGroupId);
String validityenddate = kqGroupComInfo.getValidityenddate(tmpGroupId);
if (validity.equals("1")) {
if (!DateUtil.isInDateRange(workDate, validityfromdate, validityenddate)) {
flag = false;
}
}
return flag;
}
/***
* 根据user获取考勤组id
* @param userId
* @param workDate
* @param containFixed 取不到排班取固定班
* @return
*/
public String getKQGroupId(String userId, String workDate, boolean containFixed) {
String groupId = "";
Map<String, Map<String, String>> allKqGroupsExceptSql = new HashMap<>();
List<String> kqGroups = getGroupBefore(userId, workDate, allKqGroupsExceptSql);
if(kqGroups.size() > 0) {
String tmpGroupId = kqGroups.get(0);
if(isInKqGroupValidate(tmpGroupId, workDate)) {
return tmpGroupId;
}
}
KQGroupComInfo kqGroupComInfo = new KQGroupComInfo();
List<String> lsGroupIds = this.getKQGroups(userId, workDate);
lsGroupIds.removeIf(allKqGroupsExceptSql::containsKey);
for (int i = 0; i < lsGroupIds.size(); i++) {
String tmpGroupId = Util.null2String((String) lsGroupIds.get(i));
if(isInKqGroupValidate(tmpGroupId, workDate)) {
groupId = tmpGroupId;
} else {
continue;
}
String kqtype = kqGroupComInfo.getKqtype(tmpGroupId);
// String validity = kqGroupComInfo.getValidity(tmpGroupId);
// String validityfromdate = kqGroupComInfo.getValidityfromdate(tmpGroupId);
// String validityenddate = kqGroupComInfo.getValidityenddate(tmpGroupId);
// if (validity.equals("1")) {
// if (DateUtil.isInDateRange(workDate, validityfromdate, validityenddate)) {
// groupId = tmpGroupId;
// }else{
// //超过有效期
// continue;
// }
// } else {
// groupId = tmpGroupId;
// }
//考勤组如果排班为空取下一个考勤组
if (groupId.length() > 0) {
if (containFixed && kqtype.equals("2")) {
KQShiftScheduleComInfo kqShiftScheduleComInfo = new KQShiftScheduleComInfo();
kqShiftScheduleComInfo.setShiftGroupId(Util.getIntValue(groupId));
if (Util.null2String(kqShiftScheduleComInfo.getSerialId(userId, workDate)).length() > 0 &&
Util.null2String(kqShiftScheduleComInfo.getGroupId(userId, workDate)).equals(groupId)) {
break;
}
} else {
break;
}
}
}
return groupId;
}
public List<String> getKQGroups(String userId, String kqDate) {
// if(!this.isFormat){
// return (List<String>) getObjValue(group, userId);
// }
RecordSet rs = new RecordSet();
String sql = "";
kqLog = new KQLog();
List<String> kqGroups = new ArrayList<>();
// Map<String, Map<String, String>> allKqGroupsExceptSql = new HashMap<>();
//考勤组优先级
try {
// Map<String, Map<String, String>> sqlWhereMap = sqlWhereMap();
ResourceComInfo resourceComInfo = new ResourceComInfo();
// kqGroups = getGroupBefore(userId, kqDate, allKqGroupsExceptSql);
// if(kqGroups.size() > 0) {
// return kqGroups;
// }
String subcompanyid = Util.null2String(resourceComInfo.getSubCompanyID(userId));//分部
String departmentid = Util.null2String(resourceComInfo.getDepartmentID(userId));//部门
String jobtitle = Util.null2String(resourceComInfo.getJobTitle(userId));//岗位
String sqlWhere = " and ('"+kqDate+"' between b.validatefrom and b.validateto) ";
// if(rs.getDBType().equalsIgnoreCase("oracle")) {
// sqlWhere = " and ('"+kqDate+"' between nvl(b.validatefrom,'2000-01-01') and nvl(b.validateto,'2999-12-31')) ";
// }else if((rs.getDBType()).equalsIgnoreCase("mysql")){
// sqlWhere = " and ('"+kqDate+"' between ifnull(b.validatefrom,'2000-01-01') and ifnull(b.validateto,'2999-12-31')) ";
// }else {
// sqlWhere = " and ('"+kqDate+"' between isnull(b.validatefrom,'2000-01-01') and isnull(b.validateto,'2999-12-31')) ";
// }
//人员
sql = " SELECT distinct a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b, kq_group c " +
" WHERE a.id=b.typevalue and b.type =1 and b.groupid=c.id and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1')" +
" and a.id = ?"+sqlWhere+
" order by b.groupid desc ";
rs.executeQuery(sql,userId);
while (rs.next()) {
kqGroups.add(rs.getString("groupid"));
}
//部门
if(departmentid.length()>0) {
sql = " SELECT distinct a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b , kq_group c" +
" WHERE a.departmentid = b.typevalue AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto AND b.type=3 " +
" and b.groupid=c.id and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1') " +
" and a.departmentid = ? "+
" and a.id= ? "+sqlWhere+
" order by b.groupid desc";
rs.executeQuery(sql,departmentid,userId);
while (rs.next()) {
kqGroups.add(rs.getString("groupid"));
}
}
//分部
if(subcompanyid.length()>0) {
sql = " SELECT distinct a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b, kq_group c " +
" WHERE a.subcompanyid1 = b.typevalue AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto AND b.type=2 " +
" and b.groupid=c.id and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1') " +
" and a.subcompanyid1 = ? " +
" and a.id= ? "+sqlWhere+
" order by b.groupid desc ";
rs.executeQuery(sql,subcompanyid,userId);
while (rs.next()) {
kqGroups.add(rs.getString("groupid"));
}
}
//岗位
if(jobtitle.length()>0) {
sql = " SELECT distinct a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b, kq_group c " +
" WHERE a.jobtitle = b.typevalue AND b.type=5 " +
" AND (b.jobtitlelevel=1 OR (b.jobtitlelevel=2 AND a.subcompanyid1 IN(b.jobtitlelevelvalue)) OR (b.jobtitlelevel=3 AND a.departmentid IN(b.jobtitlelevelvalue))) " +
" and b.groupid=c.id and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1') " +
" and a.jobtitle = ? " +
" and a.id= ? "+sqlWhere+
" order by b.groupid desc ";
rs.executeQuery(sql,jobtitle,userId);
while (rs.next()) {
kqGroups.add(rs.getString("groupid"));
}
}
//所有人
sql = " SELECT distinct a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b, kq_group c " +
" WHERE (b.type=6 AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto) and b.groupid=c.id " +
" and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1') " +
" and a.id = ? "+sqlWhere+
" order by b.groupid desc ";
rs.executeQuery(sql,userId);
while (rs.next()) {
kqGroups.add(rs.getString("groupid"));
}
} catch (Exception e) {
kqLog.info(e);
}
// kqGroups.removeIf(allKqGroupsExceptSql::containsKey);
return kqGroups;
}
/**
* 如果设置了有效期且查询在有效期范围内的直接用
* @return
*/
private List<String> getGroupBefore(String userId, String kqDate, Map<String, Map<String, String>> allKqGroupsExceptSql) {
StaticObj groupMemberStaticObj = StaticObj.getInstance();
RecordSet rs = new RecordSet();
List<String> kqGroups = new ArrayList<>();
try {
ResourceComInfo resourceComInfo = new ResourceComInfo();
String subcompanyid = Util.null2String(resourceComInfo.getSubCompanyID(userId));//分部
String departmentid = Util.null2String(resourceComInfo.getDepartmentID(userId));//部门
String jobtitle = Util.null2String(resourceComInfo.getJobTitle(userId));//岗位
// 人员
String param = "type#1#"+userId;
if(groupMemberStaticObj.getObject("User&GroupMember") != null) {
List<String> userGroupList = (List<String>)groupMemberStaticObj.getRecordFromObj("User&GroupMember",param);
// writeLog("userGroupList::::"+ JSON.toJSONString(userGroupList));
if(userGroupList != null) {
for (String userGourp : userGroupList) {
String groupId = userGourp.split("#")[0];
handle(allKqGroupsExceptSql, groupId, userId, "resourceId");
String validateFrom = userGourp.split("#")[1];
String validateTo = userGourp.split("#")[2];
if (kqDate.compareTo(validateFrom) >= 0 && kqDate.compareTo(validateTo) <= 0) {
kqGroups.add(groupId);
}
}
if (kqGroups.size() > 0) {
return kqGroups;
}
}
}
//部门
if (departmentid.length() > 0) {
param = "type#3#" + departmentid;
if (groupMemberStaticObj.getObject("Department&GroupMember") != null) {
List<String> departGroupList = (List<String>) groupMemberStaticObj.getRecordFromObj("Department&GroupMember", param);
// writeLog("departGroupList::::" + JSON.toJSONString(departGroupList));
if (departGroupList != null) {
for (String departGroup : departGroupList) {
String groupId = departGroup.split("#")[0];
String validateFrom = departGroup.split("#")[1];
String validateTo = departGroup.split("#")[2];
String groupseclevel = departGroup.split("#")[3];
String groupseclevelto = departGroup.split("#")[4];
int userSeclevel = Util.getIntValue(resourceComInfo.getSeclevel(userId));
if (kqDate.compareTo(validateFrom) >= 0 && kqDate.compareTo(validateTo) <= 0 && userSeclevel>=Util.getIntValue(groupseclevel)
&& userSeclevel<=Util.getIntValue(groupseclevelto)) {
if (allKqGroupsExceptSql.containsKey(groupId)) {
continue;
}
handle(allKqGroupsExceptSql, groupId, departmentid, "departmentId");
kqGroups.add(groupId);
}
}
}
if (kqGroups.size() > 0) {
return kqGroups;
}
}
}
//分部
if (subcompanyid.length() > 0) {
param = "type#2#" + subcompanyid;
if (groupMemberStaticObj.getObject("SubCompany&GroupMember") != null) {
List<String> subCompanyGroupList = (List<String>) groupMemberStaticObj.getRecordFromObj("SubCompany&GroupMember", param);
// writeLog("subCompanyGroupList::::" + JSON.toJSONString(subCompanyGroupList));
if (subCompanyGroupList != null) {
for (String subCompanyGroup : subCompanyGroupList) {
String groupId = subCompanyGroup.split("#")[0];
String validateFrom = subCompanyGroup.split("#")[1];
String validateTo = subCompanyGroup.split("#")[2];
String groupseclevel = subCompanyGroup.split("#")[3];
String groupseclevelto = subCompanyGroup.split("#")[4];
int userSeclevel = Util.getIntValue(resourceComInfo.getSeclevel(userId));
if (kqDate.compareTo(validateFrom) >= 0 && kqDate.compareTo(validateTo) <= 0 && userSeclevel>=Util.getIntValue(groupseclevel)
&& userSeclevel<=Util.getIntValue(groupseclevelto)) {
if (allKqGroupsExceptSql.containsKey(groupId)) {
continue;
}
handle(allKqGroupsExceptSql, groupId, subcompanyid, "subcompanyId");
kqGroups.add(groupId);
}
}
}
if (kqGroups.size() > 0) {
return kqGroups;
}
}
}
//岗位
if (jobtitle.length() > 0) {
param = "type#5#" + jobtitle;
if (groupMemberStaticObj.getObject("Jobtitle&GroupMember") != null) {
List<String> jobtitleGroupList = (List<String>) groupMemberStaticObj.getRecordFromObj("Jobtitle&GroupMember", param);
// writeLog("jobtitleGroupList::::" + JSON.toJSONString(jobtitleGroupList));
if (jobtitleGroupList != null) {
for (String jobtitleGroup : jobtitleGroupList) {
String groupId = jobtitleGroup.split("#")[0];
String validateFrom = jobtitleGroup.split("#")[1];
String validateTo = jobtitleGroup.split("#")[2];
String groupseclevel = jobtitleGroup.split("#")[3];
String groupseclevelto = jobtitleGroup.split("#")[4];
int userSeclevel = Util.getIntValue(resourceComInfo.getSeclevel(userId));
if (kqDate.compareTo(validateFrom) >= 0 && kqDate.compareTo(validateTo) <= 0 && userSeclevel>=Util.getIntValue(groupseclevel)
&& userSeclevel<=Util.getIntValue(groupseclevelto)) {
if (allKqGroupsExceptSql.containsKey(groupId)) {
continue;
}
handle(allKqGroupsExceptSql, groupId, jobtitle, "jobtitleId");
kqGroups.add(groupId);
}
}
}
if (kqGroups.size() > 0) {
return kqGroups;
}
}
}
//所有人
param = "type#6#0";
if (groupMemberStaticObj.getObject("All&GroupMember") != null) {
List<String> allGroupList = (List<String>) groupMemberStaticObj.getRecordFromObj("All&GroupMember", param);
// writeLog("allGroupList::::" + JSON.toJSONString(allGroupList));
if (allGroupList != null) {
for (String allGroup : allGroupList) {
String groupId = allGroup.split("#")[0];
String validateFrom = allGroup.split("#")[1];
String validateTo = allGroup.split("#")[2];
String groupseclevel = allGroup.split("#")[3];
String groupseclevelto = allGroup.split("#")[4];
int userSeclevel = Util.getIntValue(resourceComInfo.getSeclevel(userId));
if (kqDate.compareTo(validateFrom) >= 0 && kqDate.compareTo(validateTo) <= 0 && userSeclevel>=Util.getIntValue(groupseclevel)
&& userSeclevel<=Util.getIntValue(groupseclevelto)) {
if (allKqGroupsExceptSql.containsKey(groupId)) {
continue;
}
handle(allKqGroupsExceptSql, groupId, "0", "all");
kqGroups.add(groupId);
}
}
if (kqGroups.size() > 0) {
return kqGroups;
}
}
}
}catch (Exception e) {
writeLog(e);
}
return kqGroups;
}
private Map<String, Map<String, String>> sqlWhereMap() {
// 先把所有的groupid找到
RecordSet rs = new RecordSet();
Map<String, Map<String, String>> allKqGroupsExceptSql = new HashMap<>();
String sql = "select * from kq_groupmember where (isDelete is null or isDelete<>1)";
rs.executeQuery(sql);
while (rs.next()) {
String groupId = rs.getString("id");
int groupType = rs.getInt("type");
String groupTypeValue = rs.getString("typevalue");
switch (groupType) {
case 1:
handle(allKqGroupsExceptSql, groupId, groupTypeValue, "resourceId");
break;
case 2:
handle(allKqGroupsExceptSql, groupId, groupTypeValue, "subcompanyId");
break;
case 3:
handle(allKqGroupsExceptSql, groupId, groupTypeValue, "departmentId");
break;
case 5:
handle(allKqGroupsExceptSql, groupId, groupTypeValue, "jobTitleId");
break;
case 6:
handle(allKqGroupsExceptSql, groupId, groupTypeValue, "all");
break;
default:
break;
}
}
return allKqGroupsExceptSql;
}
private void handle(Map<String, Map<String, String>> allKqGroupsExceptSql, String groupId, String groupTypeValue, String key) {
Map<String, String> sqlWhereMap = null;
String sqlWhereValue = groupTypeValue;
if(allKqGroupsExceptSql.containsKey(groupId)) {
sqlWhereMap = allKqGroupsExceptSql.get(groupId);
if (sqlWhereMap.containsKey(key)) {
sqlWhereValue = sqlWhereMap.get(key) + "," + groupTypeValue;
}
} else {
sqlWhereMap = new HashMap<>();
}
sqlWhereMap.put(key, sqlWhereValue);
allKqGroupsExceptSql.put(groupId, sqlWhereMap);
}
/**
* 根据user获取所有考勤组
*
* @param userId
* @return
*/
private List<String> getKQGroups(String userId) {
if(!this.isFormat){
return (List<String>) getObjValue(group, userId);
}
RecordSet rs = new RecordSet();
String sql = "";
kqLog = new KQLog();
List<String> kqGroups = new ArrayList<>();
//考勤组优先级
try {
ResourceComInfo resourceComInfo = new ResourceComInfo();
String subcompanyid = Util.null2String(resourceComInfo.getSubCompanyID(userId));//分部
String departmentid = Util.null2String(resourceComInfo.getDepartmentID(userId));//部门
String jobtitle = Util.null2String(resourceComInfo.getJobTitle(userId));//岗位
//人员
sql = " SELECT distinct a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b, kq_group c " +
" WHERE a.id=b.typevalue and b.type =1 and b.groupid=c.id and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1')" +
" and a.id = ?"+
" order by b.groupid desc ";
rs.executeQuery(sql,userId);
while (rs.next()) {
kqGroups.add(rs.getString("groupid"));
}
//部门
if(departmentid.length()>0) {
sql = " SELECT distinct a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b , kq_group c" +
" WHERE a.departmentid = b.typevalue AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto AND b.type=3 " +
" and b.groupid=c.id and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1') " +
" and a.departmentid = ? "+
" and a.id= ? "+
" order by b.groupid desc";
rs.executeQuery(sql,departmentid,userId);
while (rs.next()) {
kqGroups.add(rs.getString("groupid"));
}
}
//分部
if(subcompanyid.length()>0) {
sql = " SELECT distinct a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b, kq_group c " +
" WHERE a.subcompanyid1 = b.typevalue AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto AND b.type=2 " +
" and b.groupid=c.id and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1') " +
" and a.subcompanyid1 = ? " +
" and a.id= ? "+
" order by b.groupid desc ";
rs.executeQuery(sql,subcompanyid,userId);
while (rs.next()) {
kqGroups.add(rs.getString("groupid"));
}
}
//岗位
if(jobtitle.length()>0) {
sql = " SELECT distinct a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b, kq_group c " +
" WHERE a.jobtitle = b.typevalue AND b.type=5 " +
" AND (b.jobtitlelevel=1 OR (b.jobtitlelevel=2 AND a.subcompanyid1 IN(b.jobtitlelevelvalue)) OR (b.jobtitlelevel=3 AND a.departmentid IN(b.jobtitlelevelvalue))) " +
" and b.groupid=c.id and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1') " +
" and a.jobtitle = ? " +
" and a.id= ? "+
" order by b.groupid desc ";
rs.executeQuery(sql,jobtitle,userId);
while (rs.next()) {
kqGroups.add(rs.getString("groupid"));
}
}
//所有人
sql = " SELECT distinct a.id AS resourceid, b.groupid, a.status FROM HrmResource a, kq_groupmember b, kq_group c " +
" WHERE (b.type=6 AND a.seclevel>=b.seclevel AND a.seclevel<=b.seclevelto) and b.groupid=c.id " +
" and (c.isdelete is null or c.isdelete <> '1') and (b.isdelete is null or b.isdelete <> '1') " +
" and a.id = ? "+
" order by b.groupid desc ";
rs.executeQuery(sql,userId);
while (rs.next()) {
kqGroups.add(rs.getString("groupid"));
}
} catch (Exception e) {
kqLog.info(e);
}
return kqGroups;
}
/**
* 根据user获取所有考勤组id
*
* @param userId
* @return
*/
public String getKQGroupIds(String userId) {
String groupId = "";
String kqDate = DateUtil.getCurrentDate();
List<String> lsGroupIds = this.getKQGroups(userId, kqDate);
if (lsGroupIds != null) {
groupId = String.join(",", lsGroupIds);
}
return groupId;
}
public String getKQGroupIds(String userId, String kqDate) {
String groupId = "";
List<String> lsGroupIds = this.getKQGroups(userId, kqDate);
if (lsGroupIds != null) {
groupId = String.join(",", lsGroupIds);
}
return groupId;
}
public KQGroupEntity getUserKQGroupInfo(String userId) {
String workDate = DateUtil.getCurrentDate();
return getUserKQGroupInfo(userId, workDate);
}
/**
* 获取考勤组相关信息
*
* @param userId
* @return
*/
public KQGroupEntity getUserKQGroupInfo(String userId, String workDate) {
return getUserKQGroupInfo(userId, workDate, true);
}
/***
* 获取考勤组相关信息
* @param userId
* @param workDate
* @param containFixed 取不到排班取固定班
* @return
*/
public KQGroupEntity getUserKQGroupInfo(String userId, String workDate, boolean containFixed) {
KQGroupEntity kqGroupEntity = null;
KQGroupComInfo kqGroupComInfo = new KQGroupComInfo();
try {
String groupid = Util.null2String(this.getKQGroupId(userId, workDate, containFixed));
if (groupid.length() > 0) {
kqGroupEntity = new KQGroupEntity();
kqGroupEntity.setId(groupid);
kqGroupEntity.setGroupname(kqGroupComInfo.getGroupname(groupid));
kqGroupEntity.setExcludeid(kqGroupComInfo.getExcludeid(groupid));
kqGroupEntity.setSubcompanyid(kqGroupComInfo.getSubcompanyid(groupid));
kqGroupEntity.setKqtype(kqGroupComInfo.getKqtype(groupid));
kqGroupEntity.setSerialids(kqGroupComInfo.getSerialids(groupid));
kqGroupEntity.setWeekday(kqGroupComInfo.getWeekday(groupid));
kqGroupEntity.setSignstart(kqGroupComInfo.getSignstart(groupid));
kqGroupEntity.setWorkhour(kqGroupComInfo.getWorkhour(groupid));
kqGroupEntity.setIsdelete(kqGroupComInfo.getIsdelete(groupid));
kqGroupEntity.setSignintype(kqGroupComInfo.getSignintype(groupid));
kqGroupEntity.setIpscope(kqGroupComInfo.getIpscope(groupid));
kqGroupEntity.setLocationcheck(kqGroupComInfo.getLocationcheck(groupid));
kqGroupEntity.setLocationcheckscope(kqGroupComInfo.getLocationcheckscope(groupid));
kqGroupEntity.setWificheck(kqGroupComInfo.getWificheck(groupid));
kqGroupEntity.setOutsidesign(kqGroupComInfo.getOutsidesign(groupid));
kqGroupEntity.setOutsignapprove(kqGroupComInfo.getOutsignApprove(groupid));
kqGroupEntity.setCalmethod(kqGroupComInfo.getCalmethod(groupid));
kqGroupEntity.setLocationshowaddress(kqGroupComInfo.getLocationshowaddress(groupid));
kqGroupEntity.setAbnormalremind(kqGroupComInfo.getAbnormalremind(groupid));
}
} catch (Exception e) {
kqLog.info(e);
}
return kqGroupEntity;
}
public void removeCache() {
super.removeCache();
}
public void setIsFormat(boolean isFormat){
this.isFormat = isFormat;
}
}

View File

@ -0,0 +1,499 @@
package com.engine.kq.biz;
import com.engine.integration.util.MyX509TrustManager;
import com.engine.kq.log.KQLog;
import net.sf.json.JSONObject;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.file.Prop;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.systeminfo.SystemEnv;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.*;
/**
* 节假日设置相关接口数据
*/
public class KQHolidaySetBiz {
private static KQLog logger = new KQLog();
/**
* 获取指定考勤组ID获取节假日设置数据
*
* @param resourceId 指定人员的ID
* @param year 指定年份
* @param month 指定月份 指定月份为空时查询指定年份一整年的数据
* @return
*/
public static List getGroupHolidaySetList(String groupId, String year, String month) {
List<Map<String, Object>> valueList = new ArrayList<Map<String, Object>>();
Map<String, Object> valueMap = new HashMap<String, Object>();
/*指定年月*/
String startDate = year;
String endDate = month;
if (month.length() == 0) {
startDate = year + "-01" + "-01";
endDate = year + "-12" + "-31";
} else if (month.length() == 1) {
startDate = year + "-0" + month + "-01";
endDate = year + "-0" + month + "-31";
} else if (month.length() == 2) {
startDate = year + "-" + month + "-01";
endDate = year + "-" + month + "-31";
}
RecordSet recordSet = new RecordSet();
KQGroupMemberComInfo kqGroupMemberComInfo = new KQGroupMemberComInfo();
KQHolidaySetComInfo holidaySetComInfo = new KQHolidaySetComInfo();
boolean isEnd = false;
for (String date = startDate; !isEnd; ) {
if (date.compareTo(endDate) >= 0) {
isEnd = true;
}
String changeType = holidaySetComInfo.getChangeType(groupId, date);
String holidayDesc = holidaySetComInfo.getHolidayDesc(groupId, date);
if (!changeType.equals("")) {
valueMap = new HashMap<String, Object>();
valueMap.put("date", date);
valueMap.put("name", holidayDesc);
valueMap.put("type", changeType);
valueList.add(valueMap);
}
date = DateUtil.getDate(date, 1);
}
return valueList;
}
/**
* 获取指定考勤组ID获取节假日设置数据
*
* @param resourceId 指定人员的ID
* @param year 指定年份
* @param month 指定月份 指定月份为空时查询指定年份一整年的数据
* @return
*/
public static List getKQHolidaySetList(String resourceId, String year, String month) {
List<Map<String, Object>> valueList = new ArrayList<Map<String, Object>>();
/*指定年月*/
String startDate = year;
String endDate = month;
if (month.length() == 0) {
startDate = year + "-01" + "-01";
endDate = year + "-12" + "-31";
} else if (month.length() == 1) {
startDate = year + "-0" + month + "-01";
endDate = year + "-0" + month + "-31";
} else if (month.length() == 2) {
startDate = year + "-" + month + "-01";
endDate = year + "-" + month + "-31";
}
valueList = getHolidaySetListByScope(resourceId, startDate, endDate);
return valueList;
}
/**
* 根据日期范围获取节假日数据
*
* @param resourceId 指定人员的ID
* @param startDate 指定日期范围的起点
* @param endDate 指定日期范围的终点
* @return
*/
public static List getHolidaySetListByScope(String resourceId, String startDate, String endDate) {
Map<String, Object> valueMap = new HashMap<String, Object>();
List<Map<String, Object>> valueList = new ArrayList<Map<String, Object>>();
KQGroupMemberComInfo kqGroupMemberComInfo = new KQGroupMemberComInfo();
KQHolidaySetComInfo holidaySetComInfo = new KQHolidaySetComInfo();
boolean isEnd = false;
for (String date = startDate; !isEnd; ) {
if (date.compareTo(endDate) >= 0) {
isEnd = true;
}
/*获取考勤组的ID因为考勤组有有效期所以需要传入日期*/
String groupId = kqGroupMemberComInfo.getKQGroupId(resourceId, date);
String changeType = holidaySetComInfo.getChangeType(groupId, date);
String holidayDesc = holidaySetComInfo.getHolidayDesc(groupId, date);
if (!changeType.equals("")&&!getWorkDay(resourceId, date)) {
valueMap = new HashMap<String, Object>();
valueMap.put("date", date);
valueMap.put("name", holidayDesc);
valueMap.put("type", changeType);
valueList.add(valueMap);
}
date = DateUtil.getDate(date, 1);
}
return valueList;
}
/**
* 判断某天是否是节假日公众假日+调配休息日
*
* @param resourceId 指定人员ID
* @param date 指定日期
* @return true-节假日false不是节假日
*/
public static boolean isHoliday(String resourceId, String date) {
return isHoliday(resourceId, date, false);
}
/**
* 判断某天是否是节假日公众假日+调配休息日+周末
*
* @param resourceId 指定人员ID
* @param date 指定日期
* @param containWeekend 是否包含周末 为true包含周末false不包含
* @return true-节假日false不是节假日
*/
public static boolean isHoliday(String resourceId, String date, boolean containWeekend) {
boolean flag = false;
if(getWorkDay(resourceId, date)){
return flag;
}
/*获取考勤组的ID因为考勤组有有效期所以需要传入日期*/
KQGroupMemberComInfo kqGroupMemberComInfo = new KQGroupMemberComInfo();
String groupId = kqGroupMemberComInfo.getKQGroupId(resourceId, date);
int changeType = getChangeType(groupId, date);
/*如果需要包含周末,判断传入的日期是不是周末*/
if (containWeekend && changeType != 2 && (DateUtil.getWeek(date) == 6 || DateUtil.getWeek(date) == 7)) {
flag = true;
}
if (changeType == 1 || changeType == 3) {
flag = true;
}
return flag;
}
/**
* 判断某天是否是节假日公众假日+调配休息日+周末
*
* @param resourceId 指定人员ID
* @param date 指定日期
* @return true-节假日false不是节假日
*/
public static boolean isDouble(String resourceId, String date) {
boolean flag = false;
/*获取考勤组的ID因为考勤组有有效期所以需要传入日期*/
KQGroupMemberComInfo kqGroupMemberComInfo = new KQGroupMemberComInfo();
String groupId = kqGroupMemberComInfo.getKQGroupId(resourceId, date);
int changeType = getChangeType(groupId, date);
if (changeType == 1 || changeType == 3) {
flag = true;
}
return flag;
}
/**
* 获取人员指定日期是否有排班的考勤排班(当考勤组属于排班制时)
*
* @param resourceId 指定人员的ID
* @param date 指定日期
* @return
*/
public static boolean getWorkDay(String resourceId, String date) {
boolean flag = false;
/*获取考勤组的ID因为考勤组有有效期所以需要传入日期*/
KQGroupMemberComInfo kqGroupMemberComInfo = new KQGroupMemberComInfo();
String groupId = kqGroupMemberComInfo.getKQGroupId(resourceId, date);
KQSettingsComInfo kqSettingsComInfo = new KQSettingsComInfo();
String holiday_is_priority = Util.null2String(kqSettingsComInfo.getMain_val("holiday_is_priority"),"0");
if("0".equals(holiday_is_priority)) {
return flag;
}
/*排班制不支持调配节假日数据*/
KQGroupComInfo kqGroupComInfo = new KQGroupComInfo();
String KQType = kqGroupComInfo.getKqtype(groupId);//考勤类型1-固定班制2-排班制3-自由班制
if (KQType.equals("2")) {
flag = true;
}
return flag;
}
/**
* 获取当前日期是何种类型(这里只考虑节假日设置)
*
* @param groupId 考勤组ID
* @param date 指定日期
* @return 1-节假日2-工作日3-休息日-1-没有设置过数据
*/
public static int getChangeType(String groupId, String date) {
int changeType = -1;//默认没有设置过节假日(节假日设置的类型1-公众假日2-调配工作日3-调配休息日)
KQHolidaySetComInfo kqHolidaySetComInfo = new KQHolidaySetComInfo();
String tmpChangetype = kqHolidaySetComInfo.getChangeType(groupId, date);
if(null != tmpChangetype){
changeType = Util.getIntValue(tmpChangetype, -1);
}
return changeType;
}
/**
* 获取调配工作日时的指定工作日(当考勤组不属于排班制时)
*
* @param resourceId 指定人员的ID
* @param date 指定日期
* @return
*/
public static int getRelatedDay(String resourceId, String date) {
int relatedDay = -1;
/*获取考勤组的ID因为考勤组有有效期所以需要传入日期*/
KQGroupMemberComInfo kqGroupMemberComInfo = new KQGroupMemberComInfo();
String groupId = kqGroupMemberComInfo.getKQGroupId(resourceId, date);
/*排班制不支持调配节假日数据*/
KQGroupComInfo kqGroupComInfo = new KQGroupComInfo();
String KQType = kqGroupComInfo.getKqtype(groupId);//考勤类型1-固定班制2-排班制3-自由班制
if (KQType.equals("2")) {
return relatedDay;
}
/*只有当调配工作日时才有对应工作日*/
KQHolidaySetComInfo kqHolidaySetComInfo = new KQHolidaySetComInfo();
int changeType = Util.getIntValue(kqHolidaySetComInfo.getChangeType(groupId, date), -1);
if (changeType == 2) {
relatedDay = Util.getIntValue(kqHolidaySetComInfo.getRelatedDay(groupId, date), 0);
}
return relatedDay;
}
/**
* 指定的考勤组初始化节假日设置数据(只初始化固定班制和自由班制)
*
* @param groupIds 指定考勤组ID(多个ID之间用,分隔)
* @param year 指定年份
* @return
*/
public static Map<String, Object> initHolidaySet(String groupIds, String year, User user) {
Map<String, Object> resultMap = new HashMap<String, Object>();
List<String> errInfoList = new ArrayList<String>();//错误信息集合
/**
* 调用网上的节假日API数据格式如下(不是JSON字符串)(此后如果原来的节假日API不能用了只要调整将新的API接口调整成如下格式即可)
* status1-成功0-失败
* sketch'简要描述错误原因'
* holidayList[{holidayDate:'',changeType:'',holidayDesc:''},,{holidayDate:'',changeType:'',holidayDesc:''}]
*/
String url = Prop.getInstance().getPropValue("kq_settings", "KQHolidaySetUrl");
Map<String, Object> tempMap = httpRequest(url +"?year="+year+"&key="+Util.getEncrypt(Util.getRandom()), user);
if ("0".equals((String) tempMap.get("status"))) {
resultMap.put("status", "0");
resultMap.put("sketch", (String) tempMap.get("sketch"));
return resultMap;
}
List<String> holidayDateList = new ArrayList<String>();
try {
List<String> groupIdList = Util.TokenizerString(groupIds, ",");//考勤组ID集合
for (int i = 0; i < groupIdList.size(); i++) {
String groupId = groupIdList.get(i);
/**
* 预先加载此考勤组已经调整了哪些日期了如果某日期在初始化之前已经调整过了删除掉原来的数据插入新的数据
*/
List<String> dateList = new ArrayList<String>();
KQHolidaySetComInfo kqHolidaySetComInfo = new KQHolidaySetComInfo();
kqHolidaySetComInfo.setTofirstRow();
while (kqHolidaySetComInfo.next()) {
if (kqHolidaySetComInfo.getGroupId().equals(groupId)) {
dateList.add(kqHolidaySetComInfo.getHolidayDate());
}
}
/**
* 预先加载固定班制周一~周日这一周中一天开始上班的是周几
*/
int relatedDay = 0;
for (int x = 0; x < 7; x++) {
KQFixedSchedulceComInfo kqFixedSchedulceComInfo = new KQFixedSchedulceComInfo();
String serialId = Util.null2String(kqFixedSchedulceComInfo.getSerialid(groupId, x));
if (!serialId.equals("")) {
relatedDay = x;
break;
}
}
/**
* 初始化改考勤组的节假日数据(只初始化)
*/
boolean flag = true;
RecordSet recordSet = new RecordSet();
KQGroupComInfo kqGroupComInfo = new KQGroupComInfo();
List<Map<String, Object>> holidayList = (List<Map<String, Object>>) tempMap.get("holidayList");
Map<String, Object> holidayMap = new HashMap<String, Object>();
if(holidayList.size()>0){
String tmpsql = "delete from kq_HolidaySet where groupId='"+groupId+"' and holidayDate>='"+year+"-01-01' and holidayDate<='"+year+"-12-31' ";
recordSet.executeUpdate(tmpsql);
}
for (int j = 0; j < holidayList.size(); j++) {
holidayMap = holidayList.get(j);
String holidayDate = year + "-" + (String) holidayMap.get("holidayDate");
if (!holidayDateList.contains(holidayDate)) {
holidayDateList.add(holidayDate);
}
int changeType = (int) holidayMap.get("changeType");
if (kqGroupComInfo.getKqtype(groupId).equals("2")&&changeType == 2 ) {
//排班制的考勤组不能初始化调配工作日
continue;
}
String holidayDesc = (String) holidayMap.get("holidayDesc");
if (dateList.contains(holidayDate)) {
String deleteSql = "delete from kq_HolidaySet where groupId=? and holidayDate=?";
recordSet.executeUpdate(deleteSql, groupId, holidayDate);
}
String sql = "insert into kq_HolidaySet(groupId,holidayDate,changeType,holidayDesc,relatedDay) values(?,?,?,?,?)";
flag = recordSet.executeUpdate(sql, groupId, holidayDate, changeType, holidayDesc, relatedDay);
if (!flag) {
errInfoList.add(SystemEnv.getHtmlLabelName(5056701, user.getLanguage()).replace("$groupName$", kqGroupComInfo.getGroupname(groupId)).replace("$holidayDate$", holidayDate));
}
}
}
/**
* 如果没有错误信息则代表初始化成功
*/
if (errInfoList.size() > 0) {
resultMap.put("status", "0");
resultMap.put("sketch", SystemEnv.getHtmlLabelName(125960, user.getLanguage()));
resultMap.put("description", errInfoList);
} else {
resultMap.put("status", "1");
resultMap.put("sketch", SystemEnv.getHtmlLabelName(20196, user.getLanguage()));
}
} catch (Exception e) {
resultMap.put("status", "0");
resultMap.put("sketch", SystemEnv.getHtmlLabelName(382661, user.getLanguage()));
resultMap.put("desscription", errInfoList);
} finally {
/*刷新缓存*/
KQHolidaySetComInfo kqHolidaySetComInfo = new KQHolidaySetComInfo();
kqHolidaySetComInfo.removeCache();
/*刷新考勤报表*/
logger.info("初始化节假日数据格式化考勤报表。groupIdList=" + com.alibaba.fastjson.JSONObject.toJSONString(groupIds) +
"。holidayDateList=" + com.alibaba.fastjson.JSONObject.toJSONString(holidayDateList));
List<String> groupIdList = Util.TokenizerString(groupIds, ",");//考勤组ID集合
new KQHolidaySetThread(groupIdList,holidayDateList).start();
}
return resultMap;
}
/**
* 请求网络上的节假日API接口获取节假日设置数据
*
* @param requestUrl
* @return
*/
private static Map<String, Object> httpRequest(String requestUrl, User user) {
Map<String, Object> resultMap = new HashMap<String, Object>();
//buffer用于接受返回的字符
StringBuffer buffer = new StringBuffer();
try {
TrustManager[] tm = {new MyX509TrustManager()};
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url= new URL(null, requestUrl, new sun.net.www.protocol.https.Handler());
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
httpUrlConn.setRequestMethod("GET");
httpUrlConn.connect();
//获得输入
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
//将bufferReader的值给放到buffer里
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
//关闭bufferReader和输入流
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream = null;
//断开连接
httpUrlConn.disconnect();
/**
* 解析JSON字符串
*/
String jsonStr = buffer.toString();
JSONObject jsonObject = JSONObject.fromObject(jsonStr).getJSONObject("data");
int code = jsonObject.optInt("code");//0服务正常-1服务出错
if (code != 0) {
//初始化节假日失败获取网络服务出错
resultMap.put("status", "0");
resultMap.put("sketch", SystemEnv.getHtmlLabelName(520011, user.getLanguage()));
return resultMap;
}
JSONObject holiday = jsonObject.getJSONObject("holiday");
if (holiday.size() == 0) {
//初始化节假日失败暂未获取到所选年份的节假日数据
resultMap.put("status", "0");
resultMap.put("sketch", SystemEnv.getHtmlLabelName(505673, user.getLanguage()));
return resultMap;
}
Map<String, Object> holidayMap = new HashMap<String, Object>();
List<Map<String, Object>> holidayList = new ArrayList<Map<String, Object>>();
Iterator iterator = holiday.keys();
while (iterator.hasNext()) {
holidayMap = new HashMap<String, Object>();
String holidayDate = (String) iterator.next();
holidayMap.put("holidayDate", holidayDate);//日期
JSONObject detailInfo = holiday.getJSONObject(holidayDate);
int wage = detailInfo.optInt("wage");
if (wage == 1) {
holidayMap.put("changeType", 2);//调配工作日
} else if (wage == 2) {
holidayMap.put("changeType", 3);//调配休息日
} else if (wage == 3) {
holidayMap.put("changeType", 1);//公众假日
}
String holidayDesc = detailInfo.getString("name");
holidayMap.put("holidayDesc", holidayDesc);//说明
holidayList.add(holidayMap);
}
resultMap.put("status", "1");
resultMap.put("sketch", SystemEnv.getHtmlLabelName(505674, user.getLanguage()));
resultMap.put("holidayList", holidayList);
} catch (Exception e) {
e.printStackTrace();
resultMap.put("status", "0");
resultMap.put("sketch", SystemEnv.getHtmlLabelName(520011, user.getLanguage()));
return resultMap;
}
return resultMap;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,319 @@
package com.engine.kq.biz;
import com.engine.kq.wfset.util.KQAttFlowCheckUtil;
import weaver.cache.CacheBase;
import weaver.cache.CacheColumn;
import weaver.cache.CacheColumnType;
import weaver.cache.PKColumn;
import weaver.general.Util;
import weaver.systeminfo.SystemEnv;
/**
* 假期规则缓存类
*/
public class KQLeaveRulesComInfo extends CacheBase {
/**
* 数据来源
*/
protected static String TABLE_NAME = "kq_leaveRules";
/**
* sql中的where信息不要以where开始
*/
protected static String TABLE_WHERE = " (isDelete is null or isDelete !=1) ";
/**
* sql中的order by信息不要以order by开始
*/
protected static String TABLE_ORDER = " showOrder,id ";
/**
* 主键
*/
@PKColumn(type = CacheColumnType.NUMBER)
protected static String PK_NAME = "id";
/**
* 假期规则名称
*/
@CacheColumn(name = "leaveName")
protected static int leaveName;
@CacheColumn(name = "SchevacationON")
protected static int SchevacationON;
@CacheColumn(name = "Schevacation")
protected static int Schevacation;
/**
* 是否禁用0-未禁用1-已禁用
*/
@CacheColumn(name = "isEnable")
protected static int isEnable;
/**
* 应用范围0-总部1-分部
*/
@CacheColumn(name = "scopeType")
protected static int scopeType;
/**
* 分部ID(当应用范围为分部时选择的分部ID)
*/
@CacheColumn(name = "scopeValue")
protected static int scopeValue;
/**
* 最小请假单位
* 1-按天请假
* 2-按半天请假
* 3-按小时请假
* 4-按整天请假
* 其他无效数据
*/
@CacheColumn(name = "minimumUnit")
protected static int minimumUnit;
/**
* 余额单位变更时的换算比例
* XX小时=1天
*/
@CacheColumn(name = "proportion")
protected static int proportion;
/**
* 日折算时长1天=XX小时
*/
@CacheColumn(name = "hoursToDay")
protected static int hoursToDay;
/**
* 按自然日计算请假时长0-不排除1-排除节假日2-排除休息日3-排除节假日和休息日
*/
@CacheColumn(name = "filterHolidays")
protected static int filterHolidays;
/**
* 计算请假时长方式
* 1-按工作日计算请假时长
* 2-按自然日计算请假时长
*/
@CacheColumn(name = "computingMode")
protected static int computingMode;
/**
* 启用假期余额
* 0-不启用
* 1-启用
*/
@CacheColumn(name = "balanceEnable")
protected static int balanceEnable;
/**
* 假期类型标识
*/
@CacheColumn(name = "leaveCode")
protected static int leaveCode;
/**
* 半天单位 时间选择方式1-下拉框选择 2-具体时间
*/
@CacheColumn(name = "timeselection")
protected static int timeselection;
/**
* 折算方式 1是四舍五入 2是向上取整 3是向下取整
*/
@CacheColumn(name = "conversion")
protected static int conversion;
/**
* 流程重复时段 1是重复 0是不重复默认不重复
*/
@CacheColumn(name = "repeat_time")
protected static int repeatTime;
public String getId(){
return (String)getRowValue(PK_INDEX);
}
public String getLeaveName() {
return (String)getRowValue(leaveName);
}
public String getLeaveName(String key){
return (String) getValue(leaveName,key);
}
public String getSchevacationON() {
return (String)getRowValue(SchevacationON);
}
public String getSchevacationON(String key){
return (String) getValue(SchevacationON,key);
}
public String getSchevacation() {
return (String)getRowValue(Schevacation);
}
public String getSchevacation(String key){
return (String) getValue(Schevacation,key);
}
public String getIsEnable() {
return (String)getRowValue(isEnable);
}
public String getIsEnable(String key){
return (String) getValue(isEnable,key);
}
public String getScopeType() {
return (String)getRowValue(scopeType);
}
public String getScopeType(String key){
return (String) getValue(scopeType,key);
}
public String getScopeValue() {
return (String)getRowValue(scopeValue);
}
public String getScopeValue(String key){
return (String) getValue(scopeValue,key);
}
public String getMinimumUnit() {
return (String)getRowValue(minimumUnit);
}
public String getMinimumUnit(String key){
return (String)getValue(minimumUnit,key);
}
public String getProportion() {
return (String)getRowValue(proportion);
}
public String getProportion(String key){
return (String)getValue(proportion,key);
}
public String getHoursToDay() {
return (String)getRowValue(hoursToDay);
}
public String getHoursToDay(String key){
return (String)getValue(hoursToDay,key);
}
public String getFilterHolidays() {
return (String)getRowValue(filterHolidays);
}
public String getFilterHolidays(String key){
return (String)getValue(filterHolidays,key);
}
public String getComputingMode() {
return (String)getRowValue(computingMode);
}
public String getComputingMode(String key){
return (String)getValue(computingMode,key);
}
public String getBalanceEnable() {
return (String)getRowValue(balanceEnable);
}
public String getBalanceEnable(String key){
return (String)getValue(balanceEnable,key);
}
public String getLeaveCode() {
return (String)getRowValue(leaveCode);
}
public String getLeaveCode(String key){
return (String)getValue(leaveCode,key);
}
public String getTimeSelection() {
String value = (String) getRowValue(timeselection);
if (value == null || value.equals("")) {
value = "1";
}
return value;
}
public String getTimeSelection(String key) {
String value = (String) getValue(timeselection, key);
if (value == null || value.equals("")) {
value = "1";
}
return value;
}
public String getConversion() {
return (String)getRowValue(conversion);
}
public String getConversion(String key){
return (String)getValue(conversion,key);
}
public String getRepeatTime() {
return (String)getRowValue(repeatTime);
}
public String getRepeatTime(String key){
return (String)getValue(repeatTime,key);
}
public String getUnitName(int language){
String unitName = "";//单位名称/小时
int minimumUnit = Util.getIntValue(getMinimumUnit(),1);
if (minimumUnit == 1 || minimumUnit == 2 || minimumUnit == 4) {
unitName = SystemEnv.getHtmlLabelName(389325, language);//()
} else {
unitName = SystemEnv.getHtmlLabelName(389326, language);//(小时)
}
return unitName;
}
public String getUnitName(String key,int language){
String unitName = "";//单位名称/小时
int minimumUnit = Util.getIntValue(getMinimumUnit(key),1);
if (minimumUnit == 1 || minimumUnit == 2 || minimumUnit == 4) {
unitName = SystemEnv.getHtmlLabelName(389325, language);//()
} else {
unitName = SystemEnv.getHtmlLabelName(389326, language);//(小时)
}
// KQTransMethod method = new KQTransMethod();
// unitName = "("+method.getMinimumUnitName4Browser(""+minimumUnit, ""+language)+")";
return unitName;
}
public String getUnitNameNew(String key,int language){
String unitName = "";//单位名称/小时
int minimumUnit = Util.getIntValue(getMinimumUnit(key),1);
if (minimumUnit == 1 || minimumUnit == 2 || minimumUnit == 4) {
unitName = SystemEnv.getHtmlLabelName(389325, language);//()
} else {
unitName = SystemEnv.getHtmlLabelName(389326, language);//(小时)
}
return unitName;
}
@Override
public void removeCache() {
super.removeCache();
KQAttFlowCheckUtil kqAttFlowCheckUtil = new KQAttFlowCheckUtil();
kqAttFlowCheckUtil.initLeaveUnit();
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,877 @@
package com.engine.kq.biz;
import com.alibaba.fastjson.JSONObject;
import com.engine.kq.bean.ImportSetting;
import com.engine.kq.entity.KQScheduleSignEntity;
import com.engine.kq.timer.KQQueue;
import com.engine.kq.timer.KQTaskBean;
import com.engine.kq.util.KQDurationCalculatorUtil;
import com.engine.kq.wfset.util.SplitActionUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import weaver.common.DateUtil;
import weaver.common.StringUtil;
import weaver.conn.BatchRecordSet;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetDataSource;
import weaver.file.ImageFileManager;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.common.Tools;
import weaver.systeminfo.SystemEnv;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
public class KQScheduleSignImport extends BaseBean {
private List errorInfo = new ArrayList();
private String fileName = "";
private String keyField = "";
private int userlanguage = 7; //登录语言
public KQScheduleSignImport() {
}
public KQScheduleSignImport(Map<String, Object> params) {
this.keyField = Util.null2String(params.get("keyField"));
if (this.keyField.length() == 0) this.keyField = "workcode";
this.fileName = Util.null2String(params.get("excelfile"));
}
/**
* 私有方法获取Excel表格对应表格中的数据
*
* @param cell Excel表格的行
* @param row Excel表格的列
* @return Excel表格对应表格中的数据
*/
private String getCellValue(HSSFCell cell, HSSFRow row) {
if (cell == null) return "";
String cellValue = "";
switch (cell.getCellType()) {
case NUMERIC:
if (HSSFDateUtil.isCellDateFormatted(cell)) {
SimpleDateFormat sdf = null;
if (cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("h:mm:ss")) {
sdf = new SimpleDateFormat("HH:mm:ss");
} else {// 日期
sdf = new SimpleDateFormat("yyyy-MM-dd");
}
Date date = cell.getDateCellValue();
cellValue = sdf.format(date);
} else {
cellValue = new java.text.DecimalFormat("0").format(cell.getNumericCellValue());
}
break;
case STRING:
cellValue = cell.getStringCellValue();
break;
case FORMULA:
cellValue = (DateFormat.getDateInstance().format((cell.getDateCellValue()))).toString();
break;
default:
break;
}
return cellValue;
}
/**
* 将Excel表格中的数据导入数据库
*/
public synchronized void ExcelToDB() {
String sql = "";
BatchRecordSet bRs = new BatchRecordSet();
List<List<Object>> lsParams = new ArrayList<>();
List<Object> params = null;
List<List<Object>> lsDelParams = new ArrayList<>();
List<Object> delParams = null;
List<String> lsFormatData = new ArrayList<>();
List<List<Object>> lsFormatParams = new ArrayList<>();
List<Object> formatParams = null;
Map<String,String> lsmap = new HashMap<>();
try {
ImageFileManager manager = new ImageFileManager();
manager.getImageFileInfoById(Util.getIntValue(this.fileName));
HSSFWorkbook workbook = new HSSFWorkbook(new POIFSFileSystem(manager.getInputStream()));
HSSFSheet sheet = workbook.getSheetAt(0);
HSSFRow row = null;
Map<String, Map<String, String>> users = getUsers(this.userlanguage);
Map<String, String> loginidMap = users.get("loginidMap");
Map<String, String> lastnameMap = users.get("lastnameMap");
Map<String, String> workcodeMap = users.get("workcodeMap");
int rowsNum = sheet.getLastRowNum();
for (int i = 1; i < rowsNum + 1; i++) {
row = sheet.getRow(i);
if (row == null || !ScanRow(row)) continue;
int tmpUserId = 0;
String tmpLoginid = "";
String tmpWorkcode = "";
String tmpLastname = "";
String tmpSigndate = "";
String tmpSigntime = "";
String tmpClientaddress = "";
int tmpIsincom = 1;
String tmpLongitude = "";
String tmpLatitude = "";
String tmpAddr = "";
for (int j = 0; j < row.getLastCellNum(); j++) {
if (j == 0) {
tmpLoginid = Util.null2String(this.getCellValue(row.getCell((short) j), row)).trim();
} else if (j == 1) {
tmpWorkcode = Util.null2String(this.getCellValue(row.getCell((short) j), row)).trim();
} else if (j == 2) {
tmpLastname = Util.null2String(this.getCellValue(row.getCell((short) j), row)).trim();
} else if (j == 3) {
tmpSigndate = Util.null2String(this.getCellValue(row.getCell((short) j), row));
if (tmpSigndate.length() == 0) continue;
SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar calendar = Calendar.getInstance();
calendar.setTime(SDF.parse(tmpSigndate + " 00:00:00"));
tmpSigndate = TimeUtil.getFormartString(calendar, "yyyy-MM-dd");
} else if (j == 4) {
tmpSigntime = Util.null2String(this.getCellValue(row.getCell((short) j), row)).trim();
if (tmpSigntime.length() == 0) continue;
if (tmpSigntime.length() > 0) {
String[] a = tmpSigntime.split(":");
if (a != null && a.length < 3) {
tmpSigntime += ":00";
}
}
SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar calendar = Calendar.getInstance();
calendar.setTime(SDF.parse("1999-01-01 " + tmpSigntime));
tmpSigntime = TimeUtil.getFormartString(calendar, "HH:mm:ss");
} else if (j == 5) {
tmpClientaddress = Util.null2String(this.getCellValue(row.getCell((short) j), row));
}
}
if (tmpLoginid.length() == 0 && tmpWorkcode.length() == 0 && tmpLastname.length() == 0) continue;
if (this.keyField.equals("loginid")) {
// tmpUserId = getUserId(tmpLoginid);
tmpUserId = StringUtil.parseToInt(loginidMap.get(tmpLoginid), 0);
} else if (this.keyField.equals("workcode")) {
// tmpUserId = getUserId(tmpWorkcode);
tmpUserId = StringUtil.parseToInt(workcodeMap.get(tmpWorkcode), 0);
} else if (this.keyField.equals("lastname")) {
// tmpUserId = getUserId(tmpLastname);
tmpUserId = StringUtil.parseToInt(lastnameMap.get(tmpLastname), 0);
}
if (tmpUserId <= 0) continue;
params = new ArrayList<>();
params.add(tmpUserId);
params.add(1);
params.add(tmpSigndate);
params.add(tmpSigntime);
params.add(tmpClientaddress);
params.add(tmpIsincom);
params.add(1);
params.add("importExcel");
params.add(tmpLongitude);
params.add(tmpLatitude);
params.add(tmpAddr);
lsParams.add(params);
String belongDate = getBelongDate(new User(tmpUserId), tmpSigndate, tmpSigntime);
String formatData = tmpUserId + "|" + tmpSigndate+ "|" + belongDate;
//Arraylist的底层源码采用的indexOf接口有性能问题单独搞下
// if (!lsFormatData.contains(formatData)) {
// lsFormatData.add(formatData);
// }
//替换为hashmap性能会高很多
if(!lsmap.containsKey(formatData)){
lsmap.put(formatData,formatData);
}
}
Map<String, List<String>> overtimeMap = Maps.newHashMap();
List<String> overtimeList = Lists.newArrayList();
//刷新报表数据
if(null != lsmap){
for(Map.Entry<String,String> entry : lsmap.entrySet()){
String mapKey = Util.null2String(entry.getKey());
String mapValue = entry.getValue();
formatParams = new ArrayList<>();
String[] formatData = Util.splitString(mapValue, "|");
// for (int i = 0; lsFormatData != null && i < lsFormatData.size(); i++) {
// formatParams = new ArrayList<>();
// String[] formatData = Util.splitString(lsFormatData.get(i), "|");
String date_1 = DateUtil.addDate(formatData[1], -1);
formatParams.add(formatData[0]);
formatParams.add(date_1);
lsFormatParams.add(formatParams);
formatParams = new ArrayList<>();
formatParams.add(formatData[0]);
formatParams.add(formatData[1]);
lsFormatParams.add(formatParams);
delParams = new ArrayList<>();
delParams.add(formatData[0]);
delParams.add(formatData[1]);
lsDelParams.add(delParams);
String resourceId = formatData[0];
String kqdate = formatData[1];
String belongDate = formatData[2];
if (overtimeMap.containsKey(resourceId)) {
List<String> tmp_overtimeList = overtimeMap.get(resourceId);
if (!tmp_overtimeList.contains(kqdate)) {
tmp_overtimeList.add(kqdate);
if(!kqdate.equals(belongDate)) {
tmp_overtimeList.add(belongDate);
}
}
} else {
if (!overtimeList.contains(kqdate)) {
overtimeList.add(kqdate);
if(!kqdate.equals(belongDate)) {
overtimeList.add(belongDate);
}
}
overtimeMap.put(resourceId, overtimeList);
}
}
}
//删除本次同步数据
sql = " delete from hrmschedulesign where signfrom='importExcel' and userid =? and signdate = ? ";
bRs.executeBatchSql(sql, lsDelParams);
sql = " insert into HrmScheduleSign (userid, usertype, signdate, signtime, clientaddress, isincom, isimport, signfrom, longitude, latitude, addr) "
+ " values(?,?,?,?,?,?,?,?,?,?,?)";
bRs.executeBatchSql(sql, lsParams);
new KQFormatBiz().format(lsFormatParams, 15);
//处理加班生成
List<KQTaskBean> tasks = new ArrayList<>();
for (Map.Entry<String, List<String>> mme : overtimeMap.entrySet()) {
String resid = mme.getKey();
List<String> overList = mme.getValue();
for (String date : overList) {
SplitActionUtil.pushOverTimeTasks(date, date, resid, tasks);
}
}
if (!tasks.isEmpty()) {
KQQueue.writeTasks(tasks);
}
} catch (Exception e) {
writeLog(e);
}
}
/**
* 验证数据的合法性
*/
public boolean ScanRow(HSSFRow row) {
boolean canImport = true;
try {
int userid = 0;
String loginid = "", workcode = "", lastname = "";
for (int j = 0; j < row.getLastCellNum(); j++) {
if (j == 0) {
//验证loginid
loginid = this.getCellValue(row.getCell((short) j), row);
} else if (j == 1) {
//验证workcode
workcode = this.getCellValue(row.getCell((short) j), row);
} else if (j == 2) {
//验证用户名
lastname = this.getCellValue(row.getCell((short) j), row);
} else if (j == 3) {
//验证考勤时间
String signdate = Util.null2String(this.getCellValue(row.getCell((short) j), row));
String signtime = Util.null2String(this.getCellValue(row.getCell((short) (j + 1)), row)).trim();
if (signdate.length() == 0) {
canImport = false;
}
if (signtime.length() == 0) {
canImport = false;
}
if (signtime.length() > 0) {
String[] a = signtime.split(":");
if (a != null && a.length < 3) {
signtime += ":00";
}
}
String signdatetime = signdate + " " + signtime;
if (signdate.length() > 0 && signtime.length() > 0 && checkData(signdatetime, "datetime"))
canImport = false;
}
}
if (this.keyField.equals("loginid")) {
if (loginid.length() == 0) canImport = false;
userid = getUserId(loginid);
} else if (this.keyField.equals("workcode")) {
if (workcode.length() == 0) canImport = false;
userid = getUserId(workcode);
} else if (this.keyField.equals("lastname")) {
if (lastname.length() == 0) canImport = false;
userid = getUserId(lastname);
}
if (userid == 0) {
canImport = false;
}
} catch (Exception e) {
writeLog(e);
}
return canImport;
}
/**
* 验证数据的合法性
*/
public List ScanFile() {
try {
ImageFileManager manager = new ImageFileManager();
manager.getImageFileInfoById(Util.getIntValue(this.fileName));
HSSFWorkbook workbook = new HSSFWorkbook(new POIFSFileSystem(manager.getInputStream()));
HSSFSheet sheet = workbook.getSheetAt(0);
HSSFRow row = null;
int number = 0;
int rowsNum = sheet.getLastRowNum();
for (int i = 1; i < rowsNum + 1; i++) {
row = sheet.getRow(i);
if (row == null) continue;
number = i+1;
int userid = 0;
String loginid = "", workcode = "", lastname = "";
for (int j = 0; j < row.getLastCellNum(); j++) {
if (j == 0) {
//验证loginid
loginid = Util.null2String(this.getCellValue(row.getCell((short) j), row)).trim();
} else if (j == 1) {
//验证workcode
workcode = Util.null2String(this.getCellValue(row.getCell((short) j), row)).trim();
} else if (j == 2) {
//验证用户名
lastname = Util.null2String(this.getCellValue(row.getCell((short) j), row)).trim();
} else if (j == 3) {
//验证考勤时间
HSSFCell cell3 = row.getCell((short) j);
String signdate = Util.null2String(this.getCellValue(cell3, row));
HSSFCell cell4 = row.getCell((short) (j + 1));
String signtime = Util.null2String(this.getCellValue(cell4, row)).trim();
if (signtime.length() > 0) {
String[] a = signtime.split(":");
if (a != null && a.length < 3) {
signtime += ":00";
}
}
if (this.keyField.equals("loginid")) {
if (loginid.length() == 0) {
errorInfo.add(SystemEnv.getHtmlLabelName(15323, userlanguage) + " " + number + " " + SystemEnv.getHtmlLabelName(503585, userlanguage));
} else {
userid = getUserId(loginid);
if (userid == 0) {
errorInfo.add(SystemEnv.getHtmlLabelName(15323, userlanguage) + " " + number + " " + SystemEnv.getHtmlLabelName(503586, userlanguage));
}
}
} else if (this.keyField.equals("workcode")) {
if (workcode.length() == 0) {
errorInfo.add(SystemEnv.getHtmlLabelName(15323, userlanguage) + " " + number + " " + SystemEnv.getHtmlLabelName(83770, userlanguage));
} else {
userid = getUserId(workcode);
if (userid == 0) {
errorInfo.add(SystemEnv.getHtmlLabelName(15323, userlanguage) + " " + number + " " + SystemEnv.getHtmlLabelName(83772, userlanguage));
}
}
} else if (this.keyField.equals("lastname")) {
if (lastname.length() == 0) {
errorInfo.add(SystemEnv.getHtmlLabelName(15323, userlanguage) + " " + number + " " + SystemEnv.getHtmlLabelName(83774, userlanguage));
} else {
userid = getUserId(lastname);
if (userid == 0) {
errorInfo.add(SystemEnv.getHtmlLabelName(15323, userlanguage) + " " + number + " " + SystemEnv.getHtmlLabelName(83777, userlanguage));
}
}
}
if (signdate.length() == 0) {
errorInfo.add(SystemEnv.getHtmlLabelName(15323, userlanguage) + " " + number + " " + SystemEnv.getHtmlLabelName(83762, userlanguage));
}
if (signtime.length() == 0) {
errorInfo.add(SystemEnv.getHtmlLabelName(15323, userlanguage) + " " + number + " " + SystemEnv.getHtmlLabelName(83763, userlanguage));
}
String signdatetime = signdate + " " + signtime;
if (signdate.length() > 0 && signtime.length() > 0 && checkData(signdatetime, "datetime"))
errorInfo.add(SystemEnv.getHtmlLabelName(15323, userlanguage) + " " + number + " " + SystemEnv.getHtmlLabelName(83768, userlanguage));
}
}
}
} catch (Exception e) {
writeLog(e);
errorInfo.add(SystemEnv.getHtmlLabelName(83779, userlanguage));
}
return errorInfo;
}
/**
* 判断数据类型
*
* @param value
* @param type
* @return
*/
public static boolean checkData(String value, String type) {
boolean boo = false;
if (type.equals("int")) {
try {
Integer.parseInt(value);
} catch (Exception e) {
boo = true;
}
} else if (type.equals("float")) {
try {
Float.parseFloat(value);
} catch (Exception e) {
boo = true;
}
} else if (type.equals("datetime")) {
try {
SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar calendar = Calendar.getInstance();
calendar.setTime(SDF.parse(value));
} catch (ParseException e) {
boo = true;
}
}
return boo;
}
public int getUserId(String val) {
int userid = 0;
RecordSet rs = new RecordSet();
String sql = "";
if (Util.isEnableMultiLang()) {
if (rs.getDBType().equalsIgnoreCase("sqlserver")) {
sql = "select id from hrmresource where ltrim(rtrim(dbo.convToMultiLang(ltrim(rtrim(" + keyField + "))," + userlanguage + ")))='" + Util.null2String(val).trim() + "'";
} else {
sql = "select id from hrmresource where ltrim(rtrim(convToMultiLang(ltrim(rtrim(" + keyField + "))," + userlanguage + ")))='" + Util.null2String(val).trim() + "'";
}
} else {
sql = "select id from hrmresource where ltrim(rtrim( " + keyField + "))='" + Util.null2String(val).trim() + "'";
}
rs.execute(sql);
if (rs.next()) {
userid = rs.getInt("id");
}
return userid;
}
public static int getUserId(String val, String keyField, int userlanguage) {
int userid = 0;
RecordSet rs = new RecordSet();
String sql = "";
if (Util.isEnableMultiLang()) {
if (rs.getDBType().equalsIgnoreCase("sqlserver")) {
sql = "select id from hrmresource where ltrim(rtrim(dbo.convToMultiLang(ltrim(rtrim(" + keyField + "))," + userlanguage + ")))='" + Util.null2String(val).trim() + "'";
} else {
sql = "select id from hrmresource where ltrim(rtrim(convToMultiLang(ltrim(rtrim(" + keyField + "))," + userlanguage + ")))='" + Util.null2String(val).trim() + "'";
}
} else {
sql = "select id from hrmresource where ltrim(rtrim(" + keyField + "))='" + Util.null2String(val).trim() + "'";
}
rs.execute(sql);
if (rs.next()) {
userid = rs.getInt("id");
}
return userid;
}
public void importData(String beginDate, String endDate, boolean isSyn) throws Exception {
writeLog("考勤机同步:importData:开始>>>>>>beginDate>>"+beginDate+">>>>>endDate>>>>"+endDate+">>>>>>"+DateUtil.getFullDate());
RecordSet rs = new RecordSet();
RecordSet delrs = new RecordSet();
String sql = "";
endDate = Tools.getDate(endDate, 1);
BatchRecordSet bRs = new BatchRecordSet();
List<List<Object>> lsParams = new ArrayList<>();
List<Object> params = null;
List<List<Object>> lsDelParams = new ArrayList<>();
List<Object> delParams = null;
List<String> lsFormatData = new ArrayList<>();
List<List<Object>> lsFormatParams = new ArrayList<>();
List<Object> formatParams = null;
Map<String, Map<String, String>> users = getUsers(this.userlanguage);
Map<String, String> loginidMap = users.get("loginidMap");
Map<String, String> lastnameMap = users.get("lastnameMap");
Map<String, String> workcodeMap = users.get("workcodeMap");
List<String> keymap = new ArrayList<>();
List<ImportSetting> lsImportSetting = new ArrayList<>();
ImportSetting importSetting = null;
sql = " select datasourceid, loginid, workcode, lastname, signdate, signtime, tablename, clientaddress,longitude,latitude,addr,memo " +
" from HrmScheduleSignSet ";
rs.execute(sql);
while (rs.next()) {
importSetting = new ImportSetting();
importSetting.setDatasourceid(Util.null2String(rs.getString("datasourceid")).trim());
importSetting.setLoginid(Util.null2String(rs.getString("loginid")).trim());
importSetting.setWorkcode(Util.null2String(rs.getString("workcode")).trim());
importSetting.setLastname(Util.null2String(rs.getString("lastname")).trim());
importSetting.setSigndate(Util.null2String(rs.getString("signdate")).trim());
importSetting.setSigntime(Util.null2String(rs.getString("signtime")).trim());
importSetting.setTablename(Util.null2String(rs.getString("tablename")).trim());
importSetting.setClientaddress(Util.null2String(rs.getString("clientaddress")).trim());
importSetting.setLongitude(Util.null2String(rs.getString("longitude")).trim());
importSetting.setLatitude(Util.null2String(rs.getString("latitude")).trim());
importSetting.setAddr(Util.null2String(rs.getString("addr")).trim());
importSetting.setMemo(Util.null2String(rs.getString("memo")).trim());
lsImportSetting.add(importSetting);
}
List<KQScheduleSignEntity> lsKQScheduleSignData = new ArrayList<>();
KQScheduleSignEntity kqScheduleSignData = null;
for (int i = 0; lsImportSetting != null && i < lsImportSetting.size(); i++) {
// DataSource ds = null;
// Connection conn = null;
try {
importSetting = lsImportSetting.get(i);
String datasourceid = importSetting.getDatasourceid();
String loginid = importSetting.getLoginid();
String workcode = importSetting.getWorkcode();
String lastname = importSetting.getLastname();
String signdate = importSetting.getSigndate();
String signtime = importSetting.getSigntime();
String tablename = importSetting.getTablename();
String clientaddress = importSetting.getClientaddress();
String longitude = importSetting.getLongitude();
String latitude = importSetting.getLatitude();
String addr = importSetting.getAddr();
String memo = importSetting.getMemo();
// ds = (DataSource) StaticObj.getServiceByFullname(("datasource." + datasourceid), DataSource.class);
// if (ds == null) continue;
// conn = ds.getConnection();
// conn.setAutoCommit(true);
// PreparedStatement pstmt = null;
// ResultSet resultSet = null;
DateFormat df = new SimpleDateFormat("HH:mm:ss");
// sql = "select * from " + tablename + " where " + signdate + " >= '" + beginDate + "' and " + signdate + " < '" + endDate + "' order by " + signdate + (signtime.length() == 0 || signtime.equalsIgnoreCase(signdate) ? "" : (", " + signtime));
sql = " select * from " + tablename + " where modedatacreatedate >= '" + beginDate + "' and modedatacreatedate < '" + endDate + "' order by modedatacreatedate,modedatacreatetime ";
//有遇到外部同步上面的conn = ds.getConnection();这个阻塞住导致下面的同步不执行下面的用法和集成领导确认
RecordSetDataSource rsds = new RecordSetDataSource(datasourceid);
// pstmt = conn.prepareStatement(sql);
// resultSet = pstmt.executeQuery();
rsds.execute(sql);
List<String> noRepertSynData = new ArrayList<>();
while (rsds.next()) {
String tmpLoginid = "";
String tmpWorkcode = "";
String tmpLastname = "";
String tmpSigndate = "";
String tmpSigntime = "";
String tmpClientaddress = "";
String tmpLongitude = "";
String tmpLatitude = "";
String tmpAddr = "";
String tmpMemo = "";
String tmpCreatedate = "";
if (loginid.length() > 0) tmpLoginid = Util.null2String(rsds.getString(loginid)).trim();
if (workcode.length() > 0) tmpWorkcode = Util.null2String(rsds.getString(workcode)).trim();
if (lastname.length() > 0) tmpLastname = Util.null2String(rsds.getString(lastname)).trim();
if (signdate.length() > 0) tmpSigndate = Util.null2String(rsds.getString(signdate)).trim();
if (clientaddress.length() > 0)
tmpClientaddress = Util.null2String(rsds.getString(clientaddress));
if (longitude.length() > 0) tmpLongitude = Util.null2String(rsds.getString(longitude)).trim();
if (latitude.length() > 0) tmpLatitude = Util.null2String(rsds.getString(latitude)).trim();
if (addr.length() > 0) tmpAddr = Util.null2String(rsds.getString(addr)).trim();
if (memo.length() > 0) tmpMemo = Util.null2String(rsds.getString(memo)).trim();
tmpCreatedate = Util.null2String(rsds.getString("modedatacreatedate")).trim();
if (signtime.length() > 0) {
tmpSigntime = Util.null2String(rsds.getString(signtime)).trim();
//判断tmpSigntime格式 08:21:11 如果为长格式需要格式化
if (tmpSigntime.length() > 8) {
if(tmpSigntime.length()<16){//有遇到signtime格式为hh:mm:ss.0000的格式导致同步不成功
tmpSigntime = tmpSigntime.substring(0,8);
}else{//比如上yyyy-mm-dd hh:mm的格式走原逻辑
tmpSigntime = df.format(Timestamp.valueOf(tmpSigntime));
}
} else if (tmpSigntime.length() < 8) {
//不带秒的情况 自动补齐
tmpSigntime += ":00";
}
} else {
tmpSigntime = "";
}
if (tmpSigndate.length() > 10) {
//如果时间为长格式从signdate字段中格式化时间
if (tmpSigndate.length() == 16) {
//不带秒的情况 自动补齐
tmpSigndate += ":00";
}
if (tmpSigntime.length() == 0) {//以signtime字段为有限
tmpSigndate = tmpSigndate.length()>19?tmpSigndate.substring(0,19):tmpSigndate;
tmpSigntime = df.format(Timestamp.valueOf(tmpSigndate));
}
tmpSigndate = Tools.formatDate(tmpSigndate, "yyyy-MM-dd");
}
//如果时间格式不带秒补齐
if (tmpSigntime.length() <= 5) {
tmpSigntime += ":00";
}
kqScheduleSignData = new KQScheduleSignEntity();
kqScheduleSignData.setLoginid(tmpLoginid);
kqScheduleSignData.setWorkcode(tmpWorkcode);
kqScheduleSignData.setLastname(tmpLastname);
kqScheduleSignData.setSigndate(tmpSigndate);
kqScheduleSignData.setSigntime(tmpSigntime);
kqScheduleSignData.setClientaddress(tmpClientaddress);
kqScheduleSignData.setLongitude(tmpLongitude);
kqScheduleSignData.setLatitude(tmpLatitude);
kqScheduleSignData.setAddr(tmpAddr);
kqScheduleSignData.setMemo(tmpMemo);
kqScheduleSignData.setCreatedate(tmpCreatedate);
lsKQScheduleSignData.add(kqScheduleSignData);
}
// resultSet.close();
// pstmt.close();
} catch (Exception e) {
writeLog(e);
}
// finally {
// if (conn != null) conn.close();
// }
}
List<String> noRepertSynData = new ArrayList<>();
for (int i = 0; lsKQScheduleSignData != null && i < lsKQScheduleSignData.size(); i++) {
kqScheduleSignData = lsKQScheduleSignData.get(i);
String tmpLoginid = kqScheduleSignData.getLoginid();
String tmpWorkcode = kqScheduleSignData.getWorkcode();
String tmpLastname = kqScheduleSignData.getLastname();
String tmpSigndate = kqScheduleSignData.getSigndate();
String tmpSigntime = kqScheduleSignData.getSigntime();
String tmpClientaddress = kqScheduleSignData.getClientaddress();
String tmpLongitude = kqScheduleSignData.getLongitude();
String tmpLatitude = kqScheduleSignData.getLatitude();
String tmpAddr = kqScheduleSignData.getAddr();
String tmpMemo = kqScheduleSignData.getMemo();
String tmpCreatedate = kqScheduleSignData.getCreatedate();
int userid = 0;
if (Util.null2String(tmpLoginid).length() > 0) {
userid = StringUtil.parseToInt(loginidMap.get(tmpLoginid), 0);
// userid = getUserId(tmpLoginid, "loginid", this.userlanguage);
}
if (userid == 0 && Util.null2String(tmpWorkcode).length() > 0) {
userid = StringUtil.parseToInt(workcodeMap.get(tmpWorkcode), 0);
// userid = getUserId(tmpWorkcode, "workcode", this.userlanguage);
}
if (userid == 0 && Util.null2String(tmpLastname).length() > 0) {
userid = StringUtil.parseToInt(lastnameMap.get(tmpLastname), 0);
// userid = getUserId(tmpLastname, "lastname", this.userlanguage);
}
if (userid <= 0) {
writeLog("人员id未找到>>>>>>>>>>" + JSONObject.toJSONString(kqScheduleSignData));
continue;
}
String dkParamData = userid + "#" + tmpCreatedate + "#" + tmpSigntime;
if (noRepertSynData.contains(dkParamData)) {
continue;
}
noRepertSynData.add(dkParamData);
params = new ArrayList<>();
params.add(userid);
params.add(1);
params.add(tmpSigndate);
params.add(tmpSigntime);
params.add(tmpClientaddress);
params.add(1);
params.add(1);
params.add("OutDataSourceSyn");
params.add(tmpLongitude);
params.add(tmpLatitude);
params.add(tmpAddr);
params.add(tmpMemo);
params.add(tmpCreatedate);
lsParams.add(params);
String belongDate = getBelongDate(new User(userid), tmpCreatedate, tmpSigntime);
String formatData = userid + "|" + tmpCreatedate+ "|" + belongDate;
if (!lsFormatData.contains(formatData)) {
lsFormatData.add(formatData);
}
}
Map<String, List<String>> overtimeMap = Maps.newHashMap();
List<String> overtimeList = Lists.newArrayList();
//刷新报表数据
for (int i = 0; lsFormatData != null && i < lsFormatData.size(); i++) {
formatParams = new ArrayList<>();
String key = lsFormatData.get(i);//String formatData = userid + "|" + tmpSigndate;
String[] formatData = Util.splitString(lsFormatData.get(i), "|");
String date_1 = DateUtil.addDate(formatData[1], -1);
formatParams.add(formatData[0]);
formatParams.add(date_1);
lsFormatParams.add(formatParams);
formatParams = new ArrayList<>();
formatParams.add(formatData[0]);
formatParams.add(formatData[1]);
lsFormatParams.add(formatParams);
if (!keymap.contains(key)) {
keymap.add(key);
delParams = new ArrayList<>();
delParams.add(formatData[0]);
delParams.add(formatData[1]);
lsDelParams.add(delParams);
}
String resourceId = formatData[0];
String kqdate = formatData[1];
String belongDate = formatData[2];
if (overtimeMap.containsKey(resourceId)) {
List<String> tmp_overtimeList = overtimeMap.get(resourceId);
if (!tmp_overtimeList.contains(kqdate)) {
tmp_overtimeList.add(kqdate);
if(!kqdate.equals(belongDate)) {
tmp_overtimeList.add(belongDate);
}
}
} else {
if (!overtimeList.contains(kqdate)) {
overtimeList.add(kqdate);
if(!kqdate.equals(belongDate)) {
overtimeList.add(belongDate);
}
}
overtimeMap.put(resourceId, overtimeList);
}
}
writeLog("同步之前删除数据:"+ JSONObject.toJSONString(lsDelParams));
writeLog("同步插入数据:"+ JSONObject.toJSONString(lsParams));
//删除本次同步数据
sql = " delete from hrmschedulesign where signfrom='OutDataSourceSyn' and userid =? and createdate = ? ";
bRs.executeBatchSql(sql, lsDelParams);
sql = " insert into HrmScheduleSign (userid, usertype, signdate, signtime, clientaddress, isincom, isimport, signfrom, longitude, latitude, addr,memo,createdate) "
+ " values(?,?,?,?,?,?,?,?,?,?,?,?,?)";
bRs.executeBatchSql(sql, lsParams);
new KQFormatBiz().format(lsFormatParams, 12);
//处理加班生成
List<KQTaskBean> tasks = new ArrayList<>();
for (Map.Entry<String, List<String>> mme : overtimeMap.entrySet()) {
String resid = mme.getKey();
List<String> overList = mme.getValue();
for (String date : overList) {
SplitActionUtil.pushOverTimeTasks(date, date, resid, tasks);
}
}
if (!tasks.isEmpty()) {
KQQueue.writeTasks(tasks);
}
}
public Map<String, Map<String, String>> getUsers(int language) {
RecordSet rs = new RecordSet();
String sql = "select id,loginid,lastname,workcode from hrmresource where status in(0,1,2,3,5)";
if (Util.isEnableMultiLang()) {
if (rs.getDBType().equalsIgnoreCase("sqlserver")) {
sql = "select id,loginid,ltrim(rtrim(dbo.convToMultiLang(ltrim(rtrim(lastname)),"+language+"))) as lastname,workcode from hrmresource where status in(0,1,2,3,5)";
} else {
sql = "select id,loginid,ltrim(rtrim(convToMultiLang(ltrim(rtrim(lastname)),"+language+"))) as lastname,workcode from hrmresource where status in(0,1,2,3,5)";
}
}
Map<String, Map<String, String>> users = new HashMap<String, Map<String, String>>();
rs.execute(sql);
Map<String, String> loginidMap = new HashMap<String, String>();
Map<String, String> lastnameMap = new HashMap<String, String>();
Map<String, String> workcodeMap = new HashMap<String, String>();
String resourceId = "", loginid = "",lastname = "", workcode = "";
while (rs.next()) {
if (StringUtil.isNull(resourceId = StringUtil.vString(rs.getString("id")))) continue;
loginid = StringUtil.vString(rs.getString("loginid"));
if (StringUtil.isNull(loginid)){
// continue;//以防离职人员账号被清空的直接跳过如果没有被清空那么也支持离职人员的同步
}else{
loginidMap.put(loginid, resourceId);
}
// if (StringUtil.isNotNull(loginid = StringUtil.vString(rs.getString("loginid")))) loginidMap.put(loginid, resourceId);
if (StringUtil.isNotNull(lastname = StringUtil.vString(rs.getString("lastname")))) lastnameMap.put(lastname, resourceId);
if (StringUtil.isNotNull(workcode = StringUtil.vString(rs.getString("workcode")))) workcodeMap.put(workcode, resourceId);
}
users.put("loginidMap", loginidMap);
users.put("lastnameMap", lastnameMap);
users.put("workcodeMap", workcodeMap);
return users;
}
public int getUserlanguage() {
return userlanguage;
}
public void setUserlanguage(int userlanguage) {
this.userlanguage = userlanguage;
}
private String getBelongDate(User user, String curDate, String signDateTime) {
String belongDate = curDate;
Map<String, Object> todayLineMap = KQDurationCalculatorUtil.getWorkButton(user, curDate,true);
if(todayLineMap != null) {
List<Map<String, String>> preInfo = (ArrayList<Map<String, String>>)todayLineMap.get("pre_signTime");
if(preInfo != null) {
for(Map<String, String> entry : preInfo) {
String pre_endtime_across = entry.get("endtime_across");
String pre_endtime = entry.get("endtime");
String signEndInfo = "1".equals(pre_endtime_across) ? (curDate+" "+pre_endtime+":00") : (DateUtil.addDate(curDate,-1)+" "+pre_endtime+":00");
String signOutDateTime = signDateTime;
if(signOutDateTime.compareTo(signEndInfo) < 0) {
belongDate = DateUtil.addDate(curDate, -1);
}
}
}
}
return belongDate;
}
}

View File

@ -0,0 +1,30 @@
package com.engine.kq.biz;
import weaver.conn.RecordSet;
import weaver.file.Prop;
import weaver.general.Util;
import weaver.hrm.common.Tools;
import weaver.interfaces.schedule.BaseCronJob;
public class KQScheduleSignImportJob extends BaseCronJob{
public void execute() {
RecordSet rs = new RecordSet();
try{
rs.writeLog("begin do KQScheduleSignImportJob invoke ...");
KQScheduleSignImport kqScheduleSignImport = new KQScheduleSignImport();
//导入策略 每天导入前一天和当天数据
int kqScheduleSignImportDay = Util.getIntValue(Prop.getInstance().getPropValue("QC637173", "KQScheduleSignImportDay"),1);//考勤自动同步同步几天前的数据默认一天
String date_from = Tools.getDate(Tools.getToday(),-kqScheduleSignImportDay);
String date_to = Tools.getDate(Tools.getToday());
rs.writeLog("do KQScheduleSignImportJob invoke..["+date_from+";"+date_to+"]");
kqScheduleSignImport.importData(date_from,date_to,false);
rs.writeLog("end do KQScheduleSignImportJob invoke ...");
}catch (Exception e) {
rs.writeLog(e) ;
}
}
}

View File

@ -0,0 +1,814 @@
package com.engine.kq.biz;
import com.alibaba.fastjson.JSON;
import com.engine.kq.biz.chain.cominfo.HalfShiftComIndex;
import com.engine.kq.biz.chain.cominfo.RestShiftComIndex;
import com.engine.kq.biz.chain.cominfo.ShiftComIndex;
import com.engine.kq.biz.chain.cominfo.ShiftInfoCominfoBean;
import com.engine.kq.biz.chain.cominfo.WorkShiftComIndex;
import com.engine.kq.biz.chain.shiftinfo.ShiftInfoBean;
import com.engine.kq.cmd.shiftmanagement.toolkit.ShiftManagementToolKit;
import com.engine.kq.entity.TimeScopeEntity;
import com.engine.kq.log.KQLog;
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import org.apache.commons.lang.math.NumberUtils;
import weaver.cache.CacheBase;
import weaver.cache.CacheColumn;
import weaver.cache.CacheColumnType;
import weaver.cache.CacheItem;
import weaver.cache.CacheMap;
import weaver.cache.PKColumn;
import weaver.conn.RecordSet;
import weaver.general.Util;
/**
* 班次管理缓存类
*/
public class KQShiftManagementComInfo extends CacheBase implements Serializable {
/*
* 需要关注 : 如果完全在 initCache 自己定义数据初始化 这个字段可以不定义
*/
protected static String TABLE_NAME = "";
/*
* 需要关注 : 如果完全在 initCache 自己定义数据初始化或者不需要指定固定的条件 这个字段可以不定义
* sql中的where信息不要以where开始
*/
protected static String TABLE_WHERE = null;
/*
* 需要关注 : 如果完全在 initCache 自己定义数据初始化或者不需要指定顺序 这个字段可以不定义 sql中的order
* by信息不要以order by开始
*
*/
protected static String TABLE_ORDER = null;
@PKColumn(type = CacheColumnType.NUMBER)
protected static String PK_NAME = "id";
@CacheColumn
protected static int shiftbean;
@CacheColumn
protected static int color;
@CacheColumn
protected static int isoffdutyfreecheck;
@CacheColumn
protected static int shiftonoffworkcount;
@CacheColumn
protected static int serial;
@CacheColumn
protected static int isresttimeopen;
@CacheColumn
protected static int worktime;
@CacheColumn
protected static int punchsetting;
@CacheColumn
protected static int cardRemind;
@CacheColumn
protected static int cardRemOfSignIn;
@CacheColumn
protected static int minsBeforeSignIn;
@CacheColumn
protected static int cardRemOfSignOut;
@CacheColumn
protected static int minsAfterSignOut;
@CacheColumn
protected static int remindMode;
@CacheColumn
protected static int remindOnPC;
@CacheColumn
protected static int signoutOnlyoff;
@CacheColumn
protected static int isRest;
@CacheColumn
protected static int overtimeRuleId;
private KQLog kqLog = new KQLog();
private boolean isFormat = false;
@Override
public CacheItem initCache(String key) {
if (key == null || "".equals(key.trim())) {
return null;
}
CacheMap localData = createCacheMap();
String sql = "";
kqLog = new KQLog();
ConcurrentHashMap<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> signoutOnlyoffMap = new ConcurrentHashMap<>();
ConcurrentHashMap<String,Object> isResetMap = new ConcurrentHashMap<>();
ConcurrentHashMap<String,Object> overtimeruleMap = new ConcurrentHashMap<>();
RecordSet rs = new RecordSet();
String getShiftInfo = "select * from kq_ShiftManagement where 1=1 and id="+key+" order by id ";
rs.execute(getShiftInfo);
while(rs.next()){
String serialid = rs.getString("id");
String isresttimeopen = rs.getString("isresttimeopen");
String color = rs.getString("color");
String shiftonoffworkcount = rs.getString("shiftonoffworkcount");
String worktime = rs.getString("worktime");
String serial = rs.getString("serial");
String punchsetting = "1";
String isoffdutyfreecheck = rs.getString("isoffdutyfreecheck");
String cardRemind = rs.getString("cardRemind");
String cardRemOfSignIn = rs.getString("cardRemOfSignIn");
String minsBeforeSignIn = rs.getString("minsBeforeSignIn");
String cardRemOfSignOut = rs.getString("cardRemOfSignOut");
String minsAfterSignOut = rs.getString("minsAfterSignOut");
String remindMode = rs.getString("remindMode");
String remindOnPC = rs.getString("remindOnPC");
String halfcalrule = rs.getString("halfcalrule");
halfcalrule = Util.null2String(halfcalrule).length() == 0 ? "0" : halfcalrule;
String halfcalpoint = rs.getString("halfcalpoint");
String halfcalpoint2cross = rs.getString("halfcalpoint2cross");
String overtimeRuleId = rs.getString("overtime_rule_id");
String signoutOnlyoff = rs.getString("signoutOnlyoff");
String isRest = rs.getString("is_rest");
getShiftInfoBean(serialid,isresttimeopen,worktime,punchsetting,shiftInfoBeanMap,halfcalrule,halfcalpoint,halfcalpoint2cross,signoutOnlyoff);
idMap.put(serialid, serialid);
colorsMap.put(serialid, color);
isoffdutyfreechecksMap.put(serialid, isoffdutyfreecheck);
shiftonoffworkcountsMap.put(serialid, shiftonoffworkcount);
serialsMap.put(serialid, serial);
isresttimeopensMap.put(serialid, isresttimeopen);
worktimesMap.put(serialid, worktime);
punchsettingsMap.put(serialid, punchsetting);
cardRemindMap.put(serialid,cardRemind);
cardRemOfSignInMap.put(serialid,cardRemOfSignIn);
minsBeforeSignInMap.put(serialid,minsBeforeSignIn);
cardRemOfSignOutMap.put(serialid,cardRemOfSignOut);
minsAfterSignOutMap.put(serialid,minsAfterSignOut);
remindModeMap.put(serialid,remindMode);
remindOnPCMap.put(serialid,remindOnPC);
signoutOnlyoffMap.put(serialid,signoutOnlyoff);
isResetMap.put(serialid,isRest);
overtimeruleMap.put(serialid,overtimeRuleId);
}
if(shiftInfoBeanMap.size()>0){
CacheItem cacheItem = createCacheItem();
Iterator<Entry<String, Object>> iterator = shiftInfoBeanMap.entrySet().iterator();
while (iterator.hasNext()) {
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(signoutOnlyoff,signoutOnlyoffMap.get(id));
cacheItem.set(isRest,isResetMap.get(id));
cacheItem.set(overtimeRuleId,overtimeruleMap.get(id));
modifyCacheItem(id, cacheItem);
}
return cacheItem;
}
} catch (Exception e) {
kqLog.info(e);
}
return null;
}
@Override
public CacheMap initCache() {
CacheMap localData = createCacheMap();
String sql = "";
kqLog = new KQLog();
ConcurrentHashMap<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> signoutOnlyoffMap = new ConcurrentHashMap<>();
ConcurrentHashMap<String,Object> isResetMap = new ConcurrentHashMap<>();
ConcurrentHashMap<String,Object> overtimeruleMap = new ConcurrentHashMap<>();
RecordSet rs = new RecordSet();
String getShiftInfo = "select * from kq_ShiftManagement where 1=1 order by id ";
rs.execute(getShiftInfo);
while(rs.next()){
String serialid = rs.getString("id");
String isresttimeopen = rs.getString("isresttimeopen");
String color = rs.getString("color");
String shiftonoffworkcount = rs.getString("shiftonoffworkcount");
String worktime = rs.getString("worktime");
String serial = rs.getString("serial");
String punchsetting = "1";
String isoffdutyfreecheck = rs.getString("isoffdutyfreecheck");
String cardRemind = rs.getString("cardRemind");
String cardRemOfSignIn = rs.getString("cardRemOfSignIn");
String minsBeforeSignIn = rs.getString("minsBeforeSignIn");
String cardRemOfSignOut = rs.getString("cardRemOfSignOut");
String minsAfterSignOut = rs.getString("minsAfterSignOut");
String remindMode = rs.getString("remindMode");
String remindOnPC = rs.getString("remindOnPC");
String halfcalrule = rs.getString("halfcalrule");
halfcalrule = Util.null2String(halfcalrule).length() == 0 ? "0" : halfcalrule;
String halfcalpoint = rs.getString("halfcalpoint");
String halfcalpoint2cross = rs.getString("halfcalpoint2cross");
String signoutOnlyoff = rs.getString("signoutOnlyoff");
String overtimeRuleId = rs.getString("overtime_rule_id");
String isRest = rs.getString("is_rest");
getShiftInfoBean(serialid,isresttimeopen,worktime,punchsetting,shiftInfoBeanMap,halfcalrule,halfcalpoint,halfcalpoint2cross,signoutOnlyoff);
idMap.put(serialid, serialid);
colorsMap.put(serialid, color);
isoffdutyfreechecksMap.put(serialid, isoffdutyfreecheck);
shiftonoffworkcountsMap.put(serialid, shiftonoffworkcount);
serialsMap.put(serialid, serial);
isresttimeopensMap.put(serialid, isresttimeopen);
worktimesMap.put(serialid, worktime);
punchsettingsMap.put(serialid, punchsetting);
cardRemindMap.put(serialid,cardRemind);
cardRemOfSignInMap.put(serialid,cardRemOfSignIn);
minsBeforeSignInMap.put(serialid,minsBeforeSignIn);
cardRemOfSignOutMap.put(serialid,cardRemOfSignOut);
minsAfterSignOutMap.put(serialid,minsAfterSignOut);
remindModeMap.put(serialid,remindMode);
remindOnPCMap.put(serialid,remindOnPC);
signoutOnlyoffMap.put(serialid,signoutOnlyoff);
isResetMap.put(serialid,isRest);
overtimeruleMap.put(serialid,overtimeRuleId);
}
if(shiftInfoBeanMap.size()>0){
Iterator<Entry<String, Object>> iterator = shiftInfoBeanMap.entrySet().iterator();
while (iterator.hasNext()) {
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(signoutOnlyoff,signoutOnlyoffMap.get(id));
cacheItem.set(isRest,isResetMap.get(id));
cacheItem.set(overtimeRuleId,overtimeruleMap.get(id));
modifyCacheItem(id, cacheItem);
localData.put(id, cacheItem);
}
}
} catch (Exception e) {
StringWriter errorsWriter = new StringWriter();
e.printStackTrace(new PrintWriter(errorsWriter));
kqLog.info(errorsWriter.toString());
}
return localData;
}
public String getId(){
return (String)getRowValue(PK_INDEX);
}
public String getColor() { return (String)getRowValue(color); }
public String getColor(String key)
{
return (String)getValue(color,key);
}
public String getIsoffdutyfreecheck() { return (String)getRowValue(isoffdutyfreecheck); }
public String getIsoffdutyfreecheck(String key)
{
return (String)getValue(isoffdutyfreecheck,key);
}
public String getShiftonoffworkcounts() { return (String)getRowValue(shiftonoffworkcount); }
public String getShiftonoffworkcounts(String key)
{
return (String)getValue(shiftonoffworkcount,key);
}
public String getSerial() { return (String)getRowValue(serial); }
public String getSerial(String key)
{
return (String)getValue(serial,key);
}
public String getIsresttimeopen() { return (String)getRowValue(isresttimeopen); }
public String getIsresttimeopen(String key)
{
return (String)getValue(isresttimeopen,key);
}
public String getWorktime() { return (String)getRowValue(worktime); }
public String getWorktime(String key)
{
return (String)getValue(worktime,key);
}
public String getPunchsetting() {
return (String) getRowValue(punchsetting);
}
public String getPunchsetting(String key) {
return (String) getValue(punchsetting, key);
}
public String getCardRemind() {
return (String) getRowValue(cardRemind);
}
public String getCardRemind(String key) {
return (String) getValue(cardRemind,key);
}
public String getCardRemOfSignIn() {
return (String) getRowValue(cardRemOfSignIn);
}
public String getCardRemOfSignIn(String key) {
return (String) getValue(cardRemOfSignIn, key);
}
public String getMinsBeforeSignIn() {
return (String) getRowValue(minsBeforeSignIn);
}
public String getMinsBeforeSignIn(String key) {
return (String) getValue(minsBeforeSignIn, key);
}
public String getCardRemOfSignOut() {
return (String) getRowValue(cardRemOfSignOut);
}
public String getCardRemOfSignOut(String key) {
return (String) getValue(cardRemOfSignOut, key);
}
public String getMinsAfterSignOut() {
return (String) getRowValue(minsAfterSignOut);
}
public String getMinsAfterSignOut(String key) {
return (String) getValue(minsAfterSignOut, key);
}
public String getRemindMode() {
return (String) getRowValue(remindMode);
}
public String getRemindMode(String key) {
return (String) getValue(remindMode, key);
}
public String getRemindOnPC() {
return (String) getRowValue(remindOnPC);
}
public String getRemindOnPC(String key) {
return (String) getValue(remindOnPC, key);
}
public String getSignoutOnlyoff() {
return (String) getRowValue(signoutOnlyoff);
}
public String getSignoutOnlyoff(String key) {
return (String) getValue(signoutOnlyoff, key);
}
public String getIsRest() {
return (String) getRowValue(isRest);
}
public String getIsRest(String key) {
return (String) getValue(isRest, key);
}
public String getOvertimeRuleId() {
return (String) getRowValue(overtimeRuleId);
}
public String getOvertimeRuleId(String key) {
return (String) getValue(overtimeRuleId, key);
}
private void getShiftInfoBean(String serialid, String isresttimeopen, String worktime,
String punchsettings,
ConcurrentHashMap<String, Object> serialMap,
String halfcalrule,String halfcalpoint,String halfcalpoint2cross, String tmp_signoutOnlyoff) 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("signoutOnlyoff", tmp_signoutOnlyoff.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){
KQWorkTime kqWorkTime = new KQWorkTime();
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));
Boolean isNonWork = kqWorkTime.isNonWork(serialidInfo);
ShiftInfoBean shiftInfoBean = new ShiftInfoBean();
shiftInfoBean.setPreSplitDate(preSplitDate);
shiftInfoBean.setSplitDate(workdate);
shiftInfoBean.setD_Mins(0.0);
shiftInfoBean.setPreSerialid(preSerialid);
shiftInfoBean.setSerialid(serialid);
shiftInfoBean.setRestShift(isNonWork?1:0);
if(containYesterday){
if(Util.getIntValue(serialid) > 0 || Util.getIntValue(preSerialid) > 0){
fillShiftInfoBean(shiftInfoBean, preSerialid, serialid);
dateWorkTimeMap.put("shiftInfoBean", shiftInfoBean);
}
}else{
if(Util.getIntValue(serialid) > 0){
fillShiftInfoBean(shiftInfoBean, preSerialid, serialid);
dateWorkTimeMap.put("shiftInfoBean", shiftInfoBean);
}
}
}
return dateWorkTimeMap;
}
/**
* 根据班次id获取对应日期的上下班时间+休息时间
* @param workdate
* @param serialidInfo
* @return
*/
public Map<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());
dateWorkTimeMap.put("halfWorkTime", cur_shiftInfoCominfoBean.getHalfWorkTime());
dateWorkTimeMap.put("halfWorkIndex", cur_shiftInfoCominfoBean.getHalfWorkIndex());
dateWorkTimeMap.put("convertAttendDay", cur_shiftInfoCominfoBean.getConvertAttendDay());
}
}
/**
* 每次获取的话都需要获取昨天和今天的班次数据
* @param shiftInfoBean
* @param preSerialid 昨天的班次
* @param serialid 今天的班次
*/
private void fillShiftInfoBean(ShiftInfoBean shiftInfoBean,String preSerialid,String serialid){
ShiftInfoCominfoBean pre_shiftInfoCominfoBean = getShiftInfoCominfoBean(preSerialid);
ShiftInfoCominfoBean cur_shiftInfoCominfoBean = getShiftInfoCominfoBean(serialid);
Map<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);
shiftInfoBean.setPreConvertAttendDay(pre_shiftInfoCominfoBean.getConvertAttendDay());
}
//把当前班次的填充好
if(cur_shiftInfoCominfoBean != null){
shiftInfoBean.setWorkIndex(cur_shiftInfoCominfoBean.getWorkTimeIndex());
shiftInfoBean.setWorkAcrossIndex(cur_shiftInfoCominfoBean.getWorkAcrossTimeIndex());
shiftInfoBean.setWorkMinsAcrossIndex(cur_shiftInfoCominfoBean.getWorkPunchMins());
shiftInfoBean.setRestIndex(cur_shiftInfoCominfoBean.getRestTimeIndex());
shiftInfoBean.setHalfWorkIndex(cur_shiftInfoCominfoBean.getHalfWorkIndex());
shiftInfoBean.setWorkmins(cur_shiftInfoCominfoBean.getWorkmins());
shiftInfoBean.setAllWorkTime(cur_shiftInfoCominfoBean.getAllWorkTime());
shiftInfoBean.setAllAcrossWorkTime(cur_shiftInfoCominfoBean.getAllAcrossWorkTime());
shiftInfoBean.setAllRestTime(cur_shiftInfoCominfoBean.getAllRestTime());
shiftInfoBean.setAllAcrossRestTime(cur_shiftInfoCominfoBean.getAllAcrossRestTime());
shiftInfoBean.setAllLongWorkTime(cur_shiftInfoCominfoBean.getAllLongWorkTime());
shiftInfoBean.setRestLongTimeIndex(cur_shiftInfoCominfoBean.getRestLongTimeIndex());
shiftInfoBean.setWorkLongTimeIndex(cur_shiftInfoCominfoBean.getWorkLongTimeIndex());
shiftInfoBean.setIsAcross(cur_shiftInfoCominfoBean.getIsAcross());
shiftInfoBean.setSerialid(serialid);
shiftInfoBean.setShiftRuleMap(shiftRuleMap);
if(cur_shiftInfoCominfoBean.getWorkAcrossLongTime() != null){
List<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());
shiftInfoBean.setConvertAttendDay(cur_shiftInfoCominfoBean.getConvertAttendDay());
}
}
public void removeShiftManagementCache(){
KQShiftRestTimeSectionComInfo kqShiftRestTimeSectionComInfo = new KQShiftRestTimeSectionComInfo();
KQShiftOnOffWorkSectionComInfo kqShiftOnOffWorkSectionComInfo = new KQShiftOnOffWorkSectionComInfo();
kqShiftRestTimeSectionComInfo.removeShiftRestTimeSectionCache();
kqShiftOnOffWorkSectionComInfo.removeShiftWorkSectionCache();
super.removeCache();
//改用redis和staticobj的方式
KQShiftManagementRedis kqShiftManagementRedis = new KQShiftManagementRedis();
kqShiftManagementRedis.resetShiftValWithRedis();
}
/**
* 根据班次获取shiftInfoCominfoBean
* @param serialid
* @return
*/
public ShiftInfoCominfoBean getShiftInfoCominfoBean(String serialid){
// Object object = getObjValue(shiftbean, serialid);
// if(object != null){
// return (ShiftInfoCominfoBean) object;
// }else{
// return null;
// }
//改用redis和staticobj的方式
KQShiftManagementRedis kqShiftManagementRedis = new KQShiftManagementRedis();
return kqShiftManagementRedis.getShiftInfoBeanMapBySql(serialid);
}
/**
* 根据人员和日期获取shiftInfoCominfoBean
* @param workdate
* @param serialidInfo
* @return
*/
public ShiftInfoCominfoBean getShiftInfoCominfoBean(String workdate,Map<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;
}
public boolean isFormat() {
return isFormat;
}
public void setFormat(boolean format) {
isFormat = format;
}
}

View File

@ -0,0 +1,179 @@
package com.engine.kq.biz;
import com.alibaba.fastjson.JSON;
import weaver.cache.*;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
public class KQShiftScheduleComInfo extends CacheBase{
protected static String TABLE_NAME = "kq_shiftschedule";
/** sql中的where信息不要以where开始 */
protected static String TABLE_WHERE = "where (isdelete is null or isdelete <> '1'or (isdelete='1' and (wfidstatus='1' or wfidstatus='2'))) ";//默认加载今天之前一个月数据
/** sql中的order by信息不要以order by开始 */
protected static String TABLE_ORDER = "id";
@PKColumn(type = CacheColumnType.NUMBER)
protected static String PK_NAME = "id";
@CacheColumn(name = "serialid")
protected static int serialid;
@CacheColumn(name = "groupid")
protected static int groupid;
private boolean isFormat = false;
private int shiftGroupId = -1;
@Override
public CacheMap initCache() throws Exception {
CacheMap localData = super.createCacheMap();
RecordSet rs = new RecordSet();
String sql = "";
if ("mysql".equals(rs.getDBType())) {
sql += " select CONCAT(resourceid,'|',kqdate) as id, serialid,groupid from kq_shiftschedule "+TABLE_WHERE + " and kqdate>='"+DateUtil.getFirstDayOfMonth(DateUtil.getCurrentDate())+"' and kqdate<='"+ DateUtil.getCurrentDate()+"'";
}else if("sqlserver".equals(rs.getDBType())){
sql += " select CONVERT(varchar,resourceid)+'|'+kqdate as id, serialid,groupid from kq_shiftschedule "+TABLE_WHERE + " and kqdate>='"+DateUtil.getFirstDayOfMonth(DateUtil.getCurrentDate())+"' and kqdate<='"+ DateUtil.getCurrentDate()+"'";
} else {
sql = "select resourceid||'|'||kqdate as id, serialid,groupid from kq_shiftschedule "+TABLE_WHERE + " and kqdate>='"+DateUtil.getFirstDayOfMonth(DateUtil.getCurrentDate())+"' and kqdate<='"+ DateUtil.getCurrentDate()+"'";
}
//这里还是要保留删除但是没有生效的数据
sql += " and (isdelete is null or isdelete <> '1' or (isdelete='1' and (wfidstatus='1' or wfidstatus='2')))";
//zj
sql += " and (wfidstatus is null or wfidstatus = '3'or (isdelete='1' and (wfidstatus='1' or wfidstatus='2')))";
rs.executeQuery(sql);
while (rs.next()) {
String id = Util.null2String(rs.getString(PK_NAME));
CacheItem row = createCacheItem();
parseResultSetToCacheItem(rs, row);
// 这里需要记得调用这个 转化方法 否则 这些自己加载的数据就不能正确转化当然你也可以直接在转化逻辑写在这里不过这样先让代码重复了
modifyCacheItem(id, row);
localData.put(id, row);
}
return localData;
}
// /**
// * 性能原因取消后续加载
// * @return
// */
// protected boolean autoInitIfNotFound() {
// return false;
// }
@Override
public CacheItem initCache(String key) {
if (key == null || "".equals(key.trim())) {
return null;
}
String[] keys = Util.splitString(key,"|");
String resourceid = keys[0];
String kqdate = keys[1];
RecordSet rs = new RecordSet();
String sql = "";
if ("mysql".equals(rs.getDBType())) {
sql += " select CONCAT(resourceid,'|',kqdate) as id, serialid,groupid from kq_shiftschedule "+TABLE_WHERE+ " and resourceid ='"+resourceid+"' and kqdate='"+kqdate+"'";
}else if("sqlserver".equals(rs.getDBType())){
sql += " select CONVERT(varchar,resourceid)+'|'+kqdate as id, serialid,groupid from kq_shiftschedule "+TABLE_WHERE+ " and resourceid ='"+resourceid+"' and kqdate='"+kqdate+"'";
} else {
sql = "select resourceid||'|'||kqdate as id, serialid,groupid from kq_shiftschedule "+TABLE_WHERE+ " and resourceid ='"+resourceid+"' and kqdate='"+kqdate+"'";
}
sql += " and (isdelete is null or isdelete <> '1'or (isdelete='1' and (wfidstatus='1' or wfidstatus='2')))";
//zj
sql += " and (wfidstatus is null or wfidstatus = '3'or (isdelete='1' and (wfidstatus='1' or wfidstatus='2')))";
rs.executeQuery(sql);
if (rs.next()) {
CacheItem cacheItem = createCacheItem();
parseResultSetToCacheItem(rs, cacheItem);
modifyCacheItem(key, cacheItem);
return cacheItem;
}
return null;
}
private String getId() {
return (String) getRowValue(PK_INDEX);
}
private String getSerialId() {
return (String) getRowValue(serialid);
}
private String getSerialId(String key) {
if(!this.isFormat){
return (String) getValue(serialid, key);
}
return getSerialidBySql(key);
}
private String getSerialidBySql(String key) {
String sql_serialid = "";
if (key == null || "".equals(key.trim())) {
return null;
}
String[] keys = Util.splitString(key,"|");
String resourceid = keys[0];
String kqdate = keys[1];
RecordSet rs = new RecordSet();
String sql = "";
if ("mysql".equals(rs.getDBType())) {
sql += " select CONCAT(resourceid,'|',kqdate) as id, serialid,groupid from kq_shiftschedule where (isdelete is null or isdelete <> '1' or (isdelete='1' and (wfidstatus='1' or wfidstatus='2'))) and resourceid ='"+resourceid+"' and kqdate='"+kqdate+"'";
}else if("sqlserver".equals(rs.getDBType())){
sql += " select CONVERT(varchar,resourceid)+'|'+kqdate as id, serialid,groupid from kq_shiftschedule where (isdelete is null or isdelete <> '1' or (isdelete='1' and (wfidstatus='1' or wfidstatus='2'))) and resourceid ='"+resourceid+"' and kqdate='"+kqdate+"'";
} else {
sql = "select resourceid||'|'||kqdate as id, serialid,groupid from kq_shiftschedule where (isdelete is null or isdelete <> '1' or (isdelete='1' and (wfidstatus='1' or wfidstatus='2'))) and resourceid ='"+resourceid+"' and kqdate='"+kqdate+"'";
}
if(shiftGroupId > 0) {
sql += " and groupid = "+shiftGroupId;
}
sql += " and (isdelete is null or isdelete <> '1' or (isdelete='1' and (wfidstatus='1' or wfidstatus='2')))";
//zj
sql += " and (wfidstatus is null or wfidstatus = '3' or (isdelete='1' and (wfidstatus='1' or wfidstatus='2')))";
rs.executeQuery(sql);
if (rs.next()) {
sql_serialid = rs.getString("serialid");
}
return sql_serialid;
}
private String getGroupId(String key) {
return (String) getValue(groupid, key);
}
public String getSerialId(String resourceid, String kqdate) {
if(Util.null2String(resourceid).length()==0||Util.null2String(kqdate).length()==0)return "";
return this.getSerialId(resourceid+"|"+kqdate);
}
public String getGroupId(String resourceid, String kqdate) {
if(Util.null2String(resourceid).length()==0||Util.null2String(kqdate).length()==0)return "";
return this.getGroupId(resourceid+"|"+kqdate);
}
public boolean isFormat() {
return isFormat;
}
public void setFormat(boolean format) {
isFormat = format;
}
public int getShiftGroupId() {
return shiftGroupId;
}
public void setShiftGroupId(int shiftGroupId) {
this.shiftGroupId = shiftGroupId;
}
}

View File

@ -0,0 +1,471 @@
package com.engine.kq.biz;
import com.alibaba.fastjson.JSON;
import com.engine.kq.biz.chain.cominfo.ShiftInfoCominfoBean;
import com.engine.kq.cmd.shiftmanagement.toolkit.ShiftManagementToolKit;
import com.engine.kq.entity.KQGroupEntity;
import com.engine.kq.entity.TimeScopeEntity;
import com.engine.kq.entity.TimeSignScopeEntity;
import com.engine.kq.entity.WorkTimeEntity;
import com.engine.kq.log.KQLog;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import weaver.common.DateUtil;
import weaver.common.StringUtil;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.resource.ResourceComInfo;
public class KQWorkTime extends BaseBean {
private KQLog kqLog = new KQLog();
private boolean isFormat = false;
public WorkTimeEntity getWorkTime(String userId) {
return getWorkTime(userId, null);
}
/**
* 判断是否是工作日
* @param userId
* @param workdate
* @return
*/
public boolean isWorkDay(String userId, String workdate) {
boolean isWorkDay = false;
if(!KQHolidaySetBiz.isHoliday(userId,workdate)) {//不是节假日且有班次
Map<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{
boolean isRest = isNonWork(serialInfo);
if(isRest){
return isWorkDay;
}
isWorkDay = Util.getIntValue(Util.null2String(serialInfo.get(workdate)))>0;
}
}
}
return isWorkDay;
}
public boolean isNonWork(Map<String, Object> serialInfo){
boolean isR = false;
if(serialInfo.containsKey("isRest")){
Boolean isRest = (Boolean) serialInfo.get("isRest");
if(isRest){
isR = true;
}
}
if(serialInfo.containsKey("isHoliday")){
Boolean isHoliday = (Boolean) serialInfo.get("isHoliday");
if(isHoliday){
isR = true;
}
}
return isR;
}
public Map<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);
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();
Map<String,Object> serialInfo = getSerialInfo(userId, workdate, false);
workTimeEntity.setIsExclude(Util.null2String(serialInfo.get("isExclude")).equals("1"));
workTimeEntity.setGroupId(Util.null2String(serialInfo.get("groupId")));
if(serialInfo!=null&&serialInfo.size()>0) {
String kqType = Util.null2String(serialInfo.get("kqType"));
Boolean isNonWork = isNonWork(serialInfo);
String dayType = "work";
if(serialInfo.containsKey("isRest")){
Boolean isRest1 = (Boolean) serialInfo.get("isRest");
if(isRest1){
dayType = "playday";
}
}
if(serialInfo.containsKey("isHoliday")){
Boolean isHoliday1 = (Boolean) serialInfo.get("isHoliday");
if(isHoliday1){
dayType = "holiday";
}
}
if(kqType.equals("3")){
Map<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")));
}else{
dayType = "playday";
}
workTimeEntity.setNonWorkShift(0);
}else{
int serialid = Util.getIntValue(Util.null2String(serialInfo.get(workdate)), 0);
int signouOnlyoff = StringUtil.parseToInt(kQShiftManagementComInfo.getSignoutOnlyoff(String.valueOf(serialid)), 0);
workTimeEntity.setSignoutOnlyoff(signouOnlyoff);
if (serialid > 0){
workTimeEntity.setNonWorkShift(isNonWork?1:0);
Map<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.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));
workTimeEntity.setWorkMins(Util.getIntValue(Util.null2String(dateWorkTimeMap.get("workMins"))));
workTimeEntity.setIsAcross(Util.null2String(dateWorkTimeMap.get("isAcross")));
workTimeEntity.setConvertAttendDay(Util.null2s(Util.null2String(dateWorkTimeMap.get("convertAttendDay")), "1.0"));
workTimeEntity.setHalfWorkTime((List<String>)dateWorkTimeMap.get("halfWorkTime"));
workTimeEntity.setHalfWorkIndex((List<int[]>)dateWorkTimeMap.get("halfWorkIndex"));
}else{
dayType = "playday";
}
}
workTimeEntity.setDayType(dayType);
}
} 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) {
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);
KQShiftManagementComInfo kqShiftManagementComInfo = new KQShiftManagementComInfo();
kqShiftManagementComInfo.setFormat(this.isFormat);
KQGroupEntity kqGroupEntity = groupMemberComInfo.getUserKQGroupInfo(userId,workdate);
ResourceComInfo resourceComInfo = new ResourceComInfo();
preworkdate = DateUtil.addDate(workdate,-1);
if(containYesterday){
Map<String, Object> pre_serialInfo = getSerialInfo(userId, preworkdate, false);
if(pre_serialInfo != null && !pre_serialInfo.isEmpty()){
if(pre_serialInfo.containsKey(preworkdate)){
serialInfo.put(preworkdate,pre_serialInfo.get(preworkdate));//获取前一天的班次
}
}
}
if(kqGroupEntity==null){//不在考勤组内
serialInfo.put("isRest",true);
return serialInfo;
}
//无需考勤人员需要计算考勤时间但不计算异常状态
// if (("," + kqGroupEntity.getExcludeid() + ",").indexOf("," + userId + ",")>-1) {//排除人员无需计算考勤时间
// return serialInfo;
// }
if (("," + kqGroupEntity.getExcludeid() + ",").indexOf("," + userId + ",")>-1) {//排除人员无需计算考勤时间
serialInfo.put("isExclude","1");
}
String begindate = Util.null2String(resourceComInfo.getCreatedate(userId)).trim();
String companyStartDate = Util.null2String(resourceComInfo.getCompanyStartDate(userId)).trim();
if(companyStartDate.length()!=10){
companyStartDate = "";
}
if(companyStartDate.length()>0 && companyStartDate.indexOf("-")>0){
begindate=companyStartDate;
}
if(begindate.length()>0 && DateUtil.compDate(begindate,workdate)<0 ){//人员入职日期前无需计算考勤如果没有入职日期已创建日期为准
// kqLog.writeLog("getSerialInfo 入职日期不满足条件:userId:"+userId+":workdate:"+workdate+":companyStartDate:"+companyStartDate+":begindate:"+begindate+":DateUtil.compDate(begindate,workdate):"+DateUtil.compDate(begindate,workdate));
serialInfo.put("isRest",true);
return serialInfo;
}
String endDate = Util.null2String(resourceComInfo.getEndDate(userId));
String status = Util.null2String(resourceComInfo.getStatus(userId));
if(status.equals("0")||status.equals("1")||status.equals("2")||status.equals("3")){
//在职
}else{
//其他状态
if(endDate.length()>0 && DateUtil.compDate(endDate,workdate)>0){//人员合同结束日期无需计算考勤
// kqLog.writeLog("getSerialInfo 人员合同结束日期不满足条件:userId:"+userId+":workdate:"+workdate+":endDate:"+endDate+":status:"+status+":DateUtil.compDate(endDate,workdate):"+DateUtil.compDate(endDate,workdate));
serialInfo.put("isRest",true);
return serialInfo;
}
}
String groupid = kqGroupEntity.getId();
String groupname = kqGroupEntity.getGroupname();
String kqtype = kqGroupEntity.getKqtype();
int dayOfweek = DateUtil.getWeek(workdate)-1;
int preDayOfweek = DateUtil.getWeek(preworkdate)-1;
boolean preDayIsHoliday = KQHolidaySetBiz.isHoliday(userId,preworkdate);
boolean isHoliday = KQHolidaySetBiz.isHoliday(userId,workdate);
serialInfo.put("isHoliday",isHoliday);
KQSettingsComInfo kqSettingsComInfo = new KQSettingsComInfo();
boolean needSkipHoliday = isHoliday;
//节假日或者调配休息日是否需要返回当天的班次
String holidayRestShift = Util.null2String(kqSettingsComInfo.getMain_val("holiday_rest_shift"),"0");
if("1".equals(holidayRestShift)){
//如果需要返回班次那么isHoliday的判断就不需要了
needSkipHoliday = false;
}
String serialid = "";
if(!kqtype.equals("2")){//处理调配工作日(除排班外)
if(KQHolidaySetBiz.getChangeType(groupid,preworkdate)==2){
preDayOfweek = KQHolidaySetBiz.getRelatedDay(userId,preworkdate);
}
if(KQHolidaySetBiz.getChangeType(groupid,workdate)==2){
dayOfweek = KQHolidaySetBiz.getRelatedDay(userId,workdate);
}
}
serialInfo.put("groupId",groupid);
serialInfo.put("groupName",groupname);
serialInfo.put("kqType",kqtype);
if (kqtype.equals("1")) {//固定班
// if(containYesterday && !serialInfo.containsKey(preworkdate)) {
// serialid = Util.null2String(kqFixedSchedulceComInfo.getSerialid(groupid,preDayOfweek));
// if(!preDayIsHoliday&&serialid.length()>0 && Util.getIntValue(serialid) > 0){
// serialInfo.put(preworkdate,serialid);//获取前一天的班次
// }
// }
if(!serialInfo.containsKey(workdate)){
serialid = Util.null2String(kqFixedSchedulceComInfo.getSerialid(groupid,dayOfweek));
if( !needSkipHoliday&&serialid.length()>0 && Util.getIntValue(serialid) > 0){
serialInfo.put(workdate, serialid);//获取当天的班次
}
}
} else if (kqtype.equals("2")) {//排班
//先取排班设置里的班次
// serialid = Util.null2String(kqShiftScheduleComInfo.getSerialId(userId,preworkdate));
// if(containYesterday && serialid.length()>0 && !preDayIsHoliday && Util.getIntValue(serialid) > 0){
// serialInfo.put(preworkdate,Util.null2String(kqShiftScheduleComInfo.getSerialId(userId,preworkdate)));//获取前一天的班次
// }
kqShiftScheduleComInfo.setShiftGroupId(Util.getIntValue(groupid));
serialid = Util.null2String(kqShiftScheduleComInfo.getSerialId(userId,workdate));
if(serialid.length()>0 && !needSkipHoliday && Util.getIntValue(serialid) > 0){
serialInfo.put(workdate,Util.null2String(kqShiftScheduleComInfo.getSerialId(userId,workdate)));//获取当天的班次
}
} else if (kqtype.equals("3")) {//自由班
List weekDay = Util.splitString2List(kqGroupEntity.getWeekday(), ",");
String signStart = Util.null2String(kqGroupEntity.getSignstart());//签到开始时间
int workMins = Util.getIntValue(Util.getIntValues(""+Util.getDoubleValue(Util.null2String(kqGroupEntity.getWorkhour()))*60));//工作时长
if(signStart.length()>0 && workMins>0) {
String calmethod = Util.null2s(kqGroupEntity.getCalmethod(),"1");
Map<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);
}
}
}
if(StringUtil.isNotNull(serialid)){
String isRest = Util.null2s(kqShiftManagementComInfo.getIsRest(serialid),"");
serialInfo.put("isRest","1".equals(isRest));
}
} catch (Exception e) {
writeLog(e);
}
return serialInfo;
}
public void setIsFormat(boolean isFormat){
this.isFormat = isFormat;
}
}

View File

@ -0,0 +1,521 @@
package com.engine.kq.biz.chain.cominfo;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
*/
public class ShiftInfoCominfoBean implements Serializable {
private static final long serialVersionUID = -1735765502081116461L;
/**
* 当前班次如果是作为前一个班次存在跨到次日的工作时段
*/
private List<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;
/**
* 当前班次作为当前班次存在如果存在跨r天的话包含跨天的休息时段显示成0-24小时的
*/
private List<String[]> restAcrossTime;
/**
* 当前班次如果是作为前一个班次存在跨到次日的休息时段
*/
private List<int[]> preRestTimeIndex;
/**
* 当前班次作为当前班次存在在0-24小时内的休息时段
*/
private List<int[]> restTimeIndex;
/**
* 当前班次作为当前班次存在如果存在跨r天的话包含跨天的休息时段显示成0-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 convertAttendDay = "";
public ShiftInfoCominfoBean() {
this.preWorkTime = new ArrayList<>();
this.workTime = new ArrayList<>();
this.workAcrossTime = new ArrayList<>();
this.preWorkTimeIndex = new ArrayList<>();
this.workTimeIndex = new ArrayList<>();
this.workAcrossTimeIndex = new ArrayList<>();
this.workAcrossLongTime = new ArrayList<>();
this.workPunchMins = new ArrayList<>();
this.preRestTime = new ArrayList<>();
this.restTime = new ArrayList<>();
this.restAcrossTime = new ArrayList<>();
this.preRestTimeIndex = new ArrayList<>();
this.restTimeIndex = new ArrayList<>();
this.restAcrossTimeIndex = new ArrayList<>();
this.restAcrossLongTime = new ArrayList<>();
this.halfWorkTime = new ArrayList<>();
this.allWorkTime = new ArrayList<>();
this.allAcrossWorkTime = new ArrayList<>();
this.allRestTime = new ArrayList<>();
this.allAcrossRestTime = new ArrayList<>();
this.eachWorkMins = new ArrayList<>();
this.workmins = 0;
this.serialid = "";
this.isAcross = "0";
this.halfcalrule = "0";
this.halfWorkIndex = new ArrayList<>();
this.timelineList = new ArrayList<>();
this.workLongTimeIndex = new ArrayList<>();
this.restLongTimeIndex = new ArrayList<>();
this.allLongWorkTime = new ArrayList<>();
this.signWorkTime = new ArrayList<>();
this.allWorkTimeisAcross = new ArrayList<>();
this.uuid = UUID.randomUUID().toString();
this.halfcalpoint = "0";
this.halfcalpoint2cross = "0";
}
public List<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 getConvertAttendDay() {
return convertAttendDay;
}
public void setConvertAttendDay(String convertAttendDay) {
this.convertAttendDay = convertAttendDay;
}
}

View File

@ -0,0 +1,804 @@
package com.engine.kq.biz.chain.shiftinfo;
import com.engine.kq.entity.TimeScopeEntity;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 1首先有个KQTimesArrayComInfo缓存类这个类把00:00-23:59的时间点都转换成了0-1439的数值
* 我把这个数值视作下标index
*
* 2假如班次设置的工作时段是
* 8:00-12:00
* 13:00-18:00
* 22:00-次日4:00
*
* 3...
*
* 4那么restTimes表示的就是休息时段15:00-16:00对应的数组下标{[100,200]}举个栗子而已
*
* 5那么workIndex表示的就是休息时段8:00-12:00...对应的数组下标{[50,80],[90,180],[250,280]}workIndexTime存的就是时间点举个栗子而已
*
* 6那么halfWorkIndex表示的就是半天规则情况下需要用到的数组下标
* 上面的例子里的工作时长的15个小时所以半天的话需要从8:00-16:30只要是满足小于这个范围段内的都是半天大于的就是1天了
* halfWorkIndex对应的数组下标就是{[50,70]}halfWorkIndexTime存的就是时间点举个栗子而已
*
* 7那么wholeWorkIndex表示的就是整天规则情况下需要用到的数组下标我只需要知道workIndex就可以了wholeWorkIndexTime存的就是时间点
*
*/
public class ShiftInfoBean {
/**
* 指定开始时间
*/
private String splitFromTime;
/**
* 指定结束时间
*/
private String splitToTime;
/**
* 指定日期 因为流程时段区间已经被拆分成一天一条了
*/
private String splitDate;
/**
* 要返回当天的工作时间区间对应的数组下标 这个是不包含跨天的
*/
private List<int[]> workIndex;
/**
* 要返回当天的工作时间区间对应的数组下标 这个是包含跨天的
*/
private List<int[]> workAcrossIndex;
/**
* 要返回当天的工作时间区间对应的时间 这个是包含跨天的
*/
private List<String[]> workAcrossTime;
/**
* 当天打卡时段时间多少分钟可以开始签到签退的
*/
private List<String[][]> workMinsAcrossIndex;
/**
* 要返回的休息时间区间对应的数组下标 不包含跨天
*/
private List<int[]> restIndex;
/**
* 要返回的休息时间区间对应的数组下标 包含跨天的
*/
private List<int[]> restAcrossIndex;
/**
* 要返回的半天规则时间区间对应的数组下标
* 这里有值的话是三个最早的开始时间 中间时间 最晚的下班时间
*/
private List<int[]> halfWorkIndex;
/**
* 工作时长
*/
private int workmins;
private int signoutOnlyoff;
/**
* 加班用的前日期是何种类型
*/
private int changeType;
/**
* 当前日期的班次
*/
private String serialid;
/**
* 指定日期的前一天因为存在跨天昨天数据可能也需要在今天统计
*/
private String preSplitDate;
/**
* 这个返回的是前一天的班次存在跨天跨到今天的工作时段区间
*/
private List<int[]> preWorkIndex;
/**
* 要返回前一天天的工作时间区间对应的数组下标 这个是包含跨天的
*/
private List<int[]> preWorkAcrossIndex;
/**
* 要返回前一天打卡时段信息多少分钟可以开始签到签退的
*/
private List<String[][]> preWorkMinsAcrossIndex;
/**
* 映射前一天的跨天和时间区间下标
*/
private Map<String,String> preWorktimeAcrossMap;
/**
* 要返回前一天的休息时间区间对应的数组下标
*/
private List<int[]> preRestIndex;
/**
* 要返回的前一天的半天规则时间区间对应的数组下标
* 这里有值的话是三个开始时间 中间时间 下班时间
*/
private List<int[]> preHalfWorkIndex;
/**
* 前一天的工作时长
*/
private int preWorkmins;
/**
* 前一个日期的班次
*/
private String preSerialid;
/**
* 得到实际时长分钟数
*/
private double D_Mins;
/**
* 流程判断的各种规则
* 半天小时的
*/
private String minimumUnit;
/**
* 流程用的时候存的值
*/
private String duration;
/**
* 针对时段跨天 流程跨天的情况23:59-24:00差一分钟的处理
*/
private String oneMoreMinute;
/**
* 当前时间段
*/
private int[] curMins;
/**
* 当前时间段
*/
private int[] preMins;
/**
* 存储所有的工作时间
*/
private List<String> allWorkTime;
/**
* 存储所有的跨天时间
*/
private List<String> allAcrossWorkTime;
/**
* 存储所有的休息时间
*/
private List<String> allRestTime;
/**
* 存储所有的休息时间
*/
private List<String> allAcrossRestTime;
/**
* 存储所有的工作时间
*/
private List<String> preAllWorkTime;
/**
* 存储所有的跨天时间
*/
private List<String> preAllAcrossWorkTime;
/**
* 存储所有的休息时间
*/
private List<String> preAllRestTime;
/**
* 存储所有的休息时间
*/
private List<String> preAllAcrossRestTime;
/**
* 是否是自由班製
*/
private boolean isfree;
/**
* 自由班制签到开始时间
*/
private String freeSignStart;
/**
* 自由班制工作时长
*/
private String freeWorkMins;
/**
* 自由班制应该签退时间
*/
private String freeSignEnd;
/**
* 自由班制 半天中间点
*/
private String freeSignMiddle;
/**
* 当前班次作为当前班次存在在0-48小时内的工作时段下标
*/
private List<int[]> workLongTimeIndex;
/**
* 当前班次作为当前班次存在在0-48小时内的工作时段下标
*/
private List<int[]> restLongTimeIndex;
/**
* 存储所有的工作时间 48小时制休息时段
*/
private List<String> allLongWorkTime;
/**
* 判断当前班次是否存在跨天
*/
private String isAcross;
/**
* 判断前一天班次是否存在跨天
*/
private String isPreAcross;
private Map<String,Object> shiftRuleMap;
/**
* 和kqformdate里的workTimeEntity用到的保持一致
*/
private List<TimeScopeEntity> signTime;//允许打卡时间
/**
* 和kqformdate里的workTimeEntity用到的保持一致
*/
private List<TimeScopeEntity> workTime;//工作时间
/**
* 半天计算规则
*/
private String halfcalrule;
/**
* 自定义 半天计算规则 时间点
*/
private String halfcalpoint;
private String halfcalpoint2cross;
/**
* 存储每一段工作时段内的工作时长
*/
private List<Integer> eachWorkMins;
/**
* 是否是非工作日 1表示是非工作日班次
*/
private int restShift;
/**
* 昨天应出勤折算天数
*/
private String preConvertAttendDay = "";
/**
* 应出勤折算天数
*/
private String convertAttendDay = "";
public ShiftInfoBean() {
this.splitFromTime = "";
this.splitToTime = "";
this.splitDate = "";
this.workIndex = new ArrayList<>();
this.workAcrossIndex = new ArrayList<>();
this.restIndex = new ArrayList<>();
this.restAcrossIndex = new ArrayList<>();
this.halfWorkIndex = new ArrayList<>();
this.workmins = 0;
this.signoutOnlyoff = 0;
this.preSplitDate = "";
this.preWorkIndex = new ArrayList<>();
this.preWorkAcrossIndex = new ArrayList<>();
this.preWorktimeAcrossMap = new HashMap<>();
this.preRestIndex = new ArrayList<>();
this.preHalfWorkIndex = new ArrayList<>();
this.preWorkmins = 0;
this.D_Mins = 0.0;
this.minimumUnit = "";
this.duration = "";
this.oneMoreMinute = "";
this.preWorkMinsAcrossIndex = new ArrayList<>();
this.workMinsAcrossIndex = new ArrayList<>();
this.preSerialid = "";
this.serialid = "";
this.workAcrossTime = new ArrayList<>();
this.isfree = false;
this.freeSignStart = "";
this.freeWorkMins = "";
this.freeSignEnd = "";
this.freeSignMiddle = "";
this.workLongTimeIndex = new ArrayList<>();
this.restLongTimeIndex = new ArrayList<>();
this.allLongWorkTime = new ArrayList<>();
this.isAcross = "";
this.isPreAcross = "";
this.shiftRuleMap = Maps.newHashMap();
this.workTime = Lists.newArrayList();
this.signTime = Lists.newArrayList();
this.halfcalrule = "";
this.halfcalpoint = "";
this.halfcalpoint2cross = "";
this.eachWorkMins = new ArrayList<>();
}
public String getSplitDate() {
return splitDate;
}
public void setSplitDate(String splitDate) {
this.splitDate = splitDate;
}
public String getSplitFromTime() {
return splitFromTime;
}
public void setSplitFromTime(String splitFromTime) {
this.splitFromTime = splitFromTime;
}
public String getSplitToTime() {
return splitToTime;
}
public void setSplitToTime(String splitToTime) {
this.splitToTime = splitToTime;
}
public List<int[]> getWorkIndex() {
return workIndex;
}
public void setWorkIndex(List<int[]> workIndex) {
this.workIndex = workIndex;
}
public List<int[]> getRestIndex() {
return restIndex;
}
public void setRestIndex(List<int[]> restIndex) {
this.restIndex = restIndex;
}
public List<int[]> getHalfWorkIndex() {
return halfWorkIndex;
}
public void setHalfWorkIndex(List<int[]> halfWorkIndex) {
this.halfWorkIndex = halfWorkIndex;
}
public double getD_Mins() {
return D_Mins;
}
public void setD_Mins(double d_Mins) {
D_Mins = d_Mins;
}
public String getPreSplitDate() {
return preSplitDate;
}
public void setPreSplitDate(String preSplitDate) {
this.preSplitDate = preSplitDate;
}
public List<int[]> getPreWorkIndex() {
return preWorkIndex;
}
public void setPreWorkIndex(List<int[]> preWorkIndex) {
this.preWorkIndex = preWorkIndex;
}
public List<int[]> getWorkAcrossIndex() {
return workAcrossIndex;
}
public void setWorkAcrossIndex(List<int[]> workAcrossIndex) {
this.workAcrossIndex = workAcrossIndex;
}
public int getWorkmins() {
return workmins;
}
public void setWorkmins(int workmins) {
this.workmins = workmins;
}
public int getSignoutOnlyoff() {
return signoutOnlyoff;
}
public void setSignoutOnlyoff(int signoutOnlyoff) {
this.signoutOnlyoff = signoutOnlyoff;
}
public String getMinimumUnit() {
return minimumUnit;
}
public void setMinimumUnit(String minimumUnit) {
this.minimumUnit = minimumUnit;
}
public List<int[]> getPreHalfWorkIndex() {
return preHalfWorkIndex;
}
public void setPreHalfWorkIndex(List<int[]> preHalfWorkIndex) {
this.preHalfWorkIndex = preHalfWorkIndex;
}
public List<int[]> getPreWorkAcrossIndex() {
return preWorkAcrossIndex;
}
public void setPreWorkAcrossIndex(List<int[]> preWorkAcrossIndex) {
this.preWorkAcrossIndex = preWorkAcrossIndex;
}
public Map<String, String> getPreWorktimeAcrossMap() {
return preWorktimeAcrossMap;
}
public void setPreWorktimeAcrossMap(
Map<String, String> preWorktimeAcrossMap) {
this.preWorktimeAcrossMap = preWorktimeAcrossMap;
}
public List<int[]> getPreRestIndex() {
return preRestIndex;
}
public void setPreRestIndex(List<int[]> preRestIndex) {
this.preRestIndex = preRestIndex;
}
public int getPreWorkmins() {
return preWorkmins;
}
public void setPreWorkmins(int preWorkmins) {
this.preWorkmins = preWorkmins;
}
public List<int[]> getRestAcrossIndex() {
return restAcrossIndex;
}
public void setRestAcrossIndex(List<int[]> restAcrossIndex) {
this.restAcrossIndex = restAcrossIndex;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public String getOneMoreMinute() {
return oneMoreMinute;
}
public void setOneMoreMinute(String oneMoreMinute) {
this.oneMoreMinute = oneMoreMinute;
}
public List<String[][]> getWorkMinsAcrossIndex() {
return workMinsAcrossIndex;
}
public void setWorkMinsAcrossIndex(List<String[][]> workMinsAcrossIndex) {
this.workMinsAcrossIndex = workMinsAcrossIndex;
}
public List<String[][]> getPreWorkMinsAcrossIndex() {
return preWorkMinsAcrossIndex;
}
public void setPreWorkMinsAcrossIndex(List<String[][]> preWorkMinsAcrossIndex) {
this.preWorkMinsAcrossIndex = preWorkMinsAcrossIndex;
}
public String getSerialid() {
return serialid;
}
public void setSerialid(String serialid) {
this.serialid = serialid;
}
public String getPreSerialid() {
return preSerialid;
}
public void setPreSerialid(String preSerialid) {
this.preSerialid = preSerialid;
}
public int[] getCurMins() {
return curMins;
}
public void setCurMins(int[] curMins) {
this.curMins = curMins;
}
public int[] getPreMins() {
return preMins;
}
public void setPreMins(int[] preMins) {
this.preMins = preMins;
}
public List<String[]> getWorkAcrossTime() {
return workAcrossTime;
}
public void setWorkAcrossTime(List<String[]> workAcrossTime) {
this.workAcrossTime = workAcrossTime;
}
public int getChangeType() {
return changeType;
}
public void setChangeType(int changeType) {
this.changeType = changeType;
}
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> 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<String> getPreAllWorkTime() {
return preAllWorkTime;
}
public void setPreAllWorkTime(List<String> preAllWorkTime) {
this.preAllWorkTime = preAllWorkTime;
}
public List<String> getPreAllAcrossWorkTime() {
return preAllAcrossWorkTime;
}
public void setPreAllAcrossWorkTime(List<String> preAllAcrossWorkTime) {
this.preAllAcrossWorkTime = preAllAcrossWorkTime;
}
public List<String> getPreAllRestTime() {
return preAllRestTime;
}
public void setPreAllRestTime(List<String> preAllRestTime) {
this.preAllRestTime = preAllRestTime;
}
public List<String> getPreAllAcrossRestTime() {
return preAllAcrossRestTime;
}
public void setPreAllAcrossRestTime(List<String> preAllAcrossRestTime) {
this.preAllAcrossRestTime = preAllAcrossRestTime;
}
public boolean isIsfree() {
return isfree;
}
public void setIsfree(boolean isfree) {
this.isfree = isfree;
}
public String getFreeSignStart() {
return freeSignStart;
}
public void setFreeSignStart(String freeSignStart) {
this.freeSignStart = freeSignStart;
}
public String getFreeWorkMins() {
return freeWorkMins;
}
public void setFreeWorkMins(String freeWorkMins) {
this.freeWorkMins = freeWorkMins;
}
public String getFreeSignEnd() {
return freeSignEnd;
}
public void setFreeSignEnd(String freeSignEnd) {
this.freeSignEnd = freeSignEnd;
}
public String getFreeSignMiddle() {
return freeSignMiddle;
}
public void setFreeSignMiddle(String freeSignMiddle) {
this.freeSignMiddle = freeSignMiddle;
}
public List<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 String getIsAcross() {
return isAcross;
}
public void setIsAcross(String isAcross) {
this.isAcross = isAcross;
}
public String getIsPreAcross() {
return isPreAcross;
}
public void setIsPreAcross(String isPreAcross) {
this.isPreAcross = isPreAcross;
}
public Map<String, Object> getShiftRuleMap() {
return shiftRuleMap;
}
public void setShiftRuleMap(Map<String, Object> shiftRuleMap) {
this.shiftRuleMap = shiftRuleMap;
}
public List<TimeScopeEntity> getSignTime() {
return signTime;
}
public void setSignTime(List<TimeScopeEntity> signTime) {
this.signTime = signTime;
}
public List<TimeScopeEntity> getWorkTime() {
return workTime;
}
public void setWorkTime(List<TimeScopeEntity> workTime) {
this.workTime = workTime;
}
public String getHalfcalrule() {
return halfcalrule;
}
public void setHalfcalrule(String halfcalrule) {
this.halfcalrule = halfcalrule;
}
public List<Integer> getEachWorkMins() {
return eachWorkMins;
}
public void setEachWorkMins(List<Integer> eachWorkMins) {
this.eachWorkMins = eachWorkMins;
}
public String getHalfcalpoint() {
return halfcalpoint;
}
public void setHalfcalpoint(String halfcalpoint) {
this.halfcalpoint = halfcalpoint;
}
public String getHalfcalpoint2cross() {
return halfcalpoint2cross;
}
public void setHalfcalpoint2cross(String halfcalpoint2cross) {
this.halfcalpoint2cross = halfcalpoint2cross;
}
public int getRestShift() {
return restShift;
}
public void setRestShift(int restShift) {
this.restShift = restShift;
}
public String getConvertAttendDay() {
return convertAttendDay;
}
public void setConvertAttendDay(String convertAttendDay) {
this.convertAttendDay = convertAttendDay;
}
public String getPreConvertAttendDay() {
return preConvertAttendDay;
}
public void setPreConvertAttendDay(String preConvertAttendDay) {
this.preConvertAttendDay = preConvertAttendDay;
}
}

View File

@ -0,0 +1,954 @@
package com.engine.kq.cmd.report;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.kq.biz.*;
import com.engine.kq.util.ExcelUtil;
import com.engine.kq.util.KQDurationCalculatorUtil;
import com.engine.kq.util.UtilKQ;
import com.engine.lingyue.util.KqUtil;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.company.SubCompanyComInfo;
import weaver.hrm.job.JobTitlesComInfo;
import weaver.hrm.resource.ResourceComInfo;
import weaver.systeminfo.SystemEnv;
import com.google.common.collect.Lists;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;
public class ExportExcelCmd extends AbstractCommonCommand<Map<String, Object>> {
private HttpServletRequest request;
private HttpServletResponse response;
private List<String> lsFieldDataKey;
private boolean isKqReportHalfOpen = "1".equals(new KQSettingsComInfo().getMain_val("kq_report_half"));
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();
KQSettingsComInfo kqSettingsComInfo = new KQSettingsComInfo();
String leavetype_is_on = Util.null2String(kqSettingsComInfo.getMain_val("leavetype_is_on"),"0");
KQReportBiz kqReportBiz = new KQReportBiz();
new KQReportBiz().insertKqReportExportLog(params, user);
JSONObject jsonObj = JSON.parseObject(Util.null2String(params.get("data")));
String attendanceSerial = Util.null2String(jsonObj.get("attendanceSerial"));
String fromDate = Util.null2String(jsonObj.get("fromDate"));
String toDate = Util.null2String(jsonObj.get("toDate"));
String typeselect = Util.null2String(jsonObj.get("typeselect"));
if (typeselect.length() == 0) typeselect = "3";
if (!typeselect.equals("") && !typeselect.equals("0") && !typeselect.equals("6")) {
if (typeselect.equals("1")) {
fromDate = TimeUtil.getCurrentDateString();
toDate = TimeUtil.getCurrentDateString();
} else {
fromDate = TimeUtil.getDateByOption(typeselect, "0");
toDate = TimeUtil.getDateByOption(typeselect, "1");
}
}
//人员状态
String status = Util.null2String(jsonObj.get("status"));
String subCompanyId = Util.null2String(jsonObj.get("subCompanyId"));
String departmentId = Util.null2String(jsonObj.get("departmentId"));
String resourceId = Util.null2String(jsonObj.get("resourceId"));
String allLevel = Util.null2String(jsonObj.get("allLevel"));
String isNoAccount = Util.null2String(jsonObj.get("isNoAccount"));
String viewScope = Util.null2String(jsonObj.get("viewScope"));
List<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);
// 没有权限的人最大只支持查询本季
Map<String, String> getRealDate = new KQReportBiz().realDate(fromDate, toDate, user, "1");
fromDate = getRealDate.get("fromDate");
toDate = getRealDate.get("toDate");
if("-1".equals(fromDate) || "-1".equals(toDate)) {
retmap.put("status", "1");
return retmap;
}
String forgotBeginWorkCheck_field = " sum(b.forgotBeginWorkCheck) ";
if(rs.getDBType().equalsIgnoreCase("oracle")) {
forgotBeginWorkCheck_field = " sum(nvl(b.forgotBeginWorkCheck,0)) ";
}else if((rs.getDBType()).equalsIgnoreCase("mysql")){
forgotBeginWorkCheck_field = " sum(ifnull(b.forgotBeginWorkCheck,0)) ";
}else {
forgotBeginWorkCheck_field = " sum(isnull(b.forgotBeginWorkCheck,0)) ";
}
Map<String,Object> definedFieldInfo = new KQFormatBiz().getDefinedField();
String definedFieldSum = Util.null2String(definedFieldInfo.get("definedFieldSum"));
String backFields = " (select sum(fdjbtians) as jbts from uf_kqgshsj u where u.xm = a.id and u.rq>='"+fromDate+"' and u.rq<= '"+toDate+"') as jbts,(select sum(gcyjzbts) as gzts from uf_kqgshsj u where u.xm = a.id and u.rq>='"+fromDate+"' and u.rq<= '"+toDate+"') as gzts,a.id,a.lastname,a.workcode,a.dsporder,b.resourceid,a.subcompanyid1 as subcompanyid,a.departmentid,a.jobtitle," +
" sum(b.workdays) as workdays,sum(b.workMins) as workMins,sum(b.attendancedays) as attendancedays," +
" sum(b.attendanceMins) as attendanceMins,sum(b.beLate) as beLate,sum(b.beLateMins) as beLateMins, " +
" sum(b.graveBeLate) as graveBeLate, sum(b.graveBeLateMins) as graveBeLateMins,sum(b.leaveEearly) as leaveEearly," +
" sum(b.leaveEarlyMins) as leaveEarlyMins, sum(b.graveLeaveEarly) as graveLeaveEarly, " +
" sum(b.graveLeaveEarlyMins) as graveLeaveEarlyMins,sum(b.absenteeism) as absenteeism, " +
" sum(b.signdays) as signdays,sum(b.signmins) as signmins, "+
" sum(b.absenteeismMins) as absenteeismMins, sum(b.forgotCheck)+"+forgotBeginWorkCheck_field+" as forgotCheck "+(definedFieldSum.length()>0?","+definedFieldSum+"":"");
if(rs.getDBType().equals("oracle")){
backFields = "/*+ index(kq_format_total IDX_KQ_FORMAT_TOTAL_KQDATE) */ "+backFields;
}
String sqlFrom = " from hrmresource a, kq_format_total b where a.id= b.resourceid and b.kqdate >='" + fromDate + "' and b.kqdate <='" + toDate + "'";
String sqlWhere = rightSql;
String groupBy = " group by a.id,a.lastname,a.workcode,a.dsporder,b.resourceid,a.subcompanyid1,a.departmentid,a.jobtitle ";
if (subCompanyId.length() > 0) {
sqlWhere += " and a.subcompanyid1 in(" + subCompanyId + ") ";
}
if (departmentId.length() > 0) {
sqlWhere += " and a.departmentid in(" + departmentId + ") ";
}
if (resourceId.length() > 0) {
sqlWhere += " and a.id in(" + resourceId + ") ";
}
if (viewScope.equals("4")) {//我的下属
if (allLevel.equals("1")) {//所有下属
sqlWhere += " and a.managerstr like '%," + user.getUID() + ",%'";
} else {
sqlWhere += " and a.managerid=" + user.getUID();//直接下属
}
}
if (!"1".equals(isNoAccount)) {
sqlWhere += " and a.loginid is not null " + (rs.getDBType().equals("oracle") ? "" : " and a.loginid<>'' ");
}
if(status.length()>0){
if (!status.equals("8") && !status.equals("9")) {
sqlWhere += " and a.status = "+status+ "";
}else if (status.equals("8")) {
sqlWhere += " and (a.status = 0 or a.status = 1 or a.status = 2 or a.status = 3) ";
}
}
String orderBy = " order by a.dsporder asc, a.lastname asc ";
String descOrderBy = " order by a.dsporder desc, a.lastname desc ";
sql = "select " + backFields + sqlFrom + sqlWhere + groupBy + orderBy;
//System.out.println("start" + DateUtil.getFullDate());
String show_card_source = Util.null2String(kqSettingsComInfo.getMain_val("show_card_source"),"0");//是否显示打卡数据以及打卡数据来源
params.put("show_card_source",show_card_source);
KQOvertimeRulesBiz kqOvertimeRulesBiz = new KQOvertimeRulesBiz();
int uintType = kqOvertimeRulesBiz.getMinimumUnit();//当前加班单位
double hoursToDay = kqOvertimeRulesBiz.getHoursToDay();//当前天跟小时计算关系
params.put("uintType",uintType);
params.put("hoursToDay",hoursToDay);
Map<String, Object> flowData = new KQReportBiz().getFlowData(params, user);
//System.out.println("end" + DateUtil.getFullDate());
// #1475814-概述满足考勤报分部部门显示及导出时显示全路径
String fullPathMainKey = "show_full_path";
String isShowFullPath = Util.null2String(kqSettingsComInfo.getMain_val(fullPathMainKey),"0");
//事假
int leaveabsencetype = Util.getIntValue(rs.getPropValue("hrm_kqreport","leaveabsencetype"));
//病假
int sickleavetype = Util.getIntValue(rs.getPropValue("hrm_kqreport","sickleavetype"));
//年假
int annualleavetype = Util.getIntValue(rs.getPropValue("hrm_kqreport","annualleavetype"));
//陪产假
int paternityleavetype = Util.getIntValue(rs.getPropValue("hrm_kqreport","paternityleavetype"));
//婚假
int marriageleavetype = Util.getIntValue(rs.getPropValue("hrm_kqreport","marriageleavetype"));
//丧假
int bereavementleavetype = Util.getIntValue(rs.getPropValue("hrm_kqreport","bereavementleavetype"));
//探亲假
int homeleavetype = Util.getIntValue(rs.getPropValue("hrm_kqreport","homeleavetype"));
//哺乳假
int breastfeedleavetype = Util.getIntValue(rs.getPropValue("hrm_kqreport","breastfeed_leave_id"));
rs.execute(sql);
int calIndex = -1;
while (rs.next()) {
data = new ArrayList<>();
String id = rs.getString("id");
for (int fieldDataKeyIdx =0;fieldDataKeyIdx<lsFieldDataKey.size();fieldDataKeyIdx++) {
String fieldName = lsFieldDataKey.get(fieldDataKeyIdx);
String fieldid = KQReportFieldComInfo.field2Id.get(fieldName);
String fieldValue = "";
//入职日期
if (fieldName.equals("companystartdate")) {
fieldValue = KqUtil.getCompanyStartDate(id);
data.add(fieldValue);
continue;
}
//转正日期
else if (fieldName.equals("comfirmdate")) {
fieldValue = KqUtil.getComfirmDate(id);
data.add(fieldValue);
continue;
}
//异动日期
else if (fieldName.equals("transactiondate")) {
fieldValue = KqUtil.getTransactionDate(fromDate,toDate,id);
data.add(fieldValue);
continue;
}
//离职日期
else if (fieldName.equals("terminationdate")) {
fieldValue = KqUtil.getTerminationDate(id);
data.add(fieldValue);
continue;
}
//片区
else if (fieldName.equals("area")) {
fieldValue = KqUtil.getArea(fromDate,toDate,id);
data.add(fieldValue);
continue;
}
//分部
else if (fieldName.equals("subcompany")) {
fieldValue = KqUtil.getSubcompany(fromDate,toDate,id);
data.add(fieldValue);
continue;
}
//部门
else if (fieldName.equals("department")) {
fieldValue = KqUtil.getDepartment(fromDate,toDate,id);
data.add(fieldValue);
continue;
}
//岗位名称
else if (fieldName.equals("positionname")) {
fieldValue = KqUtil.getPosition(fromDate,toDate,id);
data.add(fieldValue);
continue;
}
//应出勤天数
else if (fieldName.equals("requiredworkdays")) {
fieldValue = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getWorkDays(fromDate,toDate,id)));
data.add(fieldValue);
continue;
}
//实际出勤天数薪酬调整前
else if (fieldName.equals("attenddaysbeforesalary")) {
fieldValue = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getAttendDaysBeforeSalary(fromDate,toDate,id)));
data.add(fieldValue);
continue;
}
//事假天数薪酬调整前
else if (fieldName.equals("leaveabsencedaysbeforesalary")) {
fieldValue = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getBeforeSalaryLeaveDays(leaveabsencetype,fromDate,toDate,id)));
data.add(fieldValue);
continue;
}
//病假天数薪酬调整前
else if (fieldName.equals("sickleavedaysbeforesalary")) {
fieldValue = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getBeforeSalaryLeaveDays(sickleavetype,fromDate,toDate,id)));
data.add(fieldValue);
continue;
}
//年假薪酬调整前
else if (fieldName.equals("annualleavedaysbeforesalary")) {
fieldValue = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getBeforeSalaryLeaveDays(annualleavetype,fromDate,toDate,id)));
data.add(fieldValue);
continue;
}
//陪产假薪酬调整前
else if (fieldName.equals("paternityleavedaysbeforesalary")) {
fieldValue = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getBeforeSalaryLeaveDays(paternityleavetype,fromDate,toDate,id)));
data.add(fieldValue);
continue;
}
//婚假薪酬调整前
else if (fieldName.equals("marriageleavedaysbeforesalary")) {
fieldValue = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getBeforeSalaryLeaveDays(marriageleavetype,fromDate,toDate,id)));
data.add(fieldValue);
continue;
}
//丧假薪酬调整前
else if (fieldName.equals("bereavementleavedaysbeforesalary")) {
fieldValue = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getBeforeSalaryLeaveDays(bereavementleavetype,fromDate,toDate,id)));
data.add(fieldValue);
continue;
}
//探亲假薪酬调整前
else if (fieldName.equals("homeleavedaysbeforesalary")) {
fieldValue = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getBeforeSalaryLeaveDays(homeleavetype,fromDate,toDate,id)));
data.add(fieldValue);
continue;
}
//哺乳假薪酬调整前
else if (fieldName.equals("breastfeedleavedaysbeforesalary")) {
fieldValue = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getBeforeSalaryLeaveDays(breastfeedleavetype,fromDate,toDate,id)));
data.add(fieldValue);
continue;
}
//旷工天数薪酬调整前
else if (fieldName.equals("absenteeismdaysbeforesalary")) {
fieldValue = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getAbsenteeismDaysBeforeSalaryBefore(fromDate,toDate,id)));
data.add(fieldValue);
continue;
}
//旷工天数薪酬调整前总计
else if (fieldName.equals("absenteeismdayscountbeforesalary")) {
fieldValue = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getAbsenteeismDaysCountAfterSalary(fromDate,toDate,id)));
data.add(fieldValue);
continue;
}
//每次漏签计0.5天旷工
else if (fieldName.equals("forgotcheckabsenteeismdays")) {
fieldValue = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getForgotCheckAbsenteeismDaysAfter(fromDate,toDate,id)));
data.add(fieldValue);
continue;
}
//严重迟到/早退每次计0.5天旷工
else if (fieldName.equals("gravebelateleaveearlydays")) {
fieldValue = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getGraveBeLateLeaveEarlyDaysAfter(fromDate,toDate,id)));
data.add(fieldValue);
continue;
}
//实际出勤天数薪酬调整后
else if (fieldName.equals("attenddaysaftersalary")) {
fieldValue = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getAttendDaysAfterSalary(fromDate,toDate,id)));
data.add(fieldValue);
continue;
}
//事假天数薪酬调整后
else if (fieldName.equals("leaveabsencedaysaftersalary")) {
fieldValue = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getAfterSalaryLeaveDays(leaveabsencetype,fromDate,toDate,id)));
data.add(fieldValue);
continue;
}
//病假天数薪酬调整后
else if (fieldName.equals("sickleavedaysaftersalary")) {
fieldValue = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getAfterSalaryLeaveDays(sickleavetype,fromDate,toDate,id)));
data.add(fieldValue);
continue;
}
//年假薪酬调整后
else if (fieldName.equals("annualleavedaysaftersalary")) {
fieldValue = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getAfterSalaryLeaveDays(annualleavetype,fromDate,toDate,id)));
data.add(fieldValue);
continue;
}
//陪产假薪酬调整后
else if (fieldName.equals("paternityleavedaysaftersalary")) {
fieldValue = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getAfterSalaryLeaveDays(paternityleavetype,fromDate,toDate,id)));
data.add(fieldValue);
continue;
}
//婚假薪酬调整后
else if (fieldName.equals("marriageleavedaysaftersalary")) {
fieldValue = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getAfterSalaryLeaveDays(marriageleavetype,fromDate,toDate,id)));
data.add(fieldValue);
continue;
}
//丧假薪酬调整后
else if (fieldName.equals("bereavementleavedaysaftersalary")) {
fieldValue = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getAfterSalaryLeaveDays(bereavementleavetype,fromDate,toDate,id)));
data.add(fieldValue);
continue;
}
//探亲假薪酬调整后
else if (fieldName.equals("homeleavedaysaftersalary")) {
fieldValue = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getAfterSalaryLeaveDays(homeleavetype,fromDate,toDate,id)));
data.add(fieldValue);
continue;
}
//哺乳假薪酬调整后
else if (fieldName.equals("breastfeedleavedaysaftersalary")) {
fieldValue = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getAfterSalaryLeaveDays(breastfeedleavetype,fromDate,toDate,id)));
data.add(fieldValue);
continue;
}
//旷工天数薪酬调整后
else if (fieldName.equals("absenteeismdaysaftersalary")) {
fieldValue = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getAbsenteeismDaysAfterSalaryAfter(fromDate,toDate,id)));
data.add(fieldValue);
continue;
}
//旷工次数
else if (fieldName.equals("absenteeismdays")) {
fieldValue = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getAbsenteeismDays(fromDate,toDate,id)));
data.add(fieldValue);
continue;
}
//旷工次数薪酬用
else if (fieldName.equals("absenteeNumsSalary")) {
fieldValue = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getAbsenteeNumsSalary(fromDate,toDate,id)));
data.add(fieldValue);
continue;
}
//产假天数薪酬用
else if (fieldName.equals("maternityLeaveDaySalary")) {
fieldValue = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getMaternityLeaveDaySalary(fromDate,toDate,id)));
data.add(fieldValue);
continue;
}
//工伤假天数薪酬用
else if (fieldName.equals("injuryLeaveDaySalary")) {
fieldValue = KQDurationCalculatorUtil.getDurationRound(String.valueOf(KqUtil.getInjuryLeaveDaySalary(fromDate,toDate,id)));
data.add(fieldValue);
continue;
}
else
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();
if (("1").equals(leavetype_is_on)) {
KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo();
for (int i = allLeaveRules.size() - 1; i >= 0; i--) {
Map<String, Object> leaveRule = allLeaveRules.get(i);
String leaveId = Util.null2String(leaveRule.get("id"));
boolean flag = kqLeaveRulesBiz.filterSubLeaveRule(kqLeaveRulesComInfo, user, leaveId);
if (flag) {
allLeaveRules.remove(i);
}
}
}
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));
data.add(getFieldValueByUnitType(fieldValue,kqReportFieldComInfo.getUnittype(KQReportFieldComInfo.field2Id.get("overtimeTotal"))));
continue;
}else if(fieldName.equals("businessLeave") || fieldName.equals("officialBusiness")){
String businessLeaveData = Util.null2s(Util.null2String(flowData.get(id+"|"+fieldName)),"0.0");
String backType = fieldName+"_back";
String businessLeavebackData = Util.null2s(Util.null2String(flowData.get(id+"|"+backType)),"0.0");
String businessLeave = "";
try{
//以防止出现精度问题
if(businessLeaveData.length() == 0){
businessLeaveData = "0.0";
}
if(businessLeavebackData.length() == 0){
businessLeavebackData = "0.0";
}
BigDecimal b_businessLeaveData = new BigDecimal(businessLeaveData);
BigDecimal b_businessLeavebackData = new BigDecimal(businessLeavebackData);
businessLeave = b_businessLeaveData.subtract(b_businessLeavebackData).toString();
if(Util.getDoubleValue(businessLeave, -1) < 0){
businessLeave = "0.0";
}
}catch (Exception e){
}
fieldValue = KQDurationCalculatorUtil.getDurationRound(businessLeave);
} else if(Util.null2String(kqReportFieldComInfo.getCascadekey(fieldid)).length()>0){
fieldValue = Util.formatMultiLang(Util.null2String(rs.getString(fieldName)),""+user.getLanguage());
data.add(fieldValue);
List<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 {
fieldValue = Util.formatMultiLang(Util.null2String(rs.getString(fieldName)),""+user.getLanguage());
fieldValue = getFieldValueByUnitType(fieldValue,kqReportFieldComInfo.getUnittype(fieldid));
}
fieldValue = Util.formatMultiLang(fieldValue,""+user.getLanguage());
data.add(fieldValue);
}
List<Object> amData = Lists.newArrayList();
List<Object> pmData = Lists.newArrayList();
if(isKqReportHalfOpen) {
amData.addAll(data);
pmData.addAll(data);
calIndex = data.size();
}
if(showColumns.contains("kqCalendar")) {
rs.writeLog("=============== ExportExcelCmd detialDatas showColumns kqCalendar================= ");
// Map<String, Object> detialDatas = kqReportBiz.getDetialDatas(id, fromDate, toDate, user,flowData,true);
Map<String, Object> detialDatas = kqReportBiz.getDetialDatas(id, fromDate, toDate, user,flowData,true,uintType,show_card_source);
rs.writeLog("=============== ExportExcelCmd detialDatas ================= "+ detialDatas);
String user_endDate = Util.null2String(resourceComInfo.getEndDate(id));
String user_status = Util.null2String(resourceComInfo.getStatus(id));
String begindate = Util.null2String(resourceComInfo.getCreatedate(id)).trim();
String companyStartDate = Util.null2String(resourceComInfo.getCompanyStartDate(id)).trim();
if(companyStartDate.length()!=10){
companyStartDate = "";
}
if(companyStartDate.length()>0 && companyStartDate.indexOf("-")>0){
begindate=companyStartDate;
}
isEnd = false;
for (String date = fromDate; !isEnd; ) {
if (date.equals(toDate)) isEnd = true;
String dismissDate = resourceComInfo.getEndDate(id);
if(!"".equals(dismissDate) && DateUtil.compDate(dismissDate, date)>0) {
if(isKqReportHalfOpen) {
amData.add("");
pmData.add("");
} else {
data.add("");
}
} else if (DateUtil.compDate(today, date) > 0) {
if(isKqReportHalfOpen) {
amData.add("");
pmData.add("");
} else {
data.add("");
}
} else {
if(!(user_status.equals("0")||user_status.equals("1")||user_status.equals("2")||user_status.equals("3"))){
//其他状态
if(user_endDate.length()>0 && date.compareTo(user_endDate)>0){//人员合同结束日期之后
if(isKqReportHalfOpen) {
amData.add("");
pmData.add("");
} else {
data.add("");
}
cal.setTime(DateUtil.parseToDate(date));
date = DateUtil.getDate(cal.getTime(), 1);
continue;
}
}
if(begindate.length()>0 && date.compareTo(begindate)<0 ){//人员入职日期前无需计算考勤如果没有入职日期已创建日期为准
if(isKqReportHalfOpen) {
amData.add("");
pmData.add("");
} else {
data.add("");
}
cal.setTime(DateUtil.parseToDate(date));
date = DateUtil.getDate(cal.getTime(), 1);
continue;
}
if (detialDatas.get(id + "|" + date) != null) {
if(isKqReportHalfOpen) {
amData.add(((Map<String, Object>) detialDatas.get(id + "|" + date)).get("textAM"));
pmData.add(((Map<String, Object>) detialDatas.get(id + "|" + date)).get("textPM"));
} else {
data.add(((Map<String, Object>) detialDatas.get(id + "|" + date)).get("text"));
}
} else {
if(isKqReportHalfOpen) {
amData.add(SystemEnv.getHtmlLabelName(26593, user.getLanguage()));
pmData.add(SystemEnv.getHtmlLabelName(26593, user.getLanguage()));
} else {
data.add(SystemEnv.getHtmlLabelName(26593, user.getLanguage()));
}
}
}
cal.setTime(DateUtil.parseToDate(date));
date = DateUtil.getDate(cal.getTime(), 1);
}
}
if(isKqReportHalfOpen) {
dataList.add(amData);
dataList.add(pmData);
} else {
dataList.add(data);
}
}
sheet.put("dataList", dataList);
if(isKqReportHalfOpen) {
sheet.put("calIndex", calIndex);
}
sheet.put("constraintList", constraintList);
sheet.put("createFile", "1");
lsSheet.add(sheet);
workbook.put("sheet", lsSheet);
String fileName = SystemEnv.getHtmlLabelName(390351, user.getLanguage())+" "+fromDate+" "+toDate;
workbook.put("fileName", fileName);
ExcelUtil ExcelUtil = new ExcelUtil();
Map<String, Object> exportMap = ExcelUtil.export(workbook, request, response,true);
retmap.putAll(exportMap);
retmap.put("status", "1");
} catch (Exception e) {
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(382661, user.getLanguage()));
writeLog(e);
}
return retmap;
}
private Map<String, Object> getChildColumnsInfo(String parentid, User user) {
Map<String, Object> returnMap = new HashMap<>();
List<Object> titleList = new ArrayList<>();
Map<String, Object> title = null;
KQSettingsComInfo kqSettingsComInfo = new KQSettingsComInfo();
String leavetype_is_on = Util.null2String(kqSettingsComInfo.getMain_val("leavetype_is_on"),"0");
if (parentid.equals("attendanceSerial")) {//考勤班次
KQShiftManagementComInfo kqShiftManagementComInfo = new KQShiftManagementComInfo();
JSONObject jsonObj = JSON.parseObject(Util.null2String(params.get("data")));
List<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();
if (("1").equals(leavetype_is_on)) {
KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo();
for (int i = leaveRules.size() - 1; i >= 0; i--) {
Map<String, Object> leaveRule = leaveRules.get(i);
String leaveId = Util.null2String(leaveRule.get("id"));
boolean flag = kqLeaveRulesBiz.filterSubLeaveRule(kqLeaveRulesComInfo, user, leaveId);
if (flag) {
leaveRules.remove(i);
}
}
}
for (int i = 0; leaveRules != null && i < leaveRules.size(); i++) {
Map<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;
}
@Override
public BizLogContext getLogContext() {
return null;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,234 @@
package com.engine.kq.entity;
/**
* 假期余额
*/
public class KQBalanceOfLeaveEntity {
/**
* 主键ID
*/
int id;
/**
* 假期规则ID
*/
int leaveRulesId;
/**
* 人员ID
*/
int resourceId;
/**
* 所属年份
* 数据格式yyyy
*/
String belongYear;
/**
* 假期余额基数
* 混合模式下为法定年假的基数
*/
double baseAmount = 0.00;
/**
* 已用的假期余额
* 混合模式下为已用的法定年假的数量
*/
double usedAmount = 0.00;
/**
* 额外的假期余额
* 混合模式下为额外的法定年假的数量
*/
double extraAmount = 0.00;
/**
* 仅用于混合模式下的福利年假的基数
*/
double baseAmount2 = 0.00;
/**
* 仅用于混合模式下的已用的福利年假的数量
*/
double usedAmount2 = 0.00;
/**
* 仅用于混合模式下的额外的福利年假的数量
*/
double extraAmount2 = 0.00;
/**
* 是有有效0-有效1-无效
*/
int status;
/**
* 失效日期
*/
String expirationDate;
/**
* 生效日期
*/
String effectiveDate;
/**
* 最小请假单位
*/
int minimumUnit;
public KQBalanceOfLeaveEntity() {
}
public KQBalanceOfLeaveEntity(int id, int leaveRulesId, int resourceId, String belongYear, double baseAmount, double usedAmount, double extraAmount, double baseAmount2, double usedAmount2, double extraAmount2, int status, String expirationDate) {
this.id = id;
this.leaveRulesId = leaveRulesId;
this.resourceId = resourceId;
this.belongYear = belongYear;
this.baseAmount = baseAmount;
this.usedAmount = usedAmount;
this.extraAmount = extraAmount;
this.baseAmount2 = baseAmount2;
this.usedAmount2 = usedAmount2;
this.extraAmount2 = extraAmount2;
this.status = status;
this.expirationDate = expirationDate;
}
public KQBalanceOfLeaveEntity(int id, int leaveRulesId, int resourceId, String belongYear, double baseAmount, double usedAmount, double extraAmount, double baseAmount2, double usedAmount2, double extraAmount2, int status, String expirationDate ,String effectiveDate) {
this.id = id;
this.leaveRulesId = leaveRulesId;
this.resourceId = resourceId;
this.belongYear = belongYear;
this.baseAmount = baseAmount;
this.usedAmount = usedAmount;
this.extraAmount = extraAmount;
this.baseAmount2 = baseAmount2;
this.usedAmount2 = usedAmount2;
this.extraAmount2 = extraAmount2;
this.status = status;
this.expirationDate = expirationDate;
this.effectiveDate = effectiveDate;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getLeaveRulesId() {
return leaveRulesId;
}
public void setLeaveRulesId(int leaveRulesId) {
this.leaveRulesId = leaveRulesId;
}
public int getResourceId() {
return resourceId;
}
public void setResourceId(int resourceId) {
this.resourceId = resourceId;
}
public String getBelongYear() {
return belongYear;
}
public void setBelongYear(String belongYear) {
this.belongYear = belongYear;
}
public double getBaseAmount() {
return baseAmount;
}
public void setBaseAmount(double baseAmount) {
this.baseAmount = baseAmount;
}
public double getUsedAmount() {
return usedAmount;
}
public void setUsedAmount(double usedAmount) {
this.usedAmount = usedAmount;
}
public double getExtraAmount() {
return extraAmount;
}
public void setExtraAmount(double extraAmount) {
this.extraAmount = extraAmount;
}
public double getBaseAmount2() {
return baseAmount2;
}
public void setBaseAmount2(double baseAmount2) {
this.baseAmount2 = baseAmount2;
}
public double getUsedAmount2() {
return usedAmount2;
}
public void setUsedAmount2(double usedAmount2) {
this.usedAmount2 = usedAmount2;
}
public double getExtraAmount2() {
return extraAmount2;
}
public void setExtraAmount2(double extraAmount2) {
this.extraAmount2 = extraAmount2;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getExpirationDate() {
return expirationDate;
}
public void setExpirationDate(String expirationDate) {
this.expirationDate = expirationDate;
}
public String getEffectiveDate() {
return effectiveDate;
}
public void setEffectiveDate(String effectiveDate) {
this.effectiveDate = effectiveDate;
}
public int getMinimumUnit() {
return minimumUnit;
}
public void setMinimumUnit(int minimumUnit) {
this.minimumUnit = minimumUnit;
}
public boolean equals(KQBalanceOfLeaveEntity entity) {
if (this.baseAmount != entity.getBaseAmount()
|| this.extraAmount != entity.getExtraAmount()
|| this.usedAmount != entity.getUsedAmount()
|| this.baseAmount2 != entity.getBaseAmount2()
|| this.extraAmount2 != entity.getExtraAmount2()
|| this.usedAmount2 != entity.getUsedAmount2()) {
return false;
} else {
return true;
}
}
public boolean equalsByBaseAmount(KQBalanceOfLeaveEntity entity) {
if (this.baseAmount != entity.getBaseAmount()
|| this.baseAmount2 != entity.getBaseAmount2()) {
return false;
} else {
return true;
}
}
}

View File

@ -0,0 +1,235 @@
package com.engine.kq.entity;
public class KQGroupEntity {
private String id;
private String groupname;
private String excludeid;
private String excludecount;
private String subcompanyid;
private String kqtype;
private String serialids;
private String weekday;
private String signstart;
private String workhour;
private String isdelete;
private String signintype;
private String ipscope;
private String locationcheck;
private String locationcheckscope;
private String wificheck;
private String outsidesign;
private String outsignapprove;
private String validity;
private String validityfromdate;
private String validityenddate;
private String locationfacecheck;
private String locationshowaddress;
private String wififacecheck;
private String calmethod;
private String abnormalremind;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getGroupname() {
return groupname;
}
public void setGroupname(String groupname) {
this.groupname = groupname;
}
public String getExcludeid() {
return excludeid;
}
public void setExcludeid(String excludeid) {
this.excludeid = excludeid;
}
public String getExcludecount() {
return excludecount;
}
public void setExcludecount(String excludecount) {
this.excludecount = excludecount;
}
public String getSubcompanyid() {
return subcompanyid;
}
public void setSubcompanyid(String subcompanyid) {
this.subcompanyid = subcompanyid;
}
public String getKqtype() {
return kqtype;
}
public void setKqtype(String kqtype) {
this.kqtype = kqtype;
}
public String getSerialids() {
return serialids;
}
public void setSerialids(String serialids) {
this.serialids = serialids;
}
public String getWeekday() {
return weekday;
}
public void setWeekday(String weekday) {
this.weekday = weekday;
}
public String getSignstart() {
return signstart;
}
public void setSignstart(String signstart) {
this.signstart = signstart;
}
public String getWorkhour() {
return workhour;
}
public void setWorkhour(String workhour) {
this.workhour = workhour;
}
public String getIsdelete() {
return isdelete;
}
public void setIsdelete(String isdelete) {
this.isdelete = isdelete;
}
public String getSignintype() {
return signintype;
}
public void setSignintype(String signintype) {
this.signintype = signintype;
}
public String getIpscope() {
return ipscope;
}
public void setIpscope(String ipscope) {
this.ipscope = ipscope;
}
public String getLocationcheck() {
return locationcheck;
}
public void setLocationcheck(String locationcheck) {
this.locationcheck = locationcheck;
}
public String getLocationcheckscope() {
return locationcheckscope;
}
public void setLocationcheckscope(String locationcheckscope) {
this.locationcheckscope = locationcheckscope;
}
public String getOutsidesign() {
return outsidesign;
}
public String getOutsignapprove() {return outsignapprove;}
public String getValidity() {
return validity;
}
public void setValidity(String validity) {
this.validity = validity;
}
public String getValidityfromdate() {
return validityfromdate;
}
public void setValidityfromdate(String validityfromdate) {
this.validityfromdate = validityfromdate;
}
public String getValidityenddate() {
return validityenddate;
}
public void setValidityenddate(String validityenddate) {
this.validityenddate = validityenddate;
}
public void setOutsidesign(String outsidesign) {this.outsidesign = outsidesign;}
public void setOutsignapprove(String outsignapprove) {
this.outsignapprove = outsignapprove;
}
public String getWificheck() {
return wificheck;
}
public void setWificheck(String wificheck) {
this.wificheck = wificheck;
}
public String getLocationfacecheck() {
return locationfacecheck;
}
public void setLocationfacecheck(String locationfacecheck) {
this.locationfacecheck = locationfacecheck;
}
public String getLocationshowaddress() {
return locationshowaddress;
}
public void setLocationshowaddress(String locationshowaddress) {
this.locationshowaddress = locationshowaddress;
}
public String getWififacecheck() {
return wififacecheck;
}
public void setWififacecheck(String wififacecheck) {
this.wififacecheck = wififacecheck;
}
public String getCalmethod() {
return calmethod;
}
public void setCalmethod(String calmethod) {
this.calmethod = calmethod;
}
public String getAbnormalremind() {
return this.abnormalremind;
}
public void setAbnormalremind( String abnormalremind) {
this.abnormalremind = abnormalremind;
}
}

View File

@ -0,0 +1,253 @@
package com.engine.kq.entity;
/**
* 加班规则明细
*/
public class KQOvertimeRulesDetailEntity {
/**
* 加班规则明细表的ID
*/
int id;
/**
* 加班规则主表的ID
*/
int ruleId;
/**
* 日期类型1-节假日2-工作日3-休息日
*/
int dayType;
/**
* 是否允许加班0-不允许1-允许
*/
int overtimeEnable = 0;
/**
* 加班计算方式
* 1-需审批以审批单为准
* 2-需审批以打卡为准但是不能超过审批时长
* 3-无需审批根据打卡时间计算加班时长
* 4-需审批打卡和流程均统计取两者的交集
*/
int computingMode = -1;
/**
* 加班起算时间
*/
int startTime = -1;
/**
* 最小加班时长
*/
int minimumLen = -1;
int maxmumLen = -1;
/**
* 是否允许加班转调休0-不允许1-允许
*/
int paidLeaveEnable = 0;
/**
* 加班时长转调休时长的比例中的加班时长
*/
double lenOfOvertime = -1;
/**
* 加班时长转调休时长的比例中的调休时长
*/
double lenOfLeave = -1;
/**
* 是否排除休息时间
*/
int hasRestTime = 0;
/**
* 上班前 加班起算时间
*/
int before_startTime = 0;
/**
* 是否开启加班归属临界点
*/
int has_cut_point = 0;
/**
* 是否开启午休时间算加班
*/
int isovertimecal=0;
/**
* 加班归属 临界点
*/
String cut_point = "";
/**
* 加班补偿方式 1-默认加班补偿规则2-根据员工在加班流程上选择的加班补偿类型进行补偿两种
*/
int paidLeaveEnableType = 1;
/**
* 默认加班补偿方式 里转调休的方式: 1-按加班时长比例转调休时长2-按加班时长范围设置转调休时长3-按加班的时间段设置转调休时长
*/
int paidLeaveEnableDefaultType = 1;
/**
* 根据员工在加班流程上选择的加班补偿类型进行补偿 里转调休的方式: 1-按加班时长比例转调休时长2-按加班时长范围设置转调休时长3-按加班的时间段设置转调休时长
*/
int paidLeaveEnableFlowType = 1;
/**
* 排除休息时间: 1-设置休息时间2-根据加班时长扣除
*/
int restTimeType = 1;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getRuleId() {
return ruleId;
}
public void setRuleId(int ruleId) {
this.ruleId = ruleId;
}
public int getDayType() {
return dayType;
}
public void setDayType(int dayType) {
this.dayType = dayType;
}
public int getOvertimeEnable() {
return overtimeEnable;
}
public void setOvertimeEnable(int overtimeEnable) {
this.overtimeEnable = overtimeEnable;
}
public int getComputingMode() {
return computingMode;
}
public void setComputingMode(int computingMode) {
this.computingMode = computingMode;
}
public int getStartTime() {
return startTime;
}
public void setStartTime(int startTime) {
this.startTime = startTime;
}
public int getMinimumLen() {
return minimumLen;
}
public void setMinimumLen(int minimumLen) {
this.minimumLen = minimumLen;
}
public int getMaxmumLen() {
return maxmumLen;
}
public void setMaxmumLen(int maxmumLen) {
this.maxmumLen = maxmumLen;
}
public int getPaidLeaveEnable() {
return paidLeaveEnable;
}
public void setPaidLeaveEnable(int paidLeaveEnable) {
this.paidLeaveEnable = paidLeaveEnable;
}
public double getLenOfOvertime() {
return lenOfOvertime;
}
public void setLenOfOvertime(double lenOfOvertime) {
this.lenOfOvertime = lenOfOvertime;
}
public double getLenOfLeave() {
return lenOfLeave;
}
public void setLenOfLeave(double lenOfLeave) {
this.lenOfLeave = lenOfLeave;
}
public int getHasRestTime() {
return hasRestTime;
}
public void setHasRestTime(int hasRestTime) {
this.hasRestTime = hasRestTime;
}
public int getBefore_startTime() {
return before_startTime;
}
public void setBefore_startTime(int before_startTime) {
this.before_startTime = before_startTime;
}
public String getCut_point() {
return cut_point;
}
public void setCut_point(String cut_point) {
this.cut_point = cut_point;
}
public int getHas_cut_point() {
return has_cut_point;
}
public void setHas_cut_point(int has_cut_point) {
this.has_cut_point = has_cut_point;
}
public int getIsOvertimeCal() {
return isovertimecal;
}
public void setIsOvertimeCal(int isovertimecal) {
this.isovertimecal = isovertimecal;
}
public int getPaidLeaveEnableType() {
return paidLeaveEnableType;
}
public void setPaidLeaveEnableType(int paidLeaveEnableType) {
this.paidLeaveEnableType = paidLeaveEnableType;
}
public int getPaidLeaveEnableDefaultType() {
return paidLeaveEnableDefaultType;
}
public void setPaidLeaveEnableDefaultType(int paidLeaveEnableDefaultType) {
this.paidLeaveEnableDefaultType = paidLeaveEnableDefaultType;
}
public int getPaidLeaveEnableFlowType() {
return paidLeaveEnableFlowType;
}
public void setPaidLeaveEnableFlowType(int paidLeaveEnableFlowType) {
this.paidLeaveEnableFlowType = paidLeaveEnableFlowType;
}
public int getRestTimeType() {
return restTimeType;
}
public void setRestTimeType(int restTimeType) {
this.restTimeType = restTimeType;
}
}

View File

@ -0,0 +1,107 @@
package com.engine.kq.entity;
/**
* 考勤同步实体
*/
public class KQScheduleSignEntity {
String loginid = "";
String workcode = "";
String lastname = "";
String signdate = "";
String signtime = "";
String clientaddress = "";
String longitude = "";
String latitude = "";
String createdate = "";
public String getLoginid() {
return loginid;
}
public void setLoginid(String loginid) {
this.loginid = loginid;
}
public String getWorkcode() {
return workcode;
}
public void setWorkcode(String workcode) {
this.workcode = workcode;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getSigndate() {
return signdate;
}
public void setSigndate(String signdate) {
this.signdate = signdate;
}
public String getSigntime() {
return signtime;
}
public void setSigntime(String signtime) {
this.signtime = signtime;
}
public String getClientaddress() {
return clientaddress;
}
public void setClientaddress(String clientaddress) {
this.clientaddress = clientaddress;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
public String getMemo() {
return memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
public String getCreatedate() {
return createdate;
}
public void setCreatedate(String createdate) {
this.createdate = createdate;
}
String addr = "";
String memo = "";
}

View File

@ -0,0 +1,189 @@
package com.engine.kq.entity;
/**
* 考勤报表明细实体类
*/
public class KQShiftRuleEntity {
private String userId = "";
private String kqDate = "";
private int belatemins = 0;
private int gravebelatemins = 0;
private int leaveearlymins = 0;
private int graveleaveearlymins = 0;
private int absenteeismmins = 0;
private int forgotcheckmins = 0;
private int forgotBeginWorkCheckMins = 0;//上班漏签
private int earlyInMins = 0;//早到分钟数
private int lateOutMins = 0;//晚走分钟数
private String nosign_is_absent = "1";
private String nosign_ishandle = "0";
private String signInTime;
private String signOutTime;
private String early_one_mins;
//上午旷工
private boolean isAMAbsent = false;
//下午旷工
private boolean isPMAbsent = false;
private int on_absenteeismMins;
private int off_absenteeismMins;
public int getForgotBeginWorkCheckMins() {
return forgotBeginWorkCheckMins;
}
public void setForgotBeginWorkCheckMins(int forgotBeginWorkCheckMins) {
this.forgotBeginWorkCheckMins = forgotBeginWorkCheckMins;
}
public int getBelatemins() {
return belatemins;
}
public void setBelatemins(int belatemins) {
this.belatemins = belatemins;
}
public int getGravebelatemins() {
return gravebelatemins;
}
public void setGravebelatemins(int gravebelatemins) {
this.gravebelatemins = gravebelatemins;
}
public int getLeaveearlymins() {
return leaveearlymins;
}
public void setLeaveearlymins(int leaveearlymins) {
this.leaveearlymins = leaveearlymins;
}
public int getGraveleaveearlymins() {
return graveleaveearlymins;
}
public void setGraveleaveearlymins(int graveleaveearlymins) {
this.graveleaveearlymins = graveleaveearlymins;
}
public int getAbsenteeismmins() {
return absenteeismmins;
}
public void setAbsenteeismmins(int absenteeismmins) {
this.absenteeismmins = absenteeismmins;
}
public int getForgotcheckmins() {
return forgotcheckmins;
}
public void setForgotcheckmins(int forgotcheckmins) {
this.forgotcheckmins = forgotcheckmins;
}
public int getEarlyInMins() {
return earlyInMins;
}
public void setEarlyInMins(int earlyInMins) {
this.earlyInMins = earlyInMins;
}
public int getLateOutMins() {
return lateOutMins;
}
public void setLateOutMins(int lateOutMins) {
this.lateOutMins = lateOutMins;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getKqDate() {
return kqDate;
}
public void setKqDate(String kqDate) {
this.kqDate = kqDate;
}
public String getNosign_is_absent() {
return nosign_is_absent;
}
public void setNosign_is_absent(String nosign_is_absent) {
this.nosign_is_absent = nosign_is_absent;
}
public String getNosign_ishandle() {
return nosign_ishandle;
}
public void setNosign_ishandle(String nosign_ishandle) {
this.nosign_ishandle = nosign_ishandle;
}
public String getSignInTime() {
return signInTime;
}
public void setSignInTime(String signInTime) {
this.signInTime = signInTime;
}
public String getSignOutTime() {
return signOutTime;
}
public void setSignOutTime(String signOutTime) {
this.signOutTime = signOutTime;
}
public String getEarly_one_mins() {
return early_one_mins;
}
public void setEarly_one_mins(String early_one_mins) {
this.early_one_mins = early_one_mins;
}
public boolean isAMAbsent() {
return isAMAbsent;
}
public void setAMAbsent(boolean AMAbsent) {
isAMAbsent = AMAbsent;
}
public boolean isPMAbsent() {
return isPMAbsent;
}
public void setPMAbsent(boolean PMAbsent) {
isPMAbsent = PMAbsent;
}
public int getOn_absenteeismMins() {
return on_absenteeismMins;
}
public void setOn_absenteeismMins(int on_absenteeismMins) {
this.on_absenteeismMins = on_absenteeismMins;
}
public int getOff_absenteeismMins() {
return off_absenteeismMins;
}
public void setOff_absenteeismMins(int off_absenteeismMins) {
this.off_absenteeismMins = off_absenteeismMins;
}
}

View File

@ -0,0 +1,220 @@
package com.engine.kq.entity;
import java.util.List;
import java.util.Map;
/***
* 工作时间
*/
public class WorkTimeEntity {
private String groupId;//所属考勤组
private String groupName;//所属考勤组
private String kqType;//考勤类型
private String serialId;//班次
private Map<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 signoutOnlyoff;
private List<String> halfWorkTime;//半天
private List<int[]> halfWorkIndex;
/**
* 是否是非工作日 1表示是非工作日班次
*/
private int nonWorkShift;
/**
* 当前日期类型
* playday 休息日
* work 工作日
* holiday 节假日
*/
private String dayType;
/**
* 应出勤折算天数
*/
private String convertAttendDay = "";
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public String getKQType() {
return kqType;
}
public void setKQType(String kqType) {
this.kqType = kqType;
}
public String getSerialId() {
return serialId;
}
public void setSerialId(String serialId) {
this.serialId = serialId;
}
public Map<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 getNonWorkShift() {
return nonWorkShift;
}
public void setNonWorkShift(int restShift) {
this.nonWorkShift = restShift;
}
public String getDayType() {
return dayType;
}
public void setDayType(String dayType) {
this.dayType = dayType;
}
public String getConvertAttendDay() {
return convertAttendDay;
}
public void setConvertAttendDay(String convertAttendDay) {
this.convertAttendDay = convertAttendDay;
}
public int getSignoutOnlyoff() {
return signoutOnlyoff;
}
public void setSignoutOnlyoff(int signoutOnlyoff) {
this.signoutOnlyoff = signoutOnlyoff;
}
public List<String> getHalfWorkTime() {
return halfWorkTime;
}
public void setHalfWorkTime(List<String> halfWorkTime) {
this.halfWorkTime = halfWorkTime;
}
public List<int[]> getHalfWorkIndex() {
return halfWorkIndex;
}
public void setHalfWorkIndex(List<int[]> halfWorkIndex) {
this.halfWorkIndex = halfWorkIndex;
}
@Override
public String toString() {
return "WorkTimeEntity{" +
"groupId='" + groupId + '\'' +
", groupName='" + groupName + '\'' +
", kqType='" + kqType + '\'' +
", serialId='" + serialId + '\'' +
", shiftRuleInfo=" + shiftRuleInfo +
", signTime=" + signTime +
", workTime=" + workTime +
", restTime=" + restTime +
", workMins=" + workMins +
", isAcross='" + isAcross + '\'' +
", signstart='" + signstart + '\'' +
", isExclude=" + isExclude +
", calmethod='" + calmethod + '\'' +
", signoutOnlyoff=" + signoutOnlyoff +
", nonWorkShift=" + nonWorkShift +
", dayType='" + dayType + '\'' +
", convertAttendDay='" + convertAttendDay + '\'' +
'}';
}
}

View File

@ -0,0 +1,52 @@
package com.engine.kq.jucailin.genid;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.Random;
public class DefaultWorker implements Worker{
private Random random = new Random();
public DefaultWorker() {
}
public long getWorkerId() {
int max = 100000;
int min = 10000;
int s = this.random.nextInt(max) % (max - min + 1) + min;
String ip = this.getHostIp();
long workerId = 0L;
if (ip != null) {
String str = ip.replaceAll("\\.", "") + s;
workerId = Long.parseLong(str);
workerId %= 1024L;
}
return workerId;
}
private String getHostIp() {
try {
Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
while(allNetInterfaces.hasMoreElements()) {
NetworkInterface netInterface = (NetworkInterface)allNetInterfaces.nextElement();
Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
while(addresses.hasMoreElements()) {
InetAddress ip = (InetAddress)addresses.nextElement();
if (ip != null && ip instanceof Inet4Address
&& !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {
return ip.getHostAddress();
}
}
}
} catch (Exception var5) {
var5.printStackTrace();
}
return "127.0.0.1";
}
}

View File

@ -0,0 +1,16 @@
package com.engine.kq.jucailin.genid;
/**
* id生成器
*/
public class IdGenerator {
public static long generate() {
SnowflakeId snowflakeId = new SnowflakeId();
return snowflakeId.get();
}
public static void main(String[] args) {
System.out.println(generate());
}
}

View File

@ -0,0 +1,93 @@
package com.engine.kq.jucailin.genid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SnowflakeId {
private static final Logger logger = LoggerFactory.getLogger(SnowflakeId.class);
private DefaultWorker worker;
private long startTime = this._curSecond();
private long time;
private long segment = 0L;
private long workerId = this.getWorker().getWorkerId();
private long sequence = 0L;
private static final long segmentBits = 9L;
private static final long workerIdBits = 10L;
private static final long sequenceBits = 13L;
private static final long timestampShift = 32L;
private static final long segmentShift = 23L;
private static final long workerIdShift = 13L;
private static final long sequenceMask = 8191L;
private static final long maxSegment = 511L;
private long twepoch = 1483200000L;
private long _counter = 0L;
public SnowflakeId() {
this.time = this.startTime - this.twepoch;
}
public DefaultWorker getWorker() {
return new DefaultWorker();
}
public void setWorker(DefaultWorker worker) {
this.worker = worker;
}
public synchronized long get() {
long id = this.getNextId();
this.testSpeedLimit();
return id;
}
public synchronized long[] getRangeId(int sizeOfIds) {
long[] r = new long[]{this.getNextId(), 0L};
this.sequence = this.sequence + (long)sizeOfIds - 1L - 1L;
this._counter = this._counter + (long)sizeOfIds - 1L - 1L;
if (this.sequence >> 13 > 0L) {
this.sequence &= 8191L;
if (this.segment >= 511L) {
++this.time;
this.segment = 0L;
} else {
++this.segment;
}
}
r[1] = this.getNextId();
this.testSpeedLimit();
return r;
}
private long getNextId() {
++this.sequence;
++this._counter;
if (this.sequence >> 13 > 0L) {
if (this.segment >= 511L) {
++this.time;
} else {
this.sequence = 0L;
++this.segment;
}
}
return this.time << 32 | this.segment << 23 | this.workerId << 13 | this.sequence;
}
private long _curSecond() {
return System.currentTimeMillis() / 1000L;
}
private synchronized void testSpeedLimit() {
long spentTime = this._curSecond() - this.startTime + 1L;
if (spentTime <= 0L || spentTime << 22 <= this._counter) {
try {
this.wait(10L);
this.testSpeedLimit();
} catch (Exception var4) {
logger.error(var4.getMessage(), var4);
}
}
}
}

View File

@ -0,0 +1,5 @@
package com.engine.kq.jucailin.genid;
public interface Worker {
long getWorkerId();
}

View File

@ -0,0 +1,19 @@
package com.engine.kq.jucailin.util;
import java.sql.Date;
import java.sql.Timestamp;
public class KQDateUtil {
public static Date getUpdateDate(){
Long now = System.currentTimeMillis();
Date date = new Date(now);
return date;
}
public static Timestamp getUpdateTimeStamp(){
Long now = System.currentTimeMillis();
Timestamp timestamp = new Timestamp(now);
return timestamp;
}
}

View File

@ -0,0 +1,829 @@
package com.engine.kq.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import com.engine.kq.biz.KQSettingsComInfo;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.ss.util.RegionUtil;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.GCONST;
import weaver.general.Util;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ExcelUtil extends BaseBean {
private boolean isKqReportHalfOpen = "1".equals(new KQSettingsComInfo().getMain_val("kq_report_half"));
/*
* 导出数据
* */
public Map export(Map<String, Object> workBook, HttpServletRequest request, HttpServletResponse response) throws Exception {
return export(workBook, request, response,false);
}
public Map export(Map<String, Object> workBook, HttpServletRequest request, HttpServletResponse response,boolean isWrap) throws Exception {
Map<String, Object> returnMap = new HashMap<>();
String createFile = "";
try {
SXSSFWorkbook workbook = new SXSSFWorkbook(); // 创建工作簿对象
List<Object> lsSheet = (List<Object>) workBook.get("sheet");
String fileName = Util.null2String(workBook.get("fileName"));
if (fileName.length() == 0||true) fileName = "" + UUID.randomUUID();//解决lunix下中文文件无法生成问题
for (int sheetNum = 0; sheetNum < lsSheet.size(); sheetNum++) {
Map<String, Object> mySheet = (Map<String, Object>) lsSheet.get(sheetNum);
String mySheetName = Util.null2String(mySheet.get("sheetName"));
String sheetTitle = Util.null2String(mySheet.get("sheetTitle"));
List<Object> sheetMemo = (List<Object>) mySheet.get("sheetMemo");
List<Object> titleList = (List<Object>) mySheet.get("titleList");
List<Object> dataList = (List<Object>) mySheet.get("dataList");
List<Map<String, Object>> constraintList = (List<Map<String, Object>>) mySheet.get("constraintList");
createFile = Util.null2String(mySheet.get("createFile"));
int calIndex = Util.getIntValue(Util.null2String(mySheet.get("calIndex")),-1);
Sheet sheet = workbook.createSheet(mySheetName); // 创建工作表
int rowIdx = 0;
// 产生表格标题行
Row rowm = sheet.createRow(rowIdx);
Cell cellTiltle = rowm.createCell(0);
CellStyle titleStyle = this.getTitleStyle(workbook);//获取列头样式对象
CellStyle memoStyle = this.getMemoStyle(workbook);//获取备注样式对象
CellStyle columnTopStyle = this.getColumnTopStyle(workbook);//获取列头样式对象
CellStyle cellStyle = this.getCellStyle(workbook,isWrap); //单元格样式对象
int mergedRegion = titleList.size() - 1;
if (mergedRegion > 15) mergedRegion = 15;
mergedRegion = getColLength(titleList);
CellRangeAddress region = new CellRangeAddress(rowIdx, ++rowIdx, 0, mergedRegion);
RegionUtil.setBorderBottom(BorderStyle.THIN, region, sheet);
RegionUtil.setBorderLeft(BorderStyle.THIN, region, sheet);
RegionUtil.setBorderRight(BorderStyle.THIN, region, sheet);
RegionUtil.setBorderTop(BorderStyle.THIN, region, sheet);
sheet.addMergedRegionUnsafe(region);
cellTiltle.setCellStyle(titleStyle);
cellTiltle.setCellValue(sheetTitle);
for (int i = 0; sheetMemo != null && i < sheetMemo.size(); i++) {
rowm = sheet.createRow(++rowIdx);
Cell cellMemo = rowm.createCell(0);
region = new CellRangeAddress(rowIdx, ++rowIdx, 0, mergedRegion);
RegionUtil.setBorderBottom(BorderStyle.THIN, region, sheet);
RegionUtil.setBorderLeft(BorderStyle.THIN, region, sheet);
RegionUtil.setBorderRight(BorderStyle.THIN, region, sheet);
RegionUtil.setBorderTop(BorderStyle.THIN, region, sheet);
sheet.addMergedRegionUnsafe(region);
cellMemo.setCellStyle(memoStyle);
cellMemo.setCellValue(Util.null2String(sheetMemo.get(i)));
}
// // 定义所需列数
// int columnNum = titleList.size();
// HSSFRow rowRowName = sheet.createRow(++rowIdx); // 在索引2的位置创建行(最顶端的行开始的第二行)
//
// // 将列头设置到sheet的单元格中
// for (int n = 0; n < columnNum; n++) {
// Map title = (Map) titleList.get(n);
//
// HSSFCell cellRowName = rowRowName.createCell(n); //创建列头对应个数的单元格
// cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); //设置列头单元格的数据类型
// HSSFRichTextString text = new HSSFRichTextString(Util.null2String(title.get("title")));
// cellRowName.setCellValue(text); //设置列头单元格的值
// cellRowName.setCellStyle(columnTopStyle); //设置列头单元格样式
// if (n == 0) {
// sheet.setColumnWidth(n, Util.getIntValue(Util.null2String(title.get("width"))));
// } else {
// sheet.setColumnWidth(n, Util.getIntValue(Util.null2String(title.get("width"))));
// }
// }
rowIdx = this.initDynamicTitle(sheet, titleList, columnTopStyle, rowIdx);
if(isKqReportHalfOpen) {
if(calIndex > -1){
CellStyle style1 = workbook.createCellStyle();
style1.setFillPattern(FillPatternType.SOLID_FOREGROUND);
short amColor = (short) Util.getIntValue("5");
style1.setFillForegroundColor(amColor);
style1.setFillBackgroundColor(IndexedColors.BLUE.index);
style1.setAlignment(HorizontalAlignment.CENTER);
//设置底边框;
style1.setBorderBottom(BorderStyle.THIN);
//设置底边框颜色;
style1.setBottomBorderColor(IndexedColors.BLACK.index);
//设置左边框;
style1.setBorderLeft(BorderStyle.THIN);
//设置左边框颜色;
style1.setLeftBorderColor(IndexedColors.BLACK.index);
//设置右边框;
style1.setBorderRight(BorderStyle.THIN);
//设置右边框颜色;
style1.setRightBorderColor(IndexedColors.BLACK.index);
//设置顶边框;
style1.setBorderTop(BorderStyle.THIN);
//设置顶边框颜色;
style1.setTopBorderColor(IndexedColors.BLACK.index);
CellStyle style2 = workbook.createCellStyle();
style2.setFillPattern(FillPatternType.SOLID_FOREGROUND);
short pm_color = (short) Util.getIntValue("29");
style2.setFillForegroundColor(pm_color);
style2.setFillBackgroundColor(IndexedColors.RED.index);
style2.setAlignment(HorizontalAlignment.CENTER);
//设置底边框;
style2.setBorderBottom(BorderStyle.THIN);
//设置底边框颜色;
style2.setBottomBorderColor(IndexedColors.BLACK.index);
//设置左边框;
style2.setBorderLeft(BorderStyle.THIN);
//设置左边框颜色;
style2.setLeftBorderColor(IndexedColors.BLACK.index);
//设置右边框;
style2.setBorderRight(BorderStyle.THIN);
//设置右边框颜色;
style2.setRightBorderColor(IndexedColors.BLACK.index);
//设置顶边框;
style2.setBorderTop(BorderStyle.THIN);
//设置顶边框颜色;
style2.setTopBorderColor(IndexedColors.BLACK.index); //设置单元格样式
//将查询出的数据设置到sheet对应的单元格中
for (int i = 0; dataList != null && i < dataList.size(); ) {
List<Object> obj = (List<Object>) dataList.get(i);//遍历每个对象
int rowNowIndex = i + rowIdx + 1;
Row row = sheet.createRow(rowNowIndex);//创建所需的行数
for (int j = 0; j < obj.size(); j++) {
Cell cell = null; //设置单元格的数据类型
cell = row.createCell(j, CellType.STRING);
if(j < calIndex){
cell.setCellStyle(cellStyle); //设置单元格样式
addMergedRegion(sheet, rowNowIndex, rowNowIndex+1, j, j);
}else{
addMergedRegion(sheet, rowNowIndex, rowNowIndex, j, j);
cell.setCellStyle(style1); //设置单元格样式
}
String value_value = Util.null2String(obj.get(j));
cell.setCellValue(value_value); //设置单元格的值
}
List<Object> obj1 = (List<Object>) dataList.get(i+1);//遍历每个对象
Row row1 = sheet.createRow(rowNowIndex + 1);//创建所需的行数
for (int j = 0; j < obj1.size(); j++) {
Cell cell = null; //设置单元格的数据类型
cell = row1.createCell(j, CellType.STRING);
if(j < calIndex){
cell.setCellStyle(cellStyle); //设置单元格样式
}else{
addMergedRegion(sheet, rowNowIndex+1, rowNowIndex+1, j, j);
cell.setCellStyle(style2);
String value_value = Util.null2String(obj1.get(j));
cell.setCellValue(value_value); //设置单元格的值
}
}
i = i +2;
}
}
} else {
for (int i = 0; dataList != null && i < dataList.size(); i++) {
List<Object> obj = (List<Object>) dataList.get(i);//遍历每个对象
Row row = sheet.createRow(i + rowIdx + 1);//创建所需的行数
for (int j = 0; j < obj.size(); j++) {
Cell cell = null; //设置单元格的数据类型
cell = row.createCell(j, CellType.STRING);
cell.setCellValue(Util.null2String(obj.get(j))); //设置单元格的值
cell.setCellStyle(cellStyle); //设置单元格样式
}
}
}
// int columnNum = this.getColumnLength(titleList);
// //让列宽随着导出的列长自动适应
// for (int colNum = 0; colNum < columnNum; colNum++) {
// int columnWidth = sheet.getColumnWidth(colNum) / 256;
// for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
// HSSFRow currentRow;
// //当前行未被使用过
// if (sheet.getRow(rowNum) == null) {
// currentRow = sheet.createRow(rowNum);
// } else {
// currentRow = sheet.getRow(rowNum);
// }
// if (currentRow.getCell(colNum) != null) {
// //取得当前的单元格
// HSSFCell currentCell = currentRow.getCell(colNum);
// //如果当前单元格类型为字符串
// if (currentCell.getCellTypeEnum() == CellType.STRING) {
// int length = currentCell.getStringCellValue().getBytes().length;
// if (columnWidth < length) {
// //将单元格里面值大小作为列宽度
// columnWidth = length;
// }
// }
// }
// }
// //再根据不同列单独做下处理
// if (colNum == 0) {
// sheet.setColumnWidth(colNum, (columnWidth - 2) * 256);
// } else {
// sheet.setColumnWidth(colNum, (columnWidth + 4) * 256);
// }
// }
for (int i = 0; constraintList != null && i < constraintList.size(); i++) {
Map<String, Object> constraint = constraintList.get(i);
int firstRow = Util.getIntValue(Util.null2String(constraint.get("firstRow")), 0);
int endRow = Util.getIntValue(Util.null2String(constraint.get("endRow")), 0);
int firstCol = Util.getIntValue(Util.null2String(constraint.get("firstCol")), 0);
int endCol = Util.getIntValue(Util.null2String(constraint.get("endCol")), 0);
//设置下拉框数据
String[] datas = (String[]) constraint.get("constraintDatas");
String hiddenSheetName = "constraintDataSheet"+i;
Sheet hiddenSheet = workbook.createSheet(hiddenSheetName);
workbook.setSheetHidden(workbook.getSheetIndex(hiddenSheet), true);
for (int j = 0; j< datas.length; j++) {
hiddenSheet.createRow(j).createCell(0).setCellValue(datas[j]);
}
DataValidationHelper helper = sheet.getDataValidationHelper();
String formulaId = hiddenSheetName + "!$A$1:$A$" + datas.length;
DataValidationConstraint dataValidationConstraint = helper.createFormulaListConstraint(formulaId);
CellRangeAddressList cellRangeAddressList = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
DataValidation dataValidation = helper.createValidation(dataValidationConstraint, cellRangeAddressList);
//处理Excel兼容性问题
if (dataValidation instanceof DataValidation) {
dataValidation.setSuppressDropDownArrow(true);
dataValidation.setShowErrorBox(true);
} else {
dataValidation.setSuppressDropDownArrow(false);
}
sheet.addValidationData(dataValidation);
}
// for (int i = 0; constraintList != null && i < constraintList.size(); i++) {
// Map<String, Object> constraint = constraintList.get(i);
// int firstRow = Util.getIntValue(Util.null2String(constraint.get("firstRow")), 0);
// int endRow = Util.getIntValue(Util.null2String(constraint.get("endRow")), 0);
// int firstCol = Util.getIntValue(Util.null2String(constraint.get("firstCol")), 0);
// int endCol = Util.getIntValue(Util.null2String(constraint.get("endCol")), 0);
//
// //设置下拉框数据
// String[] datas = (String[]) constraint.get("constraintDatas");
// DataValidationHelper helper = sheet.getDataValidationHelper();
// DataValidationConstraint dataValidationConstraint = helper.createExplicitListConstraint(datas);
// CellRangeAddressList cellRangeAddressList = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
// DataValidation dataValidation = helper.createValidation(dataValidationConstraint, cellRangeAddressList);
// //处理Excel兼容性问题
// if (dataValidation instanceof DataValidation) {
// dataValidation.setSuppressDropDownArrow(true);
// dataValidation.setShowErrorBox(true);
// } else {
// dataValidation.setSuppressDropDownArrow(false);
// }
// sheet.addValidationData(dataValidation);
// }
}
if (workbook != null) {
if (createFile.equals("1")) {
String filePath = GCONST.getRootPath() + "/hrm/kq/tmpFile/";
File file = new File(filePath);
if (!file.exists()) {
file.mkdirs();
}
fileName = fileName +"("+DateUtil.getNowDateTimeStr()+")";
String url = filePath + fileName + ".xlsx";
String realUrl = "/hrm/kq/tmpFile/" + fileName + ".xlsx";
FileOutputStream fOut = new FileOutputStream(url);
workbook.write(fOut);
fOut.flush();
fOut.close();
returnMap.put("url", realUrl);
} else {
response.reset();
response.setContentType("application/vnd.ms-excel;charset=utf-8");
// response.setCharacterEncoding("utf-8");
String header = request.getHeader("User-Agent").toUpperCase();
if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
fileName = URLEncoder.encode(fileName, "utf-8");
fileName = fileName.replace("+", "%20"); //IE下载文件名空格变+号问题
} else {
fileName = new String(fileName.getBytes("utf-8"), "ISO_8859_1");
}
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
response.setContentType("application/msexcel");
response.setContentType("application/x-msdownload");
OutputStream responseOutput = response.getOutputStream();
workbook.write(responseOutput);
responseOutput.flush();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return returnMap;
}
/*
* 列头单元格样式
*/
private CellStyle getMemoStyle(SXSSFWorkbook workbook) {
// 设置字体
Font font = workbook.createFont();
//设置字体大小
font.setFontHeightInPoints((short) 10);
//字体加粗
font.setBold(true);
//设置字体名字
font.setFontName("宋体");
//设置样式;
CellStyle style = workbook.createCellStyle();
//设置底边框;
style.setBorderBottom(BorderStyle.THIN);
//设置底边框颜色;
style.setBottomBorderColor(IndexedColors.BLACK.index);
//设置左边框;
style.setBorderLeft(BorderStyle.THIN);
//设置左边框颜色;
style.setLeftBorderColor(IndexedColors.BLACK.index);
//设置右边框;
style.setBorderRight(BorderStyle.THIN);
//设置右边框颜色;
style.setRightBorderColor(IndexedColors.BLACK.index);
//设置顶边框;
style.setBorderTop(BorderStyle.THIN);
//设置顶边框颜色;
style.setTopBorderColor(IndexedColors.BLACK.index);
//在样式用应用设置的字体;
style.setFont(font);
//设置自动换行;
style.setWrapText(false);
//设置水平对齐的样式为居中对齐;
style.setAlignment(HorizontalAlignment.LEFT);
//设置垂直对齐的样式为居中对齐;
style.setVerticalAlignment(VerticalAlignment.CENTER);
return style;
}
/*
* 列头单元格样式
*/
private CellStyle getTitleStyle(SXSSFWorkbook workbook) {
// 设置字体
Font font = workbook.createFont();
//设置字体大小
font.setFontHeightInPoints((short) 14);
//字体加粗
font.setBold(true);
//设置字体名字
font.setFontName("宋体");
//设置样式;
CellStyle style = workbook.createCellStyle();
//设置底边框;
style.setBorderBottom(BorderStyle.THIN);
//设置底边框颜色;
style.setBottomBorderColor(IndexedColors.BLACK.index);
//设置左边框;
style.setBorderLeft(BorderStyle.THIN);
//设置左边框颜色;
style.setLeftBorderColor(IndexedColors.BLACK.index);
//设置右边框;
style.setBorderRight(BorderStyle.THIN);
//设置右边框颜色;
style.setRightBorderColor(IndexedColors.BLACK.index);
//设置顶边框;
style.setBorderTop(BorderStyle.THIN);
//设置顶边框颜色;
style.setTopBorderColor(IndexedColors.BLACK.index);
//在样式用应用设置的字体;
style.setFont(font);
//设置自动换行;
style.setWrapText(false);
//设置水平对齐的样式为居中对齐;
style.setAlignment(HorizontalAlignment.CENTER);
//设置垂直对齐的样式为居中对齐;
style.setVerticalAlignment(VerticalAlignment.CENTER);
return style;
}
/*
* 列头单元格样式
*/
private CellStyle getColumnTopStyle(SXSSFWorkbook workbook) {
// 设置字体
Font font = workbook.createFont();
//设置字体大小
font.setFontHeightInPoints((short) 11);
//字体加粗
font.setBold(true);
//设置字体名字
font.setFontName("宋体");
//设置样式;
CellStyle style = workbook.createCellStyle();
//设置底边框;
style.setBorderBottom(BorderStyle.THIN);
//设置底边框颜色;
style.setBottomBorderColor(IndexedColors.BLACK.index);
//设置左边框;
style.setBorderLeft(BorderStyle.THIN);
//设置左边框颜色;
style.setLeftBorderColor(IndexedColors.BLACK.index);
//设置右边框;
style.setBorderRight(BorderStyle.THIN);
//设置右边框颜色;
style.setRightBorderColor(IndexedColors.BLACK.index);
//设置顶边框;
style.setBorderTop(BorderStyle.THIN);
//设置顶边框颜色;
style.setTopBorderColor(IndexedColors.BLACK.index);
//在样式用应用设置的字体;
style.setFont(font);
//设置自动换行;
style.setWrapText(true);
//设置水平对齐的样式为居中对齐;
style.setAlignment(HorizontalAlignment.CENTER);
//设置垂直对齐的样式为居中对齐;
style.setVerticalAlignment(VerticalAlignment.CENTER);
return style;
}
/*
* 列数据信息单元格样式
*/
private CellStyle getCellStyle(SXSSFWorkbook workbook,boolean isWrap) {
// 设置字体
Font font = workbook.createFont();
//设置字体大小
//font.setFontHeightInPoints((short)10);
//字体加粗
//font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//设置字体名字
font.setFontName("宋体");
//设置样式;
CellStyle style = workbook.createCellStyle();
//设置底边框;
style.setBorderBottom(BorderStyle.THIN);
//设置底边框颜色;
style.setBottomBorderColor(IndexedColors.BLACK.index);
//设置左边框;
style.setBorderLeft(BorderStyle.THIN);
//设置左边框颜色;
style.setLeftBorderColor(IndexedColors.BLACK.index);
//设置右边框;
style.setBorderRight(BorderStyle.THIN);
//设置右边框颜色;
style.setRightBorderColor(IndexedColors.BLACK.index);
//设置顶边框;
style.setBorderTop(BorderStyle.THIN);
//设置顶边框颜色;
style.setTopBorderColor(IndexedColors.BLACK.index);
//在样式用应用设置的字体;
style.setFont(font);
//设置自动换行;
// style.setWrapText(false);
if(isWrap){
style.setWrapText(true);
}else{
style.setWrapText(false);
}
//设置水平对齐的样式为居中对齐;
style.setAlignment(HorizontalAlignment.LEFT);
//设置垂直对齐的样式为居中对齐;
style.setVerticalAlignment(VerticalAlignment.CENTER);
return style;
}
private CellStyle getCellStyle(SXSSFWorkbook workbook) {
// 设置字体
Font font = workbook.createFont();
//设置字体大小
//font.setFontHeightInPoints((short)10);
//字体加粗
//font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//设置字体名字
font.setFontName("宋体");
//设置样式;
CellStyle style = workbook.createCellStyle();
//设置底边框;
style.setBorderBottom(BorderStyle.THIN);
//设置底边框颜色;
style.setBottomBorderColor(IndexedColors.BLACK.index);
//设置左边框;
style.setBorderLeft(BorderStyle.THIN);
//设置左边框颜色;
style.setLeftBorderColor(IndexedColors.BLACK.index);
//设置右边框;
style.setBorderRight(BorderStyle.THIN);
//设置右边框颜色;
style.setRightBorderColor(IndexedColors.BLACK.index);
//设置顶边框;
style.setBorderTop(BorderStyle.THIN);
//设置顶边框颜色;
style.setTopBorderColor(IndexedColors.BLACK.index);
//在样式用应用设置的字体;
style.setFont(font);
//设置自动换行;
style.setWrapText(false);
//设置水平对齐的样式为居中对齐;
style.setAlignment(HorizontalAlignment.LEFT);
//设置垂直对齐的样式为居中对齐;
style.setVerticalAlignment(VerticalAlignment.CENTER);
return style;
}
public static void main(String[] args) {
String groupid = "1";
String filename = "c://33e2a90d-3347-490c-afff-21de0ef3e3af.xlsx";
int startRow = 3;
RecordSet rs = new RecordSet();
String sql = "";
try {
//必要的权限判断
List<List> lsParams = null;
List params = null;
Workbook workbook = WorkbookFactory.create(new FileInputStream(filename));
for (int idx = 0; idx < workbook.getNumberOfSheets(); idx++) {
Sheet sheet = workbook.getSheetAt(idx);
Row row = null;
Cell cell = null;
lsParams = new ArrayList();
for (int i = startRow; startRow <= sheet.getLastRowNum() && i <= sheet.getLastRowNum(); i++) {
row = sheet.getRow(i);
if (row == null) {
continue;
}
params = new ArrayList();
for (int cellIndex = 0; cellIndex < row.getLastCellNum(); cellIndex++) {
cell = row.getCell((short) cellIndex);
if (cell == null) continue;
params.add(getCellValue(cell).trim());
}
params.add(groupid);
if (Util.null2String(params.get(0)).length() > 0) {
lsParams.add(params);
}
}
if (idx == 0) {
sql = "insert into kq_loaction (loactionname,longitude,latitude,address,groupid) values (?,?,?,?,?) ";
} else {
sql = "insert into kq_wifi (wifiname,mac,groupid) values (?,?,?) ";
}
rs.executeBatchSql(sql, lsParams);
}
} catch (Exception e) {
new BaseBean().writeLog(e);
}
}
public int initDynamicTitle(Sheet sheet, List<Object> columns, CellStyle columnTopStyle, int rowIdx) {
int cur_rowIndx = rowIdx+1;
//title 总行数
int title_rows = cur_rowIndx+getRowNums(columns)-1;
createHeaderRow(sheet, cur_rowIndx, 0,columns,columnTopStyle,title_rows);
return title_rows;
}
/**
* 创建表头
*/
private int createHeaderRow(Sheet sheet, int index, int cellIndex,
List<Object> columnName, CellStyle columnTopStyle, int title_rows) {
Row row = sheet.getRow(index) == null ? sheet.createRow(index) : sheet.getRow(index);
int rows = getRowNums(columnName);
for (int i = 0, exportFieldTitleSize = columnName.size(); i < exportFieldTitleSize; i++) {
Map<String,Object> column = (Map<String, Object>) columnName.get(i);
String title = Util.null2String(column.get("title"));
createStringCell(row, cellIndex, title, columnTopStyle);
if (column.get("children") != null) {
List<Object> childchildColumns = (List<Object>) column.get("children");
// 保持原来的
int tempCellIndex = cellIndex;
cellIndex = createHeaderRow(sheet, rows == 1 ? index : index + 1, cellIndex, childchildColumns,columnTopStyle,
title_rows);
if (childchildColumns.size() > 1) {
addMergedRegion(sheet, index, index, tempCellIndex, cellIndex - 1);
}
cellIndex--;
}else{
addMergedRegion(sheet, index, title_rows, cellIndex, cellIndex);
}
cellIndex++;
}
return cellIndex;
}
/**
* 合并单元格
* @param sheet
* @param firstRow
* @param lastRow
* @param firstCol
* @param lastCol
*/
public void addMergedRegion(Sheet sheet, int firstRow, int lastRow, int firstCol, int lastCol) {
try {
if(firstRow == lastRow && firstCol == lastCol){
return ;
}
CellRangeAddress region = new CellRangeAddress(firstRow, lastRow, firstCol, lastCol);
RegionUtil.setBorderBottom(BorderStyle.THIN, region, sheet);
RegionUtil.setBorderLeft(BorderStyle.THIN, region, sheet);
RegionUtil.setBorderRight(BorderStyle.THIN, region, sheet);
RegionUtil.setBorderTop(BorderStyle.THIN, region, sheet);
sheet.addMergedRegionUnsafe(region);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 创建文本类型的Cell
*/
public void createStringCell(Row row, int cellIndex, String title, CellStyle columnTopStyle) {
Cell cellRowName = row.createCell(cellIndex); //创建列头对应个数的单元格
cellRowName.setCellType(CellType.STRING); //设置列头单元格的数据类型
cellRowName.setCellValue(title); //设置列头单元格的值
cellRowName.setCellStyle(columnTopStyle); //设置列头单元格样式
}
public int initTitle(Sheet sheet, List<Object> columns, CellStyle columnTopStyle, int rowIdx) {
List<Object> lsMergedRegion = new ArrayList<>();
Map<String, Object> mergedRegion = null;
int firstTitleRow = rowIdx + 1;
int lastTitleRow = rowIdx + 2;
Row rowRowName = sheet.createRow(++rowIdx); // 在索引2的位置创建行(最顶端的行开始的第二行)
Row childRowRowName = null;
// 定义所需列数
Map<String, Object> column = null;
List<Object> childColumn = null;
int colIdx = 0;
for (int i = 0; i < columns.size(); i++) {
column = (Map<String, Object>) columns.get(i);
childColumn = (List<Object>) column.get("children");
Cell cellRowName = rowRowName.createCell(colIdx++); //创建列头对应个数的单元格
cellRowName.setCellType(CellType.STRING); //设置列头单元格的数据类型
cellRowName.setCellValue(Util.null2String(column.get("title"))); //设置列头单元格的值
cellRowName.setCellStyle(columnTopStyle); //设置列头单元格样式
if (Util.getIntValue(Util.null2String(column.get("rowSpan"))) == 2) {
if (childRowRowName == null) {
childRowRowName = sheet.createRow(++rowIdx);
}
mergedRegion = new HashMap<String, Object>();
mergedRegion.put("startRow", firstTitleRow);
mergedRegion.put("overRow", lastTitleRow);
mergedRegion.put("startCol", colIdx - 1);
mergedRegion.put("overCol", colIdx - 1);
lsMergedRegion.add(mergedRegion);
}
if (childColumn != null) {
colIdx--;
mergedRegion = new HashMap<String, Object>();
mergedRegion.put("startRow", firstTitleRow);
mergedRegion.put("overRow", firstTitleRow);
mergedRegion.put("startCol", colIdx);
for (int j = 0; j < childColumn.size(); j++) {
column = (Map<String, Object>) childColumn.get(j);
cellRowName = childRowRowName.createCell(colIdx++); //创建列头对应个数的单元格
cellRowName.setCellType(CellType.STRING); //设置列头单元格的数据类型
cellRowName.setCellValue(Util.null2String(column.get("title"))); //设置列头单元格的值
cellRowName.setCellStyle(columnTopStyle);
}
mergedRegion.put("overCol", colIdx - 1);
if (childColumn.size() > 1) {
lsMergedRegion.add(mergedRegion);
}
}
}
for (int i = 0; i < lsMergedRegion.size(); i++) {
mergedRegion = (Map<String, Object>) lsMergedRegion.get(i);
Integer startrow = Util.getIntValue(Util.null2String(mergedRegion.get("startRow")));
Integer overrow = Util.getIntValue(Util.null2String(mergedRegion.get("overRow")));
Integer startcol = Util.getIntValue(Util.null2String(mergedRegion.get("startCol")));
Integer overcol = Util.getIntValue(Util.null2String(mergedRegion.get("overCol")));
CellRangeAddress region = new CellRangeAddress(startrow, overrow, startcol, overcol);
RegionUtil.setBorderBottom(BorderStyle.THIN, region, sheet);
RegionUtil.setBorderLeft(BorderStyle.THIN, region, sheet);
RegionUtil.setBorderRight(BorderStyle.THIN, region, sheet);
RegionUtil.setBorderTop(BorderStyle.THIN, region, sheet);
sheet.addMergedRegionUnsafe(region);
}
return rowIdx;
}
/**
* 获取具体总共有多少列
* @param columns
* @return
*/
private int getColLength(List<Object> columns) {
int length = -1;// 从0开始计算单元格的
for(int i =0 ; i < columns.size() ; i++){
Map<String,Object> column = (Map<String, Object>) columns.get(i);
if (column.get("children") != null) {
List<Object> childchildColumns = (List<Object>) column.get("children");
length += getColLength(childchildColumns) + 1;
} else {
length++;
}
}
return length;
}
/**
* 获取具体总共有多少行
*/
public int getRowNums(List<Object> columns) {
int cnt = 1;
for (int i = 0; i < columns.size(); i++) {
Map<String,Object> column = (Map<String, Object>) columns.get(i);
if (column.get("children") != null) {
List<Object> childchildColumns = (List<Object>) column.get("children");
int tmpcnt = 1+getRowNums(childchildColumns);
if(tmpcnt > cnt){
cnt = tmpcnt;
}
}
}
if(cnt > 1){
return cnt;
}else{
return 1;
}
}
public int getColumnLength(List<Object> columns) {
int columnLength = 0;
Map<String, Object> column = null;
for (int i = 0; i < columns.size(); i++) {
column = (Map<String, Object>) columns.get(i);
if (column.get("colSpan") != null) {
columnLength += Util.getIntValue(Util.null2String(column.get("colSpan")));
} else {
columnLength++;
}
}
return columnLength;
}
/**
* /**
* 获取excel单元格值
*
* @param cell 要读取的单元格对象
* @return
*/
public static String getCellValue(Cell cell) {
String cellValue = "";
if (cell == null)
return "";
switch (cell.getCellType()) {
case BOOLEAN: // 得到Boolean对象的方法
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case NUMERIC:
if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {// 先看是否是日期格式
SimpleDateFormat sft = new SimpleDateFormat("yyyy-MM-dd");
cellValue = String.valueOf(sft.format(cell.getDateCellValue())); // 读取日期格式
} else {
cellValue = String.valueOf(new Double(cell.getNumericCellValue())); // 读取数字
if (cellValue.endsWith(".0"))
cellValue = cellValue.substring(0, cellValue.indexOf("."));
}
break;
case FORMULA: // 读取公式
cellValue = cell.getCellFormula();
break;
case STRING: // 读取String
cellValue = cell.getStringCellValue();
break;
}
return cellValue;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,44 @@
package com.engine.kq.util.lingyuewuye;
import com.alibaba.fastjson.JSON;
import com.api.integration.Base;
import com.api.personalIncomeTax.web.BabyCareAction;
import com.engine.kq.biz.KQBalanceOfLeaveBiz;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.systeminfo.SystemEnv;
import java.util.Calendar;
public class ExpirationDateMethod {
public String getBalanceStatusShow(String leaveRulesId, String otherParams) {
new BaseBean().writeLog("qc3286856 leaveRulesId="+leaveRulesId+";otherParams="+ JSON.toJSONString(otherParams));
String statusShow = "";
try {
String resourceId = otherParams.split("\\+", 5)[0];
String belongYear = otherParams.split("\\+", 5)[1];
String languageId = otherParams.split("\\+", 5)[2];
String effectiveDate = otherParams.split("\\+", 5)[3];
String expirationDate = otherParams.split("\\+", 5)[4];
/*获取今天的日期、此刻的时间*/
Calendar today = Calendar.getInstance();
String currentDate = Util.add0(today.get(Calendar.YEAR), 4) + "-"
+ Util.add0(today.get(Calendar.MONTH) + 1, 2) + "-"
+ Util.add0(today.get(Calendar.DAY_OF_MONTH), 2);
new BaseBean().writeLog("qc3286856 currentDate="+currentDate);
boolean status = false;
if (currentDate.compareTo(expirationDate) <= 0){
status = true;
}
if (status) {
statusShow = SystemEnv.getHtmlLabelName(2246, Util.getIntValue(languageId, 7));
} else {
statusShow = SystemEnv.getHtmlLabelName(2245, Util.getIntValue(languageId, 7));
}
} catch (Exception e) {
e.printStackTrace();
}
return statusShow;
}
}

View File

@ -0,0 +1,80 @@
package com.engine.kq.util.lingyuewuye;
import com.alibaba.fastjson.JSON;
import com.engine.kq.biz.KQBalanceOfLeaveBiz;
import weaver.conn.RecordSet;
import weaver.file.Prop;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
public class NianJiaUtil {
public void saveExpirationDate(String ruleId,String belongyear,int organizationType,String organizationIds){
String nianjiaId = Prop.getInstance().getPropValue("lingyue_nianjia","nianjiaid");
BaseBean bb = new BaseBean();
bb.writeLog("qc3222529 nianjiaid = "+nianjiaId +";ruleId = "+ruleId);
if (!ruleId.equals(nianjiaId)){//如果传进来的假期id不是年假id不执行下面的代码
return;
}
String searchSql = "select id from hrmresource where (status in (0,1,2,3)) ";
if (organizationType == 1) {
searchSql += " and subCompanyId1 in (" + organizationIds + ") ";
} else if (organizationType == 2) {
searchSql += " and departmentId in (" + organizationIds + ") ";
} else if (organizationType == 3) {
searchSql += " and id in (" + organizationIds + ") ";
}
RecordSet searchRS = new RecordSet();
searchRS.executeQuery(searchSql);
List<List> sqlList = new ArrayList<>();
// String resourceid = "";
while (searchRS.next()){//因为同一个假期规则它生成的失效日期是一样的所以取其中一个人的id出来用于获取失效日期
String resourceid = Util.null2String(searchRS.getString("id"));
String expirationDate = KQBalanceOfLeaveBiz.getExpirationDate(ruleId,resourceid,belongyear,"","");
bb.writeLog("qc3222529 resourceid is not null ===="+resourceid+";expirationDate="+expirationDate+";ruleid="+ruleId+";belongyear="+belongyear);
List<String> list = new ArrayList<>();
list.add(expirationDate);
list.add(resourceid);
sqlList.add(list);
// resourceid = Util.null2String(searchRS.getString("id"));
// break;
}
bb.writeLog("qc3222529 sqlList:"+ JSON.toJSONString(sqlList));
// if (!resourceid.equals("")){
if (sqlList != null && sqlList.size() > 0){
// bb.writeLog("qc3222529 resourceid is not null ===="+resourceid);
// String expirationDate = KQBalanceOfLeaveBiz.getExpirationDate(ruleId,resourceid,belongyear,"","");
String sql = "update kq_BalanceOfLeave set expirationDate=? where leaveRulesId ="+ ruleId +"and belongYear ='"+belongyear+"' and resourceId = ? and (ycts is null or ycts = 0)";
RecordSet rs = new RecordSet();
boolean flag = rs.executeBatchSql(sql, sqlList);
// boolean flag = rs.executeUpdate(sql, expirationDate, ruleId,belongyear);
if (!flag){
bb.writeLog("qc3222529 修改年假失效日期出错!");
}
}
}
public static String getNianJiaExpriationDate(String ruleid,String resourceid,String belongYear){
String sql = "select * from kq_BalanceOfLeave where leaveRulesId = ? and resourceId = ? and belongYear = ?";
RecordSet rs = new RecordSet();
rs.executeQuery(sql,ruleid,resourceid,belongYear);
String expirationDate = "";
while (rs.next()){
expirationDate = Util.null2String(rs.getString("expirationDate"));
// int ycts = Util.getIntValue(rs.getString("ycts"),0);
// DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// // 解析输入的日期
// LocalDate date = LocalDate.parse(expirationDate, formatter);
// expirationDate = date.plusDays(ycts).toString();
}
return expirationDate;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,165 @@
package com.engine.lingyue.web;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.engine.common.util.ParamUtil;
import com.engine.kq.biz.KQFormatBiz;
import com.engine.kq.timer.KQQueue;
import com.engine.kq.timer.KQTaskBean;
import com.engine.kq.wfset.util.SplitActionUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.interfaces.lingyue.util.HttpUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @Title
* @Author wangchaofa
* @CreateDate 2024/7/17
* @Version 1.0
* @Description
*/
public class SynOtherKqInfoAction {
/**
* 获取 中控考勤数据
* @param request
* @param response
* @return
*/
@POST
@Path("/ZkKqInfo")
@Produces({MediaType.TEXT_PLAIN})
public String getReportData(@Context HttpServletRequest request, @Context HttpServletResponse response){
Map<String, Object> apidatas = new HashMap<String, Object>();
RecordSet rs = new RecordSet();
int kq_number = Util.getIntValue(rs.getPropValue("hrm_zhongkong","kq_number"));
HttpUtil httpUtil = new HttpUtil();
int success_num = 0;
int fail_num = 0;
try {
Map<String, Object> params = ParamUtil.request2Map(request);
// 开始时间
String startdatetime = Util.null2String(params.get("startdatetime"));
// 结束时间
String enddatetime = Util.null2String(params.get("enddatetime"));
// 指定人员id
String xmids = Util.null2String(params.get("xmids"));
List<String> lsFormatData = new ArrayList<>();
JSONObject json_main = new JSONObject();
if(startdatetime != null && !"".equals(startdatetime)){
json_main.put("starttime",startdatetime);
}
if(enddatetime != null && !"".equals(enddatetime)){
json_main.put("endtime",enddatetime);
}
if(xmids != null && !"".equals(xmids)){
// 根据人员id 查询 自定义字段 考勤卡号也就是中控考勤机那边的人员编号
for(String xmid : xmids.split(",")){
String cus_userid = httpUtil.getCusIdByUserid(xmid);
if(cus_userid != null && !"".equals(cus_userid)){
json_main.put("pin",cus_userid);
int index = 1;
json_main.put("number",kq_number);
rs.writeLog("============= SynOtherKqInfoAction getReportData json_main =============== "+ json_main);
httpUtil.SynKqData(lsFormatData,index,json_main);
}else{
apidatas.put("status", false);
apidatas.put("message", "HR系统中未维护该人员的考勤卡号");
fail_num++;
continue;
}
}
}
Map<String,List<String>> overtimeMap = Maps.newHashMap();
List<String> overtimeList = Lists.newArrayList();
List<Object> formatParams = null;
List<List<Object>> lsFormatParams = new ArrayList<>();
List<Object> delParams = null;
List<List<Object>> lsDelParams = new ArrayList<>();
for(int i=0;lsFormatData!=null&&i<lsFormatData.size();i++){
success_num ++;
formatParams = new ArrayList<>();
String[] formatData = Util.splitString(lsFormatData.get(i),"|");
String date_1 = HttpUtil.addDateDay(formatData[1],-1);
formatParams.add(formatData[0]);
formatParams.add(date_1);
lsFormatParams.add(formatParams);
formatParams = new ArrayList<>();
formatParams.add(formatData[0]);
formatParams.add(formatData[1]);
lsFormatParams.add(formatParams);
delParams = new ArrayList<>();
delParams.add(formatData[0]);
delParams.add(formatData[1]);
delParams.add(formatData[2]);
lsDelParams.add(delParams);
String resourceId = formatData[0];
String kqdate = formatData[1];
if(overtimeMap.containsKey(resourceId)){
List<String> tmp_overtimeList = overtimeMap.get(resourceId);
if(!tmp_overtimeList.contains(kqdate)){
tmp_overtimeList.add(kqdate);
}
}else{
if(!overtimeList.contains(kqdate)){
overtimeList.add(kqdate);
}
overtimeMap.put(resourceId, overtimeList);
}
}
new KQFormatBiz().format(lsFormatParams);
//处理加班生成
List<KQTaskBean> tasks = new ArrayList<>();
for(Map.Entry<String, List<String>> mme: overtimeMap.entrySet()){
String resid = mme.getKey();
List<String> overList = mme.getValue();
for(String date : overList){
SplitActionUtil.pushOverTimeTasks(date,date,resid,tasks);
}
}
if(!tasks.isEmpty()){
KQQueue.writeTasks(tasks);
}
User user = HrmUserVarify.getUser(request, response);
String message = "成功同步了 "+ success_num +" 条!失败了 "+ fail_num +" 条!";
apidatas.put("status", true);
apidatas.put("message",message);
} catch (Exception e) {
e.printStackTrace();
apidatas.put("status", false);
apidatas.put("message", "catch exception : " + e.getMessage());
}
return JSONObject.toJSONString(apidatas, SerializerFeature.DisableCircularReferenceDetect);
}
}

View File

@ -0,0 +1,551 @@
package com.fage;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import weaver.common.DateUtil;
import weaver.general.TimeUtil;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
/**
* @Title
* @Author wangchaofa
* @CreateDate 2024/7/16
* @Version 1.0
* @Description
*/
public class DemoTest {
private static final String CHARACTERS = "abcdefghijklmnopqrstuvwxyz0123456789";
private static final int LENGTH = 32;
public static void main(String[] args) throws Exception{
// String time = "12:12:13";
// System.out.println(time.substring(0,5));
//
// String a = "2024-11-01";
// System.out.println(addDateMonth(a,-2));
// List<String> list = new ArrayList<>();
//
// list.add("17918368");
// list.add("17918938");
// list.add("17918678");
// list.add("17918733");
// list.add("17918392");
//
// System.out.println(Collections.max(list));
//
// String checktime = "2024-07-10 00:01:15";
// String signDate = checktime.substring(0, 10);
// String signTime = checktime.substring(11, 19);
//
// System.out.println(signDate);
// System.out.println(signTime);
//
// String randomString = generateRandomString();
// System.out.println(randomString);
//
//
// String deptcode = "eb341f9de10c4377848434087abf770c1";
//
// boolean bool = false;
//
// // 获取所有部门信息 接口url
// // key
// String key = "56b2gxturpnypuumxq4bpwhrj1_82cpu0nqwrslzkgzp";
// String get_all_dept_url = "http://222.212.88.118:8989/api/v2/department/get/?key=" + key;
// Map<String,String> headers = new HashMap<>();
// JSONObject json_main = new JSONObject();
//
// json_main.put("deptnumber",deptcode);
//
// String encode = "utf-8";
// String stringJson = json_main.toString();
//
// String content = null;
// CloseableHttpResponse httpResponse = null;
// CloseableHttpClient closeableHttpClient = null;
// try {
// closeableHttpClient = HttpClients.createDefault();
// HttpPost httpost = new HttpPost(get_all_dept_url);
// //设置header
// httpost.setHeader("Content-type", "application/json");
// if (headers != null && headers.size() > 0) {
// for (Map.Entry<String, String> entry : headers.entrySet()) {
// httpost.setHeader(entry.getKey(),entry.getValue());
// }
// }
// //组织请求参数
// StringEntity stringEntity = new StringEntity(stringJson, encode);
// httpost.setEntity(stringEntity);
// //响应信息
// httpResponse = closeableHttpClient.execute(httpost);
// if(httpResponse != null) {
// HttpEntity entity = httpResponse.getEntity();
// content = EntityUtils.toString(entity, encode);
// if (content != null && !"".equals(content)) {
// JSONObject json = JSONObject.parseObject(content);
// System.out.println("============= pushInfo json =================== " + json);
// int ret = Integer.parseInt(json.getString("ret"));
// if(ret == 0){
// String data = json.getString("data");
// JSONObject data_json = JSONObject.parseObject(data);
// if(data_json.isEmpty()){
// System.out.println("5555555555");
// }else{
// System.out.println("666666666");
// }
// }
// }
// }
// } catch (Exception e) {
// e.printStackTrace();
// }finally{
// try {
// httpResponse.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// try { //关闭连接释放资源
// closeableHttpClient.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// String aa = "2024-11-01";
// String bb = "2024-11-30";
// System.out.println(getDays(aa,bb));
//
// String sStartDate = "2024-12-01";
// String sEndDate = "2024-12-31";
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
// Date date1 = sdf.parse(sStartDate);
// Date date2 = sdf.parse(sEndDate);
// long days = (date2.getTime() - date1.getTime()) / (24*3600*1000);
// long yushu = (date2.getTime() - date1.getTime()) % (24*3600*1000);
//
// System.out.println("days:" + days + ",yushu:" + yushu);
//
// //规整方法1
// date1.setHours(0);
// date1.setMinutes(0);
// date1.setSeconds(0);
// long days2 = (date2.getTime() - date1.getTime()) / (24*3600*1000);
// long yushu2 = (date2.getTime() - date1.getTime()) % (24*3600*1000);
//
// System.out.println("days2:" + days2 + ",yushu2:" + yushu2);
//
// //规整方法2
// String sdate1 = sdf.format(date1);
// date1 = sdf.parse(sdate1);
//
// long days3 = (date2.getTime() - date1.getTime()) / (24*3600*1000);
// long yushu3 = (date2.getTime() - date1.getTime()) % (24*3600*1000);
//
// System.out.println("days3:" + days3 + ",yushu3:" + yushu3);
//
// System.out.println(getDays(sStartDate,sEndDate));
//
//
// // 周六或周日天数
// int weekdays = 0;
// // 周一到周五天数
// int workdays = 0;
// // 格式化日期
// DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// String[] dateStartArr = parseDate(sStartDate);
// String[] dateEndtArr = parseDate(sEndDate);
// LocalDate startDate = LocalDate.of(Integer.parseInt(dateStartArr[0]), Integer.parseInt(dateStartArr[1]), Integer.parseInt(dateStartArr[2]));
// LocalDate endDate = LocalDate.of(Integer.parseInt(dateEndtArr[0]), Integer.parseInt(dateEndtArr[1]), Integer.parseInt(dateEndtArr[2]));
// // 遍历日期范围
// for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) {
// // 输出格式化后的日期字符串
// String dateString = date.format(formatter);
// // 周六或 周日
// if(isSaturdayOrSunday(dateString)) {
// weekdays++;
// }else{
// workdays++;
// }
// }
// System.out.println("workdays: "+workdays);
// System.out.println("weekdays: "+weekdays);
// String latemins = "4";
// String serial_hours = "8";
// String result = "";
// String latehours = floatDivide(latemins,"60");
// System.out.println(latehours);
// if(floatCompare(serial_hours,"0") > 0){
// result = floatDivide(latehours,serial_hours);
// }
// System.out.println(result);
//
// double aa = 21.00;
// String bb = "21.01";
// if(Double.valueOf(bb) <= aa){
// System.out.println("5555555555");
// }
// String aa = "2024-02-24 08:12:23";
// String bb = "2024-11-01";
// String cc = "2024-11-30";
// System.out.println(belongEndCalendar(aa,bb,cc));
//
// String ds = "2024-12-31";
// System.out.println(addDateDay(ds,1));
//
// int currentyear = Integer.valueOf(aa.substring(0, 4)); //
// int currentmonth = Integer.valueOf(aa.substring(5, 7)); //
// int currentday = Integer.valueOf(aa.substring(8, 10)); //
// System.out.println(aa.length());
// System.out.println(aa.substring(0,10));
String today = DateUtil.getCurrentDate();
System.out.println(today);
String dismissDate = "2024-12-17";
Calendar cal = DateUtil.getCalendar();
boolean isEnd = false;
String fromDate = "2025-05-01";
String toDate = "2025-05-31";
for (String date = fromDate; !isEnd; ) {
if (date.equals(toDate)) isEnd = true;
if(!"".equals(dismissDate) && DateUtil.compDate(dismissDate, date) > 0) {
System.out.println("111 "+date);
}else if (DateUtil.compDate(today, date) > 0) {
System.out.println("222 "+date);
}
cal.setTime(DateUtil.parseToDate(date));
date = DateUtil.getDate(cal.getTime(), 1);
}
}
/**
* 判断一个时间是否在一个时间段内
*
* @param nowTimee 指定时间
* @param beginTimee 开始时间
* @param endTimee 结束时间
*/
public static boolean belongEndCalendar(String nowTimee, String beginTimee, String endTimee) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date nowTime = null;
Date beginTime = null;
Date endTime = null;
boolean b = false;
try {
nowTime = format.parse(nowTimee);
beginTime = format.parse(beginTimee);
endTime = format.parse(endTimee);
Calendar date = Calendar.getInstance();
date.setTime(nowTime);
Calendar begin = Calendar.getInstance();
begin.setTime(beginTime);
Calendar end = Calendar.getInstance();
end.setTime(endTime);
if(nowTimee.equals(endTimee) || nowTimee.equals(beginTimee)){
b = true;
}else if(date.after(begin) && date.before(end)){//在时间段内
b = true;
}
} catch (Exception ex) {
ex.printStackTrace();
}
return b;
}
public static String generateRandomString() {
Random random = new Random();
StringBuilder sb = new StringBuilder(LENGTH);
for (int i = 0; i < LENGTH; i++) {
sb.append(CHARACTERS.charAt(random.nextInt(CHARACTERS.length())));
}
return sb.toString();
}
/**
* 对时间的月数进行加减
* @param daytime 时间的格式yyyy-MM-dd
* @param month 月数 -1则代表减一月
* @return
*/
public static String addDateMonth(String daytime, int month){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = format.parse(daytime);
if (date == null){
return "";
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MONTH, month);// day
date = cal.getTime();
cal = null;
return format.format(date);
} catch (Exception ex) {
ex.printStackTrace();
}
return "";
}
/**
* 计算两个时间字符串日期的相差天数
*
* @param sStartDate 字符串时间1
* @param sEndDate 字符串时间2
* @return 相差时间
*/
public static int getDays(String sStartDate, String sEndDate) {
int days = 0;
try {
if (!"".equals(sStartDate) && !"".equals(sEndDate)) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = sdf.parse(sStartDate);
Date date2 = sdf.parse(sEndDate);
long Days = (date2.getTime() - date1.getTime()) / (24*3600*1000);
if(Days < 0){
days = 0;
}else{
days = (int)Days+1;
}
}
}catch (Exception e){
e.printStackTrace();
}
return days;
}
/**
* 计算天数
* @param date1 日期
* @param date2 日期
* @return 天数
*/
public static int calculateDays(Date date1, Date date2) {
Calendar cal1 = Calendar.getInstance();
cal1.setTime(date1);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(date2);
int day1 = cal1.get(Calendar.DAY_OF_YEAR);
int day2 = cal2.get(Calendar.DAY_OF_YEAR);
int year1 = cal1.get(Calendar.YEAR);
int year2 = cal2.get(Calendar.YEAR);
if (year1 != year2) {//不同
int timeDistance = 0;
if (year1 < year2) {//后面日期年大于前面日期
for (int i = year1; i < year2; i++) {
if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {//闰年
timeDistance += 366;
} else {//不是闰年
timeDistance += 365;
}
}
} else {
for (int i = year2; i < year1; i++) {
if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {//闰年
timeDistance += 366;
} else {//不是闰年
timeDistance += 365;
timeDistance = 0 - timeDistance;
}
}
}
return timeDistance + (day2 - day1);
} else {//同一年
return day2 - day1;
}
}
private static String[] parseDate(String date){
if (StringUtils.isEmpty(date)) {
return new String[]{"1990", "1", "1"};
}
try {
String[] split = date.split("-");
List<String> list = new ArrayList<>(Arrays.asList(split));
// 只有年
if (list.size() == 1) {
// 添加月
list.add("1");
// 添加日
list.add("1");
}
// 只有年月
else if (list.size() == 2) {
list.add("1");
}
return list.toArray(new String[]{});
}catch (Exception e){
e.printStackTrace();
}
return null;
}
/**
* 判断 日期是否是 周六 周日
* @param dateString
* @return
*/
public static boolean isSaturdayOrSunday(String dateString) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
boolean flag = false;
try {
date = format.parse(dateString);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
if(dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY){
flag = true;
}
} catch (ParseException e) {
e.printStackTrace();
}
return flag;
}
/**
* @param a 任意数
* @return
*/
private static String isZero(String a) {
if (a==null || "".equals(a)) {
a = "0";
}
return a;
}
/**
* 大小比较
*
* @param a
* @param b
* @return -1 小于 0 等于 1 大于
*/
public static int floatCompare(String a, String b) {
a = isZero(a);
b = isZero(b);
BigDecimal bg1 = new BigDecimal(a);
BigDecimal bg2 = new BigDecimal(b);
return bg1.compareTo(bg2);
}
/**
* 方法描述 : 对两个字符串进行金额的相加
* @param a
* @param b
* @return
* String
*/
public static String floatAdd(String a, String b) {
a=a.equals("")?"0":a;
b=b.equals("")?"0":b;
BigDecimal bg1 = new BigDecimal(a);
BigDecimal bg2 = new BigDecimal(b);
BigDecimal bd = bg1.add(bg2);
return bd.toString();
}
/**
*
* 方法描述 : 对两个字符串进行金额的相减
* @param a
* @param b
* @return
* String
*/
public static String floatSubtract(String a, String b) {
a=a.equals("")?"0":a;
b=b.equals("")?"0":b;
BigDecimal bg1 = new BigDecimal(a);
BigDecimal bg2 = new BigDecimal(b);
BigDecimal bd = bg1.subtract(bg2);
return bd.toString();
}
/**
*
* 方法描述 : 对两个字符串进行金额的相乘
* @param a
* @param b
* @return
* String
*/
public static String floatMultiply(String a, String b) {
a=a.equals("")?"0":a;
b=b.equals("")?"0":b;
BigDecimal bg1 = new BigDecimal(a);
BigDecimal bg2 = new BigDecimal(b);
BigDecimal bd = bg1.multiply(bg2).setScale(4, BigDecimal.ROUND_HALF_UP);
return bd.toString();
}
/**
*
* 方法描述 : 对两个字符串进行金额的相除默认保留两位小数
* @param a
* @param b
* @return
* String
*/
public static String floatDivide(String a, String b) {
a=a.equals("")?"0":a;
b=b.equals("")?"0":b;
BigDecimal bg1 = new BigDecimal(a);
BigDecimal bg2 = new BigDecimal(b);
BigDecimal bd = bg1.divide(bg2, 4, BigDecimal.ROUND_HALF_UP);
return bd.toString();
}
/**
* 对时间的天数进行加减
* @param daytime 时间的格式yyyy-MM-dd
* @param day 天数 -1则代表减一天
* @return
*/
public static String addDateDay(String daytime, int day){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = format.parse(daytime);
if (date == null){
return "";
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH, day);// 加一天
date = cal.getTime();
cal = null;
return format.format(date);
} catch (Exception ex) {
ex.printStackTrace();
}
return "";
}
}

View File

@ -0,0 +1,812 @@
package com.lingyue.util;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.company.SubCompanyComInfo;
import weaver.hrm.companyvirtual.DepartmentVirtualComInfo;
import weaver.hrm.finance.SalaryManager;
import weaver.hrm.resource.CustomFieldTreeManager;
import weaver.hrm.resource.ResourceComInfo;
import weaver.hrm.settings.ChgPasswdReminder;
import weaver.hrm.settings.RemindSettings;
import weaver.system.SysRemindWorkflow;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* @Title
* @Author wangchaofa
* @CreateDate 2024/9/12
* @Version 1.0
* @Description
*/
public class KqUtil {
/**
* 新增更新 部门信息 同步至 中控考勤机
* @param deptid
* @return
*/
public static boolean synAddOrUpdateDeptInfo(String deptid){
boolean bool = false;
RecordSet rs = new RecordSet();
// 新增更新部门 接口url
// key
String key = rs.getPropValue("hrm_zhongkong","key");
String url = rs.getPropValue("hrm_zhongkong","add_update_dept_url");
url = url + "?key=" + key;
Map<String,String> headers = new HashMap<>();
JSONArray jsonArray = new JSONArray();
JSONObject json_main = new JSONObject();
rs.executeQuery("select * from hrmdepartment where id = ?",deptid);
rs.next();
String deptcode = Util.null2String(rs.getString("departmentcode"));
String detname = Util.null2String(rs.getString("departmentname"));
String supdepid = Util.null2String(rs.getString("supdepid"));
String subcompanyid1 = Util.null2String(rs.getString("subcompanyid1"));
if(supdepid != null && !"".equals(supdepid) && Integer.parseInt(supdepid) > 0){
String sup_deptcode = "";
String sup_Deptcode = getDeptCuscode(supdepid);
if (sup_Deptcode != null && !"".equals(sup_Deptcode)) {
sup_deptcode = sup_Deptcode;
} else {
sup_deptcode = new DepartmentComInfo().getDepartmentCode(supdepid);
}
json_main.put("parentnumber", sup_deptcode);
}else {
if (subcompanyid1 != null && !"".equals(subcompanyid1) && Integer.parseInt(subcompanyid1) > 0) {
String subcode = "";
String subCode = getSubcomCuscode(subcompanyid1);
if (subCode != null && !"".equals(subCode)) {
subcode = subCode;
} else {
subcode = new SubCompanyComInfo().getSubCompanyCode(subcompanyid1);
}
json_main.put("parentnumber", subcode);
}
}
String dept_code = "";
String deptCode = getDeptCuscode(deptid);
if(deptCode != null && !"".equals(deptCode)){
dept_code = deptCode;
}else{
dept_code = deptcode;
}
json_main.put("deptnumber",dept_code);
json_main.put("deptname",detname);
jsonArray.add(json_main);
rs.writeLog("========================== 新增或修改部门,同步至中控考勤机 ======================================");
rs.writeLog(url+" ========= "+jsonArray.toString());
int result = -1;
String msg = "";
String content = httpPost(url,headers,jsonArray.toString(),"utf-8");
if (content != null && !"".equals(content)) {
JSONObject json = JSONObject.parseObject(content);
rs.writeLog("============= httpPost pushInfo json =================== " + json);
int resultt = Integer.parseInt(json.getString("ret"));
if(resultt == 0){
result = 0;
}else{
result = 1;
}
msg = Util.null2String(json.getString("msg"));
}
//写入建模记录表
insertHrToZkJl(1,url,jsonArray,result,msg,"");
// 0成功
if(result == 0) {
bool = true;
}
return bool;
}
/**
* 新增更新 分部信息 同步至 中控考勤机
* @param subcomid
* @return
*/
public static boolean synAddOrUpdateSubComInfo(String subcomid){
boolean bool = false;
RecordSet rs = new RecordSet();
// 新增更新部门 接口url
// key
String key = rs.getPropValue("hrm_zhongkong","key");
String url = rs.getPropValue("hrm_zhongkong","add_update_dept_url");
url = url + "?key=" + key;
Map<String,String> headers = new HashMap<>();
JSONArray jsonArray = new JSONArray();
JSONObject json_main = new JSONObject();
rs.executeQuery("select * from HrmSubCompany where id = ?",subcomid);
rs.next();
String subcompanycode = Util.null2String(rs.getString("subcompanycode"));
String subcompanyname = Util.null2String(rs.getString("subcompanyname"));
String supsubcomid = Util.null2String(rs.getString("supsubcomid"));
if(supsubcomid != null && !"".equals(supsubcomid) && Integer.parseInt(supsubcomid) > 0){
String subcode = "";
String subCode = getSubcomCuscode(supsubcomid);
if (subCode != null && !"".equals(subCode)) {
subcode = subCode;
} else {
subcode = new SubCompanyComInfo().getSubCompanyCode(supsubcomid);
}
json_main.put("parentnumber", subcode);
}
String subcompany_code = "";
String subcompanyCode = getSubcomCuscode(subcomid);
if (subcompanyCode != null && !"".equals(subcompanyCode)) {
subcompany_code = subcompanyCode;
} else {
subcompany_code = subcompanycode;
}
json_main.put("deptnumber",subcompany_code);
json_main.put("deptname",subcompanyname);
jsonArray.add(json_main);
rs.writeLog("========================== 新增或修改分部,同步至中控考勤机 ======================================");
rs.writeLog(url+" ========= "+jsonArray.toString());
int result = -1;
String msg = "";
String content = httpPost(url,headers,jsonArray.toString(),"utf-8");
if (content != null && !"".equals(content)) {
JSONObject json = JSONObject.parseObject(content);
rs.writeLog("============= httpPost pushInfo json =================== " + json);
int resultt = Integer.parseInt(json.getString("ret"));
if(resultt == 0){
result = 0;
}else{
result = 1;
}
msg = Util.null2String(json.getString("msg"));
}
//写入建模记录表
insertHrToZkJl(1,url,jsonArray,result,msg,"");
// 0成功
if(result == 0) {
bool = true;
}
return bool;
}
/**
* 删除 部门信息 同步至 中控考勤机
* @param deptid
* @return
*/
public static boolean synDeleteDeptInfo(String deptid){
boolean bool = false;
RecordSet rs = new RecordSet();
// 删除部门 接口url
// key
String key = rs.getPropValue("hrm_zhongkong","key");
String url = rs.getPropValue("hrm_zhongkong","delete_dept_url");
url = url + "?key=" + key;
Map<String,String> headers = new HashMap<>();
JSONObject json_main = new JSONObject();
rs.executeQuery("select * from hrmdepartment where id = ?",deptid);
rs.next();
String deptcode = Util.null2String(rs.getString("departmentcode"));
String detname = Util.null2String(rs.getString("departmentname"));
json_main.put("deptnumber",deptcode);
rs.writeLog("========================== 删除部门,同步至中控考勤机 ======================================");
rs.writeLog(url+" ========= "+json_main.toString());
int result = -1;
String msg = "";
String content = httpPost(url,headers,json_main.toString(),"utf-8");
if (content != null && !"".equals(content)) {
JSONObject json = JSONObject.parseObject(content);
rs.writeLog("============= httpPost pushInfo json =================== " + json);
int resultt = Integer.parseInt(json.getString("ret"));
if(resultt == 0){
result = 0;
}else{
result = 1;
}
msg = Util.null2String(json.getString("msg"));
}
JSONArray jsonArray = new JSONArray();
jsonArray.add(json_main);
//写入建模记录表
insertHrToZkJl(1,url,jsonArray,result,msg,"");
// 0成功
if(result == 0) {
bool = true;
}
return bool;
}
/**
* 删除 分部信息 同步至 中控考勤机
* @param subcomid
* @return
*/
public static boolean synDeleteSubComInfo(String subcomid){
boolean bool = false;
RecordSet rs = new RecordSet();
// 新增更新部门 接口url
// key
String key = rs.getPropValue("hrm_zhongkong","key");
String url = rs.getPropValue("hrm_zhongkong","delete_dept_url");
url = url + "?key=" + key;
Map<String,String> headers = new HashMap<>();
JSONObject json_main = new JSONObject();
rs.executeQuery("select * from HrmSubCompany where id = ?",subcomid);
rs.next();
String subcompanycode = Util.null2String(rs.getString("subcompanycode"));
String subcompanyname = Util.null2String(rs.getString("subcompanyname"));
json_main.put("deptnumber",subcompanycode);
rs.writeLog("========================== 删除分部,同步至中控考勤机 ======================================");
rs.writeLog(url+" ========= "+json_main.toString());
int result = -1;
String msg = "";
String content = httpPost(url,headers,json_main.toString(),"utf-8");
if (content != null && !"".equals(content)) {
JSONObject json = JSONObject.parseObject(content);
rs.writeLog("============= httpPost pushInfo json =================== " + json);
int resultt = Integer.parseInt(json.getString("ret"));
if(resultt == 0){
result = 0;
}else{
result = 1;
}
msg = Util.null2String(json.getString("msg"));
}
JSONArray jsonArray = new JSONArray();
jsonArray.add(json_main);
//写入建模记录表
insertHrToZkJl(1,url,jsonArray,result,msg,"");
// 0成功
if(result == 0) {
bool = true;
}
return bool;
}
/**
* 新增更新 人员信息 同步至 中控考勤机
* @param userid
* @return
*/
public static boolean synAddOrUpdateUserInfo(String userid){
boolean bool = false;
RecordSet rs = new RecordSet();
RecordSet rst = new RecordSet();
// 新增更新人员 接口url
// key
String key = rs.getPropValue("hrm_zhongkong","key");
String url = rs.getPropValue("hrm_zhongkong","add_update_user_url");
url = url + "?key=" + key;
String restoreUserurl = rs.getPropValue("hrm_zhongkong","restore_user_url");
restoreUserurl = restoreUserurl + "?key=" + key;
Map<String,String> headers = new HashMap<>();
JSONArray jsonArray = new JSONArray();
JSONObject json_main = new JSONObject();
User user = new User(Integer.parseInt(userid));
String sfhl_fieldid = rs.getPropValue("hrm_zhongkong","sfhl_fieldid");
String zksfhf_fieldid = rs.getPropValue("hrm_zhongkong","zksfhf_fieldid");
String sfhl = getSfhl(userid);
try {
DepartmentComInfo DepartmentComInfo = new DepartmentComInfo();
ResourceComInfo ResourceComInfo = new ResourceComInfo();
SalaryManager SalaryManager = new SalaryManager();
ChgPasswdReminder reminder = new ChgPasswdReminder();
RemindSettings settings = reminder.getRemindSettings();
SysRemindWorkflow SysRemindWorkflow = new SysRemindWorkflow();
CustomFieldTreeManager CustomFieldTreeManager = new CustomFieldTreeManager();
DepartmentVirtualComInfo DepartmentVirtualComInfo = new DepartmentVirtualComInfo();
rs.executeQuery("select * from hrmresource where id = ?",userid);
rs.next();
String workcode = Util.fromScreen3(rs.getString("workcode"), user.getLanguage());
String lastname = Util.fromScreen3(rs.getString("lastname"), user.getLanguage()).trim();
String sex = Util.fromScreen3(rs.getString("sex"), user.getLanguage());
String departmentid = Util.fromScreen3(rs.getString("departmentid"), user.getLanguage());
String deptcode = "";
String sup_Deptcode = getDeptCuscode(departmentid);
if(sup_Deptcode != null && !"".equals(sup_Deptcode)){
deptcode = sup_Deptcode;
}else{
deptcode = new DepartmentComInfo().getDepartmentCode(departmentid);
}
String jobtitle = Util.fromScreen3(rs.getString("jobtitle"), user.getLanguage());
String joblevel = Util.fromScreen3(rs.getString("joblevel"), user.getLanguage());
String jobactivitydesc = Util.fromScreen3(rs.getString("jobactivitydesc"), user.getLanguage());
String managerid = Util.fromScreen3(rs.getString("managerid"), user.getLanguage());
String assistantid = Util.fromScreen3(rs.getString("assistantid"), user.getLanguage());
String status = Util.fromScreen3(rs.getString("status"), user.getLanguage());
String locationid = Util.fromScreen3(rs.getString("locationid"), user.getLanguage());
String workroom = Util.fromScreen3(rs.getString("workroom"), user.getLanguage());
String telephone = Util.fromScreen3(rs.getString("telephone"), user.getLanguage());
String mobile = Util.fromScreen3(rs.getString("mobile"), user.getLanguage());
String fax = Util.fromScreen3(rs.getString("fax"), user.getLanguage());
String jobcall = Util.fromScreen3(rs.getString("jobcall"), user.getLanguage());
String email = Util.fromScreen3(rs.getString("email"), user.getLanguage());
String companystartdate = Util.fromScreen3(rs.getString("companystartdate"), user.getLanguage());
String birthday = Util.null2String(rs.getString("birthday"));
String certificatenum = Util.fromScreen3(rs.getString("certificatenum"), user.getLanguage());
String pincode = "";
String cuscode = KqUtil.getCusIdByUserid(userid);
if(cuscode != null && !"".equals(cuscode)){
pincode = cuscode;
}else{
pincode = workcode;
}
//
if("0".equals(sfhl)){
jsonArray.add(pincode);
json_main.put("userpin",jsonArray);
int result = -1;
String msg = "";
String content = httpPost(restoreUserurl,headers,json_main.toString(),"utf-8");
if (content != null && !"".equals(content)) {
JSONObject json = JSONObject.parseObject(content);
rs.writeLog("============= httpPost pushInfo json =================== " + json);
int resultt = Integer.parseInt(json.getString("ret"));
if(resultt == 0){
result = 0;
//将对应的是否回流 自定义字段清空中控是否恢复 自定义字段赋值为
rst.executeUpdate("update cus_fielddata set "+ sfhl_fieldid +"=null,"+zksfhf_fieldid+"=0 where scope = 'HrmCustomFieldByInfoType' and scopeid = '-1' and id = ?",userid);
}else{
result = 1;
}
msg = Util.null2String(json.getString("msg"));
}
//写入建模记录表
insertHrToZkJl(1,restoreUserurl,jsonArray,result,msg,"");
// 0成功
if(result == 0) {
bool = true;
}
}else{
json_main.put("pin",pincode);
json_main.put("name",lastname);
json_main.put("deptnumber",deptcode);
json_main.put("telephone",telephone);
json_main.put("mobile",mobile);
json_main.put("gender","0".equals(sex)?"M":"F");
json_main.put("email",email);
json_main.put("identitycard",certificatenum);
json_main.put("birthday",birthday);
json_main.put("hiredday",companystartdate);
jsonArray.add(json_main);
rs.writeLog("=============== synAddOrUpdateUserInfo jsonArray ============== "+ jsonArray.toString());
int result = -1;
String msg = "";
String content = httpPost(url,headers,jsonArray.toString(),"utf-8");
if (content != null && !"".equals(content)) {
JSONObject json = JSONObject.parseObject(content);
rs.writeLog("============= httpPost pushInfo json =================== " + json);
int resultt = Integer.parseInt(json.getString("ret"));
if(resultt == 0){
result = 0;
}else{
result = 1;
}
msg = Util.null2String(json.getString("msg"));
}
//写入建模记录表
insertHrToZkJl(1,url,jsonArray,result,msg,"");
// 0成功
if(result == 0) {
bool = true;
}
}
return bool;
}catch (Exception e){
e.printStackTrace();
rs.writeLog(e);
}
return bool;
}
/**
* 删除 人员信息 同步至 中控考勤机
* @param userid
* @return
*/
public static boolean synDeleteUserInfo(String userid){
boolean bool = false;
RecordSet rs = new RecordSet();
// 删除部门 接口url
// key
String key = rs.getPropValue("hrm_zhongkong","key");
String url = rs.getPropValue("hrm_zhongkong","delete_user_url");
url = url + "?key=" + key;
Map<String,String> headers = new HashMap<>();
JSONObject json_main = new JSONObject();
rs.executeQuery("select * from hrmresource where id = ?",userid);
rs.next();
String usercode = Util.null2String(rs.getString("workcode"));
String username = Util.null2String(rs.getString("lastname"));
json_main.put("pin",usercode);
int result = -1;
String msg = "";
String content = httpPost(url,headers,json_main.toString(),"utf-8");
if (content != null && !"".equals(content)) {
JSONObject json = JSONObject.parseObject(content);
rs.writeLog("============= httpPost pushInfo json =================== " + json);
int resultt = Integer.parseInt(json.getString("ret"));
if(resultt == 0){
result = 0;
}else{
result = 1;
}
msg = Util.null2String(json.getString("msg"));
}
JSONArray jsonArray = new JSONArray();
jsonArray.add(json_main);
//写入建模记录表
insertHrToZkJl(1,url,jsonArray,result,msg,"");
// 0成功
if(result == 0) {
bool = true;
}
return bool;
}
/**
* 判断 部门编码 中控考勤机 是否存在
* @param deptcode
* @return
*/
public static boolean checkIsExistDeptInfo(String deptcode){
boolean bool = false;
RecordSet rs = new RecordSet();
// 获取所有部门信息 接口url
// key
String key = rs.getPropValue("hrm_zhongkong","key");
String get_all_dept_url = rs.getPropValue("hrm_zhongkong","get_all_dept_url");
get_all_dept_url = get_all_dept_url + "?key=" + key;
Map<String,String> headers = new HashMap<>();
JSONObject json_main = new JSONObject();
json_main.put("deptnumber",deptcode);
String encode = "utf-8";
String stringJson = json_main.toString();
String content = null;
CloseableHttpResponse httpResponse = null;
CloseableHttpClient closeableHttpClient = null;
try {
closeableHttpClient = HttpClients.createDefault();
HttpPost httpost = new HttpPost(get_all_dept_url);
//设置header
httpost.setHeader("Content-type", "application/json");
if (headers != null && headers.size() > 0) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpost.setHeader(entry.getKey(),entry.getValue());
}
}
//组织请求参数
StringEntity stringEntity = new StringEntity(stringJson, encode);
httpost.setEntity(stringEntity);
//响应信息
httpResponse = closeableHttpClient.execute(httpost);
if(httpResponse != null) {
HttpEntity entity = httpResponse.getEntity();
content = EntityUtils.toString(entity, encode);
if (content != null && !"".equals(content)) {
JSONObject json = JSONObject.parseObject(content);
rs.writeLog("============= checkIsExistDeptInfo pushInfo json =================== " + json);
int ret = Integer.parseInt(json.getString("ret"));
if(ret == 0){
String data = json.getString("data");
JSONObject data_json = JSONObject.parseObject(data);
if(data_json.isEmpty()){
bool = false;
}else{
bool = true;
}
}
}
}
} catch (Exception e) {
bool = false;
e.printStackTrace();
rs.writeLog(e);
}finally{
try {
httpResponse.close();
} catch (IOException e) {
bool = false;
e.printStackTrace();
}
}
try { //关闭连接释放资源
closeableHttpClient.close();
} catch (IOException e) {
bool = false;
e.printStackTrace();
}
return bool;
}
/**
* 判断 人员编码 中控考勤机 是否存在
* @param usercode
* @return
*/
public static boolean checkIsExistUserInfo(String usercode){
boolean bool = false;
RecordSet rs = new RecordSet();
// 获取所有部门信息 接口url
// key
String key = rs.getPropValue("hrm_zhongkong","key");
String get_all_user_url = rs.getPropValue("hrm_zhongkong","get_all_user_url");
get_all_user_url = get_all_user_url + "?key=" + key;
Map<String,String> headers = new HashMap<>();
JSONObject json_main = new JSONObject();
json_main.put("pinlist",usercode);
String encode = "utf-8";
String stringJson = json_main.toString();
String content = null;
CloseableHttpResponse httpResponse = null;
CloseableHttpClient closeableHttpClient = null;
try {
closeableHttpClient = HttpClients.createDefault();
HttpPost httpost = new HttpPost(get_all_user_url);
//设置header
httpost.setHeader("Content-type", "application/json");
if (headers != null && headers.size() > 0) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpost.setHeader(entry.getKey(),entry.getValue());
}
}
//组织请求参数
StringEntity stringEntity = new StringEntity(stringJson, encode);
httpost.setEntity(stringEntity);
//响应信息
httpResponse = closeableHttpClient.execute(httpost);
if(httpResponse != null) {
HttpEntity entity = httpResponse.getEntity();
content = EntityUtils.toString(entity, encode);
if (content != null && !"".equals(content)) {
JSONObject json = JSONObject.parseObject(content);
rs.writeLog("============= checkIsExistUserInfo pushInfo json =================== " + json);
int ret = Integer.parseInt(json.getString("ret"));
if(ret == 0){
String data = json.getString("data");
JSONObject data_json = JSONObject.parseObject(data);
int count = Integer.parseInt(data_json.getString("count").toString());
if(count>0){
bool = true;
}else{
bool = false;
}
}
}
}
} catch (Exception e) {
bool = false;
e.printStackTrace();
rs.writeLog(e);
}finally{
try {
httpResponse.close();
} catch (IOException e) {
bool = false;
e.printStackTrace();
}
}
try { //关闭连接释放资源
closeableHttpClient.close();
} catch (IOException e) {
bool = false;
e.printStackTrace();
}
return bool;
}
/**
* post 请求 json格式
* @param url
* @param headers
* @param stringJson
* @param encode
* @return
*/
public static String httpPost(String url, Map<String,String> headers, String stringJson, String encode){
int result = 0;
if(encode == null){
encode = "utf-8";
}
RecordSet rs = new RecordSet();
String content = "";
CloseableHttpResponse httpResponse = null;
CloseableHttpClient closeableHttpClient = null;
try {
closeableHttpClient = HttpClients.createDefault();
HttpPost httpost = new HttpPost(url);
//设置header
httpost.setHeader("Content-type", "application/json");
if (headers != null && headers.size() > 0) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpost.setHeader(entry.getKey(),entry.getValue());
}
}
//组织请求参数
StringEntity stringEntity = new StringEntity(stringJson, encode);
httpost.setEntity(stringEntity);
//响应信息
httpResponse = closeableHttpClient.execute(httpost);
if(httpResponse != null) {
HttpEntity entity = httpResponse.getEntity();
content = EntityUtils.toString(entity, encode);
// if (content != null && !"".equals(content)) {
// JSONObject json = JSONObject.parseObject(content);
// rs.writeLog("============= httpPost pushInfo json =================== " + json);
// result = Integer.parseInt(json.getString("ret"));
// }
}
} catch (Exception e) {
e.printStackTrace();
rs.writeLog(e);
}finally{
try {
httpResponse.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try { //关闭连接释放资源
closeableHttpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
return content;
}
/**
* 获取 部门中控系统id
* @param deptid
* @return
*/
public static String getDeptCuscode(String deptid){
RecordSet rs = new RecordSet();
String code = "";
rs.executeQuery("select zkxtid from hrmdepartmentdefined where deptid = ?",deptid);
if(rs.next()){
code = Util.null2String(rs.getString("zkxtid"));
}
return code;
}
/**
* 获取 分部 中控系统id
* @param subcomid
* @return
*/
public static String getSubcomCuscode(String subcomid){
RecordSet rs = new RecordSet();
String code = "";
rs.executeQuery("select zkid from hrmsubcompanydefined where subcomid = ?",subcomid);
if(rs.next()){
code = Util.null2String(rs.getString("zkid"));
}
return code;
}
/**
* 根据 人员id 获取 自定义 考勤卡号也就是 中控考勤机那边的 人员编号 pin
* @param userid
* @return
*/
public static String getCusIdByUserid(String userid){
String result = "";
RecordSet rs = new RecordSet();
String kq_fieldid = rs.getPropValue("hrm_zhongkong","kq_fieldid");
rs.executeQuery("select "+ kq_fieldid +" from cus_fielddata where scope = 'HrmCustomFieldByInfoType' and scopeid = -1 and id = ?",userid);
if(rs.next()){
result = Util.null2String(rs.getString(kq_fieldid));
}
return result;
}
public static void insertHrToZkJl(int type,String url,JSONArray jsonArray,int result,String msg,String requestid){
RecordSet rs = new RecordSet();
RecordSet rs1 = new RecordSet();
RecordSet rs2 = new RecordSet();
String currentdate = TimeUtil.getCurrentDateString();
String currenttime = TimeUtil.getOnlyCurrentTimeString();
// String currentdatetime = currentdate+" "+currenttime;
// HR同步至中控考勤机记录表
int hrtozkkqj_formmodeid = Util.getIntValue(rs.getPropValue("hrm_zhongkong","hrtozkkqj_formmodeid"));
String uuid = UUID.randomUUID().toString();
int creater = 1;
String insertSql = " insert into uf_hrtozkjlb(dyly,jkdz,jkrc,dyrq,dysj,fhjg,fhxx,lcid," +
"modedatacreater,modedatacreatedate,modedatacreatetime,formmodeid,modeuuid) " +
"values(?,?,?,?,?,?,?,?,?,?,?,?,?) ";
boolean exeRes = rs1.executeUpdate(insertSql,new Object[]{type,url,jsonArray.toString(),currentdate,currenttime,result,msg,requestid,
creater, currentdate, currenttime, hrtozkkqj_formmodeid, uuid});
int billid = -1;
if (exeRes) {
//重构权限
rs2.executeQuery(" select id from uf_hrtozkjlb where modeuuid=? ",new Object[]{uuid});
rs2.next();
billid = rs2.getInt("id");
ModeRightInfo moderight = new ModeRightInfo();
moderight.editModeDataShare(creater, hrtozkkqj_formmodeid, billid);
}
}
/**
* 获取 是否回流 0- 1-
* @param userid
* @return
*/
public static String getSfhl(String userid){
String result = "1";
RecordSet rs = new RecordSet();
String sfhl_fieldid = rs.getPropValue("hrm_zhongkong","sfhl_fieldid");
rs.executeQuery("select "+ sfhl_fieldid +" from cus_fielddata where scope = 'HrmCustomFieldByInfoType' and scopeid = '-1' and id = ?",userid);
if(rs.next()){
result = Util.null2String(rs.getString(sfhl_fieldid));
}
return result;
}
}

View File

@ -0,0 +1,120 @@
package weaver.interfaces.lingyue.action;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lingyue.util.KqUtil;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.company.DepartmentComInfo;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import java.util.*;
/**
* @Title 新员工入职 同步新增到 中控考勤机系统
* @Author wangchaofa
* @CreateDate 2024/9/19
* @Version 1.0
* @Description
*/
public class SynAddUserAction extends BaseBean implements Action {
@Override
public String execute(RequestInfo requestInfo) {
try {
RecordSet rs = new RecordSet();
RecordSet rs1 = new RecordSet();
RecordSet rs2 = new RecordSet();
String tablename = requestInfo.getRequestManager().getBillTableName();
String requestid = requestInfo.getRequestid();
String currentdate = TimeUtil.getCurrentDateString();
String currenttime = TimeUtil.getOnlyCurrentTimeString();
String currentdatetime = currentdate+" "+currenttime;
// HR同步至中控考勤机记录表
int hrtozkkqj_formmodeid = Util.getIntValue(rs.getPropValue("hrm_zhongkong","hrtozkkqj_formmodeid"));
String uuid = UUID.randomUUID().toString();
int creater = 1;
String sql = " select * from "+ tablename +" where requestid = ? ";
rs.executeQuery(sql,requestid);
while(rs.next()){
String workcode = Util.null2String(rs.getString("ygbh"));
String lastname = Util.null2String(rs.getString("xm"));
String sex = Util.null2String(rs.getString("xb"));
String departmentid = Util.null2String(rs.getString("bm"));
String deptcode = "";
String Deptcode = KqUtil.getDeptCuscode(departmentid);
if(Deptcode != null && !"".equals(Deptcode)){
deptcode = Deptcode;
}else{
deptcode = new DepartmentComInfo().getDepartmentCode(departmentid);
}
// String jobtitle = Util.null2String(rs.getString("jobtitle"));
// String joblevel = Util.null2String(rs.getString("joblevel"));
// String jobactivitydesc = Util.null2String(rs.getString("jobactivitydesc"));
// String managerid = Util.null2String(rs.getString("managerid"));
// String assistantid = Util.null2String(rs.getString("assistantid"));
// String status = Util.null2String(rs.getString("status"));
// String locationid = Util.null2String(rs.getString("locationid"));
// String workroom = Util.null2String(rs.getString("workroom"));
// String telephone = Util.null2String(rs.getString("telephone"));
String mobile = Util.null2String(rs.getString("mobile"));
// String fax = Util.null2String(rs.getString("fax"));
// String jobcall = Util.null2String(rs.getString("jobcall"));
// String email = Util.null2String(rs.getString("email"));
String companystartdate = Util.null2String(rs.getString("cjgzsj"));
String birthday = Util.null2String(rs.getString("csrq"));
String certificatenum = Util.null2String(rs.getString("sfzhm"));
// key
String key = rs.getPropValue("hrm_zhongkong","key");
String url = rs.getPropValue("hrm_zhongkong","add_update_user_url");
url = url + "?key=" + key;
Map<String,String> headers = new HashMap<>();
JSONArray jsonArray = new JSONArray();
JSONObject json_main = new JSONObject();
json_main.put("pin",workcode);
json_main.put("name",lastname);
json_main.put("deptnumber",deptcode);
json_main.put("mobile",mobile);
json_main.put("gender","0".equals(sex)?"M":"F");
json_main.put("identitycard",certificatenum);
json_main.put("birthday",birthday);
json_main.put("hiredday",companystartdate);
jsonArray.add(json_main);
rs.writeLog("========================== 新增或修改人员,同步至中控考勤机 ======================================");
rs.writeLog(url+" ========= "+jsonArray.toString());
int result = -1;
String msg = "";
String content = KqUtil.httpPost(url,headers,jsonArray.toString(),"utf-8");
if (content != null && !"".equals(content)) {
JSONObject json = JSONObject.parseObject(content);
rs.writeLog("============= httpPost pushInfo json =================== " + json);
int resultt = Integer.parseInt(json.getString("ret"));
if(resultt == 0){
result = 0;
}else{
result = 1;
}
msg = Util.null2String(json.getString("msg"));
}
writeLog(lastname +" ====== add user syn zhongkong result ========== "+ result);
//写入建模记录表
KqUtil.insertHrToZkJl(0,url,jsonArray,result,msg,requestid);
}
}catch (Exception e){
e.printStackTrace();
requestInfo.getRequestManager().setMessagecontent("新员工入职同步中控系统失败,请联系管理员!");
return Action.FAILURE_AND_CONTINUE;
}
return Action.SUCCESS;
}
}

View File

@ -0,0 +1,74 @@
//package weaver.interfaces.lingyue.action;
//
//import com.alibaba.fastjson.JSONObject;
//import com.lingyue.util.KqUtil;
//import weaver.conn.RecordSet;
//import weaver.general.BaseBean;
//import weaver.general.Util;
//import weaver.hrm.resource.ResourceComInfo;
//import weaver.interfaces.workflow.action.Action;
//import weaver.soa.workflow.request.RequestInfo;
//
//import java.util.HashMap;
//import java.util.Map;
//
///**
// * @Title 人员离职 同步删除 中控考勤机系统 人员
// * @Author wangchaofa
// * @CreateDate 2024/9/19
// * @Version 1.0
// * @Description
// */
//public class SynDeleteUserAction extends BaseBean implements Action {
// @Override
// public String execute(RequestInfo requestInfo) {
// try {
// RecordSet rs = new RecordSet();
// String tablename = requestInfo.getRequestManager().getBillTableName();
// String requestid = requestInfo.getRequestid();
//
// String sql = " select * from "+ tablename +" where requestid = ? ";
// rs.executeQuery(sql,requestid);
// while(rs.next()){
// String userid = Util.null2String(rs.getString("xm"));
// String lastname = new ResourceComInfo().getLastname(userid);
// String pincode = "";
// String cuscode = KqUtil.getCusIdByUserid(userid);
// if(cuscode != null && !"".equals(cuscode)){
// pincode = cuscode;
// }else{
// pincode = new ResourceComInfo().getWorkcode(userid);
// }
//
// // key
// String key = rs.getPropValue("hrm_zhongkong","key");
// String delete_user_url = rs.getPropValue("hrm_zhongkong","delete_user_url");
// delete_user_url = delete_user_url + "?key=" + key;
// Map<String,String> headers = new HashMap<>();
// JSONObject json_main = new JSONObject();
//
// json_main.put("pin",pincode);
//
// int result = -1;
// String content = KqUtil.httpPost(delete_user_url,headers,json_main.toString(),"utf-8");
// writeLog(lastname +" ====== delete user syn zhongkong result ========== "+ result);
// if (content != null && !"".equals(content)) {
// JSONObject json = JSONObject.parseObject(content);
// rs.writeLog("============= httpPost pushInfo json =================== " + json);
// result = Integer.parseInt(json.getString("ret"));
// }
// if(result == 0){
// return Action.SUCCESS;
// }else{
// requestInfo.getRequestManager().setMessagecontent("员工离职同步中控系统失败,请联系管理员!");
// return Action.FAILURE_AND_CONTINUE;
// }
// }
// }catch (Exception e){
// e.printStackTrace();
// requestInfo.getRequestManager().setMessagecontent("员工离职同步中控系统失败,请联系管理员!");
// return Action.FAILURE_AND_CONTINUE;
// }
// return Action.SUCCESS;
// }
//}

View File

@ -0,0 +1,142 @@
package weaver.interfaces.lingyue.action;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lingyue.util.KqUtil;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.resource.ResourceComInfo;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* @Title 员工调动 同步新增到 中控考勤机系统
* @Author wangchaofa
* @CreateDate 2024/9/20
* @Version 1.0
* @Description
*/
public class SynTransUserAction extends BaseBean implements Action {
@Override
public String execute(RequestInfo requestInfo) {
try {
RecordSet rs = new RecordSet();
RecordSet rs1 = new RecordSet();
RecordSet rs2 = new RecordSet();
String tablename = requestInfo.getRequestManager().getBillTableName();
String requestid = requestInfo.getRequestid();
String currentdate = TimeUtil.getCurrentDateString();
String currenttime = TimeUtil.getOnlyCurrentTimeString();
String currentdatetime = currentdate+" "+currenttime;
// HR同步至中控考勤机记录表
int hrtozkkqj_formmodeid = Util.getIntValue(rs.getPropValue("hrm_zhongkong","hrtozkkqj_formmodeid"));
String uuid = UUID.randomUUID().toString();
int creater = 1;
// key
String key = rs.getPropValue("hrm_zhongkong","key");
String url = rs.getPropValue("hrm_zhongkong","add_update_user_url");
url = url + "?key=" + key;
Map<String,String> headers = new HashMap<>();
JSONArray jsonArray = new JSONArray();
JSONObject json_main = new JSONObject();
String sql = " select * from "+ tablename +" where requestid = ? ";
rs.executeQuery(sql,requestid);
while(rs.next()){
String userid = Util.null2String(rs.getString("ygxm"));
String lastname = new ResourceComInfo().getLastname(userid);
// String sex = Util.null2String(rs.getString("xb"));
String departmentid = Util.null2String(rs.getString("bm"));
String pincode = "";
String cuscode = KqUtil.getCusIdByUserid(userid);
if(cuscode != null && !"".equals(cuscode)){
pincode = cuscode;
}else{
pincode = new ResourceComInfo().getWorkcode(userid);
}
json_main.put("pin",pincode);
if(departmentid != null && !"".equals(departmentid)) {
String deptcode = "";
String Deptcode = KqUtil.getDeptCuscode(departmentid);
if (Deptcode != null && !"".equals(Deptcode)) {
deptcode = Deptcode;
} else {
deptcode = new DepartmentComInfo().getDepartmentCode(departmentid);
}
json_main.put("deptnumber",deptcode);
}
// String jobtitle = Util.null2String(rs.getString("jobtitle"));
// String joblevel = Util.null2String(rs.getString("joblevel"));
// String jobactivitydesc = Util.null2String(rs.getString("jobactivitydesc"));
// String managerid = Util.null2String(rs.getString("managerid"));
// String assistantid = Util.null2String(rs.getString("assistantid"));
// String status = Util.null2String(rs.getString("status"));
// String locationid = Util.null2String(rs.getString("locationid"));
// String workroom = Util.null2String(rs.getString("workroom"));
// String telephone = Util.null2String(rs.getString("telephone"));
// String mobile = Util.null2String(rs.getString("mobile"));
// String fax = Util.null2String(rs.getString("fax"));
// String jobcall = Util.null2String(rs.getString("jobcall"));
// String email = Util.null2String(rs.getString("email"));
// String companystartdate = Util.null2String(rs.getString("cjgzsj"));
// String birthday = Util.null2String(rs.getString("csrq"));
// String certificatenum = Util.null2String(rs.getString("sfzhm"));
json_main.put("name",lastname);
// json_main.put("mobile",mobile);
// json_main.put("gender","0".equals(sex)?"M":"F");
// json_main.put("identitycard",certificatenum);
// json_main.put("birthday",birthday);
// json_main.put("hiredday",companystartdate);
jsonArray.add(json_main);
int result = -1;
String msg = "";
String content = KqUtil.httpPost(url,headers,jsonArray.toString(),"utf-8");
if (content != null && !"".equals(content)) {
JSONObject json = JSONObject.parseObject(content);
rs.writeLog("============= httpPost pushInfo json =================== " + json);
int resultt = Integer.parseInt(json.getString("ret"));
if(resultt == 0){
result = 0;
}else{
result = 1;
}
msg = Util.null2String(json.getString("msg"));
}
writeLog(lastname +" ====== trans user syn zhongkong result ========== "+ result);
//写入建模记录表
KqUtil.insertHrToZkJl(0,url,jsonArray,result,msg,requestid);
if(result == 0){
return Action.SUCCESS;
}else{
requestInfo.getRequestManager().setMessagecontent("员工调动同步中控系统失败,请联系管理员!");
return Action.FAILURE_AND_CONTINUE;
}
}
}catch (Exception e){
e.printStackTrace();
requestInfo.getRequestManager().setMessagecontent("员工调动同步中控系统失败,请联系管理员!");
return Action.FAILURE_AND_CONTINUE;
}
return Action.SUCCESS;
}
}

View File

@ -0,0 +1,211 @@
package weaver.interfaces.lingyue.job;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lingyue.util.KqUtil;
import weaver.conn.RecordSet;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.resource.ResourceComInfo;
import weaver.interfaces.schedule.BaseCronJob;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* @Title
* @Author wangchaofa
* @CreateDate 2024/10/30
* @Version 1.0
* @Description
*/
public class SynDeleteUserToZkJob extends BaseCronJob {
@Override
public void execute() {
RecordSet rs = new RecordSet();
rs.writeLog("------------------------- start to syn unsyn HRM user info to zhongkong -----------------------------------");
String tablename = rs.getPropValue("hrm_zhongkong","deleteuser_table");
String key = rs.getPropValue("hrm_zhongkong","key");
String url = rs.getPropValue("hrm_zhongkong","leave_user_url");
url = url + "?key=" + key;
Map<String,String> headers = new HashMap<>();
// 当前日期
String currentdate = TimeUtil.getCurrentDateString();
// 2个月前的日期
String lasttwomonth = addDateMonth(currentdate,-2);
String where = " and (a.tyzhgzr >= '"+ lasttwomonth +"' and a.tyzhgzr <= '"+ currentdate +"') ";
try{
// 查询最终离职日期 是在 2月前和当前日期范围内并且流程是归档的
String sql = "select a.*,b.lastoperatedate,b.lastoperatetime from "+tablename+" a,workflow_requestbase b where a.requestid=b.requestid and b.currentnodetype=3 "+ where;
rs.executeQuery(sql);
while(rs.next()){
JSONObject json_main = new JSONObject();
String requestid = Util.null2String(rs.getString("requestid"));
//姓名
String userid = Util.null2String(rs.getString("xm"));
String workcode = new ResourceComInfo().getWorkcode(userid);
String pincode = "";
String cuscode = KqUtil.getCusIdByUserid(userid);
if(cuscode != null && !"".equals(cuscode)){
pincode = cuscode;
}else{
pincode = workcode;
}
// 离职原因
String lzyyid = Util.null2String(rs.getString("lzyy"));
String lzyyname = getLzyyname(lzyyid);
// 离职类型 下拉框 0 - 主动 1 - 被动
int lzlxid = Util.getIntValue(rs.getString("lzlx"));
int lzlx = -1;
if(lzlxid==0){
lzlx = 2;
}else{
lzlx = 1;
}
// 最后离职日期
String tyzhgzr = Util.null2String(rs.getString("tyzhgzr"));
String lastoperatetime = Util.null2String(rs.getString("lastoperatetime"));
String lasttime = lastoperatetime.substring(0,5);
if(tyzhgzr != null && !"".equals(tyzhgzr)){
// 加一天
tyzhgzr = addDateDay(tyzhgzr,1);
}
//离职时间
String leavetime = tyzhgzr+" "+lasttime;
//中控是否恢复 0- 1-
String zksfhf = getZksfhf(userid);
if("".equals(zksfhf) || "1".equals(zksfhf)){
// 人员离职的入参
json_main.put("pin",pincode);
json_main.put("leavedate",leavetime);
json_main.put("leavetype",lzlx);
json_main.put("reason",lzyyname);
int result = -1;
String msg = "";
String content = KqUtil.httpPost(url, headers, json_main.toString(), "utf-8");
if (content != null && !"".equals(content)) {
JSONObject json = JSONObject.parseObject(content);
rs.writeLog("============= httpPost pushInfo json =================== " + json);
int resultt = Integer.parseInt(json.getString("ret"));
if (resultt == 0) {
result = 0;
} else {
result = 1;
}
msg = Util.null2String(json.getString("msg"));
}
JSONArray jsonArray = new JSONArray();
jsonArray.add(json_main);
//写入建模记录表
KqUtil.insertHrToZkJl(3,url,jsonArray,result,msg,requestid);
}
}
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 获取 离职原因 名称
* @param lzyyid
* @return
*/
public static String getLzyyname(String lzyyid){
String result = "";
RecordSet rs = new RecordSet();
String lzyy_fieldid = rs.getPropValue("hrm_zhongkong","lzyy_fieldid");
if (lzyyid != null && !"".equals(lzyyid)) {
rs.executeQuery("select selectname from workflow_selectitem where cancel=0 and fieldid = ? and selectvalue=?", lzyy_fieldid, lzyyid);
if (rs.next()) {
result = Util.null2String(rs.getString("selectname"));
}
}
return result;
}
/**
* 对时间的月数进行加减
* @param daytime 时间的格式yyyy-MM-dd
* @param month 月数 -1则代表减一月
* @return
*/
public static String addDateMonth(String daytime, int month){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = format.parse(daytime);
if (date == null){
return "";
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MONTH, month);// day
date = cal.getTime();
cal = null;
return format.format(date);
} catch (Exception ex) {
ex.printStackTrace();
}
return "";
}
/**
* 对时间的天数进行加减
* @param daytime 时间的格式yyyy-MM-dd
* @param day 天数 -1则代表减一天
* @return
*/
public static String addDateDay(String daytime, int day){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = format.parse(daytime);
if (date == null){
return "";
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH, day);// 加一天
date = cal.getTime();
cal = null;
return format.format(date);
} catch (Exception ex) {
ex.printStackTrace();
}
return "";
}
/**
* 获取 中控是否恢复 0- 1-
* @param userid
* @return
*/
public static String getZksfhf(String userid){
String result = "";
RecordSet rs = new RecordSet();
String zksfhf_fieldid = rs.getPropValue("hrm_zhongkong","zksfhf_fieldid");
rs.executeQuery("select "+ zksfhf_fieldid +" from cus_fielddata where scope = 'HrmCustomFieldByInfoType' and scopeid = '-1' and id = ?",userid);
if(rs.next()){
result = Util.null2String(rs.getString(zksfhf_fieldid));
}
return result;
}
}

View File

@ -0,0 +1,96 @@
package weaver.interfaces.lingyue.job;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lingyue.util.KqUtil;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.company.DepartmentComInfo;
import weaver.interfaces.schedule.BaseCronJob;
import java.util.HashMap;
import java.util.Map;
/**
* @Title 该任务主要是 针对 新员工入职流程归档后同步中控考勤机其中同步败的再次同步
* @Author wangchaofa
* @CreateDate 2024/10/9
* @Version 1.0
* @Description
*/
public class SynNewUserToZkJob extends BaseCronJob {
@Override
public void execute() {
RecordSet rs = new RecordSet();
RecordSet rs1 = new RecordSet();
RecordSet rs2 = new RecordSet();
rs.writeLog("------------------------- start to syn unsyn HRM user info to zhongkong -----------------------------------");
String tablename = rs.getPropValue("hrm_zhongkong","newuser_table");
String key = rs.getPropValue("hrm_zhongkong","key");
String url = rs.getPropValue("hrm_zhongkong","add_update_user_url");
url = url + "?key=" + key;
Map<String,String> headers = new HashMap<>();
JSONArray jsonArray = new JSONArray();
try{
rs.executeQuery("select a.* from "+ tablename +" a,workflow_requestbase b where a.requestid=b.requestid and b.currentnodetype='3'");
while(rs.next()){
JSONObject json_main = new JSONObject();
String workcode = Util.null2String(rs.getString("ygbh"));
String lastname = Util.null2String(rs.getString("xm"));
String sex = Util.null2String(rs.getString("xb"));
String departmentid = Util.null2String(rs.getString("bm"));
String deptcode = "";
String Deptcode = KqUtil.getDeptCuscode(departmentid);
if(Deptcode != null && !"".equals(Deptcode)){
deptcode = Deptcode;
}else{
deptcode = new DepartmentComInfo().getDepartmentCode(departmentid);
}
String mobile = Util.null2String(rs.getString("mobile"));
String companystartdate = Util.null2String(rs.getString("cjgzsj"));
String birthday = Util.null2String(rs.getString("csrq"));
String certificatenum = Util.null2String(rs.getString("sfzhm"));
json_main.put("pin",workcode);
json_main.put("name",lastname);
json_main.put("deptnumber",deptcode);
json_main.put("mobile",mobile);
json_main.put("gender","0".equals(sex)?"M":"F");
json_main.put("identitycard",certificatenum);
json_main.put("birthday",birthday);
json_main.put("hiredday",companystartdate);
// 不存在
if(!KqUtil.checkIsExistUserInfo(workcode)){
jsonArray.add(json_main);
}
}
int result = -1;
String msg = "";
String content = KqUtil.httpPost(url,headers,jsonArray.toString(),"utf-8");
if (content != null && !"".equals(content)) {
JSONObject json = JSONObject.parseObject(content);
rs.writeLog("============= httpPost pushInfo json =================== " + json);
int resultt = Integer.parseInt(json.getString("ret"));
if(resultt == 0){
result = 0;
}else{
result = 1;
}
msg = Util.null2String(json.getString("msg"));
}
rs.writeLog(" ====== syn unsyn HRM user info to zhongkong result ========== "+ result);
//写入建模记录表
KqUtil.insertHrToZkJl(2,url,jsonArray,result,msg,"");
}catch (Exception e){
e.printStackTrace();
rs.writeLog(e);
}
rs.writeLog("------------------------- end to syn unsyn HRM user info to zhongkong -----------------------------------");
}
}

View File

@ -0,0 +1,129 @@
//package weaver.interfaces.lingyue.job;
//
//import com.alibaba.fastjson.JSONObject;
//import com.engine.kq.biz.KQFormatBiz;
//import com.engine.kq.timer.KQQueue;
//import com.engine.kq.timer.KQTaskBean;
//import com.engine.kq.wfset.util.SplitActionUtil;
//import com.google.common.collect.Lists;
//import com.google.common.collect.Maps;
//import weaver.conn.RecordSet;
//import weaver.general.TimeUtil;
//import weaver.general.Util;
//import weaver.interfaces.lingyue.util.HttpUtil;
//import weaver.interfaces.schedule.BaseCronJob;
//
//import java.util.*;
//
///**
// * @Title
// * @Author wangchaofa
// * @CreateDate 2024/7/11
// * @Version 1.0
// * @Description
// */
//public class SynOtherKqInfoJob extends BaseCronJob {
//
// @Override
// public void execute() {
// // 同步当日的考勤数据
// SynTodayKqInfo();
// }
//
// // 同步当天的考勤数据
// public void SynTodayKqInfo(){
// RecordSet rs = new RecordSet();
//
// rs.writeLog("------------------------- start to syn today other kqinfo -----------------------------------");
// String currentdate = TimeUtil.getCurrentDateString();
// String currenttime = TimeUtil.getOnlyCurrentTimeString();
// String currentdatetime = currentdate + " " + currenttime;
//
// String startTime = currentdate + " 00:00:00";
// String endTime = "";
// // 当前时间小于 12 那就查询 0点到11点的打卡数据
// if(!HttpUtil.compareDate(currentdatetime,currentdate+" 12:00:00")){
// endTime = currentdate + " 11:00:00";
// }
// //查询 11点到23点的打卡数据
// else{
// startTime = currentdate + " 11:00:01";
// endTime = currentdate + " 23:59:59";
// }
//
// int kq_number = Util.getIntValue(rs.getPropValue("hrm_zhongkong","kq_number"));
// List<String> lsFormatData = new ArrayList<>();
// JSONObject json_main = new JSONObject();
// try{
// int index = 1;
// json_main.put("starttime",startTime);
// json_main.put("endtime",endTime);
// json_main.put("number",kq_number);
//
// HttpUtil httpUtil = new HttpUtil();
// httpUtil.SynKqData(lsFormatData,index,json_main);
//
// Map<String,List<String>> overtimeMap = Maps.newHashMap();
// List<String> overtimeList = Lists.newArrayList();
// List<Object> formatParams = null;
// List<List<Object>> lsFormatParams = new ArrayList<>();
// List<Object> delParams = null;
// List<List<Object>> lsDelParams = new ArrayList<>();
//
// rs.writeLog("------------- lsFormatData size ------------- "+ lsFormatData.size());
//
// for(int i=0;lsFormatData!=null&&i<lsFormatData.size();i++){
// formatParams = new ArrayList<>();
// String[] formatData = Util.splitString(lsFormatData.get(i),"|");
// String date_1 = HttpUtil.addDateDay(formatData[1],-1);
// formatParams.add(formatData[0]);
// formatParams.add(date_1);
// lsFormatParams.add(formatParams);
//
// formatParams = new ArrayList<>();
// formatParams.add(formatData[0]);
// formatParams.add(formatData[1]);
// lsFormatParams.add(formatParams);
//
// delParams = new ArrayList<>();
// delParams.add(formatData[0]);
// delParams.add(formatData[1]);
// delParams.add(formatData[2]);
// lsDelParams.add(delParams);
//
// String resourceId = formatData[0];
// String kqdate = formatData[1];
// if(overtimeMap.containsKey(resourceId)){
// List<String> tmp_overtimeList = overtimeMap.get(resourceId);
// if(!tmp_overtimeList.contains(kqdate)){
// tmp_overtimeList.add(kqdate);
// }
// }else{
// if(!overtimeList.contains(kqdate)){
// overtimeList.add(kqdate);
// }
// overtimeMap.put(resourceId, overtimeList);
// }
// }
//
// new KQFormatBiz().format(lsFormatParams);
// //处理加班生成
// List<KQTaskBean> tasks = new ArrayList<>();
// for(Map.Entry<String, List<String>> mme: overtimeMap.entrySet()){
// String resid = mme.getKey();
// List<String> overList = mme.getValue();
// for(String date : overList){
// SplitActionUtil.pushOverTimeTasks(date,date,resid,tasks);
// }
// }
// if(!tasks.isEmpty()){
// KQQueue.writeTasks(tasks);
// }
// rs.writeLog("------------------------- end to syn today other kqinfo -----------------------------------");
// }catch (Exception e){
// e.printStackTrace();
// rs.writeLog("------------------------- syn today other kqinfo error ----------------------------------- "+ e);
// }
// }
//
//}

View File

@ -0,0 +1,94 @@
package weaver.interfaces.lingyue.job;
import com.lingyue.util.KqUtil;
import weaver.conn.RecordSet;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.resource.ResourceComInfo;
import weaver.interfaces.schedule.BaseCronJob;
/**
* @Title 该计划任务主要是针对 1遍历所有的分部信息到中控考勤系统不存在的再次同步
* 2遍历所有的部门信息到中控考勤系统不存在的再次同步
* 3遍历所有的人员信息到中控考勤系统不存在的再次同步
* @Author wangchaofa
* @CreateDate 2024/7/19
* @Version 1.0
* @Description
*/
public class SynSubcomDeptUserInfoJob extends BaseCronJob {
@Override
public void execute() {
SynHrmDeptInfo();
}
// 同步HR系统的部门数据 中控考勤机 里面
public void SynHrmDeptInfo(){
RecordSet rs = new RecordSet();
RecordSet rs1 = new RecordSet();
RecordSet rs2 = new RecordSet();
rs.writeLog("------------------------- start to syn HRM subcom、dept、user info to zhongkong -----------------------------------");
String currentdate = TimeUtil.getCurrentDateString();
String currenttime = TimeUtil.getOnlyCurrentTimeString();
String currentdatetime = currentdate + " " + currenttime;
try{
rs.executeQuery("select * from hrmsubcompany where 1=1 and (canceled = '0' or canceled is null) ");
while(rs.next()){
//分部编码
String subcomid = Util.null2String(rs.getString("id"));
// //分部编码
// String subcompanycode = Util.null2String(rs.getString("subcompanycode"));
// //上级分部id
// String supsubcomid = Util.null2String(rs.getString("supsubcomid"));
//
// boolean bool = KqUtil.checkIsExistDeptInfo(subcompanycode);
//不存在需要同步新增
// if(!bool){
KqUtil.synAddOrUpdateSubComInfo(subcomid);
// }
}
rs1.executeQuery("select * from hrmdepartment where 1=1 and (canceled = '0' or canceled is null) ");
while(rs1.next()){
//分部编码
String deptid = Util.null2String(rs1.getString("id"));
// //分部编码
// String departmentcode = Util.null2String(rs1.getString("departmentcode"));
// //上级分部id
// String supdeptid = Util.null2String(rs1.getString("supdepid"));
//
// boolean bool = KqUtil.checkIsExistDeptInfo(departmentcode);
//不存在需要同步新增
// if(!bool){
KqUtil.synAddOrUpdateDeptInfo(deptid);
// }
}
rs2.executeQuery("select * from hrmresource where status < 4 ");
while(rs2.next()){
String userid = Util.null2String(rs2.getString("id"));
// String pincode = "";
// String cuscode = KqUtil.getCusIdByUserid(userid);
// if(cuscode != null && !"".equals(cuscode)){
// pincode = cuscode;
// }else{
// pincode = new ResourceComInfo().getWorkcode(userid);
// }
// boolean bool = KqUtil.checkIsExistUserInfo(pincode);
// 不存在需要同步新增
// if(!bool){
KqUtil.synAddOrUpdateUserInfo(userid);
// }
}
rs.writeLog("------------------------- end to syn HRM subcom、dept、user info to zhongkong -----------------------------------");
}catch (Exception e){
e.printStackTrace();
rs.writeLog("------------------------- syn HRM subcom、dept、user info to zhongkong is error ----------------------------------- "+ e);
}
}
}

View File

@ -0,0 +1,309 @@
package weaver.interfaces.lingyue.job;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.time.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import weaver.conn.BatchRecordSet;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.schedule.BaseCronJob;
import java.io.IOException;
import java.util.*;
/**
* 从中控考勤机机同步打卡数据计划任务
*
*/
public class SyncKqDataFromZKJob extends BaseCronJob {
//已同步的数据记录
private static List<String> recordList;
//人员工号-id信息
private static Map<String, String> userMap;
//插入的建模数据
private static List<List<Object>> plist;
private String billid;
@Override
public void execute() {
BaseBean bb = new BaseBean();
String url = Util.null2String(bb.getPropValue("hrm_zhongkong", "get_kqinfo_url"));
int kq_number = Util.getIntValue(bb.getPropValue("hrm_zhongkong","kq_number"));
String key = bb.getPropValue("hrm_zhongkong","key");
url = url + "?key=" + key;
//考勤原始记录表模块id
String formmodeid = Util.null2String(bb.getPropValue("hrm_zhongkong", "zkkqjkqsj_formmodeid"));
String modedatacreater = "1"; //模块创建人id
String modedatacreatertype = "0"; //创建人类型(插入默认值0即可)
String modedatacreatedate = DateUtil.getCurrentTime("yyyy-MM-dd");
String modedatacreatetime = DateUtil.getCurrentTime("HH:mm:ss");
recordList = new ArrayList<>(kq_number);
userMap = getUserMap();
plist = new ArrayList<>(kq_number);
RecordSet rs = new RecordSet();
String sql = "select max(kqsjid) as lsid from uf_kqjysdkjl";
rs.execute(sql);
rs.next();
String maxid = Util.null2String(rs.getString("lsid"));
if(StringUtils.isNotBlank(billid)){
maxid = billid;
recordList = getRecordList(billid);
}
bb.writeLog("SyncKqDataFromZKJob plist1:" + plist.size());
getTrafficRecords(formmodeid, modedatacreater, modedatacreatertype, modedatacreatedate, modedatacreatetime, url, maxid);
bb.writeLog("SyncKqDataFromZKJob plist2:" + plist.size());
//批量插入建模数据
StringBuffer sb = new StringBuffer();
sb.append("insert into uf_kqjysdkjl(");
sb.append("MODEUUID,formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime,");
sb.append("oary,kqsjid,pin,ename,deptnumber,deptname,checkdate,checktime,sn,alias");
sb.append(")values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
BatchRecordSet batchRecordSet = new BatchRecordSet();
batchRecordSet.executeBatchSql(sb.toString(), plist);
//权限重构
sql = "select id from uf_kqjysdkjl where modedatacreatedate = '" + modedatacreatedate + "' and modedatacreatetime='" + modedatacreatetime + "'";
rs.execute(sql);
while (rs.next()) {
int billid = Integer.parseInt(rs.getString("id"));
ModeRightInfo info = new ModeRightInfo();
info.setNewRight(true);
info.rebuildModeDataShareByEdit(1, Integer.parseInt(formmodeid), billid);
}
//更新人员的id
sql = "select id,pin from uf_kqjysdkjl where (oary is null or oary = '' or oary = '-9999' or loginid is null or loginid = '' or workcode is null or workcode = '')";
rs.execute(sql);
while (rs.next()) {
String id = Util.null2String(rs.getString("id"));
String pin = Util.null2String(rs.getString("pin"));
String userid = Util.null2String(userMap.get(pin));
if ("".equals(pin) || "".equals(userid)) {
continue;
}
updateUserId(id, userid);
}
}
/**
* 已同步考勤记录id
*
* @return
*/
private List<String> getRecordList(String billid) {
RecordSet rs = new RecordSet();
int kq_number = Util.getIntValue(rs.getPropValue("hrm_zhongkong","kq_number"));
List<String> list = new ArrayList<>(kq_number);
rs.executeQuery("select kqsjid from uf_kqjysdkjl where kqsjid >= ?", billid);
while (rs.next()) {
String txjluuid = Util.null2String(rs.getString("kqsjid"));
list.add(txjluuid);
}
return list;
}
/**
* 人员id以及自定义考勤编号字段
*
* @return
*/
private Map<String, String> getUserMap() {
Map<String, String> map = new HashMap<>();
RecordSet rs = new RecordSet();
String kq_fieldid = rs.getPropValue("hrm_zhongkong","kq_fieldid");
String sql = "select a.id,b."+kq_fieldid+" as kqbh from hrmresource a left join cus_fielddata b on a.id=b.id where b.scope='HrmCustomFieldByInfoType' and a.status < 4 and b.scopeid=-1 and (b."+kq_fieldid+" != '' or b."+kq_fieldid+" is not null)";
String id = "";
String kqbh = "";
rs.execute(sql);
while (rs.next()) {
id = Util.null2String(rs.getString("id"));
kqbh = Util.null2String(rs.getString("kqbh"));
map.put(kqbh, id);
}
return map;
}
private void getTrafficRecords(String formmodeid, String modedatacreater, String modedatacreatertype, String modedatacreatedate, String modedatacreatetime, String url, String maxid) {
BaseBean bb = new BaseBean();
int kq_number = Util.getIntValue(bb.getPropValue("hrm_zhongkong","kq_number"));
JSONObject requestBody = new JSONObject();
requestBody.put("id", Util.getIntValue(maxid));
requestBody.put("number", kq_number);
bb.writeLog("-SyncKqDataFromZKJob-url:" + url);
Map<String,String> headers = new HashMap<>();
String result = httpPostKqData(url,headers,requestBody.toString(),"utf-8");
bb.writeLog("-SyncKqDataFromZKJob-result:" + result);
JSONObject resObj = JSONObject.parseObject(result);
int ret = (int) resObj.get("ret");
if (ret == 0) {
JSONObject data = (JSONObject) resObj.get("data");
JSONArray listArr = (JSONArray) data.get("items");
if (listArr.size() > 0) {
//插入数据到建模表
for (int i = 0; i < listArr.size(); i++) {
JSONObject list = (JSONObject) listArr.get(i);
String id = Util.null2String(list.get("id"));
if (recordList.contains(id)) {
continue;
} else {
//插入数据到建模表
//考勤编号
String kqbh = Util.null2String(list.get("pin"));
//人员id
String userid = Util.null2String(userMap.get(kqbh));
if ("".equals(kqbh) || "".equals(userid)) {
userid = "-9999";
}
String datetime = Util.null2String(list.get("checktime"));
String checkdate = Util.null2String(datetime.substring(0, 10));
String checktime = Util.null2String(datetime.substring(11, 19));
String ename = Util.null2String(list.get("ename"));
String deptnumber = Util.null2String(list.get("deptnumber"));
String deptname = Util.null2String(list.get("deptname"));
String sn = Util.null2String(list.get("sn"));
String alias = Util.null2String(list.get("alias"));
List<Object> listobj = new ArrayList<>();
listobj.add(UUID.randomUUID().toString());
listobj.add(formmodeid);
listobj.add(modedatacreater);
listobj.add(modedatacreatertype);
listobj.add(modedatacreatedate);
listobj.add(modedatacreatetime);
//业务字段
listobj.add(userid);
listobj.add(id);
listobj.add(kqbh);
listobj.add(ename);
listobj.add(deptnumber);
listobj.add(deptname);
listobj.add(checkdate);
listobj.add(checktime);
listobj.add(sn);
listobj.add(alias);
plist.add(listobj);
}
}
}
}
}
private void updateUserId(String id, String userid) {
RecordSet rs = new RecordSet();
Map<String, String> map = getUserInfoMap(userid);
String loginid = Util.null2String(map.get("loginid"));
String workcode = Util.null2String(map.get("workcode"));
rs.executeUpdate("update uf_kqjysdkjl set oary = ?,loginid = ?,workcode = ? where id = ?", userid, loginid, workcode, id);
}
/**
* 获取员工信息
*
* @param userid
* @return
*/
private Map<String, String> getUserInfoMap(String userid) {
Map<String, String> map = new HashMap<>();
String sql = "select loginid,workcode from hrmresource where id = ?";
RecordSet rs = new RecordSet();
rs.executeQuery(sql, userid);
String loginid = "";
String workcode = "";
while (rs.next()) {
loginid = Util.null2String(rs.getString("loginid"));
workcode = Util.null2String(rs.getString("workcode"));
map.put("loginid", loginid);
map.put("workcode", workcode);
}
return map;
}
/**
* post 请求 json格式
* @param url
* @param headers
* @param stringJson
* @param encode
* @return
*/
public static String httpPostKqData(String url, Map<String,String> headers, String stringJson, String encode){
String result = "";
if(encode == null){
encode = "utf-8";
}
RecordSet rs = new RecordSet();
String content = null;
CloseableHttpResponse httpResponse = null;
CloseableHttpClient closeableHttpClient = null;
try {
closeableHttpClient = HttpClients.createDefault();
HttpPost httpost = new HttpPost(url);
//设置header
httpost.setHeader("Content-type", "application/json");
if (headers != null && headers.size() > 0) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpost.setHeader(entry.getKey(),entry.getValue());
}
}
//组织请求参数
StringEntity stringEntity = new StringEntity(stringJson, encode);
httpost.setEntity(stringEntity);
//响应信息
httpResponse = closeableHttpClient.execute(httpost);
if(httpResponse != null) {
HttpEntity entity = httpResponse.getEntity();
content = EntityUtils.toString(entity, encode);
if (content != null && !"".equals(content)) {
JSONObject json = JSONObject.parseObject(content);
result = json.toString();
}
}
} catch (Exception e) {
e.printStackTrace();
rs.writeLog(e);
}finally{
try {
httpResponse.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try { //关闭连接释放资源
closeableHttpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}

View File

@ -0,0 +1,528 @@
package weaver.interfaces.lingyue.util;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wbi.util.Util;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.TimeUtil;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* @Title
* @Author wangchaofa
* @CreateDate 2024/7/11
* @Version 1.0
* @Description
*/
public class HttpUtil {
/**
* post 请求 json格式
* @param url
* @param headers
* @param stringJson
* @param encode
* @return
*/
public static int httpPost(String url, Map<String,String> headers, String stringJson, String encode){
int result = 0;
if(encode == null){
encode = "utf-8";
}
RecordSet rs = new RecordSet();
String content = null;
CloseableHttpResponse httpResponse = null;
CloseableHttpClient closeableHttpClient = null;
try {
closeableHttpClient = HttpClients.createDefault();
HttpPost httpost = new HttpPost(url);
//设置header
httpost.setHeader("Content-type", "application/json");
if (headers != null && headers.size() > 0) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpost.setHeader(entry.getKey(),entry.getValue());
}
}
//组织请求参数
StringEntity stringEntity = new StringEntity(stringJson, encode);
httpost.setEntity(stringEntity);
//响应信息
httpResponse = closeableHttpClient.execute(httpost);
if(httpResponse != null) {
HttpEntity entity = httpResponse.getEntity();
content = EntityUtils.toString(entity, encode);
if (content != null && !"".equals(content)) {
JSONObject json = JSONObject.parseObject(content);
rs.writeLog("============= pushInfo json =================== " + json);
result = Integer.parseInt(json.getString("ret"));
}
}
} catch (Exception e) {
result = -1;
e.printStackTrace();
rs.writeLog(e);
}finally{
try {
httpResponse.close();
} catch (IOException e) {
result = -1;
e.printStackTrace();
}
}
try { //关闭连接释放资源
closeableHttpClient.close();
} catch (IOException e) {
result = -1;
e.printStackTrace();
}
return result;
}
/**
* 对时间的天数进行加减
* @param daytime 时间的格式yyyy-MM-dd HH:mm:ss
* @param day 天数 -1则代表减一天
* @return
*/
public static String addDateDay(String daytime, int day){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = format.parse(daytime);
if (date == null){
return "";
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH, day);// 加一天
date = cal.getTime();
cal = null;
return format.format(date);
} catch (Exception ex) {
ex.printStackTrace();
}
return "";
}
/**
* 比较时间的大小
* @param a
* @param b
* @return
* @throws ParseException
*/
public static boolean compareDate(String a, String b) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
boolean bool = false;
try {
long t1 = sdf.parse(a).getTime();
long t2 = sdf.parse(b).getTime();
if (t1 >= t2) {
bool = true;
} else {
bool = false;
}
}catch (Exception e){
e.printStackTrace();
}
return bool;
}
/**
* post 请求 json格式
* @param url
* @param headers
* @param stringJson
* @param encode
* @return
*/
public static String httpPostKqData(String url, Map<String,String> headers, String stringJson, String encode){
String result = "";
if(encode == null){
encode = "utf-8";
}
RecordSet rs = new RecordSet();
String content = null;
CloseableHttpResponse httpResponse = null;
CloseableHttpClient closeableHttpClient = null;
try {
closeableHttpClient = HttpClients.createDefault();
HttpPost httpost = new HttpPost(url);
//设置header
httpost.setHeader("Content-type", "application/json");
if (headers != null && headers.size() > 0) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpost.setHeader(entry.getKey(),entry.getValue());
}
}
//组织请求参数
StringEntity stringEntity = new StringEntity(stringJson, encode);
httpost.setEntity(stringEntity);
//响应信息
httpResponse = closeableHttpClient.execute(httpost);
if(httpResponse != null) {
HttpEntity entity = httpResponse.getEntity();
content = EntityUtils.toString(entity, encode);
if (content != null && !"".equals(content)) {
JSONObject json = JSONObject.parseObject(content);
rs.writeLog("============= pushInfo json =================== " + json);
int success = Integer.parseInt(json.getString("ret"));
String data = json.getString("data").toString();
// 成功的
if(success == 0){
result = json.getString("data").toString();
}
}
}
} catch (Exception e) {
e.printStackTrace();
rs.writeLog(e);
}finally{
try {
httpResponse.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try { //关闭连接释放资源
closeableHttpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
* 根据 自定义 考勤卡号 获取 人员id
* @param fieldvalue
* @return
*/
public String getUserIdByPin(String fieldvalue){
String result = "";
RecordSet rs = new RecordSet();
String kq_fieldid = rs.getPropValue("hrm_zhongkong","kq_fieldid");
// rs.executeQuery("select id from hrmresource where workcode = ?",fieldvalue);
rs.executeQuery("select a.id from cus_fielddata a,hrmresource b where a.id=b.id and a.scope = 'HrmCustomFieldByInfoType' and a.scopeid = -1 and "+ kq_fieldid +" = ?",fieldvalue);
if(rs.next()){
result = Util.null2String(rs.getString("id"));
}
return result;
}
/**
* 根据 人员id 获取 自定义 考勤卡号也就是 中控考勤机那边的 人员编号 pin
* @param userid
* @return
*/
public String getCusIdByUserid(String userid){
String result = "";
RecordSet rs = new RecordSet();
String kq_fieldid = rs.getPropValue("hrm_zhongkong","kq_fieldid");
rs.executeQuery("select "+ kq_fieldid +" from cus_fielddata where scope = 'HrmCustomFieldByInfoType' and scopeid = -1 and id = ?",userid);
// rs.executeQuery("select workcode from hrmresource where id = ?",userid);
if(rs.next()){
result = Util.null2String(rs.getString(kq_fieldid));
// result = Util.null2String(rs.getString("workcode"));
}
return result;
}
public void SynKqData(List<String> lsFormatData, int index, JSONObject json_main){
RecordSet rs = new RecordSet();
RecordSet rs1 = new RecordSet();
RecordSet rs2 = new RecordSet();
RecordSet rst = new RecordSet();
String currentdate = TimeUtil.getCurrentDateString();
String currenttime = TimeUtil.getOnlyCurrentTimeString();
String currentdatetime = currentdate + " " + currenttime;
Map<String,String> headers = new HashMap<>();
String key = rs.getPropValue("hrm_zhongkong","key");
String get_kqinfo_url = rs.getPropValue("hrm_zhongkong","get_kqinfo_url");
int zkkqjkqsj_formmodeid = weaver.general.Util.getIntValue(rs.getPropValue("hrm_zhongkong","zkkqjkqsj_formmodeid"));
int creater = 1;
boolean bool = false;
get_kqinfo_url = get_kqinfo_url + "?key=" + key;
List<List<Object>> lsParams = new ArrayList<>();
List<String> idList = new ArrayList<>();
json_main.put("id",index);
rs.writeLog("============= SynKqData json_main =============== "+ json_main);
String result = httpPostKqData(get_kqinfo_url,headers,json_main.toString(),"utf-8");
if(result != null && !"".equals(result)) {
JSONObject json1 = JSONObject.parseObject(result);
String items = json1.getString("items").toString();
JSONArray data_jsonArray = JSONArray.parseArray(items);
rs.writeLog("============= SynKqData data_jsonArray size =============== "+ data_jsonArray.size());
if (data_jsonArray.size() > 1) {
bool = true;
for (int i = 0; i < data_jsonArray.size(); i++) {
JSONObject jsonObject = JSONObject.parseObject(data_jsonArray.get(i).toString());
String lsh = "";
String pin = "";
String ename = "";
String deptnumber = "";
String deptname = "";
String checktime = "";
String sn = "";
String alias = "";
String verify = "";
String stateno = "";
String state = "";
if (jsonObject.containsKey("id")) {
lsh = jsonObject.get("id").toString();
idList.add(lsh);
}
if (jsonObject.containsKey("pin")) {
pin = jsonObject.get("pin").toString();
}
if (jsonObject.containsKey("ename")) {
ename = jsonObject.get("ename").toString();
}
if (jsonObject.containsKey("deptnumber")) {
deptnumber = jsonObject.get("deptnumber").toString();
}
if (jsonObject.containsKey("deptname")) {
deptname = jsonObject.get("deptname").toString();
}
if (jsonObject.containsKey("checktime")) {
checktime = jsonObject.get("checktime").toString();
}
if (jsonObject.containsKey("sn")) {
sn = jsonObject.get("sn").toString();
}
if (jsonObject.containsKey("alias")) {
alias = jsonObject.get("alias").toString();
}
if (jsonObject.containsKey("verify")) {
verify = jsonObject.get("verify").toString();
}
if (jsonObject.containsKey("stateno")) {
stateno = jsonObject.get("stateno").toString();
}
if (jsonObject.containsKey("state")) {
state = jsonObject.get("state").toString();
}
String userid = getUserIdByPin(pin);
if(userid != null && !"".equals(userid)){
String signDate = "";
String signTime = "";
int usertype = 1;
int signType = 1;
int isincom = 1;
String signfrom = "OutDataSourceSyn";
String addr = "";
int isimport = 1;
signDate = checktime.substring(0, 10);
signTime = checktime.substring(11, 19);
signType = 1;
List<Object> params = new ArrayList<>();
params.add(userid);
params.add(usertype);
params.add(signType);
params.add(signDate);
params.add(signTime);
params.add("");
params.add(isincom);
params.add(isimport);
params.add(signfrom);
params.add("");
params.add("");
params.add(addr);
params.add("中控考勤机数据同步");
lsParams.add(params);
String formatData = userid + "|" + signDate + "|" + signTime;
if (!lsFormatData.contains(formatData)) {
lsFormatData.add(formatData);
}
boolean isdelte = deleteByInfo(userid,signDate,signTime);
boolean isok = InsertByInfo(userid,usertype,signDate,signTime,"",isincom,isimport,signfrom,"","",addr,"中控考勤机数据同步");
rs.writeLog("isdelte:" + isdelte+"isok:"+isok);
rs1.executeQuery("select * from uf_zkkqjkqsj where lsh = ?",lsh);
//不存在
if(!rs1.next()) {
int billid = -1;
String uuid = UUID.randomUUID().toString();
boolean exeRes = rst.executeUpdate("insert into uf_zkkqjkqsj(lsh,verify,checktime,sn,alias,pin,ename,deptnumber,deptname,stateno,state,modedatacreater,modedatacreatedate,modedatacreatetime,formmodeid,modeuuid) values(?,?,?,?,?,?,?,?," +
"?,?,?,?,?,?,?,?)",
new Object[]{lsh, verify, checktime, sn, alias, pin, ename, deptnumber, deptname, stateno, state, creater, currentdate, currenttime, zkkqjkqsj_formmodeid, uuid});
if (exeRes) {
//重构权限
rs2.executeQuery(" select id from uf_zkkqjkqsj where modeuuid=? ", new Object[]{uuid});
rs2.next();
billid = rs2.getInt("id");
ModeRightInfo moderight = new ModeRightInfo();
moderight.editModeDataShare(creater, zkkqjkqsj_formmodeid, billid);
}
}
}
}
}else{
if(data_jsonArray.size() > 0){
JSONObject jsonObject = JSONObject.parseObject(data_jsonArray.get(0).toString());
String lsh = "";
String pin = "";
String ename = "";
String deptnumber = "";
String deptname = "";
String checktime = "";
String sn = "";
String alias = "";
String verify = "";
String stateno = "";
String state = "";
if (jsonObject.containsKey("id")) {
lsh = jsonObject.get("id").toString();
idList.add(lsh);
}
if (jsonObject.containsKey("pin")) {
pin = jsonObject.get("pin").toString();
}
if (jsonObject.containsKey("ename")) {
ename = jsonObject.get("ename").toString();
}
if (jsonObject.containsKey("deptnumber")) {
deptnumber = jsonObject.get("deptnumber").toString();
}
if (jsonObject.containsKey("deptname")) {
deptname = jsonObject.get("deptname").toString();
}
if (jsonObject.containsKey("checktime")) {
checktime = jsonObject.get("checktime").toString();
}
if (jsonObject.containsKey("sn")) {
sn = jsonObject.get("sn").toString();
}
if (jsonObject.containsKey("alias")) {
alias = jsonObject.get("alias").toString();
}
if (jsonObject.containsKey("verify")) {
verify = jsonObject.get("verify").toString();
}
if (jsonObject.containsKey("stateno")) {
stateno = jsonObject.get("stateno").toString();
}
if (jsonObject.containsKey("state")) {
state = jsonObject.get("state").toString();
}
String userid = getUserIdByPin(pin);
if(userid != null && !"".equals(userid)){
String signDate = "";
String signTime = "";
int usertype = 1;
int signType = 1;
int isincom = 1;
String signfrom = "OutDataSourceSyn";
String addr = "";
int isimport = 1;
signDate = checktime.substring(0, 10);
signTime = checktime.substring(11, 19);
signType = 1;
List<Object> params = new ArrayList<>();
params.add(userid);
params.add(usertype);
params.add(signType);
params.add(signDate);
params.add(signTime);
params.add("");
params.add(isincom);
params.add(isimport);
params.add(signfrom);
params.add("");
params.add("");
params.add(addr);
params.add("中控考勤机数据同步");
lsParams.add(params);
String formatData = userid + "|" + signDate + "|" + signTime;
if (!lsFormatData.contains(formatData)) {
lsFormatData.add(formatData);
}
boolean isdelte = deleteByInfo(userid,signDate,signTime);
boolean isok = InsertByInfo(userid,usertype,signDate,signTime,"",isincom,isimport,signfrom,"","",addr,"中控考勤机数据同步");
rs.writeLog("isdelte:" + isdelte+"isok:"+isok);
rs1.executeQuery("select * from uf_zkkqjkqsj where lsh = ?",lsh);
//不存在
if(!rs1.next()) {
int billid = -1;
String uuid = UUID.randomUUID().toString();
boolean exeRes = rst.executeUpdate("insert into uf_zkkqjkqsj(lsh,verify,checktime,sn,alias,pin,ename,deptnumber,deptname,stateno,state,modedatacreater,modedatacreatedate,modedatacreatetime,formmodeid,modeuuid) values(?,?,?,?,?,?,?,?," +
"?,?,?,?,?,?,?,?)",
new Object[]{lsh, verify, checktime, sn, alias, pin, ename, deptnumber, deptname, stateno, state, creater, currentdate, currenttime, zkkqjkqsj_formmodeid, uuid});
if (exeRes) {
//重构权限
rs2.executeQuery(" select id from uf_zkkqjkqsj where modeuuid=? ", new Object[]{uuid});
rs2.next();
billid = rs2.getInt("id");
ModeRightInfo moderight = new ModeRightInfo();
moderight.editModeDataShare(creater, zkkqjkqsj_formmodeid, billid);
}
}
}
}
}
}
if(bool){
index = Integer.parseInt(Collections.max(idList));
json_main.put("id",index);
SynKqData(lsFormatData,index,json_main);
}
}
/**
* 删除
* @param userId
* @param signdate
* @param signtime
*/
public static Boolean deleteByInfo(String userId,String signdate,String signtime){
RecordSet rs = new RecordSet();
String sql = "delete from hrmschedulesign where signfrom='OutDataSourceSyn' and userid =? and signdate = ? and signtime = ? ";
boolean isdelete = rs.executeUpdate(sql,userId,signdate,signtime);
return isdelete;
}
/**
* 新增
* @param userId
* @param signdate
* @param signtime
*/
public static Boolean InsertByInfo(String userId,Integer usertype,String signdate,String signtime,String clientaddress,Integer isincom,Integer isimport,String signfrom,String longitude,String latitude,String addr,String memo){
RecordSet rs = new RecordSet();
String sql = " insert into HrmScheduleSign (userid, usertype, signdate, signtime, clientaddress, isincom, isimport, signfrom, longitude, latitude, addr,memo) "
+ " values(?,?,?,?,?,?,?,?,?,?,?,?)";
boolean isok = rs.executeUpdate(sql,userId,usertype,signdate,signtime,clientaddress,isincom,isimport,signfrom,longitude,latitude,addr,memo);
return isok;
}
}