合并远程分支
jingwei
youhong.ai 2023-05-10 14:15:35 +08:00
commit daaefd64c2
113 changed files with 12225 additions and 302 deletions

View File

@ -6,6 +6,7 @@ import com.api.bokang.xiao.zscq.service.ReserveService;
import com.api.bokang.xiao.zscq.service.impl.ReserveServiceImpl;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import org.apache.log4j.Logger;
import weaver.bokang.xiao.zscq.store.TableNameStore;
import weaver.file.ImageFileManager;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
@ -17,7 +18,9 @@ import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@ -48,77 +51,68 @@ public class ReserveSelectController {
@Produces(MediaType.APPLICATION_JSON)
public String reserveSelect(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody Map<String,Object> param) {
try{
log.info("====== into getReportData success =======");
log.info("====== into reserveSelect success =======");
log.info("param:"+param);
User loginUser = HrmUserVarify.getUser(request, response);
List<Map<String, Object>> result = reserveService.reserveSelect(param);
List<Map<String, Object>> result = reserveService.reserveTrigger(param);
return ApiResult.success(result);
}catch (Exception e){
log.error("获取搜索组件信息 ==> "+ Util.getErrString(e));
log.error("反选执行出现异常 reserveSelect execute error ==> "+ Util.getErrString(e));
return ApiResult.error(e.getMessage());
}
}
//@GET
//@Path("/batch")
//@Produces(MediaType.APPLICATION_OCTET_STREAM)
//public void downloadFiles(@QueryParam("ids") String ids, @Context HttpServletResponse response) {
// try {
// log.info("Start downloading files: {}"+ids);
// // 解析文件ID列表
// List<Long> idList = Arrays.stream(ids.split(","))
// .map(Long::parseLong)
// .collect(Collectors.toList());
//
// // 生成压缩文件名
// String zipFileName = "attachments.zip";
//
// // 设置响应头,告诉浏览器该响应体是一个附件,浏览器会自动下载该响应体
// response.setContentType(MediaType.APPLICATION_OCTET_STREAM);
// response.setHeader("Content-Disposition", "attachment; filename=\"" + zipFileName + "\"");
//
// // 创建压缩输出流
// try (ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream())) {
//
// // 遍历文件ID列表将对应的文件加入到压缩文件中
// for (Long id : idList) {
// // 通过ID获取文件信息
// WeaverFile file = WeaverFileUtil.getFileMsgById(id);
//
// // 获取文件名和后缀名
// String fileName = file.getName();
// String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1);
//
// // 创建一个ZipEntry表示压缩文件中的一个文件
// ZipEntry zipEntry = new ZipEntry(fileName);
// zipEntry.setSize(file.getSize());
// zipEntry.setTime(System.currentTimeMillis());
//
// // 将ZipEntry添加到压缩输出流中
// zipOutputStream.putNextEntry(zipEntry);
//
// // 将文件内容写入到压缩输出流中
// byte[] buffer = new byte[BUFFER_SIZE];
// int len;
// try (InputStream inputStream = file.getInputStream()) {
// while ((len = inputStream.read(buffer)) > 0) {
// zipOutputStream.write(buffer, 0, len);
// }
// }
// zipOutputStream.closeEntry();
// }
//
// // 刷新压缩输出流
// zipOutputStream.flush();
// }
// log.info("Finish downloading files: {}"+ids);
// } catch (Exception e) {
// log.error("下载附件异常: {}"+Util.getErrString(e));
// // 如果出现异常,返回一个空的响应体
// response.reset();
// response.setContentType(MediaType.APPLICATION_OCTET_STREAM);
// response.setContentLength(0);
// }
//}
@GET
@Path("/batchDownload")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response downloadBatchFiles(@QueryParam("datePicker") String datePicker,
@QueryParam("checkResult") String checkResult,
@QueryParam("checkResultShow") String checkResultShow) {
log.info("====== into downloadBatchFiles success =======");
log.info(String.format("====== datePicker:[%s] checkResult:[%s] checkResultShow:[%s] =======",datePicker,checkResult,checkResultShow));
Map<String,Object> param = new HashMap<>(8);
param.put("datePicker",datePicker);
param.put("checkResult",checkResult);
param.put("checkResultShow",checkResultShow);
String zipFileName = reserveService.getFileName(param) + ".zip";
StreamingOutput streamingOutput = outputStream -> {
try {
reserveService.batchDownload(param, outputStream);
} catch (Exception e) {
log.error("下载文件异常 download zip error ==>"+Util.getErrString(e));
}
};
log.info("zip file name ==>"+zipFileName);
return Response.ok(streamingOutput, MediaType.APPLICATION_OCTET_STREAM)
.header("Content-Disposition", "attachment; filename=\"" + zipFileName + "\"")
.build();
}
@GET
@Path("/refreshStore")
public String refreshStore(@Context HttpServletRequest request, @Context HttpServletResponse response){
try{
log.info("====== into refreshStore success =======");
TableNameStore.getInstance().refresh();
return ApiResult.successNoData();
}catch (Exception e){
log.error("refreshStore execute error ==> "+ Util.getErrString(e));
return ApiResult.error(e.getMessage());
}
}
@GET
@Path("/doRepossessedSign")
public String doRepossessedSign(@QueryParam("requestId") String requestId){
try{
log.info("====== into doRepossessedSign success =======");
log.info("requestId =>"+requestId);
new ReserveServiceImpl().doRepossessedSign(Util.getIntValue(requestId),new User(1));
return ApiResult.successNoData();
}catch (Exception e){
log.error("refreshStore execute error ==> "+ Util.getErrString(e));
return ApiResult.error(e.getMessage());
}
}
}

View File

@ -0,0 +1,28 @@
package com.api.bokang.xiao.zscq.entity;
import aiyh.utils.annotation.recordset.SqlOracleDbFieldAnn;
import lombok.Data;
/**
* @ClassName SendFileEntity
* @Author
* @Date 2023/4/23 10:10
* @Description <h1></h1>
**/
@Data
public class SendFileEntity {
@SqlOracleDbFieldAnn(value = "ID")
private Integer id;
@SqlOracleDbFieldAnn(value = "DEPART_ID")
private Integer departId;
@SqlOracleDbFieldAnn(value = "DEPART_NAME")
private String departName;
@SqlOracleDbFieldAnn(value = "SQH")
private String requestNumber;
private WeaverFile weaverFile;
}

View File

@ -0,0 +1,26 @@
package com.api.bokang.xiao.zscq.entity;
import aiyh.utils.annotation.recordset.SqlOracleDbFieldAnn;
import lombok.Data;
/**
* @ClassName WeaverFile
* @Author
* @Date 2023/4/23 10:09
* @Description <h1></h1>
**/
@Data
public class WeaverFile {
@SqlOracleDbFieldAnn(value = "IMAGEFILEID")
private Integer imageFileId;
@SqlOracleDbFieldAnn(value = "DOCID")
private Integer docId;
@SqlOracleDbFieldAnn(value = "FILESIZE")
private Integer fileSize;
@SqlOracleDbFieldAnn(value = "IMAGEFILENAME")
private String fileName;
}

View File

@ -0,0 +1,56 @@
package com.api.bokang.xiao.zscq.mapper;
import aiyh.utils.annotation.recordset.*;
import com.api.bokang.xiao.zscq.entity.SendFileEntity;
import com.api.bokang.xiao.zscq.entity.WeaverFile;
import java.util.List;
import java.util.Map;
/**
* @ClassName QueryMapper
* @Author
* @Date 2023/4/23 10:14
* @Description <h1></h1>
**/
@SqlMapper
public interface QueryMapper {
/**
* <h2></h2>
* @param param
* @return
*/
@Select("select gjj.id as id,depart.id as depart_id,depart.DEPARTMENTNAME as depart_name,xgfj,sqh " +
" from uf_gjjtb gjj " +
" inner join hrmdepartment depart on gjj.xfqj = depart.id " +
" where concat(',',concat(sjpcdxk,',')) like concat('%,',concat(#{datePicker},',%')) " +
" and hcqkdx = #{checkResult} and gjj.xgfj is not null ")
@Associations( @Association(property = "weaverFile",column = "xgfj",id = @Id(value = Integer.class,methodId = 1)))
List<SendFileEntity> queryDownloadList(Map<String,Object> param);
/**
* <h2></h2>
* @param docId docId
* @return
*/
@AssociationMethod(value = 1)
@Select("select dm.docid,dm.imagefileid,dm.imagefilename,file.filesize " +
" from docimagefile dm inner join imagefile file on dm.imagefileid = file.imagefileid" +
" where docid = #{docId}")
WeaverFile queryFile(@ParamMapper("id")Integer docId);
/**
* <h2></h2>
* @param tableName
* @param fieldName
* @return
*/
@Select("select selectvalue,selectname " +
" from workflow_selectitem se " +
" inner join workflow_billfield bf on se.fieldid = bf.id " +
" inner join workflow_bill bi on bf.billid = bi.id " +
" where tablename = #{tableName} and bf.fieldname = #{fieldName} ")
List<Map<String,Object>> querySelectItem(@ParamMapper("tableName") String tableName,@ParamMapper("fieldName") String fieldName);
}

View File

@ -19,7 +19,7 @@ public interface ReserveSelectMapper {
* @param requestId id
* @return
*/
@Select("select operator userId,operatortype userType from workflow_requestlog where requestid=#{requestId}" +
@Select("select operator userid,operatortype usertype from workflow_requestlog where requestid=#{requestId}" +
" and (logtype='2' or logtype='0' or logtype='3' or logtype='e') " +
" and exists(select 1 from workflow_currentoperator where requestid=workflow_requestlog.requestid and userid=workflow_requestlog.operator and usertype=workflow_requestlog.operatortype and isremark='2' and preisremark='0' and operatedate is not null and operatedate>' ') " +
" group by operator,operatortype order by max(logid) desc")
@ -30,7 +30,7 @@ public interface ReserveSelectMapper {
* @param requestId id
* @return
*/
@Select("select userid userId,usertype userType from workflow_currentoperator where requestid = #{requestId} and isremark = '2' and preisremark='0' and operatedate is not null and operatedate>' ' order by operatedate desc ,operatetime desc")
@Select("select userid,usertype from workflow_currentoperator where requestid = #{requestId} and isremark = '2' and preisremark='0' and operatedate is not null and operatedate>' ' order by operatedate desc ,operatetime desc")
Map<String,Integer> queryOperator(@ParamMapper("requestId")String requestId);
/**
@ -38,17 +38,26 @@ public interface ReserveSelectMapper {
* @param param
* @return
*/
@Select("select id, $t{applicationNoField}, $t{workflowInfoField}, $t{checkResultField} from $t{modeTableName} where $t{dateField} = #{datePicker}")
@Select("select id, $t{applicationNoField}, $t{workflowInfoField}, $t{checkResultField} from $t{modeTableName} where concat(',',concat($t{dateField},',')) like #{datePicker} and ($t{markField} <> 0 or $t{markField} is not null)")
@CaseConversion(value = false)
List<Map<String, Object>> queryModeList(Map<String, Object> param);
/**
* <h2></h2>
* @param param
* @return
*/
@Update("update $t{modeTableName} set $t{markField} = 1 " +
" where concat(',',concat($t{dateField},',')) like #{datePicker}")
boolean updateModeDataStatus(@ParamMapper("param") Map<String, Object> param);
/**
* <h2></h2>
* @param forceOverList id
* @param param
* @return
*/
@Update("update $t{param.modeTableName} set $t{param.checkResultField} = #{param.repossessedValue} " +
@Update("update $t{param.modeTableName} set $t{param.markField} = #{param.repossessedValue} " +
" where $t{param.workflowInfoField} in (${doRepossessedList})")
boolean updateRepossessed(@ParamMapper("doRepossessedList") List<String> forceOverList,
@ParamMapper("param") Map<String, Object> param);

View File

@ -3,6 +3,7 @@ package com.api.bokang.xiao.zscq.service;
import aiyh.utils.Util;
import org.apache.log4j.Logger;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
@ -22,4 +23,26 @@ public interface ReserveService {
* @return
*/
List<Map<String,Object>> reserveSelect(Map<String,Object> param);
/**
* <h2></h2>
* @param param
* @return
*/
List<Map<String,Object>> reserveTrigger(Map<String,Object> param);
/**
* <h2></h2>
* @param param
* @param outputStream
* @throws Exception
*/
void batchDownload(Map<String,Object> param, OutputStream outputStream) throws Exception;
/**
* <h2></h2>
* @param param
* @return
*/
String getFileName(Map<String,Object> param);
}

View File

@ -1,16 +1,27 @@
package com.api.bokang.xiao.zscq.service.impl;
import aiyh.utils.Util;
import com.alibaba.fastjson.JSON;
import com.api.bokang.xiao.zscq.entity.SendFileEntity;
import com.api.bokang.xiao.zscq.entity.WeaverFile;
import com.api.bokang.xiao.zscq.mapper.QueryMapper;
import com.api.bokang.xiao.zscq.mapper.ReserveSelectMapper;
import com.api.bokang.xiao.zscq.service.ReserveService;
import weaver.bokang.xiao.zscq.config.service.ModeChangeService;
import weaver.conn.RecordSet;
import weaver.file.ImageFileManager;
import weaver.hrm.User;
import weaver.workflow.workflow.RequestForceDrawBack;
import weaver.workflow.workflow.WfForceDrawBack;
import weaver.workflow.workflow.WfForceOver;
import weaver.workflow.workflow.WfFunctionManageUtil;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
@ -23,6 +34,8 @@ public class ReserveServiceImpl implements ReserveService {
private final ReserveSelectMapper reserveSelectMapper = Util.getMapper(ReserveSelectMapper.class);
private final QueryMapper queryMapper = Util.getMapper(QueryMapper.class);
private final WfForceOver wfForceOver = new WfForceOver();
private final WfFunctionManageUtil wfFunctionManageUtil = new WfFunctionManageUtil();
@ -30,6 +43,11 @@ public class ReserveServiceImpl implements ReserveService {
private final WfForceDrawBack wfForceDrawBack = new WfForceDrawBack();
private final RequestForceDrawBack requestForceDrawBack = new RequestForceDrawBack();
private final ModeChangeService modeChangeService = new ModeChangeService();
private static final int BUFFER_SIZE = 4096;
/**
* <h2></>
* @param requestIdList id
@ -51,15 +69,19 @@ public class ReserveServiceImpl implements ReserveService {
* @param user
* @return
*/
private boolean doRepossessedSign(int requestId,User user){
public boolean doRepossessedSign(int requestId,User user){
//查询最后一个操作者
Map<String, Integer> operateInfo = reserveSelectMapper.queryRequestMsg(String.valueOf(requestId));
log.info(" doRepossessedSign operateInfo ==>"+operateInfo);
if(Objects.isNull(operateInfo)){
operateInfo = reserveSelectMapper.queryOperator(String.valueOf(requestId));
}
int tempUser = operateInfo.get("userId");
int tempUserType = operateInfo.get("userType");
log.info(" doRepossessedSign operateInfo ==>"+operateInfo);
if(Objects.isNull(operateInfo)){
log.error(String.format("流程 requestId:[%s] 操作者 operateInfo no find 流程可能未归档 !!!",requestId));
return false;
}
int tempUser = operateInfo.get("userid");
int tempUserType = operateInfo.get("usertype");
boolean canForceDrawBack = false;
if(RequestForceDrawBack.isOldRequest(requestId) == RequestForceDrawBack.OLDDATA){
canForceDrawBack = wfForceDrawBack.isHavePurview(requestId, user.getUID(), Integer.parseInt(user.getLogintype()), tempUser, tempUserType);
@ -68,6 +90,7 @@ public class ReserveServiceImpl implements ReserveService {
}
if (canForceDrawBack && wfFunctionManageUtil.haveOtherOperationRight(requestId)) {
int result = requestForceDrawBack.foreceDrawBack(user, requestId, true, tempUser, tempUserType);
log.info(String.format("流程 requestId:[%s] 撤回结果 drawBack result:[%d] message:[%s]",requestId,result,requestForceDrawBack.getMessage()));
return requestForceDrawBack.isAddInOperateSuccess();
}else{
return false;
@ -97,9 +120,9 @@ public class ReserveServiceImpl implements ReserveService {
String checkResult = Util.null2String(modeInfo.get(checkResultField));
int requestId = Util.getIntValue(Util.null2String(modeInfo.get(workflowInfoField)));
if(checkResult.equals(checkResultValue)){
forceOverList.add(requestId+"");
}else {
doRepossessedList.add(requestId);
}else {
forceOverList.add(requestId+"");
}
}
log.info(String.format("doRepossessedList ==> %s forceOverList ==> %s",doRepossessedList,forceOverList));
@ -111,4 +134,91 @@ public class ReserveServiceImpl implements ReserveService {
}
return result;
}
@Override
public List<Map<String, Object>> reserveTrigger(Map<String, Object> param) {
List<Map<String, Object>> result = new ArrayList<>();
String applicationNoField = Util.null2String(param.get("applicationNoField"));
String workflowInfoField = Util.null2String(param.get("workflowInfoField"));
String formId = Util.null2String(param.get("formId"));
List<Map<String, Object>> modeList = reserveSelectMapper.queryModeList(param);
if(Objects.nonNull(modeList) && !modeList.isEmpty()){
for (Map<String, Object> modeMap : modeList) {
Map<String,Object> dealResult = new HashMap<>();
try{
modeChangeService.changeOtherMode(modeMap,formId,2);
dealResult.put(Util.null2String(modeMap.get(applicationNoField)),true);
}catch (Exception e){
log.error("执行异常 reserveTrigger error ==>"+modeMap);
dealResult.put(Util.null2String(modeMap.get(applicationNoField)),false);
}
result.add(dealResult);
}
reserveSelectMapper.updateModeDataStatus(param);
}
return result;
}
@Override
public void batchDownload(Map<String,Object> param, OutputStream outputStream) throws IOException {
List<SendFileEntity> sendList = queryMapper.queryDownloadList(param);
if(Objects.isNull(sendList) || sendList.isEmpty()){
log.info("附件列表为空 attachment empty !!!");
//throw new CustomerException("附件列表查询为空");
return;
}
log.info("查询到的附件信息 query fileList ==>"+ JSON.toJSONString(sendList));
// 1. 将 SendFileEntity 按照 departName 分组
Map<String, List<SendFileEntity>> sendMap = sendList.stream().collect(Collectors.groupingBy(SendFileEntity::getDepartName));
// 2. 创建 ZipOutputStream
ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(outputStream));
// 3. 遍历 SendFileEntity
for (Map.Entry<String, List<SendFileEntity>> entry : sendMap.entrySet()) {
String departName = entry.getKey();
List<SendFileEntity> fileList = entry.getValue();
// 4. 创建目录
ZipEntry dirEntry = new ZipEntry(departName + File.separator);
zipOutputStream.putNextEntry(dirEntry);
// 5. 将附件信息合并成一个压缩包
for (SendFileEntity sendFileEntity : fileList) {
WeaverFile fileMsg = sendFileEntity.getWeaverFile();
int imageFileId = fileMsg.getImageFileId();
String fileName = fileMsg.getFileName();
String fileType = fileName.substring(fileName.lastIndexOf("."));
String tempFileName = sendFileEntity.getRequestNumber() + fileType;
InputStream inputStream = ImageFileManager.getInputStreamById(imageFileId);
// 6. 将单个附件写入 ZipOutputStream
ZipEntry fileEntry = new ZipEntry(departName + File.separator + tempFileName);
zipOutputStream.putNextEntry(fileEntry);
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
zipOutputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
}
}
// 7. 关闭 ZipOutputStream
zipOutputStream.close();
}
@Override
public String getFileName(Map<String, Object> param) {
String fileName = "";
List<Map<String, Object>> selectItems = queryMapper.querySelectItem("uf_gjjtb", "sjpcdxk");
if(Objects.nonNull(selectItems) && !selectItems.isEmpty()){
Map<String, String> map = selectItems.stream().collect(Collectors
.toMap(
item -> Util.null2String(item.get("selectvalue")),
item -> Util.null2String(item.get("selectname"))
)
);
String datePicker = Util.null2String(param.get("datePicker"));
String checkResultShow = new String(Util.null2String(param.get("checkResultShow")).getBytes(), StandardCharsets.UTF_8);
String datePickerShow = Util.null2String(map.get(datePicker));
fileName = datePickerShow + checkResultShow;
}
return fileName;
}
}

View File

@ -0,0 +1,618 @@
package com.api.interfaces.liyi;
import com.alibaba.fastjson.JSON;
import com.api.interfaces.liyi.common.ApiResult;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Path("/xsd/DataCenterApi")
public class DataCenterApi extends BaseBean {
@GET
@Path("/getCompInfo")
@Produces(MediaType.TEXT_PLAIN)
public String getCompInfo(@Context HttpServletRequest request, @Context HttpServletResponse response){
ApiResult<Map<String,Object>> apiResult = new ApiResult<>();
RecordSet rs = new RecordSet();
String idCard = Util.null2String(request.getParameter("id_card"));
String tableName = getFormId("datacenter_table");
HashMap<String,Object> comMap = new HashMap<>();
try {
if(!idCard.equals("")){
String id = "";
String sql = "select top 1 * from "+tableName+" where field016 = '"+idCard+"' order by id desc";
writeLog("------sql zb------"+sql);
rs.executeQuery(sql);
if(rs.next()){
id = rs.getString("id");
String ypgw = rs.getString("field055");
String ypgw_xz = getSelectName(tableName,null,"field055",ypgw);
String djrq = rs.getString("field007");
String xm = rs.getString("field008");
String xb = rs.getString("field052");
String xb_xz = getSelectName(tableName,null,"field052",xb);
String csrq = rs.getString("field010");
String mz = rs.getString("field053");
String mz_xz = getSelectName(tableName,null,"field053",mz);
String jg = rs.getString("field056");
String jg_xz = getSelectName(tableName,null,"field056",jg);
String hy = rs.getString("field085");
String hy_xz = getSelectName(tableName,null,"field085",hy);
String zzmm = rs.getString("field054");
String zzmm_xz = getSelectName(tableName,null,"field054",zzmm);
String sj = rs.getString("field015");
String yx = rs.getString("field017");
String pro = rs.getString("field077");
String city = rs.getString("field078");
String qx = rs.getString("field079");
String xxdz = rs.getString("field080");
String xpro = rs.getString("field081");
String xcity = rs.getString("field082");
String xqx = rs.getString("field083");
String xxxdz = rs.getString("field084");
String jjlxr = rs.getString("field020");
String jjlxrgx = rs.getString("field086");
jjlxrgx = getSelectName(tableName,null,"field086",jjlxrgx);
String lxrdh = rs.getString("field022");
String english = rs.getString("field023");
english = getSelectName(tableName,null,"field023",english);
String cert = rs.getString("field061");
String eng_fj = rs.getString("field058");
String qtyz = rs.getString("field059");
String djzs = rs.getString("field062");
String qtyz_fj = rs.getString("field060");
String zyzg = rs.getString("field063");
String zyzgzs = rs.getString("field064");
String zyzg_fj = rs.getString("field065");
String qtjn = rs.getString("field066");
String bgrj = rs.getString("field067");
String qtjn_fj = rs.getString("field068");
String xqah = rs.getString("field025");
String gdxzsq = rs.getString("field026");
String qwxzsq = rs.getString("field027");
String sbyf = rs.getString("field028");
String sbnf = rs.getString("field029");
String gzlxdh = rs.getString("field030");
String zmr = rs.getString("field031");
String zmrgw = rs.getString("field032");
String sfjcldht = rs.getString("field033");
String sfjlcf = rs.getString("field034");
String sfjb = rs.getString("field035");
String sfss = rs.getString("field036");
String sfyhjkgz = rs.getString("field037");
String sfyytj = rs.getString("field038");
String sftgbszy = rs.getString("field039");
String tjrxm = rs.getString("field040");
String tjrgx = rs.getString("field041");
String bgsqs = rs.getString("field042");
String gxr = rs.getString("field046");
String gxrgx = rs.getString("field047");
String tbr = rs.getString("field048");
String sfty = rs.getString("field069");
/* update by bokang.xiao */
//现居住地址
String residentialAddress = rs.getString("field045");
//现居地址邮编
String residentialPostcode = rs.getString("field104");
//家庭住址
String familyAddress = rs.getString("field105");
//法定联系地址
String contactAddress = rs.getString("field106");
//法定联系地址邮编
String contactPostcode = rs.getString("field107");
//紧急联系人地址
String emergencyContactAddress = rs.getString("field108");
//一寸照片
String headPicture = rs.getString("field109");
//公积金账户及所在城市
String providentFundAccount = rs.getString("field110");
//开户行
String openingBank = rs.getString("field111");
//银行卡号
String bankCardNo = rs.getString("field112");
comMap.put("residentialAddress",residentialAddress);
comMap.put("residentialPostcode",residentialPostcode);
comMap.put("familyAddress",familyAddress);
comMap.put("contactAddress",contactAddress);
comMap.put("contactPostcode",contactPostcode);
comMap.put("emergencyContactAddress",emergencyContactAddress);
comMap.put("providentFundAccount",providentFundAccount);
comMap.put("openingBank",openingBank);
comMap.put("bankCardNo",bankCardNo);
comMap.put("headPicture",headPicture);
/* update by bokang.xiao */
comMap.put("ypgw",ypgw);
comMap.put("ypgw_xz",ypgw_xz);
comMap.put("djrq",djrq);
comMap.put("xm",xm);
comMap.put("xb",xb);
comMap.put("xb_xz",xb_xz);
comMap.put("csrq",csrq);
comMap.put("mz",mz);
comMap.put("mz_xz",mz_xz);
comMap.put("jg",jg);
comMap.put("jg_xz",jg_xz);
comMap.put("hy",hy);
comMap.put("hy_xz", hy_xz);
comMap.put("zzmm",zzmm);
comMap.put("zzmm_xz",zzmm_xz);
comMap.put("sj",sj);
comMap.put("yx",yx);
comMap.put("pro",pro);
comMap.put("city",city);
comMap.put("qx",qx);
comMap.put("xxdz",xxdz);
comMap.put("xpro",xpro);
comMap.put("xcity",xcity);
comMap.put("xqx",xqx);
comMap.put("xxxdz",xxxdz);
comMap.put("jjlxr",jjlxr);
comMap.put("jjlxrgx",jjlxrgx);
comMap.put("lxrdh",lxrdh);
comMap.put("english",english);
comMap.put("cert",cert);
comMap.put("eng_fj",eng_fj);
comMap.put("qtyz",qtyz);
comMap.put("djzs",djzs);
comMap.put("qtyz_fj",qtyz_fj);
comMap.put("zyzg",zyzg);
comMap.put("zyzgzs",zyzgzs);
comMap.put("zyzg_fj",zyzg_fj);
comMap.put("qtjn",qtjn);
comMap.put("bgrj",bgrj);
comMap.put("qtjn_fj",qtjn_fj);
comMap.put("xqah",xqah);
comMap.put("gdxzsq",gdxzsq);
comMap.put("qwxzsq",qwxzsq);
comMap.put("sbyf",sbyf);
comMap.put("sbnf",sbnf);
comMap.put("gzlxdh",gzlxdh);
comMap.put("zmr",zmr);
comMap.put("zmrgw",zmrgw);
comMap.put("sfjcldht",sfjcldht);
comMap.put("sfjlcf",sfjlcf);
comMap.put("sfjb",sfjb);
comMap.put("sfss",sfss);
comMap.put("sfyhjkgz",sfyhjkgz);
comMap.put("sfyytj",sfyytj);
comMap.put("sftgbszy",sftgbszy);
comMap.put("tjrxm",tjrxm);
comMap.put("tjrgx",tjrgx);
comMap.put("bgsqs",bgsqs);
comMap.put("gxr",gxr);
comMap.put("gxrgx",gxrgx);
comMap.put("sfty",sfty);
comMap.put("tbr",tbr);
}
List<HashMap<String,String>> dt1_list = new ArrayList<>();
sql = "select * from "+tableName+"_dt1 where mainid = '"+id+"'";
writeLog("------sql dt1------"+sql);
rs.executeQuery(sql);
while(rs.next()){
HashMap<String,String> dt1_map = new HashMap<>();
String xl = rs.getString("field008");
String xl_xz = getSelectName(tableName,tableName+"_dt1","field008",xl);
String start = rs.getString("field009");
String end = rs.getString("field010");
String xx = rs.getString("field004");
String zy = rs.getString("field005");
String xxxs = rs.getString("field011");
String xxxs_xz = getSelectName(tableName,tableName+"_dt1","field011",xxxs);
String xw = rs.getString("field012");
String xw_xz = getSelectName(tableName,tableName+"_dt1","field012",xw);
dt1_map.put("xl",xl);
dt1_map.put("xl_xz",xl_xz);
dt1_map.put("start",start);
dt1_map.put("end",end);
dt1_map.put("xx",xx);
dt1_map.put("zy",zy);
dt1_map.put("xxxs",xxxs);
dt1_map.put("xxxs_xz",xxxs_xz);
dt1_map.put("xw",xw);
dt1_map.put("xw_xz",xw_xz);
dt1_list.add(dt1_map);
}
writeLog("------sql dt1--data----"+dt1_list.toString());
comMap.put("dt1",dt1_list);
List<HashMap<String,String>> dt2_list = new ArrayList<>();
sql = "select * from "+tableName+"_dt2 where mainid = '"+id+"'";
rs.executeQuery(sql);
writeLog("------sql dt2------"+sql);
while(rs.next()){
HashMap<String,String> dt2_map = new HashMap<>();
String start = rs.getString("field008");
String end = rs.getString("field009");
String gzdw = rs.getString("field003");
String gzdwdz = rs.getString("field004");
String gw = rs.getString("field005");
String lzyy = rs.getString("field006");
String lxdh = rs.getString("field007");
dt2_map.put("start",start);
dt2_map.put("end",end);
dt2_map.put("gzdw",gzdw);
dt2_map.put("gzdwdz",gzdwdz);
dt2_map.put("gw",gw);
dt2_map.put("lzyy",lzyy);
dt2_map.put("lxdh",lxdh);
dt2_list.add(dt2_map);
}
writeLog("------sql dt2--data----"+dt2_list.toString());
comMap.put("dt2",dt2_list);
List<HashMap<String,String>> dt3_list = new ArrayList<>();
sql = "select * from "+tableName+"_dt3 where mainid = '"+id+"'";
writeLog("------sql dt3-----"+sql);
rs.executeQuery(sql);
while(rs.next()){
HashMap<String,String> dt3_map = new HashMap<>();
String xm = rs.getString("field001");
String gx = rs.getString("field005");
String gx_xz = getSelectName(tableName,tableName+"_dt3","field005",gx);
String nl = rs.getString("field003");
String gzdw = rs.getString("field004");
dt3_map.put("xm",xm);
dt3_map.put("gx",gx);
dt3_map.put("gx_xz",gx_xz);
dt3_map.put("nl",nl);
dt3_map.put("gzdw",gzdw);
dt3_list.add(dt3_map);
}
writeLog("------sql dt3--data----"+dt3_list.toString());
comMap.put("dt3",dt3_list);
List<HashMap<String,String>> dt4_list = new ArrayList<>();
sql = "select * from "+tableName+"_dt4 where mainid = '"+id+"'";
writeLog("------sql dt4------"+sql);
rs.executeQuery(sql);
while(rs.next()){
HashMap<String,String> dt4_map = new HashMap<>();
String yz = rs.getString("field001");
String cert = rs.getString("field002");
dt4_map.put("qtyz",yz);
dt4_map.put("djzs",cert);
dt4_list.add(dt4_map);
}
writeLog("------sql dt4--data----"+dt4_list.toString());
comMap.put("dt4",dt4_list);
List<HashMap<String,String>> dt5_list = new ArrayList<>();
sql ="select * from "+tableName+"_dt5 where mainid = '"+id+"'";
writeLog("------sql dt5------"+sql);
rs.executeQuery(sql);
while(rs.next()){
HashMap<String,String> dt5_map = new HashMap<>();
String zgzs = rs.getString("field001");
String bgrj = rs.getString("field002");
dt5_map.put("zgzs",zgzs);
dt5_map.put("bgrj",bgrj);
dt5_list.add(dt5_map);
}
writeLog("------sql dt5--data----"+dt5_list.toString());
comMap.put("dt5",dt5_list);
List<HashMap<String,String>> dt6_list = new ArrayList<>();
sql = "select * from "+tableName+"_dt6 where mainid = '"+id+"'";
writeLog("------sql dt6------"+sql);
rs.executeQuery(sql);
while(rs.next()){
HashMap<String,String> dt6_map = new HashMap<>();
String wbk = rs.getString("field001");
dt6_map.put("wbk",wbk);
dt6_list.add(dt6_map);
}
writeLog("------sql dt6--data----"+dt6_list.toString());
comMap.put("dt6",dt6_list);
List<HashMap<String,String>> dt7_list = new ArrayList<>();
sql = "select * from "+tableName+"_dt7 where mainid = '"+id+"'";
writeLog("------sql dt7------"+sql);
rs.executeQuery(sql);
while(rs.next()){
HashMap<String,String> dt7_map = new HashMap<>();
String kcmc = rs.getString("field001");
String ksrq = rs.getString("field002");
String jsrq = rs.getString("field003");
dt7_map.put("kcmc",kcmc);
dt7_map.put("ksrq",ksrq);
dt7_map.put("jsrq",jsrq);
dt7_list.add(dt7_map);
}
writeLog("------sql dt7--data----"+dt7_list.toString());
comMap.put("dt7",dt7_list);
List<HashMap<String,String>> dt8_list = new ArrayList<>();
sql = "select * from "+tableName+"_dt8 where mainid = '"+id+"'";
writeLog("------sql dt8------"+sql);
rs.executeQuery(sql);
while(rs.next()){
HashMap<String,String> dt8_map = new HashMap<>();
String jlqk = rs.getString("field001");
String jlqk_xz = getSelectName(tableName,tableName+"_dt8","field001",jlqk);
String nr1 = rs.getString("field002");
String nr2 = rs.getString("field003");
dt8_map.put("jlqk",jlqk);
dt8_map.put("jlqk_xz",jlqk_xz);
dt8_map.put("nr1",nr1);
dt8_map.put("nr2",nr2);
dt8_list.add(dt8_map);
}
writeLog("------sql dt8--data----"+dt8_list.toString());
comMap.put("dt8",dt8_list);
List<HashMap<String,String>> dt9_list = new ArrayList<>();
sql = "select * from "+tableName+"_dt9 where mainid = '"+id+"'";
writeLog("------sql dt9------"+sql);
rs.executeQuery(sql);
while(rs.next()){
HashMap<String,String> dt9_map = new HashMap<>();
String rq = rs.getString("field001");
String nr = rs.getString("field002");
String yy = rs.getString("field003");
String lb = rs.getString("field004");
String jb = rs.getString("field005");
String dw = rs.getString("field006");
String je = rs.getString("field007");
String bz = rs.getString("field008");
dt9_map.put("rq",rq);
dt9_map.put("nr",nr);
dt9_map.put("yy",yy);
dt9_map.put("lb",lb);
dt9_map.put("jb",jb);
dt9_map.put("dw",dw);
dt9_map.put("je",je);
dt9_map.put("bz",bz);
dt9_list.add(dt9_map);
}
writeLog("------sql dt9--data----"+dt9_list.toString());
comMap.put("dt9",dt9_list);
List<HashMap<String,String>> dt10_list = new ArrayList<>();
sql = "select * from "+tableName+"_dt10 where mainid = '"+id+"'";
writeLog("------sql dt10------"+sql);
rs.executeQuery(sql);
while(rs.next()){
HashMap<String,String> dt10_map = new HashMap<>();
String rq = rs.getString("field001");
String nr = rs.getString("field002");
String yy = rs.getString("field003");
String lb = rs.getString("field004");
String jb = rs.getString("field005");
String dw = rs.getString("field006");
String je = rs.getString("field007");
String bz = rs.getString("field008");
dt10_map.put("rq",rq);
dt10_map.put("nr",nr);
dt10_map.put("yy",yy);
dt10_map.put("lb",lb);
dt10_map.put("jb",jb);
dt10_map.put("dw",dw);
dt10_map.put("je",je);
dt10_map.put("bz",bz);
dt10_list.add( dt10_map);
}
writeLog("------sql dt10--data----"+dt10_list.toString());
comMap.put("dt10",dt10_list);
List<HashMap<String,String>> dt11_list = new ArrayList<>();
sql = "select * from "+tableName+"_dt11 where mainid = '"+id+"'";
writeLog("------sql dt11------"+sql);
rs.executeQuery(sql);
while(rs.next()){
HashMap<String,String> dt11_map = new HashMap<>();
String rq = rs.getString("field001");
String cg = rs.getString("field002");
String jg = rs.getString("field003");
String zl = rs.getString("field004");
String bz = rs.getString("field005");
dt11_map.put("rq",rq);
dt11_map.put("cg",cg);
dt11_map.put("jg",jg);
dt11_map.put("zl",zl);
dt11_map.put("bz",bz);
dt11_list.add( dt11_map);
}
writeLog("------sql dt11--data----"+dt11_list.toString());
comMap.put("dt11",dt11_list);
List<HashMap<String,String>> dt12_list = new ArrayList<>();
sql = "select * from "+tableName+"_dt12 where mainid = '"+id+"'";
writeLog("------sql dt12------"+sql);
rs.executeQuery(sql);
while(rs.next()){
HashMap<String,String> dt12_map = new HashMap<>();
String rq = rs.getString("field001");
String tm = rs.getString("field002");
String cbs = rs.getString("field003");
String mt = rs.getString("field004");
String bz = rs.getString("field005");
dt12_map.put("rq",rq);
dt12_map.put("tm",tm);
dt12_map.put("cbs",cbs);
dt12_map.put("mt",mt);
dt12_map.put("bz",bz);
dt12_list.add( dt12_map);
}
writeLog("------sql dt12--data----"+dt12_list.toString());
comMap.put("dt12",dt12_list);
List<HashMap<String,String>> dt13_list = new ArrayList<>();
sql = "select * from "+tableName+"_dt13 where mainid = '"+id+"'";
writeLog("------sql dt13------"+sql);
rs.executeQuery(sql);
while(rs.next()){
HashMap<String,String> dt13_map = new HashMap<>();
String ksrq = rs.getString("field001");
String jsrq = rs.getString("field002");
String mc = rs.getString("field003");
String je = rs.getString("field004");
String gj = rs.getString("field005");
String gjly = rs.getString("field006");
String zq = rs.getString("field007");
String zw = rs.getString("field008");
String bz = rs.getString("field009");
dt13_map.put("ksrq",ksrq);
dt13_map.put("jsrq",jsrq);
dt13_map.put("mc",mc);
dt13_map.put("je",je);
dt13_map.put("gj",gj);
dt13_map.put("gjly",gjly);
dt13_map.put("zq",zq);
dt13_map.put("zw",zw);
dt13_map.put("bz",bz);
dt13_list.add( dt13_map);
}
writeLog("------sql dt12--data----"+dt13_list.toString());
comMap.put("dt13",dt13_list);
writeLog("------sql data-----"+comMap.toString());
apiResult.success(true,comMap,"success");
}else {
apiResult.fail("id_card为空");
}
} catch (Exception e) {
e.printStackTrace();
apiResult.fail("error");
}
return JSON.toJSONString(apiResult);
}
@GET
@Path("/updateAcc")
@Produces(MediaType.TEXT_PLAIN)
public String updateAcc(@Context HttpServletRequest request, @Context HttpServletResponse response){
ApiResult<Boolean> apiResult = new ApiResult<>();
RecordSet rs = new RecordSet();
String billid = Util.null2String(request.getParameter("id"));
String tableName = getFormId("datacenter_table");
try {
//------请在下面编写业务逻辑代码------
String sql = "select * from "+tableName+" where id = '"+billid+"'";
new BaseBean().writeLog("----datacenter---sql-:"+sql);
rs.executeQuery(sql);
if(rs.next()){
String confirm = rs.getString("field051");
new BaseBean().writeLog("----datacenter---confirm--:"+confirm);
if(!confirm.equals("")){
String eng_fj1 = rs.getString("field058");
String qtyz_fj1 = rs.getString("field060");
String zyzg_fj1 = rs.getString("field065");
String qtjn_fj1 = rs.getString("field068");
String eng_fj = rs.getString("field070");
String qtyz_fj = rs.getString("field071");
String zyzg_fj = rs.getString("field072");
String qtjn_fj = rs.getString("field073");
if(!eng_fj.equals("")){
eng_fj1 += ","+eng_fj;
}
if(!qtyz_fj.equals("")){
qtyz_fj1 += ","+qtyz_fj;
}
if(!zyzg_fj.equals("")){
zyzg_fj1 += ","+zyzg_fj;
}
if(!qtjn_fj.equals("")){
qtjn_fj1 += ","+qtjn_fj;
}
sql = "update "+tableName+" set field058=?,field060=?,field065=?,field068=? where id = '"+billid+"'";
rs.executeUpdate(sql,eng_fj1,qtyz_fj1,zyzg_fj1,qtjn_fj1);
}
apiResult.success(true,true,"success");
}
} catch (Exception e) {
e.printStackTrace();
apiResult.fail("error");
}
return JSON.toJSONString(apiResult);
}
@GET
@Path("/updateData")
@Produces(MediaType.TEXT_PLAIN)
public String updateData(@Context HttpServletRequest request, @Context HttpServletResponse response){
ApiResult<Boolean> apiResult = new ApiResult<>();
RecordSet rs = new RecordSet();
String billid = Util.null2String(request.getParameter("id"));
String tableName = getFormId("datacenter_table");
try {
//------请在下面编写业务逻辑代码------
String sql = "update "+tableName+" set field076 = '正式入职' where id = '"+billid+"'";
new BaseBean().writeLog("----datacenter---sql-:"+sql);
rs.executeQuery(sql);
} catch (Exception e) {
e.printStackTrace();
apiResult.fail("error");
}
return JSON.toJSONString(apiResult);
}
public static String getFormId(String name){
RecordSet recordSet = new RecordSet();
String sql = "select cs from uf_xtpzb1 where xtbs ='"+name+"'";
recordSet.execute(sql);
if(recordSet.next()){
return recordSet.getString("cs");
}else {
return "";
}
}
/**
*
* @param maintableName
* @param detailtableName
* @param fieldName
* @param selectValue
* @return
*/
public String getSelectName(String maintableName, String detailtableName, String fieldName, String selectValue){
//writeLog("CSX--enter getSelectName");
RecordSet rs0 = new RecordSet();
String choiceBoxName = "";
StringBuffer sql= new StringBuffer();
sql.append("select t1.selectname \n");
sql.append("from workflow_SelectItem t1\n");
sql.append(", workflow_billfield t2\n");
sql.append(", workflow_bill t3\n");
sql.append(" where t1.fieldid=t2.id ");
sql.append("and t2.billid=t3.id and t3.tablename='").append(maintableName).append("'");
if(detailtableName==null){
detailtableName=" ";
//writeLog("detailtableName->"+detailtableName);
}
//writeLog("!StringUtils.isNotBlank(detailtableName)->"+!org.apache.commons.lang.StringUtils.isNotBlank(detailtableName));
if(!com.alipay.oceanbase.jdbc.StringUtils.isNotBlank(detailtableName)){
if(rs0.getDBType().equalsIgnoreCase("oracle")){//判断数据库类型是不是Oracle
sql.append(" and t2.detailtable is null\n");
}else{
sql.append(" and t2.detailtable ='' \n");
}
}else{
sql.append(" and t2.detailtable ='").append(detailtableName).append("' \n");
}
sql.append(" and t2.fieldname='").append(fieldName);
sql.append("'\n and t1.selectvalue='").append(selectValue).append("'");
//writeLog("getChoiceBoxNameSql->\n"+sql.toString());
rs0.execute(sql.toString());
if(rs0.next()){
choiceBoxName = rs0.getString("selectname");
}
//writeLog("ChoiceBoxName->"+choiceBoxName);
return choiceBoxName;
}
}

View File

@ -0,0 +1,59 @@
package com.api.interfaces.liyi.common;
public class ApiResult<T> {
private boolean success;
private String message;
private T data;
public ApiResult() {
}
public void success(boolean success, T data, String message) {
this.success = success;
this.data = data;
this.message = message;
}
public ApiResult<T> success(T data) {
this.data = data;
this.success = true;
this.message = "";
return this;
}
public ApiResult<T> fail(String message) {
this.message = message;
this.success = false;
this.data = null;
return this;
}
public boolean isSuccess() {
return this.success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getMessage() {
return this.message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return this.data;
}
public void setData(T data) {
this.data = data;
}
}

View File

@ -0,0 +1,602 @@
package com.api.interfaces.liyi.crod;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.api.interfaces.liyi.service.HuilianyiClientService;
import com.api.interfaces.liyi.service.impl.HuilianyiClientServiceImpl;
import com.engine.common.util.ServiceUtil;
import weaver.conn.RecordSet;
import weaver.formmode.exttools.impexp.common.DateUtils;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.interfaces.schedule.BaseCronJob;
import weaver.soa.workflow.request.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
public class HuilianyiTravelJob extends BaseCronJob {
private HuilianyiClientService getHuilianyiClientService(){
return ServiceUtil.getService(HuilianyiClientServiceImpl.class);
}
@Override
public void execute() {
try {
// RecordSet rs = new RecordSet();
// RequestService service = new RequestService();
// String nowdate = TimeUtil.getCurrentTimeString();
String ccsq_wfid = getFormId("ccsq_wfid");
String ccbg_wfid = getFormId("ccbg_wfid");
String ccsqTable = getFormId("ccsq_tablename");
String ccbgTable = getFormId("ccbg_tablename");
//String query_time = getFormId("query_time");
String currentDateTime = DateUtils.getCurrentDateTime();
String[] s = currentDateTime.split(" ");
String hour = s[1].split(":")[0];
String startTime = "";
// if(Integer.parseInt(hour)>0){
// startTime = DateUtils.getCurrentDate() + " " + query_time;
//
// }else {
// startTime = DateUtils.getCurrentDate()+ " 12:00:00";
// }
String cur_date = DateUtils.getCurrentDate();
String cur_year = cur_date.split("-")[0];
String cur_month = cur_date.split("-")[1];
startTime = cur_year+"-"+cur_month+"-"+"01 00:00:00";
//startTime = "2022-11-24 12:00:00";
/**
* token
*/
String resp = getHuilianyiClientService().getToken();
JSONObject res = JSONUtil.parseObj(resp);
List<String> resp_list = new ArrayList<>();
if(null != res.get("access_token")){
new BaseBean().writeLog("------token----:"+res.getStr("access_token"));
String token = res.getStr("access_token");
/**
*
*/
HttpResponse response1 = getHuilianyiClientService().
getTravelApplication(res.getStr("access_token"), startTime, currentDateTime, "1003,1012", "1", "100");
resp = response1.body();
String total = response1.header("X-Total-Count");
new BaseBean().writeLog("------1st resp--"+resp);
if(resp.equals("[]")){
new BaseBean().writeLog("------no resp--");
}
else {
resp_list.add(resp);
}
new BaseBean().writeLog("----total----"+total);
int page = (Integer.parseInt(total)/100) + 1;
if(page > 1){
for(int i = 2;i <= page;i++){
/**
*
*/
HttpResponse response2 = getHuilianyiClientService().
getTravelApplication(res.getStr("access_token"),startTime,currentDateTime,"1003,1012",String.valueOf(i),"100");
String resp2 = response2.body();
new BaseBean().writeLog("------either resp--"+resp2);
if(resp2.equals("[]")){
new BaseBean().writeLog("------no resp--");
}
else {
resp_list.add(resp2);
}
}
}
for (String result : resp_list) {
JSONArray jsonArray = JSONUtil.parseArray(result);
parseCreateReq(jsonArray,ccbg_wfid,ccsq_wfid,ccbgTable,ccsqTable,token);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
* @param jsonArray
* @param ccbg_wfid
* @param ccsq_wfid
* @param ccbgTable
* @param ccsqTable
*/
private void parseCreateReq(JSONArray jsonArray, String ccbg_wfid, String ccsq_wfid, String ccbgTable, String ccsqTable,String token) {
RecordSet rs = new RecordSet();
RequestService service = new RequestService();
String nowdate = TimeUtil.getCurrentTimeString();
String tokenUrl = getFormId("hly_tokenUrl");
jsonArray.stream().map(o -> (JSONObject) o).forEach(result -> {
try {
Set<String> comp_uid = new HashSet<>();
List<String> emp_id = new ArrayList<>();
String companions = "";
JSONObject applicant = ((JSONObject) result).getJSONObject("applicant");
String status = ((JSONObject) result).getStr("status");
String employeeID =((JSONObject) applicant).getStr("employeeID");
String fullName = applicant.getStr("fullName");
JSONArray custFormValues = ((JSONObject) result).getJSONArray("custFormValues");
custFormValues.stream().map(o -> (JSONObject) o).forEach(data ->{
String fieldName = ((JSONObject) data).getStr("fieldName");
if(fieldName.equals("出差人员")){
JSONArray comp_value = ((JSONObject) data).getJSONArray("value");
comp_value.stream().map(o -> (JSONObject) o).forEach(comp ->{
String userOID = ((JSONObject) comp).getStr("userOID");
comp_uid.add(userOID);
});
}
});
if(comp_uid.size()>0){
for (String uid : comp_uid) {
HttpResponse user_res = HttpUtil.createGet(tokenUrl + "/api/open/user/"+uid)
.header("Authorization", "Bearer ".concat(token))//头信息,多个头信息多次调用此方法即可
.header("Content-Type", "application/json")
.timeout(1000 * 120)
.execute();
String user_resp = user_res.body();
//out.println("----user_resp:"+user_resp);
JSONObject compInfo = JSONUtil.parseObj(user_resp);
String empid = compInfo.getStr("employeeID");
if(empid==null){
}else {
if(!emp_id.contains(empid)){
emp_id.add(empid);
}
}
}
}
if(emp_id.size()>0){
if(emp_id.size()>1){
List<String> empids = emp_id;
for (String txr_id : empids) {
rs.executeQuery("select id from hrmresource where workcode = '"+txr_id+"'");
while (rs.next()){
if(companions.equals("")){
companions = rs.getString("id");
}else {
companions += ","+rs.getString("id");
}
}
}
}
}
String departmentNumber = ((JSONObject) result).getStr("departmentNumber");
String version = ((JSONObject) result).getStr("version");
String businessCode = ((JSONObject) result).getStr("businessCode");
Boolean closed = ((JSONObject) result).getBool("closed");
Boolean participantClosed = ((JSONObject) result).getBool("participantClosed");
JSONObject travelApplication = ((JSONObject) result).getJSONObject("travelApplication");
String startDate = travelApplication.getStr("startDate");
startDate = startDate.replace("T", " ");
startDate = startDate.replace("Z", "");
//转时区
startDate = convertDateGMT(startDate);
String endDate = travelApplication.getStr("endDate");
endDate = endDate.replace("T", " ");
endDate = endDate.replace("Z", "");
//转时区
endDate = convertDateGMT(endDate);
new BaseBean().writeLog("------result-1---:"+fullName+"---"+employeeID+"---txrids"+companions+"---"+departmentNumber+"---"+version+"---"+businessCode+"---"+startDate+"---"+endDate+"---close---"+closed+"--partclose--"+participantClosed);
String fromDate = "";
String fromTime = "";
String toDate = "";
String toTime = "";
//2022-11-17 09:00
if(startDate!=null){
fromDate = startDate.split(" ")[0];
String time = startDate.split(" ")[1];
fromTime = time.split(":")[0]+":"+time.split(":")[1];
}
if(endDate!=null){
toDate = endDate.split(" ")[0];
String time = endDate.split(" ")[1];
toTime = time.split(":")[0]+":"+time.split(":")[1];
}
String reqName_sq = "";
String reqName_bg = "";
String workflowname = "";
String req_sql = "";
String id = "";
req_sql = "select id,departmentid from hrmresource where workcode = '"+employeeID+"'";
rs.executeQuery(req_sql);
if(rs.next()){
id = rs.getString("id");
departmentNumber = rs.getString("departmentid");
}
//出差 及 变更逻辑
if(status.equals("1003")){
if(Integer.parseInt(version)==0){
req_sql = "select workflowname from workflow_base where id = '"+ccsq_wfid+"'";
rs.executeQuery(req_sql);
while (rs.next()){
workflowname = rs.getString("workflowname");
}
reqName_sq = workflowname+"-"+fullName+"-"+ DateUtils.getCurrentDate();
Map<String, String> mainTable = new HashMap<>();
mainTable.put("resourceId",id);
mainTable.put("gh",employeeID);
mainTable.put("departmentId",departmentNumber);
mainTable.put("fromDate",fromDate);
mainTable.put("fromTime",fromTime);
mainTable.put("toDate",toDate);
mainTable.put("toTime",toTime);
mainTable.put("status","1003");
mainTable.put("version",version);
mainTable.put("sqdh",businessCode);
mainTable.put("companion",companions);
new BaseBean().writeLog("------data---"+mainTable.toString());
req_sql = "select count(id) as count from "+ccsqTable+" where sqdh = '"+businessCode+"' and version = 0";
rs.executeQuery(req_sql);
if(rs.next()){
int count = rs.getInt("count");
if(count==0){
String reqId = creatRequest("1", ccsq_wfid, reqName_sq, false, mainTable, null);
RequestInfo request = service.getRequest(Integer.valueOf(reqId));
Boolean submit = service.nextNodeBySubmit(request, Integer.valueOf(reqId), 1, nowdate);
if (submit) {
new BaseBean().writeLog(reqId + "提交成功");
} else {
new BaseBean().writeLog(reqId + "流程提交异常");
}
}
}
}
else if(Integer.parseInt(version)>=1){
String changerequestid = "";
String changetype = "";
String ver = "1";
String ccks_date = "";
String ccks_time = "";
String ccjs_date = "";
String ccjs_time = "";
String kqsc = "";
String bgsc = "";
String req_id = "";
/**
* 1
*
*
*
*/
// req_sql = "select top 1 requestid,id,changetype,version from "+ccbgTable+" where sqdh = '"+businessCode+"' and changetype='1' order by version desc,id desc";
// rs.executeQuery(req_sql);
// if(rs.next()){
// changerequestid = Util.null2String(rs.getString("requestid"));
// changetype = rs.getString("changetype");
// req_id = rs.getString("id");
// ver = rs.getString("version");
// }
// //没有变更
// if(changerequestid.equals("")){
//先查出差
req_sql = "select top 1 * from "+ccsqTable+" where sqdh = '"+businessCode+"' order by version desc ";
rs.executeQuery(req_sql);
if(rs.next()){
ver = rs.getString("version");
changerequestid = Util.null2String(rs.getString("requestid"));
ccks_date = rs.getString("fromDate");
ccks_time = rs.getString("fromTime");
ccjs_date = rs.getString("toDate");
ccjs_time = rs.getString("toTime");
}
//如果有 新建变更 撤销
if(!changerequestid.equals("")){
//只有 出差最大的版本比 获取的版本小 才需要变更撤销
//如果第二天同样的数据进来 就不会重复撤销
new BaseBean().writeLog("--new-:"+version+"---wf:"+ver);
if(Integer.parseInt(ver) < Integer.parseInt(version)){
req_sql = "select top 1 requestid,id,version from "+ccbgTable+" where sqdh = '"+businessCode+"' and changetype='1' and status = '1003' order by version desc ";
rs.executeQuery(req_sql);
String bgversion = "0";
String bgreq = "";
if(rs.next()){
bgversion = rs.getString("version");
bgreq = rs.getString("requestid");
}
if((!bgreq.equals("") && Integer.parseInt(bgversion)< Integer.parseInt(version)) || bgreq.equals("")){
//如果未查到撤销对变更,但是有出差,先起变更撤销出差
//获取流程名
req_sql = "select workflowname from workflow_base where id = '"+ccbg_wfid+"'";
rs.executeQuery(req_sql);
while (rs.next()){
workflowname = rs.getString("workflowname");
}
reqName_bg = workflowname+"-"+fullName+"-"+ DateUtils.getCurrentDate();
Map<String, String> mainTable = new HashMap<>();
mainTable.put("resourceId",id);
mainTable.put("gh",employeeID);
mainTable.put("status","1003");
mainTable.put("version",version);
mainTable.put("companion",companions);
mainTable.put("changetype","1");
mainTable.put("sqdh",businessCode);
mainTable.put("changerequestid",changerequestid);
LinkedHashMap<String, List<Map<String, String>>> detail = new LinkedHashMap<>();
List<Map<String, String>> list = new ArrayList<>();
Map<String,String> map = new HashMap<>();
map.put("detail_attendancefromDate",ccks_date);
map.put("detail_attendancefromTime",ccks_time);
map.put("detail_attendancetoDate",ccjs_date);
map.put("detail_attendancetoTime",ccjs_time);
//map.put("detail_attendanceduration",kqsc);
map.put("detail_changefromDate",fromDate);
map.put("detail_changefromTime",fromTime);
map.put("detail_changetoDate",toDate);
map.put("detail_changetoTime",toTime);
//map.put("detail_changeduration",bgsc);
list.add(map);
detail.put("1",list);
new BaseBean().writeLog("------data---"+detail.toString());
new BaseBean().writeLog("------create version---"+version);
if(!version.equals("0")){
String reqId = creatRequest("1", ccbg_wfid, reqName_bg, false, mainTable, detail);
RequestInfo request = service.getRequest(Integer.valueOf(reqId));
Boolean submit = service.nextNodeBySubmit(request, Integer.valueOf(reqId), 1, nowdate);
if (submit) {
new BaseBean().writeLog(reqId + "提交成功");
} else {
new BaseBean().writeLog(reqId + "流程提交异常");
}
}
}
}
}
// }
req_sql = "select count(id) as count from "+ccsqTable+" where sqdh = '"+businessCode+"' and version = '"+version+"'";
rs.executeQuery(req_sql);
if(rs.next()){
int count = rs.getInt("count");
if(count==0){
req_sql = "select workflowname from workflow_base where id = '"+ccsq_wfid+"'";
rs.executeQuery(req_sql);
while (rs.next()){
workflowname = rs.getString("workflowname");
}
reqName_sq = workflowname+"-"+fullName+"-"+ DateUtils.getCurrentDate();
Map<String, String> mainTable = new HashMap<>();
mainTable.put("resourceId",id);
mainTable.put("gh",employeeID);
mainTable.put("departmentId",departmentNumber);
mainTable.put("fromDate",fromDate);
mainTable.put("fromTime",fromTime);
mainTable.put("toDate",toDate);
mainTable.put("toTime",toTime);
mainTable.put("status","1003");
mainTable.put("version",version);
mainTable.put("sqdh",businessCode);
mainTable.put("companion",companions);
new BaseBean().writeLog("------data---"+mainTable.toString());
String reqId = creatRequest("1", ccsq_wfid, reqName_sq, false, mainTable, null);
RequestInfo request = service.getRequest(Integer.valueOf(reqId));
Boolean submit = service.nextNodeBySubmit(request, Integer.valueOf(reqId), 1, nowdate);
if (submit) {
new BaseBean().writeLog(reqId + "提交成功");
} else {
new BaseBean().writeLog(reqId + "流程提交异常");
}
}
}
}
}
// 出差作废逻辑
else if(status.equals("1012")){
Map<String, String> mainTable = new HashMap<>();
mainTable.put("resourceId",id);
mainTable.put("gh",employeeID);
mainTable.put("status",status);
mainTable.put("version",version);
mainTable.put("changetype","1");
mainTable.put("sqdh",businessCode);
String changerequestid = "";
String req_id = "" ;
String changetype = "";
String ccks_date = "";
String ccks_time = "";
String ccjs_date = "";
String ccjs_time = "";
String bgversion = "0";
String ccversion = "0";
req_sql = "select top 1 requestid,id,version from "+ccbgTable+" where sqdh = '"+businessCode+"' and changetype='1' and status = '1012' order by version desc ";
rs.executeQuery(req_sql);
if(rs.next()){
changerequestid = Util.null2String(rs.getString("requestid"));
}
if(changerequestid.equals("")){
req_sql = "select top 1 * from "+ccsqTable+" where sqdh = '"+businessCode+"' order by version desc";
rs.executeQuery(req_sql);
if(rs.next()){
changerequestid = Util.null2String(rs.getString("requestid"));
ccversion = rs.getString("version");
ccks_date = rs.getString("fromDate");
ccks_time = rs.getString("fromTime");
ccjs_date = rs.getString("toDate");
ccjs_time = rs.getString("toTime");
}
//获取流程名
req_sql = "select workflowname from workflow_base where id = '"+ccbg_wfid+"'";
rs.executeQuery(req_sql);
while (rs.next()){
workflowname = rs.getString("workflowname");
}
reqName_bg = workflowname+"-"+fullName+"-"+ DateUtils.getCurrentDate();
mainTable.put("changerequestid",changerequestid);
LinkedHashMap<String, List<Map<String, String>>> detail = new LinkedHashMap<>();
List<Map<String, String>> list = new ArrayList<>();
Map<String,String> map = new HashMap<>();
map.put("detail_attendancefromDate",ccks_date);
map.put("detail_attendancefromTime",ccks_time);
map.put("detail_attendancetoDate",ccjs_date);
map.put("detail_attendancetoTime",ccjs_time);
//map.put("detail_attendanceduration",kqsc);
map.put("detail_changefromDate",fromDate);
map.put("detail_changefromTime",fromTime);
map.put("detail_changetoDate",toDate);
map.put("detail_changetoTime",toTime);
//map.put("detail_changeduration",bgsc);
list.add(map);
detail.put("1",list);
new BaseBean().writeLog("------data---"+detail.toString());
//if(!changerequestid.equals("") && Integer.parseInt(version)>Integer.parseInt(bgversion) && Integer.parseInt(version)>Integer.parseInt(ccversion)){
if(!changerequestid.equals("")){
String reqId = creatRequest("1", ccbg_wfid, reqName_bg, false, mainTable, detail);
RequestInfo request = service.getRequest(Integer.valueOf(reqId));
Boolean submit = service.nextNodeBySubmit(request, Integer.valueOf(reqId), 1, nowdate);
if (submit) {
new BaseBean().writeLog(reqId + "提交成功");
} else {
new BaseBean().writeLog(reqId + "流程提交异常");
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
});
}
/**
*
*
* @param createrId id
* @param workflowId id
* @param requestName
* @param isNextFlow
* @param mainTable Map key: value:
* @param detail (LinkedHashMap) Map key: value List {Map key: value:
* }
* @return
*/
public String creatRequest(
String createrId,
String workflowId,
String requestName,
boolean isNextFlow,
Map<String, String> mainTable,
LinkedHashMap<String, List<Map<String, String>>> detail
) throws Exception {
if (mainTable == null || "0".equals(createrId) || "0".equals(workflowId)) {
return "0";
}
//请求基本信息
RequestInfo requestInfo = new RequestInfo();
requestInfo.setCreatorid(createrId); // 创建人
requestInfo.setWorkflowid(workflowId); // 工作流id
requestInfo.setDescription(requestName); // 标题
if (!isNextFlow) { // 是否提交下一节点
requestInfo.setIsNextFlow("0");
}
// 主表信息
MainTableInfo mainTableInfo = new MainTableInfo();
Property[] propertyArray = new Property[mainTable.size()];
int p = 0;
for (Map.Entry<String, String> entry : mainTable.entrySet()) {
propertyArray[p] = new Property();
propertyArray[p].setName(entry.getKey());
propertyArray[p].setValue(entry.getValue());
p++;
}
mainTableInfo.setProperty(propertyArray);
requestInfo.setMainTableInfo(mainTableInfo);
// 明细信息
DetailTableInfo detailTableInfo = new DetailTableInfo();
if (detail != null) {
DetailTable[] detailTables = new DetailTable[detail.size()];
int ds = 0;
for (Map.Entry<String, List<Map<String, String>>> entry : detail.entrySet()) {
DetailTable detailTable = new DetailTable();
List<Map<String, String>> list = entry.getValue();
for (Map<String, String> map : list) {
Row row = new Row();
for (Map.Entry<String, String> rentry : map.entrySet()) {
Cell cell = new Cell();
cell.setName("" + rentry.getKey());
cell.setValue("" + rentry.getValue());
row.addCell(cell);
}
detailTable.addRow(row);
}
detailTable.setId(entry.getKey());
detailTables[ds] = detailTable;
ds++;
}
detailTableInfo.setDetailTable(detailTables);
requestInfo.setDetailTableInfo(detailTableInfo); // 明细表
}
RequestService service = new RequestService();
String requestid = service.createRequest(requestInfo);
// 创建请求id
if(requestid == null){
throw new RuntimeException("创建流程失败");
}
int requestidInt = Integer.valueOf(requestid);
if(requestidInt < 0){
throw new RuntimeException("创建流程失败");
}
return requestid;
}
/**
*
* @param name
* @return
*/
public static String getFormId(String name){
RecordSet recordSet = new RecordSet();
String sql = "select cs from uf_xtpzb1 where xtbs ='"+name+"'";
recordSet.execute(sql);
if(recordSet.next()){
return recordSet.getString("cs");
}else {
return "";
}
}
/**
*
* @param dateStr
* @return
* @throws ParseException
*/
public String convertDateGMT(String dateStr) throws ParseException {
String sourceTimeZone = "GMT";
String targetTimeZone = "GMT+8";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//获取传入的时间值
Long time = new Date(sdf.parse(dateStr).getTime()).getTime();
//获取源时区时间相对的GMT时间
Long sourceRelativelyGMT = time - TimeZone.getTimeZone(sourceTimeZone).getRawOffset();
//GMT时间+目标时间时区的偏移量获取目标时间
Long targetTime = sourceRelativelyGMT + TimeZone.getTimeZone(targetTimeZone).getRawOffset();
Date date = new Date(targetTime);
return sdf.format(date);
}
}

View File

@ -0,0 +1,23 @@
package com.api.interfaces.liyi.service;
import cn.hutool.http.HttpResponse;
import java.util.Map;
public interface HuilianyiClientService {
/**
* token
* @return
*/
String getToken();
/**
*
* @return
*/
HttpResponse getTravelApplication(String token, String startDate, String endDate, String status, String page, String size);
HttpResponse getCompInfo(String token, String uid);
}

View File

@ -0,0 +1,76 @@
package com.api.interfaces.liyi.service.impl;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.api.interfaces.liyi.service.HuilianyiClientService;
import com.engine.core.impl.Service;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.rsa.security.Base64;
import java.util.HashMap;
import java.util.Map;
public class HuilianyiClientServiceImpl extends Service implements HuilianyiClientService {
private static String clientId = "4b8b787c-40c1-4349-8217-5535a8327175";//需要替换
private static String securet = "OTY4ZWJkZTQtOWRmZC00Y2QwLThmMTktNGQ3ZGFjNzUwMDI2";//需要替换
private static String tokenUrl = "https://apistage.huilianyi.com/gateway";//需要替换
@Override
public String getToken() {
clientId = getFormId("hly_clientId");
securet = getFormId("hly_securet");
tokenUrl = getFormId("hly_tokenUrl");
int MAX_TIME_OUT = 1000 * 120;
String authStr = clientId.concat(":").concat(securet);
String authStrEnc = new String(Base64.encodeBase64(authStr.getBytes()));
String response = HttpUtil.createPost(tokenUrl+"/oauth/token?grant_type=client_credentials&scope=write")
.header("Authorization", "Basic ".concat(authStrEnc))//头信息,多个头信息多次调用此方法即可
.timeout(MAX_TIME_OUT)
.execute().body();
return response;
}
@Override
public HttpResponse getTravelApplication(String token, String startDate, String endDate, String status, String page, String size) {
// String url = tokenUrl+"/api/open/travelApplication?access_token={AccessToken}&startDate={startDate}&endDate={endDate}&status={status}" +
// "&page={page}&size={size}";
int MAX_TIME_OUT = 1000 * 120;
tokenUrl = getFormId("hly_tokenUrl");
HttpResponse resp = HttpUtil.createGet(tokenUrl + "/api/open/travelApplication?access_token=" + token + "" +
"&startDate=" + startDate + "&endDate=" + endDate + "&status=" + status + "&page=" + page + "&size=" + size + "")
.header("Authorization", "Bearer ".concat(token))//头信息,多个头信息多次调用此方法即可
.header("Content-Type", "application/json")
.timeout(MAX_TIME_OUT)
.execute();
String response = resp.body();
String total = resp.header("X-Total-Count");
new BaseBean().writeLog("-- hly--resp---:"+response);
Map<String,String> resMap = new HashMap<>();
resMap.put("total",total);
resMap.put("resp",response);
return resp;
}
@Override
public HttpResponse getCompInfo(String token, String uid) {
int MAX_TIME_OUT = 1000 * 120;
HttpResponse user_res = HttpUtil.createGet(tokenUrl + "/api/open/user/"+uid)
.header("Authorization", "Bearer ".concat(token))//头信息,多个头信息多次调用此方法即可
.header("Content-Type", "application/json")
.timeout(MAX_TIME_OUT)
.execute();
return user_res;
}
public static String getFormId(String name){
RecordSet recordSet = new RecordSet();
String sql = "select cs from uf_xtpzb1 where xtbs ='"+name+"'";
recordSet.execute(sql);
if(recordSet.next()){
return recordSet.getString("cs");
}else {
return "";
}
}
}

View File

@ -0,0 +1,155 @@
package com.api.nonstandardext.zenner.job;
import com.api.nonstandardext.zenner.model.sap.PeriodBalance;
import com.api.nonstandardext.zenner.utils.SAPWebserviceTool;
import net.sf.json.JSONObject;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.schedule.BaseCronJob;
import java.util.Calendar;
/**
*
*
* 1. SAP
*
* 2. b2e0005() b2e0012()
* b2e0035
* b2e0035
*
* 3.OA
*/
public class SyncAccountInfoFromSapJob extends BaseCronJob {
BaseBean logger = new BaseBean();
private final static String JobName = " SyncAccountInfoFromSapJob ";
private String interfaceName;
private String theNearPeriod;
private String comCodes; //6000
private String sapAccount; //10020103
public String getInterfaceName() {
return interfaceName;
}
public void setInterfaceName(String interfaceName) {
this.interfaceName = interfaceName;
}
public String getTheNearPeriod() {
return theNearPeriod;
}
public void setTheNearPeriod(String theNearPeriod) {
this.theNearPeriod = theNearPeriod;
}
public String getComCodes() {
return comCodes;
}
public void setComCodes(String comCodes) {
this.comCodes = comCodes;
}
public String getSapAccount() {
return sapAccount;
}
public void setSapAccount(String sapAccount) {
this.sapAccount = sapAccount;
}
public void execute() {
logger.writeLog("-----" + JobName + " Begin------");
RecordSet rs = new RecordSet();
try {
logger.writeLog("-----" + JobName + " getInterfaceName------" + getInterfaceName());
// if (getInterfaceName().indexOf("syncGlaccPeriodBalancesFromSap") >= 0){
SAPWebserviceTool tool = new SAPWebserviceTool();
String webserviceUrl = tool.getSystemParamValue("SAP_OA011_Webservice_URL");
Integer nearPeriod = Integer.parseInt(getTheNearPeriod());
String[] companyCodes = getComCodes().split(",");
for (int c = 0; c < companyCodes.length; c++){
if ("".equals(companyCodes[c])){
continue;
}
Calendar cal = Calendar.getInstance();
for (int i = 1; i <= nearPeriod; i++){
syncGlaccPeriodBalancesFromSap(companyCodes[c], (cal.get(Calendar.MONTH) + 1) + "", cal.get(Calendar.YEAR) + "", getSapAccount(), tool);
cal.add(Calendar.MONTH, -1);
}
}
// }
} catch (Exception e) {
logger.writeLog(JobName + " 获取异常: " + e.getMessage());
e.printStackTrace();
}
logger.writeLog("--------------------" + JobName + " End---------------------------");
}
public void syncGlaccPeriodBalancesFromSap(String comCode, String period, String year, String glAccount, SAPWebserviceTool tool) throws Exception {
String params = tool.callParams_011(comCode, period, year, glAccount);
JSONObject result = tool.callInterface_011(params);
logger.writeLog(JobName + " syncGlaccPeriodBalancesFromSap result : " + result);
JSONObject balanceResponse = result.getJSONObject("balanceResponse");
PeriodBalance periodBalance = new PeriodBalance();
periodBalance.setIvCompCode(comCode);
periodBalance.setIvFiscYear(year);
periodBalance.setIvFisPeriod(period);
periodBalance.setEvBalance(Util.null2String(balanceResponse.getString("EvBalance")));
periodBalance.setEvPerSales(Util.null2String(balanceResponse.getString("EvPerSales")));
periodBalance.setEvCreditPer(Util.null2String(balanceResponse.getString("EvCreditPer")));
periodBalance.setEvDebitsPer(Util.null2String(balanceResponse.getString("EvDebitsPer")));
periodBalance.setEvCurrency(Util.null2String(balanceResponse.getString("EvCurrency")));
periodBalance.setGlAccount(glAccount);
periodBalance.save(periodBalance, 52, "uf_period_balance");
// String result = "";
//// String url = "http://127.0.0.1/uapws/service/nc65to63projectsysplugin";//这是接口地址,注意去掉.wsdl否则会报错
// Service service = new Service();
// Call call = (Call) service.createCall();
// call.setTargetEndpointAddress(webserviceUrl);
// String parametersName = "string";//设置参数名
// call.setOperationName("ZoaGlGetglaccperiodbalances");//设置方法名
// call.addParameter("IvComCode", XMLType.XSD_STRING, ParameterMode.IN);//方法参数1参数名、2参数类型、3.入参
// call.addParameter("IvFisPeriod", XMLType.XSD_STRING, ParameterMode.IN);//方法参数1参数名、2参数类型、3.入参
// call.addParameter("IvFiscYear", XMLType.XSD_STRING, ParameterMode.IN);//方法参数1参数名、2参数类型、3.入参
// call.addParameter("IvGlAccount", XMLType.XSD_STRING, ParameterMode.IN);//方法参数1参数名、2参数类型、3.入参
// call.setReturnType(XMLType.XSD_STRING);//返回类型
// JSONObject keyParams = new JSONObject();
// keyParams.put("IvComCode", 6000);
// keyParams.put("IvFisPeriod", 8);
// keyParams.put("IvFiscYear", 2022);
// keyParams.put("IvGlAccount", 12345);
// String str = keyParams.toString();
// logger.writeLog(JobName + " syncSapData Service Call str : " + str);
// Object resultObject = call.invoke(new Object[] { 6000, 8, 2022, 12345 });//调用接口
// result = (String) resultObject;
}
public void setModeRight(int creater, int modeid, int sourceid) {
ModeRightInfo moderightinfo = new ModeRightInfo();
moderightinfo.setNewRight(true);
moderightinfo.editModeDataShare(creater, modeid, sourceid);
}
}

View File

@ -0,0 +1,259 @@
package com.api.nonstandardext.zenner.job;
import com.api.nonstandardext.zenner.model.bank.DayBalance;
import com.api.nonstandardext.zenner.service.bank.Bank_b2e0005_Service;
import com.api.nonstandardext.zenner.utils.ZennerApiService;
import com.api.nonstandardext.zenner.utils.ZennerUtil;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.schedule.BaseCronJob;
import java.io.File;
import java.util.*;
/**
*
*
* 1. b2e0005() b2e0012()
* b2e0035
* b2e0035
*
* 2. SAP
*
* 3.OA
*/
public class SyncAccountStatementJob extends BaseCronJob {
BaseBean logger = new BaseBean();
private String interfaceName;
private final static String JobName = " SyncAccountStatementJob ";
public String getInterfaceName() {
return interfaceName;
}
public void setInterfaceName(String interfaceName) {
this.interfaceName = interfaceName;
}
public void execute() {
logger.writeLog("-----" + JobName + " Begin------");
RecordSet rs = new RecordSet();
ZennerApiService zennerApiService = new ZennerApiService();
try {
logger.writeLog("-----" + JobName + " getInterfaceName------" + getInterfaceName());
//银行
String bankApiUrl = zennerApiService.getSystemConfigValue("BANK_API_URL");
String bankSql = "select * from uf_bank_account";
rs.execute(bankSql);
while (rs.next()){
syncBank_b2e0005(bankApiUrl, Util.null2String(rs.getString("lxh")), Util.null2String(rs.getString("yxzh")));
}
} catch (Exception e) {
logger.writeLog(JobName + " 获取异常: " + e.getMessage());
e.printStackTrace();
}
logger.writeLog("--------------------" + JobName + " End---------------------------");
}
/**
* b2e0005
* @param bankApiUrl
* @throws Exception
*/
public void syncBank_b2e0005(String bankApiUrl, String ibknum, String actacn) throws Exception {
String dirPath = "E:\\WEAVER\\bank\\";
File dir = new File(dirPath);
if (!dir.exists()) {
dir.mkdirs();
}
logger.writeLog(JobName + "..syncBank_b2e0005......bankApiUrl: " + bankApiUrl);
//当日账号余额
Map<String, String> xmlParams = new HashMap<>();
xmlParams.put("termid", "E192168000104");
xmlParams.put("trnid", "");
xmlParams.put("cusopr", "395169759");
xmlParams.put("custid", "387679060");
xmlParams.put("trncod", "b2e0005");
xmlParams.put("token", "");
xmlParams.put("ibknum", ibknum);
xmlParams.put("actacn", actacn);
String xmlFileUrl = dirPath + "b2e0005_" + ZennerUtil.parseToDateString(Calendar.getInstance().getTime(), ZennerUtil.formatYYYYMMDD)+ ".xml";
logger.writeLog(JobName + ".syncBank_b2e0005.......xmlFileUrl: " + xmlFileUrl);
Bank_b2e0005_Service bankB2e0005Service = new Bank_b2e0005_Service();
bankB2e0005Service.createXml(xmlFileUrl, xmlParams);
String apiParams = bankB2e0005Service.getXmlString(xmlFileUrl);
Integer pLen = apiParams.length();
int ps = 500;
int logPageNum = pLen / ps;
int i = 0;
if (pLen <= ps){
logger.writeLog(JobName + ".syncBank_b2e0005.......voucherParams last: " + apiParams);
} else {
for (i = 0; i < logPageNum; i++){
logger.writeLog(JobName + ".syncBank_b2e0005.......voucherParams " + i + " : " + apiParams.substring(i * ps, (i + 1) * 500));
}
logger.writeLog(JobName + ".syncBank_b2e0005.......voucherParams last: " + apiParams.substring((i-1) * 500));
}
logger.writeLog(JobName + " bankApiUrl : " + bankApiUrl);
String result = ZennerUtil.httpPostToken(bankApiUrl, new HashMap<>(), apiParams);
logger.writeLog(JobName + " syncBank_b2e0005 result : " + result);
Document doc = DocumentHelper.parseText(result); // 将xml转为dom对象
Element root = doc.getRootElement(); // 获取根节点
List<Element> elements = root.elements("trans");//获取名称为env:Body的子节点
DayBalance dayBalance = new DayBalance();
boolean statusOk = false;
for (Object l2 : elements) { //遍历子元素
Element l2Element = (Element) l2;
logger.writeLog("l2Element name :" + l2Element.getName());
List<Element> elementsL3 = l2Element.elements();
for (Object l3 : elementsL3) { //遍历子元素
Element l3Element = (Element) l3;
List<Element> elementsL4 = l3Element.elements();
for (Object l4 : elementsL4) { //遍历子元素
Element dataElement = (Element) l4;
logger.writeLog("l4Element name :" + dataElement.getName());
if ("status".equals(dataElement.getName())){
List<Element> elementsL5 = dataElement.elements();
for (Object l5 : elementsL5) { //遍历子元素
Element l5Element = (Element) l5;
if ("rspcod".equals(l5Element.getName())) {
logger.writeLog("rspcod:" + l5Element.getStringValue());
if (l5Element.getStringValue().equals("B001")){
statusOk = true;
} else {
statusOk = false;
}
}
if ("rspmsg".equals(l5Element.getName())) {
logger.writeLog("rspmsg:" + l5Element.getStringValue());
}
}
}
logger.writeLog("statusOk:" + statusOk);
if (statusOk){
logger.writeLog("dataElement.getName():" + dataElement.getName());
if ("b2e0005-rs".equals(dataElement.getName())){
List<Element> elementsData = dataElement.elements();
for (Object data : elementsData) { //遍历子元素
Element l4Element = (Element) data;
if ("account".equals(l4Element.getName())){
List<Element> elementsL5 = l4Element.elements();
for (Object l5 : elementsL5) { //遍历子元素
Element l5Element = (Element) l5;
if ("ibknum".equals(l5Element.getName())) {
logger.writeLog("ibknum:" + l5Element.getStringValue());
dayBalance.setIbknum(l5Element.getStringValue());
}
if ("actacn".equals(l5Element.getName())) {
logger.writeLog("actacn:" + l5Element.getStringValue());
dayBalance.setActacn(l5Element.getStringValue());
}
if ("curcde".equals(l5Element.getName())) {
logger.writeLog("curcde:" + l5Element.getStringValue());
dayBalance.setCurcde(l5Element.getStringValue());
}
if ("actname".equals(l5Element.getName())) {
logger.writeLog("actname:" + l5Element.getStringValue());
dayBalance.setActname(l5Element.getStringValue());
}
}
}
if ("balance".equals(l4Element.getName())) {
List<Element> elementsL5 = l4Element.elements();
for (Object l5 : elementsL5) { //遍历子元素
Element l5Element = (Element) l5;
if ("bokbal".equals(l5Element.getName())) {
logger.writeLog("bokbal:" + l5Element.getStringValue());
dayBalance.setBokbal(l5Element.getStringValue());
}
if ("avabal".equals(l5Element.getName())) {
logger.writeLog("avabal:" + l5Element.getStringValue());
dayBalance.setAvabal(l5Element.getStringValue());
}
if ("currentavabal".equals(l5Element.getName())) {
logger.writeLog("currentavabal:" + l5Element.getStringValue());
if ("".equals(l5Element.getStringValue())){
dayBalance.setCurrentavabal("0");
} else {
dayBalance.setCurrentavabal(l5Element.getStringValue());
}
}
if ("stpamt".equals(l5Element.getName())) {
logger.writeLog("stpamt:" + l5Element.getStringValue());
if ("".equals(l5Element.getStringValue())){
dayBalance.setStpamt("0");
} else {
dayBalance.setStpamt(l5Element.getStringValue());
}
}
if ("ovramt".equals(l5Element.getName())) {
logger.writeLog("ovramt:" + l5Element.getStringValue());
dayBalance.setOvramt("".equals(l5Element.getStringValue()) ? "0" : l5Element.getStringValue());
}
if ("frzamt".equals(l5Element.getName())) {
logger.writeLog("frzamt:" + l5Element.getStringValue());
dayBalance.setFrzamt("".equals(l5Element.getStringValue()) ? "0" : l5Element.getStringValue());
}
if ("effauthamt".equals(l5Element.getName())) {
logger.writeLog("effauthamt:" + l5Element.getStringValue());
dayBalance.setEffauthamt("".equals(l5Element.getStringValue()) ? "0" : l5Element.getStringValue());
}
if ("effusdoverbal".equals(l5Element.getName())) {
logger.writeLog("effusdoverbal:" + l5Element.getStringValue());
dayBalance.setEffusdoverbal("".equals(l5Element.getStringValue()) ? "0" : l5Element.getStringValue());
}
if ("effuseablequota".equals(l5Element.getName())) {
logger.writeLog("effuseablequota:" + l5Element.getStringValue());
dayBalance.setEffuseablequota("".equals(l5Element.getStringValue()) ? "0" : l5Element.getStringValue());
}
}
}
if ("baldat".equals(l4Element.getName())) {
logger.writeLog("baldat:" + l4Element.getStringValue());
if (!"".equals(l4Element.getStringValue())){
Date date = ZennerUtil.parseToDate(l4Element.getStringValue(), ZennerUtil.formatYYYYMMDD_NoSplit);
dayBalance.setBaldat(ZennerUtil.parseToDateString(date, ZennerUtil.formatYYYYMMDD));
}
}
}
}
}
}
}
}
dayBalance.save(dayBalance, 50, "uf_bank_day_balance");
logger.writeLog(JobName + " result dayBalance: " + dayBalance.toString());
}
}

View File

@ -0,0 +1,332 @@
package com.api.nonstandardext.zenner.job;
import com.api.nonstandardext.zenner.model.bank.TradeInfo;
import com.api.nonstandardext.zenner.service.bank.Bank_b2e0035_Service;
import com.api.nonstandardext.zenner.utils.ZennerApiService;
import com.api.nonstandardext.zenner.utils.ZennerUtil;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.schedule.BaseCronJob;
import java.io.File;
import java.util.*;
/**
*
*
* 1. b2e0005() b2e0012()
* b2e0035
* b2e0035
*
* 2. SAP
*
* 3.OA
*/
public class SyncAccountTradeInfoJob extends BaseCronJob {
BaseBean logger = new BaseBean();
private String interfaceName;
private final static String JobName = " SyncAccountTradeInfoJob ";
public String getInterfaceName() {
return interfaceName;
}
public void setInterfaceName(String interfaceName) {
this.interfaceName = interfaceName;
}
public void execute() {
logger.writeLog("-----" + JobName + " Begin------");
RecordSet rs = new RecordSet();
ZennerApiService zennerApiService = new ZennerApiService();
try {
logger.writeLog("-----" + JobName + " getInterfaceName------" + getInterfaceName());
//银行
String bankApiUrl = zennerApiService.getSystemConfigValue("BANK_API_URL");
String bankSql = "select * from uf_bank_account";
rs.execute(bankSql);
int pageSize = 50;
while (rs.next()){
int total = syncBank_b2e0035(bankApiUrl, Util.null2String(rs.getString("lxh")), Util.null2String(rs.getString("yxzh")), 1, pageSize);
Integer totalPage = (total + pageSize - 1) / pageSize;
logger.writeLog(JobName + " totalPage:" + totalPage);
for (int pageNo = 2; pageNo <= totalPage; pageNo++) {
int startNo = (pageNo - 1) * pageSize;
int endNo = pageNo * pageSize;
logger.writeLog(JobName + " startNo:" + startNo + " endNo:" + endNo);
int pageTotal = syncBank_b2e0035(bankApiUrl, Util.null2String(rs.getString("lxh")), Util.null2String(rs.getString("yxzh")), startNo, pageSize);
logger.writeLog(JobName + " total:" + pageTotal);
}
}
} catch (Exception e) {
logger.writeLog(JobName + " 获取异常: " + e.getMessage());
e.printStackTrace();
}
logger.writeLog("--------------------" + JobName + " End---------------------------");
}
/**
*
* @param bankApiUrl
* @throws Exception
*/
public int syncBank_b2e0035(String bankApiUrl, String ibknum, String actacn, int start, int end) throws Exception {
int notenum = 0;
String dirPath = "E:\\WEAVER\\bank\\";
File dir = new File(dirPath);
if (!dir.exists()) {
dir.mkdirs();
}
//当日账号余额
Map<String, String> xmlParams = new HashMap<>();
xmlParams.put("termid", "E192168000104");
xmlParams.put("trnid", "");
xmlParams.put("cusopr", "395169759");
xmlParams.put("custid", "387679060");
xmlParams.put("trncod", "b2e0035");
xmlParams.put("token", "");
xmlParams.put("type", "2002");
xmlParams.put("ibknum", ibknum);
xmlParams.put("actacn", actacn);
xmlParams.put("from", "20220919");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, -1);
xmlParams.put("to", ZennerUtil.parseToDateString(cal.getTime(), ZennerUtil.formatYYYYMMDD_NoSplit));
xmlParams.put("amountFrom", "1");
xmlParams.put("amountTo", "100000");
xmlParams.put("begnum", start + "");
xmlParams.put("recnum", end + "");
xmlParams.put("direction", "0");
String xmlFileUrl = dirPath + "b2e0035_" + ZennerUtil.parseToDateString(Calendar.getInstance().getTime(), ZennerUtil.formatYYYYMMDD)+ ".xml";
logger.writeLog(JobName + " xmlFileUrl : " + xmlFileUrl);
Bank_b2e0035_Service bankB2e0035Service = new Bank_b2e0035_Service();
bankB2e0035Service.createXml(xmlFileUrl, xmlParams);
String apiParams = bankB2e0035Service.getXmlString(xmlFileUrl);
Integer pLen = apiParams.length();
int ps = 500;
int logPageNum = pLen / ps;
int i = 0;
if (pLen <= ps){
logger.writeLog(JobName + "........voucherParams last: " + apiParams);
} else {
for (i = 0; i < logPageNum; i++){
logger.writeLog(JobName + "........voucherParams " + i + " : " + apiParams.substring(i * ps, (i + 1) * 500));
}
logger.writeLog(JobName + "........voucherParams last: " + apiParams.substring((i-1) * 500));
}
logger.writeLog(JobName + " bankApiUrl : " + bankApiUrl);
String result = ZennerUtil.httpPostToken(bankApiUrl, new HashMap<>(), apiParams);
logger.writeLog(JobName + " syncBank_b2e0035 result : " + result);
Document doc = DocumentHelper.parseText(result); // 将xml转为dom对象
Element root = doc.getRootElement(); // 获取根节点
List<Element> elements = root.elements("trans");//获取名称为env:Body的子节点
List<TradeInfo> tradeInfoList = new ArrayList<>();
boolean statusOk = false;
for (Object l2 : elements) { //遍历子元素
Element l2Element = (Element) l2;
logger.writeLog(JobName + "l2Element name :" + l2Element.getName());
List<Element> elementsL3 = l2Element.elements();
for (Object l3 : elementsL3) { //遍历子元素
Element l3Element = (Element) l3;
List<Element> elementsL4 = l3Element.elements();
for (Object l4 : elementsL4) { //遍历子元素
Element dataElement = (Element) l4;
logger.writeLog(JobName + "l4Element name :" + dataElement.getName());
if ("status".equals(dataElement.getName())){
List<Element> elementsL5 = dataElement.elements();
for (Object l5 : elementsL5) { //遍历子元素
Element l5Element = (Element) l5;
if ("rspcod".equals(l5Element.getName())) {
logger.writeLog("rspcod:" + l5Element.getStringValue());
if (l5Element.getStringValue().equals("B001") || l5Element.getStringValue().equals("B002")){
statusOk = true;
} else {
statusOk = false;
}
}
if ("rspmsg".equals(l5Element.getName())) {
logger.writeLog(JobName + "rspmsg:" + l5Element.getStringValue());
}
}
}
if ("totalnum".equals(dataElement.getName())){
logger.writeLog("totalnum:" + dataElement.getStringValue());
}
if ("notenum".equals(dataElement.getName())){
logger.writeLog("notenum:" + dataElement.getStringValue());
String notenumStr = Util.null2String(dataElement.getStringValue());
if ("".equals(notenum)){
notenumStr = "0";
}
notenum = Integer.parseInt(notenumStr);
}
logger.writeLog("statusOk:" + statusOk);
if (statusOk){
logger.writeLog(JobName + "dataElement.getName():" + dataElement.getName());
if ("b2e0035-rs".equals(dataElement.getName())){
TradeInfo tradeInfo = new TradeInfo();
List<Element> elementsData = dataElement.elements();
for (Object data : elementsData) { //遍历子元素
Element l4Element = (Element) data;
if ("fractn".equals(l4Element.getName())){
List<Element> elementsL5 = l4Element.elements();
for (Object l5 : elementsL5) { //遍历子元素
Element l5Element = (Element) l5;
if ("ibknum".equals(l5Element.getName())) {
tradeInfo.setIbknum(l5Element.getStringValue());
}
if ("actacn".equals(l5Element.getName())) {
tradeInfo.setActacn(l5Element.getStringValue());
}
if ("acntname".equals(l5Element.getName())) {
tradeInfo.setAcntname(l5Element.getStringValue());
}
if ("ibkname".equals(l5Element.getName())) {
tradeInfo.setIbkname(l5Element.getStringValue());
}
if ("outref".equals(l5Element.getName())) {
tradeInfo.setOutref(l5Element.getStringValue());
}
}
}
if ("toactn".equals(l4Element.getName())) {
List<Element> elementsL5 = l4Element.elements();
for (Object l5 : elementsL5) { //遍历子元素
Element l5Element = (Element) l5;
if ("toibkn".equals(l5Element.getName())) {
logger.writeLog(JobName + "toibkn:" + l5Element.getStringValue());
tradeInfo.setToibkn(l5Element.getStringValue());
}
if ("actacn".equals(l5Element.getName())) {
logger.writeLog(JobName + "actacn:" + l5Element.getStringValue());
tradeInfo.setActacn_receipt(l5Element.getStringValue());
}
if ("toname".equals(l5Element.getName())) {
logger.writeLog(JobName + "toname:" + l5Element.getStringValue());
tradeInfo.setToname(l5Element.getStringValue());
}
if ("tobank".equals(l5Element.getName())) {
logger.writeLog(JobName + "tobank:" + l5Element.getStringValue());
tradeInfo.setTobank(l5Element.getStringValue());
}
if ("tobref".equals(l5Element.getName())) {
logger.writeLog(JobName + "tobref:" + l5Element.getStringValue());
tradeInfo.setTobref(l5Element.getStringValue());
}
}
}
if ("txndate".equals(l4Element.getName())) {
if (!"".equals(l4Element.getStringValue())){
Date date = ZennerUtil.parseToDate(l4Element.getStringValue(), ZennerUtil.formatYYYYMMDD_NoSplit);
tradeInfo.setTxndate_time(ZennerUtil.parseToDateString(date, ZennerUtil.formatYYYYMMDD));
}
}
if ("txnamt".equals(l4Element.getName())) {
if (!"".equals(l4Element.getStringValue())){
tradeInfo.setTxnamt(l4Element.getStringValue());
}
}
if ("acctbal".equals(l4Element.getName())) {
if (!"".equals(l4Element.getStringValue())){
tradeInfo.setAcctbal(l4Element.getStringValue());
}
}
if ("avlbal".equals(l4Element.getName())) {
if (!"".equals(l4Element.getStringValue())){
tradeInfo.setAvlbal(l4Element.getStringValue());
}
}
if ("frzamt".equals(l4Element.getName())) {
if (!"".equals(l4Element.getStringValue())){
tradeInfo.setFrzamt(l4Element.getStringValue());
}
}
if ("overdramt".equals(l4Element.getName())) {
if (!"".equals(l4Element.getStringValue())){
tradeInfo.setOverdramt(l4Element.getStringValue());
}
}
if ("avloverdramt".equals(l4Element.getName())) {
if (!"".equals(l4Element.getStringValue())){
tradeInfo.setAvloverdramt(l4Element.getStringValue());
}
}
if ("useinfo".equals(l4Element.getName())) {
if (!"".equals(l4Element.getStringValue())){
tradeInfo.setUseinfo(l4Element.getStringValue());
}
}
if ("furinfo".equals(l4Element.getName())) {
if (!"".equals(l4Element.getStringValue())){
tradeInfo.setFy(l4Element.getStringValue());
}
}
if ("transtype".equals(l4Element.getName())) {
if (!"".equals(l4Element.getStringValue())){
tradeInfo.setTranstype(l4Element.getStringValue());
}
}
if ("trncur".equals(l4Element.getName())) {
if (!"".equals(l4Element.getStringValue())){
tradeInfo.setTrncur(l4Element.getStringValue());
}
}
if ("direction".equals(l4Element.getName())) {
if (!"".equals(l4Element.getStringValue())){
tradeInfo.setDirection(l4Element.getStringValue());
}
}
}
tradeInfoList.add(tradeInfo);
}
}
}
}
}
logger.writeLog(JobName + " result tradeInfoList size: " + tradeInfoList.size());
for (TradeInfo tradeInfo : tradeInfoList){
if (!"".equals(tradeInfo.getIbknum())){
tradeInfo.save(tradeInfo, 51, "uf_bank_trade_info");
}
}
return notenum;
}
}

View File

@ -0,0 +1,379 @@
package com.api.nonstandardext.zenner.model.bank;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
*
*/
public class DayBalance extends BaseBean {
private Integer formmodeid;
private String modedatacreater;
private String modedatacreatertype;
private String modedatacreatedate;
private String modedatacreatetime;
//联行号
private String ibknum;
//账号
private String actacn;
//货币码
private String curcde;
//账户户名
private String actname;
//账面余额
private String bokbal;
//有效余额
private String avabal;
//一户通主账户活期账户余额
private String currentavabal;
//圈存金额
private String stpamt;
//透支额度
private String ovramt;
//冻结余额
private String frzamt;
//有效额度
private String effauthamt;
//有效已用额度
private String effusdoverbal;
//有效未用额度
private String effuseablequota;
//系统日期
private String baldat;
public Integer save(DayBalance ufModel, Integer formmodeid, String tableName) {
String modelName = "银行当日余额";
Integer billId = 0;
try {
RecordSet rs = new RecordSet();
String fieldSql = "";
String valueSql = "";
boolean result = false;
String currentDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
ufModel.setFormmodeid(formmodeid);
ufModel.setModedatacreater("1");
ufModel.setModedatacreatertype("0");
ufModel.setModedatacreatedate(currentDateTime.substring(0, 10));
ufModel.setModedatacreatetime(currentDateTime.substring(11));
String existSql = "select id from " + tableName + " where ibknum='" + ufModel.getIbknum() + "' and actacn='" + ufModel.getActacn() + "' and curcde='" + ufModel.getCurcde() + "' and baldat='" + ufModel.getBaldat() + "'";
rs.execute(existSql);
if (rs.next()) {
billId = rs.getInt("id");
String msg = update(modelName, tableName, ufModel);
if (!"".equals(msg)){
this.writeLog(modelName + " 保存异常: " + msg);
}
return billId;
}
// 获取实体类的所有属性返回Field数组
Field[] field = ufModel.getClass().getDeclaredFields();
// 遍历所有属性
for (int i = 0; i < field.length; i++) {
// 获取属性的名字,并将属性第一个字符大写
String name = field[i].getName();
name = name.substring(0, 1).toUpperCase() + name.substring(1);
// 得到属性类型
String type = field[i].getGenericType().toString();
if (type.equals("class java.lang.String")) {
Method m = ufModel.getClass().getMethod("get" + name);
// 调用getter方法获取属性值
String value = (String) m.invoke(ufModel);
if (value != null) {
fieldSql += "," + name;
valueSql += ",'" + value.trim() + "'";
}
}
if (type.equals("class java.lang.Integer")) {
Method m = ufModel.getClass().getMethod("get" + name);
// 调用getter方法获取属性值
Integer value = (Integer) m.invoke(ufModel);
if (value != null) {
fieldSql += "," + name;
valueSql += "," + value + "";
}
}
}
if (!"".equals(fieldSql)) {
fieldSql = fieldSql.substring(1);
valueSql = valueSql.substring(1);
String insertSql = "insert into " + tableName + " (" + fieldSql + ") values (" + valueSql + ")";
result = rs.execute(insertSql);
if (!result) {
return -1;
}
RecordSet rightRs = new RecordSet();
writeLog(modelName + ", insertSql ->" + insertSql + ", result:" + result + ", formmodeid: " + formmodeid);
rightRs.execute("SELECT id FROM " + tableName + " where ibknum='" + ufModel.getIbknum() + "' and actacn='" + ufModel.getActacn() + "' and curcde='" + ufModel.getCurcde() + "' and baldat='" + ufModel.getBaldat() + "'");
if (rightRs.next()) {
billId = rightRs.getInt("id");
this.setModeRight(1, formmodeid, billId);
}
}
} catch (Exception e) {
writeLog(modelName + ", 新增报错 ->" + e.getMessage());
e.printStackTrace();
return -1;
}
return billId;
}
public String update(String modelName, String tableName, DayBalance ufModel) throws Exception{
writeLog(modelName + ", update -> formmodeid: " + formmodeid);
RecordSet rs = new RecordSet();
String setSql = "";
boolean result = false;
try {
// 获取实体类的所有属性返回Field数组
Field[] field = ufModel.getClass().getDeclaredFields();
// 遍历所有属性
for(int i = 0; i < field.length; i++) {
// 获取属性的名字,并将属性第一个字符大写
String name = field[i].getName();
name = name.substring(0, 1).toUpperCase() + name.substring(1);
// 主键不更新
if("Ibknum".equals(name) || "Actacn".equals(name) || "Curcde".equals(name) || "Baldat".equals(name) || "Modedatacreatedate".equals(name) || "Modedatacreatetime".equals(name)) {
continue;
}
// 得到属性类型
String type = field[i].getGenericType().toString();
if (type.equals("class java.lang.String")) {
Method m = ufModel.getClass().getMethod("get" + name);
// 调用getter方法获取属性值
String value = (String) m.invoke(ufModel);
if (value != null) {
setSql += "," + name + "='" + value + "'";
}
}
if (type.equals("class java.lang.Integer")) {
Method m = ufModel.getClass().getMethod("get" + name);
// 调用getter方法获取属性值
Integer value = (Integer) m.invoke(ufModel);
if (value != null) {
setSql += "," + name + "=" + value;
}
}
}
if(!"".equals(setSql)) {
setSql = setSql.substring(1);
String updateSql = "update " + tableName + " set " + setSql + " where ibknum='" + ufModel.getIbknum() + "' and actacn='" + ufModel.getActacn() + "' and curcde='" + ufModel.getCurcde() + "' and baldat='" + ufModel.getBaldat() + "'";
writeLog(modelName + ", updateSql ->" + updateSql);
result = rs.execute(updateSql);
if (!result){
return "修改失败";
}
}
} catch (Exception e){
writeLog(modelName + ", 修改报错 ->" + e.getMessage());
e.printStackTrace();
return e.getMessage();
}
return "";
}
public void setModeRight(int creater, int modeid, int sourceid) {
ModeRightInfo moderightinfo = new ModeRightInfo();
moderightinfo.setNewRight(true);
moderightinfo.editModeDataShare(creater, modeid, sourceid);
}
public Integer getFormmodeid() {
return formmodeid;
}
public void setFormmodeid(Integer formmodeid) {
this.formmodeid = formmodeid;
}
public String getModedatacreater() {
return modedatacreater;
}
public void setModedatacreater(String modedatacreater) {
this.modedatacreater = modedatacreater;
}
public String getModedatacreatertype() {
return modedatacreatertype;
}
public void setModedatacreatertype(String modedatacreatertype) {
this.modedatacreatertype = modedatacreatertype;
}
public String getModedatacreatedate() {
return modedatacreatedate;
}
public void setModedatacreatedate(String modedatacreatedate) {
this.modedatacreatedate = modedatacreatedate;
}
public String getModedatacreatetime() {
return modedatacreatetime;
}
public void setModedatacreatetime(String modedatacreatetime) {
this.modedatacreatetime = modedatacreatetime;
}
public String getIbknum() {
return ibknum;
}
public void setIbknum(String ibknum) {
this.ibknum = ibknum;
}
public String getActacn() {
return actacn;
}
public void setActacn(String actacn) {
this.actacn = actacn;
}
public String getCurcde() {
return curcde;
}
public void setCurcde(String curcde) {
this.curcde = curcde;
}
public String getActname() {
return actname;
}
public void setActname(String actname) {
this.actname = actname;
}
public String getBokbal() {
return bokbal;
}
public void setBokbal(String bokbal) {
this.bokbal = bokbal;
}
public String getAvabal() {
return avabal;
}
public void setAvabal(String avabal) {
this.avabal = avabal;
}
public String getCurrentavabal() {
return currentavabal;
}
public void setCurrentavabal(String currentavabal) {
this.currentavabal = currentavabal;
}
public String getStpamt() {
return stpamt;
}
public void setStpamt(String stpamt) {
this.stpamt = stpamt;
}
public String getOvramt() {
return ovramt;
}
public void setOvramt(String ovramt) {
this.ovramt = ovramt;
}
public String getFrzamt() {
return frzamt;
}
public void setFrzamt(String frzamt) {
this.frzamt = frzamt;
}
public String getEffauthamt() {
return effauthamt;
}
public void setEffauthamt(String effauthamt) {
this.effauthamt = effauthamt;
}
public String getEffusdoverbal() {
return effusdoverbal;
}
public void setEffusdoverbal(String effusdoverbal) {
this.effusdoverbal = effusdoverbal;
}
public String getEffuseablequota() {
return effuseablequota;
}
public void setEffuseablequota(String effuseablequota) {
this.effuseablequota = effuseablequota;
}
public String getBaldat() {
return baldat;
}
public void setBaldat(String baldat) {
this.baldat = baldat;
}
@Override
public String toString() {
return "DayBalance{" +
"ibknum='" + ibknum + '\'' +
", actacn='" + actacn + '\'' +
", curcde='" + curcde + '\'' +
", actname='" + actname + '\'' +
", bokbal='" + bokbal + '\'' +
", avabal='" + avabal + '\'' +
", currentavabal='" + currentavabal + '\'' +
", stpamt='" + stpamt + '\'' +
", ovramt='" + ovramt + '\'' +
", frzamt='" + frzamt + '\'' +
", effauthamt='" + effauthamt + '\'' +
", effusdoverbal='" + effusdoverbal + '\'' +
", effuseablequota='" + effuseablequota + '\'' +
", baldat='" + baldat + '\'' +
'}';
}
}

View File

@ -0,0 +1,582 @@
package com.api.nonstandardext.zenner.model.bank;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
*
*/
public class TradeInfo extends BaseBean {
private Integer formmodeid;
private String modedatacreater;
private String modedatacreatertype;
private String modedatacreatedate;
private String modedatacreatetime;
//付款行号
private String ibknum;
//付款账号
private String actacn;
//货币码
private String curcde;
//账户户名
private String actname;
//付款人
private String acntname;
//付款人开户行名
private String ibkname;
//汇款行业务编号
private String outref;
//收款行号
private String toibkn;
//收款账号
private String actacn_receipt;
//收款行业务编号
private String tobref;
//收款人
private String toname;
//被代理行号
private String mactibkn;
//被代理账号
private String mactacn;
//被代理账户名
private String mactname;
//被代理账户开户行名
private String mactbank;
//凭证号或传票号
private String vchnum;
//记录标识号
private String transid;
//客户业务编号后12位
private String insid;
//交易时间
private String txndate_time;
//金额
private String txnamt;
//交易后余额
private String acctbal;
//可用余额
private String avlbal;
//冻结金额
private String frzamt;
//透支额度
private String overdramt;
//可用透支额度
private String avloverdramt;
//用途
private String useinfo;
//附言
private String fy;
//业务类型
private String transtype;
//货币名称
private String trncur;
//来往账标识
private String direction;
//收款人开户行名
private String tobank;
public Integer save(TradeInfo ufModel, Integer formmodeid, String tableName) {
String modelName = "银行交易信息";
Integer billId = 0;
try {
RecordSet rs = new RecordSet();
String fieldSql = "";
String valueSql = "";
boolean result = false;
String currentDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
ufModel.setFormmodeid(formmodeid);
ufModel.setModedatacreater("1");
ufModel.setModedatacreatertype("0");
ufModel.setModedatacreatedate(currentDateTime.substring(0, 10));
ufModel.setModedatacreatetime(currentDateTime.substring(11));
String existSql = "select id from " + tableName + " where ibknum='" + ufModel.getIbknum() + "' and actacn='" + ufModel.getActacn() + "' and outref='" + ufModel.getOutref() + "'";
rs.execute(existSql);
if (rs.next()) {
billId = rs.getInt("id");
String msg = update(modelName, tableName, ufModel);
if (!"".equals(msg)){
this.writeLog(modelName + " 保存异常: " + msg);
}
return billId;
}
// 获取实体类的所有属性返回Field数组
Field[] field = ufModel.getClass().getDeclaredFields();
// 遍历所有属性
for (int i = 0; i < field.length; i++) {
// 获取属性的名字,并将属性第一个字符大写
String name = field[i].getName();
name = name.substring(0, 1).toUpperCase() + name.substring(1);
// 得到属性类型
String type = field[i].getGenericType().toString();
if (type.equals("class java.lang.String")) {
Method m = ufModel.getClass().getMethod("get" + name);
// 调用getter方法获取属性值
String value = (String) m.invoke(ufModel);
if (value != null) {
fieldSql += "," + name;
valueSql += ",'" + value.trim() + "'";
}
}
if (type.equals("class java.lang.Integer")) {
Method m = ufModel.getClass().getMethod("get" + name);
// 调用getter方法获取属性值
Integer value = (Integer) m.invoke(ufModel);
if (value != null) {
fieldSql += "," + name;
valueSql += "," + value + "";
}
}
}
if (!"".equals(fieldSql)) {
fieldSql = fieldSql.substring(1);
valueSql = valueSql.substring(1);
String insertSql = "insert into " + tableName + " (" + fieldSql + ") values (" + valueSql + ")";
result = rs.execute(insertSql);
if (!result) {
return -1;
}
RecordSet rightRs = new RecordSet();
writeLog(modelName + ", insertSql ->" + insertSql + ", result:" + result + ", formmodeid: " + formmodeid);
rightRs.execute("SELECT id FROM " + tableName + " where ibknum='" + ufModel.getIbknum() + "' and actacn='" + ufModel.getActacn() + "' and outref='" + ufModel.getOutref() + "'");
if (rightRs.next()) {
billId = rightRs.getInt("id");
this.setModeRight(1, formmodeid, billId);
}
}
} catch (Exception e) {
writeLog(modelName + ", 新增报错 ->" + e.getMessage());
e.printStackTrace();
return -1;
}
return billId;
}
public String update(String modelName, String tableName, TradeInfo ufModel) throws Exception{
writeLog(modelName + ", update -> formmodeid: " + formmodeid);
RecordSet rs = new RecordSet();
String setSql = "";
boolean result = false;
try {
// 获取实体类的所有属性返回Field数组
Field[] field = ufModel.getClass().getDeclaredFields();
// 遍历所有属性
for(int i = 0; i < field.length; i++) {
// 获取属性的名字,并将属性第一个字符大写
String name = field[i].getName();
name = name.substring(0, 1).toUpperCase() + name.substring(1);
// 主键不更新
if("Ibknum".equals(name) || "Actacn".equals(name) || "Curcde".equals(name) || "Baldat".equals(name) || "Modedatacreatedate".equals(name) || "Modedatacreatetime".equals(name)) {
continue;
}
// 得到属性类型
String type = field[i].getGenericType().toString();
if (type.equals("class java.lang.String")) {
Method m = ufModel.getClass().getMethod("get" + name);
// 调用getter方法获取属性值
String value = (String) m.invoke(ufModel);
if (value != null) {
setSql += "," + name + "='" + value + "'";
}
}
if (type.equals("class java.lang.Integer")) {
Method m = ufModel.getClass().getMethod("get" + name);
// 调用getter方法获取属性值
Integer value = (Integer) m.invoke(ufModel);
if (value != null) {
setSql += "," + name + "=" + value;
}
}
}
if(!"".equals(setSql)) {
setSql = setSql.substring(1);
String updateSql = "update " + tableName + " set " + setSql + " where ibknum='" + ufModel.getIbknum() + "' and actacn='" + ufModel.getActacn() + "' and outref='" + ufModel.getOutref() + "'";
writeLog(modelName + ", updateSql ->" + updateSql);
result = rs.execute(updateSql);
if (!result){
return "修改失败";
}
}
} catch (Exception e){
writeLog(modelName + ", 修改报错 ->" + e.getMessage());
e.printStackTrace();
return e.getMessage();
}
return "";
}
public void setModeRight(int creater, int modeid, int sourceid) {
ModeRightInfo moderightinfo = new ModeRightInfo();
moderightinfo.setNewRight(true);
moderightinfo.editModeDataShare(creater, modeid, sourceid);
}
public Integer getFormmodeid() {
return formmodeid;
}
public void setFormmodeid(Integer formmodeid) {
this.formmodeid = formmodeid;
}
public String getModedatacreater() {
return modedatacreater;
}
public void setModedatacreater(String modedatacreater) {
this.modedatacreater = modedatacreater;
}
public String getModedatacreatertype() {
return modedatacreatertype;
}
public void setModedatacreatertype(String modedatacreatertype) {
this.modedatacreatertype = modedatacreatertype;
}
public String getModedatacreatedate() {
return modedatacreatedate;
}
public void setModedatacreatedate(String modedatacreatedate) {
this.modedatacreatedate = modedatacreatedate;
}
public String getModedatacreatetime() {
return modedatacreatetime;
}
public void setModedatacreatetime(String modedatacreatetime) {
this.modedatacreatetime = modedatacreatetime;
}
public String getIbknum() {
return ibknum;
}
public void setIbknum(String ibknum) {
this.ibknum = ibknum;
}
public String getActacn() {
return actacn;
}
public void setActacn(String actacn) {
this.actacn = actacn;
}
public String getCurcde() {
return curcde;
}
public void setCurcde(String curcde) {
this.curcde = curcde;
}
public String getActname() {
return actname;
}
public void setActname(String actname) {
this.actname = actname;
}
public String getAcntname() {
return acntname;
}
public void setAcntname(String acntname) {
this.acntname = acntname;
}
public String getIbkname() {
return ibkname;
}
public void setIbkname(String ibkname) {
this.ibkname = ibkname;
}
public String getOutref() {
return outref;
}
public void setOutref(String outref) {
this.outref = outref;
}
public String getToibkn() {
return toibkn;
}
public void setToibkn(String toibkn) {
this.toibkn = toibkn;
}
public String getActacn_receipt() {
return actacn_receipt;
}
public void setActacn_receipt(String actacn_receipt) {
this.actacn_receipt = actacn_receipt;
}
public String getTobref() {
return tobref;
}
public void setTobref(String tobref) {
this.tobref = tobref;
}
public String getToname() {
return toname;
}
public void setToname(String toname) {
this.toname = toname;
}
public String getMactibkn() {
return mactibkn;
}
public void setMactibkn(String mactibkn) {
this.mactibkn = mactibkn;
}
public String getMactacn() {
return mactacn;
}
public void setMactacn(String mactacn) {
this.mactacn = mactacn;
}
public String getMactname() {
return mactname;
}
public void setMactname(String mactname) {
this.mactname = mactname;
}
public String getMactbank() {
return mactbank;
}
public void setMactbank(String mactbank) {
this.mactbank = mactbank;
}
public String getVchnum() {
return vchnum;
}
public void setVchnum(String vchnum) {
this.vchnum = vchnum;
}
public String getTransid() {
return transid;
}
public void setTransid(String transid) {
this.transid = transid;
}
public String getInsid() {
return insid;
}
public void setInsid(String insid) {
this.insid = insid;
}
public String getTxndate_time() {
return txndate_time;
}
public void setTxndate_time(String txndate_time) {
this.txndate_time = txndate_time;
}
public String getTxnamt() {
return txnamt;
}
public void setTxnamt(String txnamt) {
this.txnamt = txnamt;
}
public String getAcctbal() {
return acctbal;
}
public void setAcctbal(String acctbal) {
this.acctbal = acctbal;
}
public String getAvlbal() {
return avlbal;
}
public void setAvlbal(String avlbal) {
this.avlbal = avlbal;
}
public String getFrzamt() {
return frzamt;
}
public void setFrzamt(String frzamt) {
this.frzamt = frzamt;
}
public String getOverdramt() {
return overdramt;
}
public void setOverdramt(String overdramt) {
this.overdramt = overdramt;
}
public String getAvloverdramt() {
return avloverdramt;
}
public void setAvloverdramt(String avloverdramt) {
this.avloverdramt = avloverdramt;
}
public String getUseinfo() {
return useinfo;
}
public void setUseinfo(String useinfo) {
this.useinfo = useinfo;
}
public String getFy() {
return fy;
}
public void setFy(String fy) {
this.fy = fy;
}
public String getTranstype() {
return transtype;
}
public void setTranstype(String transtype) {
this.transtype = transtype;
}
public String getTrncur() {
return trncur;
}
public void setTrncur(String trncur) {
this.trncur = trncur;
}
public String getDirection() {
return direction;
}
public void setDirection(String direction) {
this.direction = direction;
}
public String getTobank() {
return tobank;
}
public void setTobank(String tobank) {
this.tobank = tobank;
}
@Override
public String toString() {
return "TradeInfo{" +
"ibknum='" + ibknum + '\'' +
", actacn='" + actacn + '\'' +
", curcde='" + curcde + '\'' +
", actname='" + actname + '\'' +
", acntname='" + acntname + '\'' +
", ibkname='" + ibkname + '\'' +
", outref='" + outref + '\'' +
", toibkn='" + toibkn + '\'' +
", actacn_receipt='" + actacn_receipt + '\'' +
", tobref='" + tobref + '\'' +
", toname='" + toname + '\'' +
", mactibkn='" + mactibkn + '\'' +
", mactacn='" + mactacn + '\'' +
", mactname='" + mactname + '\'' +
", mactbank='" + mactbank + '\'' +
", vchnum='" + vchnum + '\'' +
", transid='" + transid + '\'' +
", insid='" + insid + '\'' +
", txndate_time='" + txndate_time + '\'' +
", txnamt='" + txnamt + '\'' +
", acctbal='" + acctbal + '\'' +
", avlbal='" + avlbal + '\'' +
", frzamt='" + frzamt + '\'' +
", overdramt='" + overdramt + '\'' +
", avloverdramt='" + avloverdramt + '\'' +
", useinfo='" + useinfo + '\'' +
", fy='" + fy + '\'' +
", transtype='" + transtype + '\'' +
", trncur='" + trncur + '\'' +
", direction='" + direction + '\'' +
", tobank='" + tobank + '\'' +
'}';
}
}

View File

@ -0,0 +1,314 @@
package com.api.nonstandardext.zenner.model.sap;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
*
*/
public class PeriodBalance extends BaseBean {
private Integer formmodeid;
private String modedatacreater;
private String modedatacreatertype;
private String modedatacreatedate;
private String modedatacreatetime;
private String IvCompCode;
private String IvFiscYear;
private String IvFisPeriod;
//累计余额
private String EvBalance;
//期间余额
private String EvPerSales;
//期间贷方发生额
private String EvCreditPer;
//期间借方发生额
private String EvDebitsPer;
//币种
private String EvCurrency;
//科目
private String glAccount;
public Integer save(PeriodBalance ufModel, Integer formmodeid, String tableName) {
String modelName = "期间余额";
Integer billId = 0;
try {
RecordSet rs = new RecordSet();
String fieldSql = "";
String valueSql = "";
boolean result = false;
String currentDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
ufModel.setFormmodeid(formmodeid);
ufModel.setModedatacreater("1");
ufModel.setModedatacreatertype("0");
ufModel.setModedatacreatedate(currentDateTime.substring(0, 10));
ufModel.setModedatacreatetime(currentDateTime.substring(11));
String existSql = "select id from " + tableName + " where IvCompCode='" + ufModel.getIvCompCode() + "' and IvFiscYear='" + ufModel.getIvFiscYear() + "' and IvFisPeriod='" + ufModel.getIvFisPeriod() + "'";
rs.execute(existSql);
if (rs.next()) {
billId = rs.getInt("id");
String msg = update(modelName, tableName, ufModel);
if (!"".equals(msg)){
this.writeLog(modelName + " 保存异常: " + msg);
}
return billId;
}
// 获取实体类的所有属性返回Field数组
Field[] field = ufModel.getClass().getDeclaredFields();
// 遍历所有属性
for (int i = 0; i < field.length; i++) {
// 获取属性的名字,并将属性第一个字符大写
String name = field[i].getName();
name = name.substring(0, 1).toUpperCase() + name.substring(1);
// 得到属性类型
String type = field[i].getGenericType().toString();
if (type.equals("class java.lang.String")) {
Method m = ufModel.getClass().getMethod("get" + name);
// 调用getter方法获取属性值
String value = (String) m.invoke(ufModel);
if (value != null) {
fieldSql += "," + name;
valueSql += ",'" + value.trim() + "'";
}
}
if (type.equals("class java.lang.Integer")) {
Method m = ufModel.getClass().getMethod("get" + name);
// 调用getter方法获取属性值
Integer value = (Integer) m.invoke(ufModel);
if (value != null) {
fieldSql += "," + name;
valueSql += "," + value + "";
}
}
}
if (!"".equals(fieldSql)) {
fieldSql = fieldSql.substring(1);
valueSql = valueSql.substring(1);
String insertSql = "insert into " + tableName + " (" + fieldSql + ") values (" + valueSql + ")";
result = rs.execute(insertSql);
if (!result) {
return -1;
}
RecordSet rightRs = new RecordSet();
writeLog(modelName + ", insertSql ->" + insertSql + ", result:" + result + ", formmodeid: " + formmodeid);
rightRs.execute("SELECT id FROM " + tableName + " where IvCompCode='" + ufModel.getIvCompCode() + "' and IvFiscYear='" + ufModel.getIvFiscYear() + "' and IvFisPeriod='" + ufModel.getIvFisPeriod() + "'");
if (rightRs.next()) {
billId = rightRs.getInt("id");
this.setModeRight(1, formmodeid, billId);
}
}
} catch (Exception e) {
writeLog(modelName + ", 新增报错 ->" + e.getMessage());
e.printStackTrace();
return -1;
}
return billId;
}
public String update(String modelName, String tableName, PeriodBalance ufModel) throws Exception{
writeLog(modelName + ", update -> formmodeid: " + formmodeid);
RecordSet rs = new RecordSet();
String setSql = "";
boolean result = false;
try {
// 获取实体类的所有属性返回Field数组
Field[] field = ufModel.getClass().getDeclaredFields();
// 遍历所有属性
for(int i = 0; i < field.length; i++) {
// 获取属性的名字,并将属性第一个字符大写
String name = field[i].getName();
name = name.substring(0, 1).toUpperCase() + name.substring(1);
// 主键不更新
if("IvCompCode".equals(name) || "IvFiscYear".equals(name) || "IvFisPeriod".equals(name) || "Modedatacreatedate".equals(name) || "Modedatacreatetime".equals(name)) {
continue;
}
// 得到属性类型
String type = field[i].getGenericType().toString();
if (type.equals("class java.lang.String")) {
Method m = ufModel.getClass().getMethod("get" + name);
// 调用getter方法获取属性值
String value = (String) m.invoke(ufModel);
if (value != null) {
setSql += "," + name + "='" + value + "'";
}
}
if (type.equals("class java.lang.Integer")) {
Method m = ufModel.getClass().getMethod("get" + name);
// 调用getter方法获取属性值
Integer value = (Integer) m.invoke(ufModel);
if (value != null) {
setSql += "," + name + "=" + value;
}
}
}
if(!"".equals(setSql)) {
setSql = setSql.substring(1);
String updateSql = "update " + tableName + " set " + setSql + " where IvCompCode='" + ufModel.getIvCompCode() + "' and IvFiscYear='" + ufModel.getIvFiscYear() + "' and IvFisPeriod='" + ufModel.getIvFisPeriod() + "'";
writeLog(modelName + ", updateSql ->" + updateSql);
result = rs.execute(updateSql);
if (!result){
return "修改失败";
}
}
} catch (Exception e){
writeLog(modelName + ", 修改报错 ->" + e.getMessage());
e.printStackTrace();
return e.getMessage();
}
return "";
}
public void setModeRight(int creater, int modeid, int sourceid) {
ModeRightInfo moderightinfo = new ModeRightInfo();
moderightinfo.setNewRight(true);
moderightinfo.editModeDataShare(creater, modeid, sourceid);
}
public Integer getFormmodeid() {
return formmodeid;
}
public void setFormmodeid(Integer formmodeid) {
this.formmodeid = formmodeid;
}
public String getModedatacreater() {
return modedatacreater;
}
public void setModedatacreater(String modedatacreater) {
this.modedatacreater = modedatacreater;
}
public String getModedatacreatertype() {
return modedatacreatertype;
}
public void setModedatacreatertype(String modedatacreatertype) {
this.modedatacreatertype = modedatacreatertype;
}
public String getModedatacreatedate() {
return modedatacreatedate;
}
public void setModedatacreatedate(String modedatacreatedate) {
this.modedatacreatedate = modedatacreatedate;
}
public String getModedatacreatetime() {
return modedatacreatetime;
}
public void setModedatacreatetime(String modedatacreatetime) {
this.modedatacreatetime = modedatacreatetime;
}
public String getEvBalance() {
return EvBalance;
}
public void setEvBalance(String evBalance) {
EvBalance = evBalance;
}
public String getEvPerSales() {
return EvPerSales;
}
public void setEvPerSales(String evPerSales) {
EvPerSales = evPerSales;
}
public String getEvCreditPer() {
return EvCreditPer;
}
public void setEvCreditPer(String evCreditPer) {
EvCreditPer = evCreditPer;
}
public String getEvDebitsPer() {
return EvDebitsPer;
}
public void setEvDebitsPer(String evDebitsPer) {
EvDebitsPer = evDebitsPer;
}
public String getEvCurrency() {
return EvCurrency;
}
public void setEvCurrency(String evCurrency) {
EvCurrency = evCurrency;
}
public String getGlAccount() {
return glAccount;
}
public void setGlAccount(String glAccount) {
this.glAccount = glAccount;
}
public String getIvCompCode() {
return IvCompCode;
}
public void setIvCompCode(String ivCompCode) {
IvCompCode = ivCompCode;
}
public String getIvFiscYear() {
return IvFiscYear;
}
public void setIvFiscYear(String ivFiscYear) {
IvFiscYear = ivFiscYear;
}
public String getIvFisPeriod() {
return IvFisPeriod;
}
public void setIvFisPeriod(String ivFisPeriod) {
IvFisPeriod = ivFisPeriod;
}
@Override
public String toString() {
return "PeriodBalance{" +
"IvCompCode='" + IvCompCode + '\'' +
", IvFiscYear='" + IvFiscYear + '\'' +
", IvFisPeriod='" + IvFisPeriod + '\'' +
", EvBalance='" + EvBalance + '\'' +
", EvPerSales='" + EvPerSales + '\'' +
", EvCreditPer='" + EvCreditPer + '\'' +
", EvDebitsPer='" + EvDebitsPer + '\'' +
", EvCurrency='" + EvCurrency + '\'' +
", glAccount='" + glAccount + '\'' +
'}';
}
}

View File

@ -0,0 +1,130 @@
package com.api.nonstandardext.zenner.service.bank;
import org.xml.sax.helpers.AttributesImpl;
import weaver.general.BaseBean;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.util.*;
public class Bank_b2e0005_Service extends BaseBean {
private final static String ServiceName = " Bank_b2e0005_Service ";
public void createXml(String xmlFileUrl, Map<String, String> params) throws Exception{
SAXTransformerFactory tff = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
// 2、通过SAXTransformerFactory创建一个TransformerHandler的对象
TransformerHandler handler = tff.newTransformerHandler();
// 3、通过handler创建一个Transformer对象
Transformer tr = handler.getTransformer();
// 4、通过Transformer对象对生成的xml文件进行设置
// 设置编码方式
tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
// 设置是否换行
tr.setOutputProperty(OutputKeys.INDENT, "yes");
// 5、创建一个Result对象
File f = new File(xmlFileUrl);
// 判断文件是否存在
if (!f.exists()) {
f.createNewFile();
}
Result result = new StreamResult(new FileOutputStream(f));
// 6、使RESULT与handler关联
handler.setResult(result);
// 打开document
handler.startDocument();
AttributesImpl attrImpl = new AttributesImpl();
this.writeLog(ServiceName + "........params: " + params.toString());
attrImpl.addAttribute("", "", "version", "", "100");
attrImpl.addAttribute("", "", "security", "", "true");
attrImpl.addAttribute("", "", "lang", "", "chs");
handler.startElement("", "", "bocb2e", attrImpl);
attrImpl.clear();
attrImpl.addAttribute("", "", "id", "", "11074E1000000000S6SL");
handler.startElement("", "", "head", attrImpl);
attrImpl.clear();
handler.startElement("", "", "termid", attrImpl);
handler.characters(params.get("termid").toCharArray(), 0, params.get("termid").length());
handler.endElement("", "", "termid");
handler.startElement("", "", "trnid", attrImpl);
handler.characters(params.get("trnid").toCharArray(), 0, params.get("trnid").length());
handler.endElement("", "", "trnid");
handler.startElement("", "", "cusopr", attrImpl);
handler.characters(params.get("cusopr").toCharArray(), 0, params.get("cusopr").length());
handler.endElement("", "", "cusopr");
handler.startElement("", "", "custid", attrImpl);
handler.characters(params.get("custid").toCharArray(), 0, params.get("custid").length());
handler.endElement("", "", "custid");
handler.startElement("", "", "trncod", attrImpl);
handler.characters(params.get("trncod").toCharArray(), 0, params.get("trncod").length());
handler.endElement("", "", "trncod");
handler.startElement("", "", "token", attrImpl);
handler.characters(params.get("token").toCharArray(), 0, params.get("token").length());
handler.endElement("", "", "token");
handler.endElement("", "", "head");
attrImpl.clear();
handler.startElement("", "", "trans", attrImpl);
this.writeLog(ServiceName + "........params 2 : " + params.toString());
handler.startElement("", "", "trn-b2e0005-rq", attrImpl);
handler.startElement("", "", "b2e0005-rq", attrImpl);
handler.startElement("", "", "account", attrImpl);
handler.startElement("", "", "ibknum", attrImpl);
handler.characters(params.get("ibknum").toCharArray(), 0, params.get("ibknum").length());
handler.endElement("", "", "ibknum");
handler.startElement("", "", "actacn", attrImpl);
handler.characters(params.get("actacn").toCharArray(), 0, params.get("actacn").length());
handler.endElement("", "", "actacn");
handler.endElement("", "", "account");
handler.endElement("", "", "b2e0005-rq");
handler.endElement("", "", "trn-b2e0005-rq");
handler.endElement("", "", "trans");
handler.endElement("", "", "bocb2e");
this.writeLog(ServiceName + "........params 3 : " + params.toString());
// 关闭document
handler.endDocument();
}
public String getXmlString(String xmlFileUrl) {
StringBuilder sb = new StringBuilder();
try {
InputStream inputStream = new FileInputStream(xmlFileUrl);
BufferedReader br=new BufferedReader(new InputStreamReader(inputStream));
String line="";
for(line=br.readLine();line!=null;line=br.readLine()) {
sb.append(line+"\n");
}
} catch (FileNotFoundException e) {
this.writeLog(ServiceName + " e 1 : " + e.getMessage());
} catch (IOException e) {
this.writeLog(ServiceName + " e 2 : " + e.getMessage());
}
return sb.toString();
}
}

View File

@ -0,0 +1,160 @@
package com.api.nonstandardext.zenner.service.bank;
import org.xml.sax.helpers.AttributesImpl;
import weaver.general.BaseBean;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.util.Map;
public class Bank_b2e0035_Service extends BaseBean {
private final static String ServiceName = " Bank_b2e0035_Service ";
public void createXml(String xmlFileUrl, Map<String, String> params) throws Exception{
SAXTransformerFactory tff = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
// 2、通过SAXTransformerFactory创建一个TransformerHandler的对象
TransformerHandler handler = tff.newTransformerHandler();
// 3、通过handler创建一个Transformer对象
Transformer tr = handler.getTransformer();
// 4、通过Transformer对象对生成的xml文件进行设置
// 设置编码方式
tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
// 设置是否换行
tr.setOutputProperty(OutputKeys.INDENT, "yes");
// 5、创建一个Result对象
File f = new File(xmlFileUrl);
// 判断文件是否存在
if (!f.exists()) {
f.createNewFile();
}
Result result = new StreamResult(new FileOutputStream(f));
// 6、使RESULT与handler关联
handler.setResult(result);
// 打开document
handler.startDocument();
AttributesImpl attrImpl = new AttributesImpl();
attrImpl.addAttribute("", "", "version", "", "110");
attrImpl.addAttribute("", "", "locale", "", "zh_CN");
handler.startElement("", "", "bocb2e", attrImpl);
attrImpl.clear();
handler.startElement("", "", "head", attrImpl);
attrImpl.clear();
handler.startElement("", "", "termid", attrImpl);
handler.characters(params.get("termid").toCharArray(), 0, params.get("termid").length());
handler.endElement("", "", "termid");
handler.startElement("", "", "trnid", attrImpl);
handler.characters(params.get("trnid").toCharArray(), 0, params.get("trnid").length());
handler.endElement("", "", "trnid");
handler.startElement("", "", "cusopr", attrImpl);
handler.characters(params.get("cusopr").toCharArray(), 0, params.get("cusopr").length());
handler.endElement("", "", "cusopr");
handler.startElement("", "", "custid", attrImpl);
handler.characters(params.get("custid").toCharArray(), 0, params.get("custid").length());
handler.endElement("", "", "custid");
handler.startElement("", "", "trncod", attrImpl);
handler.characters(params.get("trncod").toCharArray(), 0, params.get("trncod").length());
handler.endElement("", "", "trncod");
handler.startElement("", "", "token", attrImpl);
handler.characters(params.get("token").toCharArray(), 0, params.get("token").length());
handler.endElement("", "", "token");
handler.endElement("", "", "head");
attrImpl.clear();
handler.startElement("", "", "trans", attrImpl);
handler.startElement("", "", "trn-b2e0035-rq", attrImpl);
handler.startElement("", "", "b2e0035-rq", attrImpl);
handler.startElement("", "", "ibknum", attrImpl);
handler.characters(params.get("ibknum").toCharArray(), 0, params.get("ibknum").length());
handler.endElement("", "", "ibknum");
handler.startElement("", "", "actacn", attrImpl);
handler.characters(params.get("actacn").toCharArray(), 0, params.get("actacn").length());
handler.endElement("", "", "actacn");
handler.startElement("", "", "type", attrImpl);
handler.characters(params.get("type").toCharArray(), 0, params.get("type").length());
handler.endElement("", "", "type");
handler.startElement("", "", "datescope", attrImpl);
handler.startElement("", "", "from", attrImpl);
handler.characters(params.get("from").toCharArray(), 0, params.get("from").length());
handler.endElement("", "", "from");
handler.startElement("", "", "to", attrImpl);
handler.characters(params.get("to").toCharArray(), 0, params.get("to").length());
handler.endElement("", "", "to");
handler.endElement("", "", "datescope");
handler.startElement("", "", "amountscope", attrImpl);
handler.startElement("", "", "from", attrImpl);
handler.characters(params.get("amountFrom").toCharArray(), 0, params.get("amountFrom").length());
handler.endElement("", "", "from");
handler.startElement("", "", "to", attrImpl);
handler.characters(params.get("amountTo").toCharArray(), 0, params.get("amountTo").length());
handler.endElement("", "", "to");
handler.endElement("", "", "amountscope");
handler.startElement("", "", "begnum", attrImpl);
handler.characters(params.get("begnum").toCharArray(), 0, params.get("begnum").length());
handler.endElement("", "", "begnum");
handler.startElement("", "", "recnum", attrImpl);
handler.characters(params.get("recnum").toCharArray(), 0, params.get("recnum").length());
handler.endElement("", "", "recnum");
handler.startElement("", "", "direction", attrImpl);
handler.characters(params.get("direction").toCharArray(), 0, params.get("direction").length());
handler.endElement("", "", "direction");
handler.endElement("", "", "b2e0035-rq");
handler.endElement("", "", "trn-b2e0035-rq");
handler.endElement("", "", "trans");
handler.endElement("", "", "bocb2e");
// 关闭document
handler.endDocument();
}
public String getXmlString(String xmlFileUrl) {
StringBuilder sb = new StringBuilder();
try {
InputStream inputStream = new FileInputStream(xmlFileUrl);
BufferedReader br=new BufferedReader(new InputStreamReader(inputStream));
String line="";
for(line=br.readLine();line!=null;line=br.readLine()) {
sb.append(line+"\n");
}
} catch (FileNotFoundException e) {
this.writeLog(ServiceName + " e 1 : " + e.getMessage());
} catch (IOException e) {
this.writeLog(ServiceName + " e 2 : " + e.getMessage());
}
return sb.toString();
}
}

View File

@ -0,0 +1,288 @@
package com.api.nonstandardext.zenner.utils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.xml.XMLSerializer;
import org.apache.http.HttpEntity;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
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.BasicCredentialsProvider;
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.general.BaseBean;
import weaver.general.Util;
import java.io.IOException;
/**
*
* -SAP
* @Date: 2022/9/09 10:06
*/
public class SAPWebserviceTool extends BaseBean {
//SAP接口日志表名称
private String Logger_Mode_Table = this.getSystemParamValue("SAPInterface_Logger_Mode_TableName");
//SAP接口日志模块ID
private int Logger_Mode_ID = Util.getIntValue(this.getSystemParamValue("SAPInterface_Logger_Mode_ID"),0);
//获取SAP接口认证头参数值(用户名)
private String authenticator_username = this.getSystemParamValue("SAP_Webservice_Authenticator_Username");
//获取SAP接口认证头参数值(密码)
private String authenticator_password = this.getSystemParamValue("SAP_Webservice_Authenticator_Password");
public String getSystemParamValue(String uuid){
String paramvalue = "";
if(!"".equals(uuid)){
String select_sql = "select paramvalue from uf_systemconfig where uuid = ?";
RecordSet rs = new RecordSet();
rs.executeQuery(select_sql,uuid);
if(rs.next()){
paramvalue = Util.null2String(rs.getString(1));
}
}
return paramvalue;
}
/**
*
*/
public SAPWebserviceTool(){
if("".equals(authenticator_username)){
authenticator_username = this.getSystemParamValue("SAP_Webservice_Authenticator_Username");
}
if("".equals(authenticator_password)){
authenticator_password = this.getSystemParamValue("SAP_Webservice_Authenticator_Password");
}
}
public String callParams_011(String comCode, String period, String year, String glAccount){
String params = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:urn=\"urn:sap-com:document:sap:soap:functions:mc-style\">\n" +
" <soapenv:Header/>\n" +
" <soapenv:Body>\n" +
" <urn:ZoaGlGetglaccperiodbalances>\n" +
" <IvCompCode>$comCode$</IvCompCode>\n" +
" <IvFisPeriod>$period$</IvFisPeriod>\n" +
" <IvFiscYear>$year$</IvFiscYear>\n" +
" <IvGlAccount>$glAccount$</IvGlAccount>\n" +
" </urn:ZoaGlGetglaccperiodbalances>\n" +
" </soapenv:Body>\n" +
"</soapenv:Envelope>";
params = params.replace("$comCode$", comCode);
params = params.replace("$period$", period);
params = params.replace("$year$", year);
params = params.replace("$glAccount$", glAccount);
this.writeLog(" xml params:[" + params.toString() + "]");
return params;
}
/**
* {
* "@xmlns:n0": "urn:sap-com:document:sap:soap:functions:mc-style",
* "EsReturn": {
* "Type": [],
* "Code": [],
* "Message": [],
* "LogNo": [],
* "LogMsgNo": "000000",
* "MessageV1": [],
* "MessageV2": [],
* "MessageV3": [],
* "MessageV4": []
* },
* "EvBalance": "19715385.21",
* "EvCreditPer": "-220.0",
* "EvCurrency": "CNY",
* "EvDebitsPer": "15718007.26",
* "EvPerSales": "15717787.26",
* "EvRc": "S"
* }
* @param params
* @return
*/
public JSONObject callInterface_011(String params){
JSONObject result = new JSONObject();
String webservice_url = this.getSystemParamValue("SAP_OA011_Webservice_URL");//"http://ashca160.minol.org:8004/sap/bc/srt/rfc/sap/zoa_outgoing_document_post1/400/s1/b1";
this.writeLog("xml webservice_url:[" + webservice_url + "]");
this.writeLog("authenticator_username:[" + authenticator_username + "] authenticator_password[" + authenticator_password + "]");
try {
String webservice_result = sendPostData(webservice_url, params, authenticator_username, authenticator_password);
result.put("webservice_result", webservice_result);
this.writeLog("sap webservice_result:[" + webservice_result + "]");
if(null != webservice_result && !"".equals(webservice_result)){
XMLSerializer xmlSerializer = new XMLSerializer();
JSONObject results = (JSONObject) xmlSerializer.read(webservice_result);
JSONObject balanceResponse = results.getJSONObject("soap-env:Body").getJSONObject("n0:ZoaGlGetglaccperiodbalancesResponse");
this.writeLog("balanceResponse toString:[" + balanceResponse.toString() + "]");
String evRc = balanceResponse.getString("EvRc");//返回代码 S 成功,E 错误,W 警告,I 信息,A 中断
if ("S".equals(evRc)){
result.put("balanceResponse", balanceResponse);
} else {
String message = "";
if(isJson(balanceResponse.getString("EtReturn"))){
JSONObject EtReturn = balanceResponse.getJSONObject("EtReturn").getJSONObject("item");
String TYPE = EtReturn.getString("TYPE");
String MESSAGE = EtReturn.getString("MESSAGE");
message = MESSAGE;
}else{
JSONArray EtReturn = balanceResponse.getJSONArray("EtReturn");
for(int k=0;k<EtReturn.size();k++){
JSONObject EtReturnitem = EtReturn.getJSONObject(k);
String TYPE = EtReturnitem.getString("TYPE");
String MESSAGE = EtReturnitem.getString("MESSAGE");
if(!"".equals(MESSAGE)){
message += " " + MESSAGE;
}
}
}
result.put("success",false);
result.put("message",message);
}
}else{
result.put("success",false);
result.put("message","");
}
}catch (Exception e){
this.writeLog("Exception:[" + e.getMessage() + "]");
result.put("success",false);
result.put("message",e.toString()+"/"+e.getMessage());
e.printStackTrace();
} finally {
this.writeLog("resultmap:[" + result + "]");
}
return result;
}
// public String loginEas(String kingdeeHost, org.apache.axis.client.Call call, String USER_NAME, String USER_PASSWORD, String DATACENTER_NAME) {
// WSContext rs = null;
// try {
// call.setTargetEndpointAddress("http://ashca162.minol.org:8006/sap/bc/srt/wsdl/bndg_5914D161EA5B9D2FE100000019011AA2/wsdl11/allinone/ws_policy/document?sap-client=400");
//
// call.setOperationName("login");
// call.setTimeout(Integer.valueOf(1000 * 600000 * 60));
// call.setMaintainSession(true);
//
// String DB_TYPE = "0";
//
// call.addParameter("userName", XMLType.XSD_STRING, ParameterMode.IN);
// call.addParameter("password", XMLType.XSD_STRING, ParameterMode.IN);
// call.addParameter("slnName", XMLType.XSD_STRING, ParameterMode.IN);
// call.addParameter("dcName", XMLType.XSD_STRING, ParameterMode.IN);
// call.addParameter("language", XMLType.XSD_STRING, ParameterMode.IN);
// call.addParameter("dbType", XMLType.XSD_INT, ParameterMode.IN);
// logger.writeLog("kingdeeHost : " + kingdeeHost);
// call.setReturnType(new QName("urn:client", "WSContext"));
// call.setReturnClass(WSContext.class);
// logger.writeLog("DATACENTER_NAME : " + DATACENTER_NAME);
// rs = (WSContext) call.invoke(new Object[]{USER_NAME, USER_PASSWORD, "eas", DATACENTER_NAME, "l2", Integer.valueOf(DB_TYPE)});
// } catch (Exception e) {
// logger.writeLog("exception : " + e.getMessage());
// e.printStackTrace();
// }
// this.writeLog(" loginEas rs : " + rs.getSessionId());
// String sessionId = rs.getSessionId();
// this.writeLog(" loginEas sessionId : " + sessionId);
// return sessionId;
// }
public static boolean isJson(String content) {
try {
JSONObject.fromObject(content);
return true;
} catch (Exception e) {
return false;
}
}
public static boolean isJsonArray(String content) {
try {
JSONArray.fromObject(content);
return true;
} catch (Exception e) {
return false;
}
}
/**
* POST
* @param interface_url
* @return
*/
private String sendPostData(String interface_url,String params, String username, String password) {
String reponsedata = "";
try {
//设置超时时间
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setSocketTimeout(30000)
.setConnectTimeout(30000)
.setConnectionRequestTimeout(30000)
.build();
//使用帮助类HttpClients创建CloseableHttpClient对象
CloseableHttpClient client;
if(!"".equals(username) && !"".equals(password)){
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY,new UsernamePasswordCredentials(username, password));
client = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).setDefaultRequestConfig(defaultRequestConfig).build();
}else{
client = HttpClients.createDefault();
}
//HTTP请求类型创建HttpPost实例
HttpPost post = new HttpPost(interface_url);
//使用addHeader方法添加请求头部,诸如User-Agent, Accept-Encoding等参数.
post.setHeader("Content-Type", "text/xml;charset=UTF-8");
//组织数据
StringEntity se = new StringEntity(params,"UTF-8");
//设置编码格式
se.setContentEncoding("utf-8");
//设置数据类型
se.setContentType("text/xml");
//对于POST请求,把请求体填充进HttpPost实体.
post.setEntity(se);
//通过执行HttpPost请求获取CloseableHttpResponse实例 ,从此CloseableHttpResponse实例中获取状态码,错误信息,以及响应页面等等.
CloseableHttpResponse response = client.execute(post);
int StatusCode = response.getStatusLine().getStatusCode();
this.writeLog("====>>>StatusCode["+StatusCode+"]");
//通过HttpResponse接口的getEntity方法返回响应信息并进行相应的处理
HttpEntity entity = response.getEntity();
reponsedata = EntityUtils.toString(entity);
//最后关闭HttpClient资源.
client.close();
} catch (IOException e) {
this.writeLog("====>>>sendPostData Exception["+e.getMessage() + "/" + e.toString()+"]");
// TODO Auto-generated catch block
e.printStackTrace();
}
return reponsedata;
}
}

View File

@ -0,0 +1,20 @@
package com.api.nonstandardext.zenner.utils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
public class ZennerApiService extends BaseBean {
//通过parambs配置标识查找系统参数配置表获取配置值
public String getSystemConfigValue(String configKey){
String configValue = "";
RecordSet rs = new RecordSet();
String corpSecretSql = "select paramvalue from uf_systemconfig where uuid = '" + configKey + "'";
rs.execute(corpSecretSql);
if (rs.next()){
configValue = Util.null2String(rs.getString("paramvalue"));
}
return configValue;
}
}

View File

@ -0,0 +1,373 @@
package com.api.nonstandardext.zenner.utils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.http.client.utils.DateUtils;
import weaver.general.BaseBean;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import java.io.*;
import java.net.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.Set;
public class ZennerUtil {
public final static SimpleDateFormat formatYYYYMMDDHHMMSS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public final static SimpleDateFormat formatYYYYMMDD = new SimpleDateFormat("yyyy-MM-dd");
public final static SimpleDateFormat formatYYYYMMDD_NoSplit = new SimpleDateFormat("yyyyMMdd");
public static boolean isJsonObject(String content) {
try {
JSONObject.fromObject(content);
return true;
} catch (Exception e) {
return false;
}
}
public static boolean isJsonArray(String content) {
try {
JSONArray.fromObject(content);;
return true;
} catch (Exception e) {
return false;
}
}
public static String parseToDateString(Date date, SimpleDateFormat formatInfo) {
if (date == null) {
return "";
}
return formatInfo.format(date);
}
public static Date parseToDate(String dateString, SimpleDateFormat formatInfo){
try {
return formatInfo.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
public static String httpPostToken(String httpUrl, Map<String, String> headParams, String bodyParams) {
BaseBean log = new BaseBean();
log.writeLog(httpUrl);
log.writeLog(headParams);
log.writeLog(bodyParams);
String result = "";
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod(httpUrl);
Set<String> keySet = headParams.keySet();
for (String key : keySet) {
postMethod.setRequestHeader(key, headParams.get(key));
}
postMethod.setRequestBody(bodyParams);
postMethod.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
log.writeLog(postMethod);
try {
int httpStatus = httpClient.executeMethod(postMethod);
byte[] resultByte = postMethod.getResponseBody();
result = new String(resultByte, "UTF-8");
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public static String proxyHttp(boolean needProxy, String proxyIp, String proxyPort, String userId, String password, String url, String param, String encoding){
OutputStreamWriter out = null;
BufferedReader in = null;
String result = "";
BaseBean logger = new BaseBean();
try {
URL realUrl = new URL(url);
HttpURLConnection conn = null;
if (needProxy){
@SuppressWarnings("static-access")
Proxy proxy = new Proxy(Proxy.Type.DIRECT.HTTP, new InetSocketAddress(proxyIp, Integer.parseInt(proxyPort)));
conn = (HttpURLConnection) realUrl.openConnection(proxy);
} else {
conn = (HttpURLConnection) realUrl.openConnection();
}
logger.writeLog("发送 POST needProxy : " +needProxy);
logger.writeLog("发送 POST conn : " +conn);
logger.writeLog("发送 POST userId : " +userId);
logger.writeLog("发送 POST no proxy : ");
if (needProxy){
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
if (getRequestorType().equals( RequestorType.PROXY )) {
return new PasswordAuthentication(userId, password.toCharArray() );
}
return super.getPasswordAuthentication();
}
});
}
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST"); // POST方法
// 设置通用的请求属性
if (needProxy){
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
}
// conn.setRequestProperty("Authorization", "Basic " + encoding);
logger.writeLog("发送 POST encoding : "+ encoding);
conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
conn.connect();
// 获取URLConnection对象对应的输出流
out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
// 发送请求参数
out.write(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
logger.writeLog("发送 POST line : "+ line);
result += line;
}
logger.writeLog("发送 POST result : "+ result);
} catch (Exception e) {
logger.writeLog("发送 POST 请求出现异常!"+e);
e.printStackTrace();
} finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
// public static String httpsGet(String baseUrl,String encoderNum) {
// BufferedReader in = null;
// BaseBean baseBean = new BaseBean();
// try {
// SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
// javax.net.ssl.TrustManager[] truset = new javax.net.ssl.TrustManager[1];
// javax.net.ssl.TrustManager tm = new DefaultTmForAllist();
// truset[0] = tm;
// sslContext.init(null, truset, null);
// SSLSocketFactory factory = sslContext.getSocketFactory();
// URL u = new URL(baseUrl);
// HttpsURLConnection huconn = (HttpsURLConnection) u.openConnection();
// huconn.setSSLSocketFactory(factory);
// huconn.setRequestProperty("Authorization","Basic " + encoderNum);
// StringBuilder result = new StringBuilder();
// huconn.connect();
//// baseBean.writeLog("httpsGet execute baseUrl..1." + baseUrl);
// in = new BufferedReader(new InputStreamReader(huconn.getInputStream(), "UTF-8"));
// String line;
// while ((line = in.readLine()) != null) {
// result.append(line);
// }
// if (in != null) {
// in.close();
// }
//// baseBean.writeLog("httpsGet execute result..1." + result.toString());
// // 打印返回结果
// return result.toString();
// } catch (Exception e) {
// baseBean.writeLog("httpsGet execute exception...message:" + e.getMessage());
// if (in != null) {
// try {
// in.close();
// } catch (IOException ioException) {
// ioException.printStackTrace();
// baseBean.writeLog("关闭报错");
// baseBean.writeLog(ioException.getMessage());
// }
// }
// return "";
// }
// }
public static String httpGet(String baseUrl){
String url = baseUrl;
try {
URL u = new URL(url);
HttpURLConnection huconn = (HttpURLConnection) u.openConnection();
BufferedReader in = null;
StringBuilder result = new StringBuilder();
huconn.connect();
in = new BufferedReader(new InputStreamReader(huconn.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
if (in != null) {
in.close();
}
return result.toString();
} catch (Exception e) {
return "";
}
}
// public static String httpsPost(String httpUrl, String content) throws Exception {
// BufferedReader in = null;
// SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
// javax.net.ssl.TrustManager [] truset = new javax.net.ssl.TrustManager[1];
// javax.net.ssl.TrustManager tm = new DefaultTmForAllist();
// truset[0] = tm;
// sslContext.init(null,truset,null);
// SSLSocketFactory factory = sslContext.getSocketFactory();
////https://blog.csdn.net/pk5454754/article/details/80092974?utm_medium=distribute.pc_relevant_download.none-task-blog-baidujs-1.nonecase&depth_1-utm_source=distribute.pc_relevant_download.none-task-blog-baidujs-1.nonecase
// URL u = new URL(httpUrl);
// HttpsURLConnection conn = (HttpsURLConnection) u.openConnection();
// conn.setDoOutput(true);
// conn.addRequestProperty("connection", "Keep-Alive");
// conn.setRequestMethod("POST");
// conn.setSSLSocketFactory(factory);
// StringBuilder result = new StringBuilder();
// conn.connect();
// DataOutputStream out = new DataOutputStream(conn.getOutputStream());
// out.write(content.getBytes("utf-8"));
// // 刷新、关闭
// out.flush();
// out.close();
// in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
// String line;
// while ((line = in.readLine()) != null) {
// result.append(line);
// }
// if (in != null) {
// in.close();
// }
// return result.toString();
// }
public static String httpPostForXwwwForm(String httpUrl, Map<String, String> headParams, Map<String, String> paramsMap){
String result = "";
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod(httpUrl);
Set<String> keySet = headParams.keySet();
for (String key : keySet) {
postMethod.setRequestHeader(key, headParams.get(key));
}
Set<String> paramsSet = paramsMap.keySet();
for (String key : paramsSet) {
postMethod.setParameter(key, paramsMap.get(key));
}
postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
try {
int httpStatus = httpClient.executeMethod(postMethod);
byte[] resultByte = postMethod.getResponseBody();
result = new String(resultByte, "UTF-8");
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
*
*/
public static int getQuarter() {
Calendar c = Calendar.getInstance();
int month = c.get(Calendar.MONTH) + 1;
int quarter = 0;
if (month >= 1 && month <= 3) {
quarter = 1;
} else if (month >= 4 && month <= 6) {
quarter = 2;
} else if (month >= 7 && month <= 9) {
quarter = 3;
} else {
quarter = 4;
}
return quarter;
}
/**
* num
*/
public static String[] getCurrQuarter(int num) {
String[] s = new String[2];
String str = "";
// 设置本年的季
Calendar quarterCalendar = null;
switch (num) {
case 1: // 本年到现在经过了一个季度在加上前4个季度
quarterCalendar = Calendar.getInstance();
quarterCalendar.set(Calendar.MONTH, 3);
quarterCalendar.set(Calendar.DATE, 1);
quarterCalendar.add(Calendar.DATE, -1);
str = DateUtils.formatDate(quarterCalendar.getTime(), "yyyy-MM-dd");
s[0] = str.substring(0, str.length() - 5) + "01-01";
s[1] = str;
break;
case 2: // 本年到现在经过了二个季度,在加上前三个季度
quarterCalendar = Calendar.getInstance();
quarterCalendar.set(Calendar.MONTH, 6);
quarterCalendar.set(Calendar.DATE, 1);
quarterCalendar.add(Calendar.DATE, -1);
str = DateUtils.formatDate(quarterCalendar.getTime(), "yyyy-MM-dd");
s[0] = str.substring(0, str.length() - 5) + "04-01";
s[1] = str;
break;
case 3:// 本年到现在经过了三个季度,在加上前二个季度
quarterCalendar = Calendar.getInstance();
quarterCalendar.set(Calendar.MONTH, 9);
quarterCalendar.set(Calendar.DATE, 1);
quarterCalendar.add(Calendar.DATE, -1);
str = DateUtils.formatDate(quarterCalendar.getTime(), "yyyy-MM-dd");
s[0] = str.substring(0, str.length() - 5) + "07-01";
s[1] = str;
break;
case 4:// 本年到现在经过了四个季度,在加上前一个季度
quarterCalendar = Calendar.getInstance();
str = DateUtils.formatDate(quarterCalendar.getTime(), "yyyy-MM-dd");
s[0] = str.substring(0, str.length() - 5) + "10-01";
s[1] = str.substring(0, str.length() - 5) + "12-31";
break;
}
return s;
}
}

View File

@ -0,0 +1,66 @@
package com.api.xuanran.wang.sh_bigdata.sso.controller;
import aiyh.utils.Util;
import aiyh.utils.excention.CustomerException;
import com.alibaba.fastjson.JSONObject;
import com.api.xuanran.wang.sh_bigdata.sso.service.OtherSystemToOAService;
import com.api.xuanran.wang.sh_bigdata.sso.service.impl.OtherSystemToOAServiceImpl;
import com.sun.jersey.api.view.Viewable;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import weaver.integration.util.SessionUtil;
import weaver.xuanran.wang.sh_bigdata.common.util.ShBigDataUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Context;
import java.util.Map;
/**
* <h1>oa</h1>
*
* @author xuanran.wang
* @date 2023/4/17 14:22
*/
@Path("/wxr/sh_big_data/sso")
public class OtherSystemToOAController {
private final Logger log = Util.getLogger();
private final OtherSystemToOAService service = new OtherSystemToOAServiceImpl();
@Path("/login/{appId}")
@GET
public Viewable login(@PathParam("appId") String appId,
@Context HttpServletRequest request,
@Context HttpServletResponse response) {
try {
log.info("appId : " + appId);
String code = Util.null2DefaultStr(request.getParameter("code"),"");
log.info("sso login code : " + code);
if(StringUtils.isBlank(code)){
throw new CustomerException("code is null!");
}
// 获取重定向地址和secret
Map<String, String> redirectUrlAndCorpsecret = service.getRedirectUrlAndCorpsecret(appId);
String redirectUrl = Util.null2DefaultStr(redirectUrlAndCorpsecret.get("REDIRECTURL"),"");
log.info("successSendRedirectUrl : " + redirectUrl);
if(StringUtils.isBlank(redirectUrl)){
throw new CustomerException("redirectUrl is null! " + JSONObject.toJSONString(redirectUrlAndCorpsecret));
}
int userId = service.getUserFromOtherSys(code, redirectUrlAndCorpsecret);
SessionUtil.createSession(userId + "", request, response);
response.sendRedirect(redirectUrl);
}catch (Exception e){
log.error("sso error : " + e.getMessage());
log.error(Util.getErrString(e));
try {
response.sendRedirect(Util.null2DefaultStr(ShBigDataUtil.getPropertiesValByKey("loginErrorSendRedirectUrl"),"/login/login.jsp"));
}catch (Exception ec){
log.error("sendRedirect error " + ec.getMessage());
}
}
return null;
}
}

View File

@ -0,0 +1,44 @@
package com.api.xuanran.wang.sh_bigdata.sso.mapper;
import aiyh.utils.annotation.recordset.ParamMapper;
import aiyh.utils.annotation.recordset.Select;
import aiyh.utils.annotation.recordset.SqlMapper;
import java.util.Map;
/**
* <h1>oa mapper</h1>
*
* @author xuanran.wang
* @date 2023/4/18 09:54
*/
@SqlMapper
public interface OtherSystemToOAMapper {
/**
* <h1>outKeyoa ID</h1>
* @author xuanran.wang
* @dateTime 2023/4/20 11:46
* @param outKey id
* @return oa ID
**/
@Select("select id from hrmresource where outkey = #{outKey}")
int selectUserIdByOutKey(@ParamMapper("outKey") String outKey);
/**
* <h1>appId </h1>
* @author xuanran.wang
* @dateTime 2023/4/20 11:47
* @param appId appId
* @return
**/
@Select("select zydz from uf_AppPortal where zcsjbs = #{appId}")
String selectRedirectUrlByAppId(@ParamMapper("appId") String appId);
/**
* <h1>appId </h1>
* @author xuanran.wang
* @dateTime 2023/4/20 11:47
* @param appId appId
* @return
**/
@Select("select zydz redirectUrl, secret from uf_AppPortal where zcsjbs = #{appId}")
Map<String, String> selectRedirectUrlAndSecretByAppId(@ParamMapper("appId") String appId);
}

View File

@ -0,0 +1,49 @@
package com.api.xuanran.wang.sh_bigdata.sso.service;
import weaver.xuanran.wang.sh_bigdata.common.entity.CusSuccess;
import java.util.Map;
/**
* <h1>oa</h1>
*
* @author xuanran.wang
* @date 2023/4/17 14:27
*/
public interface OtherSystemToOAService {
/**
* <h1>codeid</h1>
* @author xuanran.wang
* @dateTime 2023/4/18 13:29
* @param url
* @param params
* @param headers
* @param cusSuccess /
* @return
**/
int getUserIdByCode(String url, Map<String, Object> params, Map<String, String> headers, CusSuccess cusSuccess, Map<String, String> redirectUrlSecret);
/**
* <h1>codeoaid</h1>
* @author xuanran.wang
* @dateTime 2023/4/18 13:30
* @param code code
* @return oaid
**/
int getUserFromOtherSys(String code, Map<String, String> redirectUrlSecret);
/**
* <h1>appIdoa</h1>
* @author xuanran.wang
* @dateTime 2023/4/20 11:14
* @param appId appId
* @return
**/
String getLoginSuccessSendRedirectUrl(String appId);
/**
* <h1>appIdcorpsecret</h1>
* @author xuanran.wang
* @dateTime 2023/4/20 11:14
* @param appId appId
* @return
**/
Map<String, String> getRedirectUrlAndCorpsecret(String appId);
}

View File

@ -0,0 +1,97 @@
package com.api.xuanran.wang.sh_bigdata.sso.service.impl;
import aiyh.utils.Util;
import aiyh.utils.excention.CustomerException;
import com.alibaba.fastjson.JSONObject;
import com.api.xuanran.wang.sh_bigdata.sso.mapper.OtherSystemToOAMapper;
import com.api.xuanran.wang.sh_bigdata.sso.service.OtherSystemToOAService;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import weaver.xuanran.wang.sh_bigdata.common.entity.CusSuccess;
import weaver.xuanran.wang.sh_bigdata.common.util.RequestMasterPlate;
import weaver.xuanran.wang.sh_bigdata.common.util.ShBigDataUtil;
import java.util.HashMap;
import java.util.Map;
/**
* <h1>oa</h1>
*
* @author xuanran.wang
* @date 2023/4/17 14:35
*/
public class OtherSystemToOAServiceImpl implements OtherSystemToOAService {
private final RequestMasterPlate requestMasterPlate = new RequestMasterPlate();
private final CusSuccess cusSuccess = CusSuccess.builder()
.successField("code")
.successValue(0)
.errorMsg("msg")
.dataKey("data.id")
.build();
private final OtherSystemToOAMapper otherSystemToOAMapper = Util.getMapper(OtherSystemToOAMapper.class);
private final Logger log = Util.getLogger();
@Override
public int getUserIdByCode(String url, Map<String, Object> params, Map<String, String> headers, CusSuccess cusSuccess, Map<String, String> redirectUrlSecret) {
String secret = Util.null2DefaultStr(redirectUrlSecret.get("SECRET"), "");
log.info("secret : " + secret);
if(StringUtils.isBlank(secret)){
throw new CustomerException("secret is null! " + JSONObject.toJSONString(redirectUrlSecret));
}
return requestMasterPlate.apiGet(ShBigDataUtil.addToken2Url(url, secret), params ,new HashMap<>(), cusSuccess);
}
@Override
public int getUserFromOtherSys(String code, Map<String, String> redirectUrlSecret) {
HashMap<String, Object> params = new HashMap<>();
params.put("code", code);
// 获取第三方系统id
String getUserInfoByCodeUrl = ShBigDataUtil.getPropertiesValByKey("getUserInfoByCodeUrl");
int codeId;
try {
codeId = getUserIdByCode(getUserInfoByCodeUrl, params, new HashMap<>(), cusSuccess, redirectUrlSecret);
}catch (Exception e){
String getUserIdDebug = ShBigDataUtil.getPropertiesValByKey("getUserIdDebug");
// 开启调试模式
if("1".equals(getUserIdDebug)){
codeId = Util.getIntValue(ShBigDataUtil.getPropertiesValByKey("getUserIdDebugOutKey"), 109);
log.info("debug codeId : " + codeId);
}else {
throw new CustomerException(e.getMessage());
}
}
if(codeId < 0){
throw new CustomerException(Util.logStr("code : {}, not found in {} .", code, getUserInfoByCodeUrl));
}
int id = otherSystemToOAMapper.selectUserIdByOutKey(codeId + "");
if(id < 0){
throw new CustomerException(Util.logStr("code : {} not found in OA!", id));
}
return id;
}
@Override
public String getLoginSuccessSendRedirectUrl(String appId) {
String defaultUrl = Util.null2DefaultStr(ShBigDataUtil.getPropertiesValByKey("loginSuccessSendRedirectUrl"), "/wui/index.html#/main");
String url = otherSystemToOAMapper.selectRedirectUrlByAppId(appId);
if(StringUtils.isBlank(appId) || StringUtils.isBlank(url)){
return defaultUrl;
}
return url;
}
@Override
public Map<String, String> getRedirectUrlAndCorpsecret(String appId) {
Map<String, String> res = otherSystemToOAMapper.selectRedirectUrlAndSecretByAppId(appId);
if(MapUtils.isEmpty(res)){
throw new CustomerException(Util.logStr("该appId在建模配置中不存在配置!"));
}
long count = res.values().stream().filter(StringUtils::isBlank).count();
if(count > 0){
throw new CustomerException(Util.logStr("该appId查询重定向地址或secret数据为空!: {}", JSONObject.toJSONString(res)));
}
return res;
}
}

View File

@ -71,7 +71,7 @@ public class BatchCreateWorkFlowController {
return ApiResult.success(service.batchCreateWorkflow(user, workflows));
}catch (Exception e){
log.error(Util.logStr("batchCreate error : {}", e.getMessage()));
return ApiResult.error(500,"批量创建流程接口发生异常! 异常信息 :[ " + e.getMessage() + " ]");
return ApiResult.error(500, e.getMessage());
}
}

View File

@ -16,7 +16,7 @@ import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
/**
* <h1></h1>
* <h1></h1>
*
* @author xuanran.wang
* @date 2023/3/1 10:56

View File

@ -37,9 +37,7 @@ public class BatchCreateWorkflowService {
private final Logger log = Util.getLogger();
private static final String CUSTOM_ID = "customId";
// private final MeetingMapper meetingTransMapper = Util.getTransMapper(MeetingMapper.class);
private final MeetingService meetingService = new MeetingService();
/**
* <h1> </h1>
@ -97,7 +95,7 @@ public class BatchCreateWorkflowService {
}
}
if(errors.size() > 0){
throw new CustomerException("创建流程失败!错误参数流程 : \n" + JSONObject.toJSONString(errors));
throw new CustomerException(JSONObject.toJSONString(errors));
}
return res;
}catch (Exception e){

View File

@ -0,0 +1,45 @@
package com.api.xuanran.wang.traffic_bank.email.controller;
import aiyh.utils.ApiResult;
import aiyh.utils.Util;
import com.alibaba.fastjson.JSONObject;
import com.api.xuanran.wang.traffic_bank.email.service.EmailOutSendService;
import com.api.xuanran.wang.traffic_bank.email.service.impl.EmailOutSendServiceImpl;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.Map;
/**
* <h1></h1>
*
* @author xuanran.wang
* @date 2023/4/18 14:11
*/
@Path("/wxr/traffic_bank/email")
public class EmailOutSendController {
private final EmailOutSendService service = new EmailOutSendServiceImpl();
@Path("/send")
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public String sendEmail(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody Map<String, Object> param) {
try {
service.sendEmail(param);
return ApiResult.success(null);
}catch (Exception e){
Util.getLogger().error("EmailOutSendController error " + e.getMessage());
Util.getLogger().error(Util.getErrString(e));
return ApiResult.error("发送邮件异常 : " + e.getMessage());
}
}
}

View File

@ -0,0 +1,17 @@
package com.api.xuanran.wang.traffic_bank.email.entity;
import lombok.Data;
/**
* <h1></h1>
*
* @author xuanran.wang
* @date 2023/4/18 14:23
*/
@Data
public class EmailOutConfigDetail {
private String interfaceField;
private String fieldName;
private String cusStyleClass;
private int mergeCell;
}

View File

@ -0,0 +1,21 @@
package com.api.xuanran.wang.traffic_bank.email.entity;
import lombok.Data;
import java.util.List;
/**
* <h1></h1>
*
* @author xuanran.wang
* @date 2023/4/18 14:17
*/
@Data
public class EmailOutConfigMain {
private int transType;
private String templatePath;
private String emailAddressCusSql;
private int enable;
private String titleField;
private List<EmailOutConfigDetail> configDetailList;
}

View File

@ -0,0 +1,42 @@
package com.api.xuanran.wang.traffic_bank.email.mapper;
import aiyh.utils.annotation.recordset.*;
import com.api.xuanran.wang.traffic_bank.email.entity.EmailOutConfigDetail;
import com.api.xuanran.wang.traffic_bank.email.entity.EmailOutConfigMain;
import weaver.xuanran.wang.sh_bigdata.org_hrm_async.entity.OrgHrmAsyncConfigDetail;
import java.util.List;
import java.util.Map;
/**
* <h1>mapper</h1>
*
* @author xuanran.wang
* @date 2023/4/18 14:26
*/
@SqlMapper
public interface EmailOutSendMapper {
@Select("select * from uf_email_out_config where trans_type = #{transType}")
@CollectionMappings({
@CollectionMapping(property = "configDetailList",
column = "id",
id = @Id(value = Integer.class, methodId = 1))
})
EmailOutConfigMain selectConfigByTypeId(@ParamMapper("transType") int transType);
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2023/3/1 16:39
* @param mainId id
* @return
**/
@Select("select * from uf_email_out_config_dt1 where mainid = #{mainId}")
@CollectionMethod(1)
List<EmailOutConfigDetail> selectConfigDetail(@ParamMapper("mainId") int mainId);
@Select(custom = true)
String selectCustomerSql(@SqlString String sql, Map<String, Object> map);
}

View File

@ -0,0 +1,17 @@
package com.api.xuanran.wang.traffic_bank.email.service;
import com.api.xuanran.wang.traffic_bank.email.entity.EmailOutConfigMain;
import java.util.List;
import java.util.Map;
/**
* <h1></h1>
*
* @author xuanran.wang
* @date 2023/4/18 14:15
*/
public interface EmailOutSendService {
EmailOutConfigMain selectConfigByTransType(int type);
void sendEmail(Map<String, Object> params);
}

View File

@ -0,0 +1,120 @@
package com.api.xuanran.wang.traffic_bank.email.service.impl;
import aiyh.utils.Util;
import aiyh.utils.excention.CustomerException;
import com.alibaba.fastjson.JSONObject;
import com.api.xuanran.wang.traffic_bank.email.entity.EmailOutConfigDetail;
import com.api.xuanran.wang.traffic_bank.email.entity.EmailOutConfigMain;
import com.api.xuanran.wang.traffic_bank.email.mapper.EmailOutSendMapper;
import com.api.xuanran.wang.traffic_bank.email.service.EmailOutSendService;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import weaver.email.EmailWorkRunnable;
import java.util.*;
/**
* <h1></h1>
*
* @author xuanran.wang
* @date 2023/4/18 14:33
*/
public class EmailOutSendServiceImpl implements EmailOutSendService {
private final EmailOutSendMapper emailOutSendMapper = Util.getMapper(EmailOutSendMapper.class);
private final Logger log = Util.getLogger();
@Override
public EmailOutConfigMain selectConfigByTransType(int type) {
EmailOutConfigMain configMain = emailOutSendMapper.selectConfigByTypeId(type);
Assert.notNull(configMain, Util.logStr("type= {}, not found config in uf_email_out_config!", type));
List<EmailOutConfigDetail> configDetailList = configMain.getConfigDetailList();
Assert.notEmpty(configDetailList, Util.logStr("type= {}, not found config in uf_email_out_config_dt1!", type));
return configMain;
}
@Override
public void sendEmail(Map<String, Object> param) {
int type = Util.getIntValue(Util.null2DefaultStr(param.get("type"), ""), -1);
EmailOutConfigMain outConfigMain = selectConfigByTransType(type);
List<Map<String, Object>> data = (List<Map<String, Object>>) param.get("data");
Map<String, Object> map = convertConfigToMail(outConfigMain, data);
List<String> addressList = (List<String>) map.get("address");
String title = Util.null2DefaultStr(map.get("title"),"");
String email = Util.null2DefaultStr(map.get("email"), "");
log.info("sendEmailInfo => \n " + JSONObject.toJSONString(map));
if(CollectionUtils.isEmpty(addressList)){
log.error("address is empty!");
return;
}
for (String address : addressList) {
EmailWorkRunnable workRunnable = new EmailWorkRunnable(address, title, email);
if(!workRunnable.emailCommonRemind()){
throw new CustomerException(Util.logStr("发送邮件失败! 邮件地址: {}, 标题: {}, 内容: {}",address, title, email));
}
}
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2023/4/19 11:05
* @param outConfigMain
* @param params
* @return map
**/
public Map<String, Object> convertConfigToMail(EmailOutConfigMain outConfigMain, List<Map<String, Object>> params){
List<EmailOutConfigDetail> detailConfig = outConfigMain.getConfigDetailList();
String title = "";
String titleField = Util.null2DefaultStr(outConfigMain.getTitleField(),"");
String emailAddressCusSql = outConfigMain.getEmailAddressCusSql();
String sql = Util.sbc2dbcCase(emailAddressCusSql);
List<String> emailList = new ArrayList<>();
StringBuilder sb = new StringBuilder();
int size = 0;
// 表头
for (EmailOutConfigDetail detail : detailConfig) {
sb.append("<td>").append(detail.getFieldName()).append("</td>");
size++;
}
sb.append("</tr>");
for (Map<String, Object> param : params) {
sb.append("<tr>");
for (EmailOutConfigDetail detail : detailConfig) {
int mergeCell = detail.getMergeCell();
if(mergeCell > 0){
sb.append("<td ")
.append(" colspan=\"")
.append(mergeCell)
.append("\"").append(">");
sb.append(Util.null2DefaultStr(param.get(detail.getInterfaceField()),""));
}else {
sb.append("<td>").append(Util.null2DefaultStr(param.get(detail.getInterfaceField()),""));
}
sb.append("</td>");
}
sb.append("</tr>");
String email = emailOutSendMapper.selectCustomerSql(sql, param);
if(StringUtils.isNotBlank(email)){
emailList.add(email);
}
if(StringUtils.isNotBlank(titleField)){
title = Util.null2DefaultStr(param.get(titleField),"");
}
}
String html = outConfigMain.getTemplatePath();
html = html
.replace("\n"," ")
.replace("\t"," ")
.replace("{tableInfo}", sb.toString())
.replace("{?data.size}", size + "")
.replace("{?title}", title);
Map<String, Object> email = new HashMap<>();
email.put("title", title);
email.put("email", html);
email.put("address", emailList);
return email;
}
}

View File

@ -0,0 +1,324 @@
package com.engine.hrm.cmd.departmentfielddefined;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.cloudstore.dev.api.util.TextUtil;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.biz.EncryptConfigBiz;
import com.engine.common.entity.BizLogContext;
import com.engine.common.entity.EncryptFieldEntity;
import com.engine.common.enums.EncryptMould;
import com.engine.core.interceptor.CommandContext;
import org.apache.log4j.Logger;
import weaver.bokang.xiao.tbxc.mapper.FormFieldMapper;
import weaver.conn.RecordSet;
import weaver.general.LabelUtil;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.hrm.definedfield.HrmDeptFieldManagerE9;
import weaver.hrm.definedfield.HrmFieldComInfo;
import weaver.matrix.MatrixUtil;
import weaver.systeminfo.SystemEnv;
import weaver.workflow.field.BrowserComInfo;
/**
*
* @author lvyi
*
*/
public class GetFieldDefinedCmd extends AbstractCommonCommand<Map<String, Object>> {
private final FormFieldMapper formFieldMapper = aiyh.utils.Util.getMapper(FormFieldMapper.class);
private final Logger log = aiyh.utils.Util.getLogger();
public GetFieldDefinedCmd(Map<String, Object> params, User user) {
this.user = user;
this.params = params;
}
@Override
public Map<String, Object> execute(CommandContext commandContext) {
Map<String, Object> retmap = new HashMap<String, Object>();
List<Map<String, Object>> lsFieldInfo = new ArrayList<Map<String, Object>>();
Map<String, Object> fieldInfo = null;
Map<String, Object> recordInfo = null;
Map<String, Object> propsInfo = null;
Map<String, Object> comInfo = null;
List<Object> fieldTypeInfo = null;
List<Object> lsComDetialInfo = null;
Map<String, Object> comDetialInfo = null;
try {
if (!HrmUserVarify.checkUserRight("DeptDefineInfo1:DeptMaintain1", user)) {
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage()));
return retmap;
}
int groupId = Util.getIntValue((String)params.get("groupId"));
boolean encryptEnable = EncryptConfigBiz.getEncryptEnable(EncryptMould.HRM.getCode());
int scopeId = 5;
BrowserComInfo BrowserComInfo = new BrowserComInfo();
HrmFieldComInfo HrmFieldComInfo = new HrmFieldComInfo();
HrmDeptFieldManagerE9 hfm = new HrmDeptFieldManagerE9(scopeId);
List lsGroup = hfm.getLsGroup();
lsGroup = hfm.getLsGroup();
int idx = 0;
boolean canDel = false;
for (int i = 0; lsGroup != null && i < lsGroup.size(); i++) {
String groupid = (String) lsGroup.get(i);
List lsField = hfm.getLsField(groupid);
if(!groupid.equals(""+groupId)){
continue;
}
if (lsField.size() == 0)
continue;
for (int j = 0; lsField != null && j < lsField.size(); j++) {
String fieldid = (String) lsField.get(j);
String issystem = HrmFieldComInfo.getIssystem(fieldid);
String fieldname = HrmFieldComInfo.getFieldname(fieldid);
boolean isUsed = false;
if (issystem.equals("1")) {
isUsed = true;
} else {
isUsed = hfm.getIsUsed(fieldid, fieldname);
}
String fieldlabel = HrmFieldComInfo.getLabel(fieldid);
String fieldfdbtype = HrmFieldComInfo.getFielddbtype(fieldid);
String fieldhtmltype = HrmFieldComInfo.getFieldhtmltype(fieldid);
String fieldtype = HrmFieldComInfo.getFieldType(fieldid);
String fielddmlurl = HrmFieldComInfo.getFieldDmlurl(fieldid);
String fieldstrlength = hfm.getStrLength(fieldfdbtype, fieldhtmltype, fieldtype);
String allowhide = HrmFieldComInfo.getAllowhide(fieldid);
String isUse = HrmFieldComInfo.getIsused(fieldid);
String isMand = HrmFieldComInfo.getIsmand(fieldid);
String dsporder = HrmFieldComInfo.getDsporder(fieldid);
String textheight = ""+HrmFieldComInfo.getTextheight(fieldid);
//判断人力资源类型 字段是否通过矩阵被流程引用
boolean isUsed_ = false;
if (fieldtype.equals("1") || fieldtype.equals("17")) {
isUsed_ = MatrixUtil.isUsed(fieldname, "2");
if (isUsed_)
isUsed = isUsed_;
}
List<Object> fieldTypeObj = new ArrayList<Object>();
String fieldType = "";
if (fieldhtmltype.equals("1")) {
fieldTypeObj.add("input");
fieldType = SystemEnv.getHtmlLabelName(688, user.getLanguage());
if (fieldhtmltype.equals("1")) {
if (fieldtype.equals("1")) {
fieldTypeObj.add("text");
fieldType += " " + SystemEnv.getHtmlLabelName(608, user.getLanguage());
fieldType += " " + SystemEnv.getHtmlLabelName(608, user.getLanguage()) + ":" + fieldstrlength;
fieldTypeObj.add(fieldstrlength);
} else if (fieldtype.equals("2")) {
fieldTypeObj.add("int");
fieldType += " " + SystemEnv.getHtmlLabelName(696, user.getLanguage());
} else if (fieldtype.equals("3")) {
fieldTypeObj.add("float");
fieldType += " " + SystemEnv.getHtmlLabelName(697, user.getLanguage());
}
}
} else if (fieldhtmltype.equals("2")) {
fieldTypeObj.add("textarea");
fieldType = SystemEnv.getHtmlLabelName(689, user.getLanguage());
//fieldType += " " + SystemEnv.getHtmlLabelName(689, user.getLanguage())+textheight+" "+(fieldtype.equals("1")?"":"");
} else if (fieldhtmltype.equals("3")) {
fieldTypeObj.add("browser");
List<Object> replaceDatas = new ArrayList<Object>();
Map<String, Object> tmp = new HashMap<String, Object>();
tmp.put("value", fieldtype);
tmp.put("valueSpan", SystemEnv.getHtmlLabelName(Util.getIntValue(BrowserComInfo.getBrowserlabelid(fieldtype), 0), user.getLanguage()));
Map<String, Object> tmp1 = new HashMap<String, Object>();
tmp1.put("id", fieldtype);
tmp1.put("name", SystemEnv.getHtmlLabelName(Util.getIntValue(BrowserComInfo.getBrowserlabelid(fieldtype), 0), user.getLanguage()));
replaceDatas.add(tmp1);
tmp.put("replaceDatas", replaceDatas);
fieldTypeObj.add(tmp);
if(fieldtype.equals("161")||fieldtype.equals("162") || fieldtype.equals("256") || fieldtype.equals("257")){
tmp = new HashMap<String, Object>();
tmp.put("value", fielddmlurl);
tmp.put("valueSpan", getName(fielddmlurl));
fieldTypeObj.add(tmp);
}
fieldType = SystemEnv.getHtmlLabelName(695, user.getLanguage());
fieldType += " " + SystemEnv.getHtmlLabelName(Util.getIntValue(BrowserComInfo.getBrowserlabelid(fieldtype), 0), user.getLanguage());
if ("emptyVal".equals(fielddmlurl) || "".equals(fielddmlurl)) {
} else {
fieldType += " " + getName(fielddmlurl);
}
} else if (fieldhtmltype.equals("4")) {
fieldTypeObj.add("check");
fieldType = SystemEnv.getHtmlLabelName(691, user.getLanguage());
} else if (fieldhtmltype.equals("5")) {
fieldTypeObj.add("select");
fieldTypeObj.add("select");
List<Object> datas = new ArrayList<Object>();
Map<String, Object> tmp = new HashMap<String, Object>();
Map<String, Object> data = null;
RecordSet rs = new RecordSet();
rs.executeSql("select selectvalue, selectname, isdefault, cancel from hrm_selectitem where fieldid=" + fieldid + " order by listorder");
int key = 0;
while (rs.next()) {
data = new HashMap<String, Object>();
data.put("option", rs.getString("selectname"));
data.put("default", rs.getString("isdefault"));
data.put("unuse", rs.getString("cancel"));
datas.add(data);
}
tmp.put("datas", datas);
tmp.put("sort", "horizontal");
fieldTypeObj.add(tmp);
fieldType = SystemEnv.getHtmlLabelName(690, user.getLanguage());
} else if (fieldhtmltype.equals("6")) {
fieldTypeObj.add("upload");
fieldTypeObj.add("file");
fieldType = SystemEnv.getHtmlLabelName(17616, user.getLanguage());
fieldType += " " + SystemEnv.getHtmlLabelName(20798, user.getLanguage());
//fieldType += " " + (fieldtype.equals("1") ? SystemEnv.getHtmlLabelName(20798, user.getLanguage()) : SystemEnv.getHtmlLabelName(20001, user.getLanguage()));
}
fieldInfo = new HashMap<String, Object>();
recordInfo = new HashMap<String, Object>();
recordInfo.put("id", fieldid);
recordInfo.put("fieldlabel", TextUtil.toBase64ForMultilang(new LabelUtil().getMultiLangLabel(fieldlabel)));
recordInfo.put("fieldname", fieldname);
recordInfo.put("fieldType", fieldType);
recordInfo.put("fieldTypeObj", fieldTypeObj);
recordInfo.put("enable", isUse);
recordInfo.put("required", isMand);
recordInfo.put("viewAttr", isUsed || issystem.equals("1") ? 1 : 2);
recordInfo.put("key", dsporder);
//分部或部门时查询对应是否可编辑字段 update by bokang.xiao
log.info(String.format("查询对应字段信息 ==> groupId:%s fieldId:%s",groupId,fieldid));
if(groupId == 6 || groupId == 7) {
recordInfo.put("isEdit", formFieldMapper.queryIsEdit(fieldid, groupId));
}
log.info("recordInfo ==>"+ JSON.toJSONString(recordInfo));
if (encryptEnable && ((fieldhtmltype.equals("1")||fieldhtmltype.equals("2")) && !issystem.equals("1")) ) {
//只支持单行文本,多行文本
String tablename = "hrmdepartmentdefined";
EncryptFieldEntity encryptFieldEntity = EncryptConfigBiz.getFieldEncryptConfig(tablename,fieldname);
recordInfo.put("encryptId", encryptFieldEntity!=null?encryptFieldEntity.getId():"");
recordInfo.put("tablename", tablename);
recordInfo.put("canEncrypt", "1");
}
fieldInfo.put("record", recordInfo);
propsInfo = new HashMap<String, Object>();
Map<String, Object> checkPropsInfo = new HashMap<String, Object>();
Map<String, Object> checkPropsDetialInfo = null;
checkPropsDetialInfo = new HashMap<String, Object>();
checkPropsDetialInfo.put("viewAttr", allowhide.equals("1") ? 2 : 1);
checkPropsInfo.put("enable", checkPropsDetialInfo);
checkPropsInfo.put("required", checkPropsDetialInfo);
propsInfo.put("checkProps", checkPropsInfo);
fieldInfo.put("props", propsInfo);
comInfo = new HashMap<String, Object>();
lsComDetialInfo = new ArrayList<Object>();
comDetialInfo = new HashMap<String, Object>();
comDetialInfo.put("label", "");
comDetialInfo.put("type", "INPUT");
comDetialInfo.put("width", "15%");
comDetialInfo.put("key", "fieldlabel");
comDetialInfo.put("viewAttr", "3");
lsComDetialInfo.add(comDetialInfo);
comInfo.put("fieldlabel", lsComDetialInfo);
lsComDetialInfo = new ArrayList<Object>();
comDetialInfo = new HashMap<String, Object>();
comDetialInfo.put("label", "");
comDetialInfo.put("type", "TEXT");
comDetialInfo.put("width", "15%");
comDetialInfo.put("key", "fieldname");
comDetialInfo.put("viewAttr", "3");
lsComDetialInfo.add(comDetialInfo);
comInfo.put("fieldname", lsComDetialInfo);
lsComDetialInfo = new ArrayList<Object>();
comDetialInfo = new HashMap<String, Object>();
comDetialInfo.put("label", "");
comDetialInfo.put("type", fieldhtmltype.equals("5") ? "CUSTOMFIELD" : "TEXT");
comDetialInfo.put("width", "60%");
comDetialInfo.put("key", "fieldType");
lsComDetialInfo.add(comDetialInfo);
comInfo.put("fieldType", lsComDetialInfo);
fieldInfo.put("com", comInfo);
fieldTypeInfo = new ArrayList<Object>();
fieldTypeInfo.add("select");
fieldTypeInfo.add("select");
Map<String, Object> fieldTypeParamInfo = new HashMap<String, Object>();
List<Object> lsFieldTypeParamDetialInfo = new ArrayList<Object>();
Map<String, Object> fieldTypeParamDetialInfo = null;
if (fieldhtmltype.equals("5")) {
//hfm.getSelectItem(fieldid);
RecordSet rs = new RecordSet();
rs.executeSql("select selectvalue, selectname, isdefault, cancel from hrm_selectitem where fieldid=" + fieldid + " order by listorder");
int key = 0;
while (rs.next()) {
fieldTypeParamDetialInfo = new HashMap<String, Object>();
fieldTypeParamDetialInfo.put("key", key++);
fieldTypeParamDetialInfo.put("id", rs.getString("selectvalue"));
fieldTypeParamDetialInfo.put("option", rs.getString("selectname"));
fieldTypeParamDetialInfo.put("default", rs.getString("isdefault"));
fieldTypeParamDetialInfo.put("unuse", rs.getString("cancel"));
lsFieldTypeParamDetialInfo.add(fieldTypeParamDetialInfo);
}
fieldTypeParamInfo.put("datas", lsFieldTypeParamDetialInfo);
fieldTypeParamInfo.put("sort", "horizontal");
fieldTypeInfo.add(fieldTypeParamInfo);
fieldInfo.put("fieldType", fieldTypeInfo);
}
lsFieldInfo.add(fieldInfo);
}
}
retmap.put("status", "1");
retmap.put("data", lsFieldInfo);
retmap.put("encryptEnable",encryptEnable);
} catch (Exception e) {
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(382661, user.getLanguage()));
writeLog(e);
}
return retmap;
}
private String getName(String showname) {
RecordSet rs = new RecordSet();
if (showname != null && !"".equals(showname)) {
//兼容老数据如果id有moduleid则去掉
int index = showname.indexOf(".");
if (index > 0) {
showname = showname.substring(index + 1);
}
String sql = "select name from datashowset where showname='" + showname + "'";
rs.executeSql(sql);
if (rs.next()) {
return Util.null2String(rs.getString("name"));
}
}
return "";
}
@Override
public BizLogContext getLogContext() {
// TODO Auto-generated method stub
return null;
}
}

View File

@ -0,0 +1,302 @@
package com.engine.hrm.cmd.departmentfielddefined;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.biz.SimpleBizLogger;
import com.engine.common.constant.BizLogSmallType4Hrm;
import com.engine.common.constant.BizLogType;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.hrm.entity.FieldBean;
import com.engine.hrm.entity.FieldSelectOptionBean;
import com.engine.hrm.util.HrmUtil;
import org.apache.log4j.Logger;
import weaver.bokang.xiao.tbxc.mapper.FormFieldMapper;
import weaver.conn.RecordSet;
import weaver.docs.docs.FieldParam;
import weaver.general.LabelUtil;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.hrm.common.database.dialect.DialectUtil;
import weaver.hrm.definedfield.HrmDeptFieldManagerE9;
import weaver.hrm.definedfield.HrmFieldComInfo;
import weaver.matrix.MatrixUtil;
import weaver.systeminfo.SystemEnv;
/**
*
* @author lvyi
*
*/
public class SaveFieldDefinedCmd extends AbstractCommonCommand<Map<String, Object>>{
private SimpleBizLogger logger;
private final Logger log = aiyh.utils.Util.getLogger();
private final FormFieldMapper formFieldMapper = aiyh.utils.Util.getMapper(FormFieldMapper.class);
public SaveFieldDefinedCmd(Map<String, Object> params, User user) {
this.user = user;
this.params = params;
RecordSet rs = new RecordSet();
String sql = "";
String data = Util.null2String(params.get("data"));
JSONObject jsonObj = JSON.parseObject(data);
String groupId = Util.null2String(jsonObj.get("groupId"));
this.logger = new SimpleBizLogger();
BizLogContext bizLogContext = new BizLogContext();
bizLogContext.setLogType(BizLogType.HRM_ENGINE);//模块类型
bizLogContext.setBelongType(BizLogSmallType4Hrm.HRM_ENGINE_DEPARTMENTFIELDDEFINED);//所属大类型
bizLogContext.setLogSmallType(BizLogSmallType4Hrm.HRM_ENGINE_DEPARTMENTFIELDDEFINED);//当前小类型
bizLogContext.setParams(params);//当前request请求参数
logger.setUser(user);//当前操作人
String mainSql = "SELECT a.*, b.labelname FROM hrm_fieldgroup a, htmllabelinfo b WHERE a.grouplabel= b.indexid and a.id= "+groupId+" and b.languageid="+user.getLanguage();
logger.setMainSql(mainSql,"id");//主表sql
logger.setMainPrimarykey("id");//主日志表唯一key
logger.setMainTargetNameColumn("labelname");//当前targetName对应的列对应日志中的对象名
SimpleBizLogger.SubLogInfo subLogInfo = logger.getNewSubLogInfo();
String subSql = "SELECT * FROM hrm_formfield WHERE groupid = "+groupId;
subLogInfo.setSubSql(subSql,"fieldid");
logger.addSubLogInfo(subLogInfo);
logger.before(bizLogContext);
}
@Override
public Map<String, Object> execute(CommandContext commandContext) {
Map<String, Object> retmap = new HashMap<String, Object>();
RecordSet rs = new RecordSet();
HrmFieldComInfo HrmFieldComInfo = new HrmFieldComInfo();
String sql = "";
try {
if(!HrmUserVarify.checkUserRight("DeptDefineInfo1:DeptMaintain1",user)) {
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage()));
return retmap;
}
String data = Util.null2String(params.get("data"));
JSONObject jsonObj = JSON.parseObject(data);
String groupId = Util.null2String(jsonObj.get("groupId"));
String groupType = "";
sql = "SELECT grouptype FROM hrm_fieldgroup WHERE id="+groupId;
rs.executeSql(sql);
if(rs.next()){
groupType = rs.getString("groupType");
}
List<String> listFieldLabel = new ArrayList<String>();
List<String> listFieldName = new ArrayList<String>();
sql = " SELECT fieldlabel FROM hrm_formfield WHERE groupid IN (SELECT id FROM hrm_fieldgroup WHERE grouptype = "+groupType+") and groupid not in("+groupId+")";
rs.executeQuery(sql);
while(rs.next()){
listFieldLabel.add(SystemEnv.getHtmlLabelNames(rs.getString("fieldlabel"), user.getLanguage()));
}
sql = " SELECT fieldname FROM hrm_formfield WHERE groupid IN (SELECT id FROM hrm_fieldgroup WHERE grouptype = "+groupType+") and groupid not in("+groupId+")";
rs.executeQuery(sql);
while(rs.next()){
listFieldName.add(rs.getString("fieldname").toLowerCase());
}
JSONArray records = (JSONArray)jsonObj.get("records");
for(int i=0; i<records.size();i++){
FieldBean fieldBean = (FieldBean) JSONObject.toJavaObject((JSONObject)records.get(i), FieldBean.class);
listFieldLabel.add(Util.formatMultiLang(Util.null2String(fieldBean.getFieldlabel()),""+user.getLanguage()));
listFieldName.add(Util.null2String(fieldBean.getFieldname()).toLowerCase());
}
if(listFieldLabel.size() != new HashSet<String>(listFieldLabel).size()||
listFieldName.size() != new HashSet<String>(listFieldName).size()){
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(383055, user.getLanguage()));
return retmap;
}
for(int i=0; i<records.size();i++){
FieldBean fieldBean = (FieldBean) JSONObject.toJavaObject((JSONObject)records.get(i), FieldBean.class);
fieldBean.initFieldType("department");
//部门和分部添加自定义字段时多一个列属性 update by bokang.xiao
log.info("save department groupId ==>"+groupId);
if("6".equals(groupId) || "7".equals(groupId)){
this.save(fieldBean,groupId,records.getJSONObject(i));
}else {
this.save(fieldBean, groupId);
}
}
HrmFieldComInfo.removeFieldCache();
//同步部门数据到矩阵
MatrixUtil.sysDepartmentData();
retmap.put("status", "1");
} catch (Exception e) {
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(382661,user.getLanguage()));
writeLog(e);
}
return retmap;
}
/**
* <h2></h2>
* @author bokang.xiao
* @param fieldBean
* @param groupId id
* @param fieldJson JSON
*/
private void save(FieldBean fieldBean, String groupId,JSONObject fieldJson){
try {
HrmUtil hrmUtil = new HrmUtil();
HrmDeptFieldManagerE9 hfm = new HrmDeptFieldManagerE9(5);
String fieldId = Util.null2String(fieldBean.getId());
String fieldLabel = Util.null2String(fieldBean.getFieldlabel());
String fieldName = Util.null2String(fieldBean.getFieldname());
String fieldHtmlType = "";
String type = "";
String typeDetial = "";
String dmlUrl = "";
if(fieldBean.getFieldTypeBean()!=null){
fieldHtmlType = Util.null2String(fieldBean.getFieldTypeBean().getFieldHtmlType());
type = Util.null2String(fieldBean.getFieldTypeBean().getFieldType());
if(fieldHtmlType.equals("1")||fieldHtmlType.equals("2")){
typeDetial = Util.null2String(fieldBean.getFieldTypeBean().getOtherParam());
}else if(fieldHtmlType.equals("66") || fieldHtmlType.equals("67")){
dmlUrl = Util.null2String(fieldBean.getFieldTypeBean().getOtherParam());
} else if (type.equals("161") || type.equals("162") || type.equals("256")|| type.equals("257")) {
dmlUrl = Util.null2String(fieldBean.getFieldTypeBean().getOtherParam());
}
}
String isUse = Util.null2String(fieldBean.getEnable(),"0");
String isMand = Util.null2String(fieldBean.getRequired(),"0");
String fieldOrder = Util.null2String(fieldBean.getKey());
int temId = Util.getIntValue(fieldId,-1);
//int lableid = hrmUtil.getFieldLabelId(fieldLabel);
int lableid = new LabelUtil().getLabelId(fieldLabel);
if(Util.null2String(fieldId).length()==0){
FieldParam fp = new FieldParam();
if(fieldHtmlType.equals("1")){
fp.setSimpleText(Util.getIntValue(type,-1),typeDetial);
}else if(fieldHtmlType.equals("2")){
fp.setText();
}else if(fieldHtmlType.equals("3")){
fp.setBrowser(Util.getIntValue(type,-1));
}else if(fieldHtmlType.equals("4")){
fp.setCheck();
}else if(fieldHtmlType.equals("5")){
fp.setSelect();
}else if(fieldHtmlType.equals("6")){
fp.setAttach();
}
temId = hfm.addField(fieldName, fp.getFielddbtype(), fieldHtmlType, type, ""+lableid, fieldOrder, isMand, isUse, groupId, dmlUrl);
//添加字段值isEdit
String isEdit = Util.null2String(fieldJson.getString("isEdit"),"1");
formFieldMapper.updateHrmFormField(isEdit,temId+"",groupId);
}else{
//只允许更改显示属性,数据库层面的不允许修改
hfm.editField(fieldId, ""+lableid, fieldOrder, isMand, isUse, groupId);
//添加字段值isEdit
String isEdit = Util.null2String(fieldJson.getString("isEdit"),"1");
formFieldMapper.updateHrmFormField(isEdit,fieldId,groupId);
}
if(fieldHtmlType.equals("5")){
List<FieldSelectOptionBean> lsSelectOption = fieldBean.getFieldTypeBean().getLsSelectOption();
hfm.checkSelectField(temId, lsSelectOption);
}
}catch (Exception e) {
writeLog(e);
}
}
private void save(FieldBean fieldBean, String groupId){
try {
HrmUtil hrmUtil = new HrmUtil();
HrmDeptFieldManagerE9 hfm = new HrmDeptFieldManagerE9(5);
String fieldId = Util.null2String(fieldBean.getId());
String fieldLabel = Util.null2String(fieldBean.getFieldlabel());
String fieldName = Util.null2String(fieldBean.getFieldname());
String fieldHtmlType = "";
String type = "";
String typeDetial = "";
String dmlUrl = "";
if(fieldBean.getFieldTypeBean()!=null){
fieldHtmlType = Util.null2String(fieldBean.getFieldTypeBean().getFieldHtmlType());
type = Util.null2String(fieldBean.getFieldTypeBean().getFieldType());
if(fieldHtmlType.equals("1")||fieldHtmlType.equals("2")){
typeDetial = Util.null2String(fieldBean.getFieldTypeBean().getOtherParam());
}else if(fieldHtmlType.equals("66") || fieldHtmlType.equals("67")){
dmlUrl = Util.null2String(fieldBean.getFieldTypeBean().getOtherParam());
} else if (type.equals("161") || type.equals("162") || type.equals("256")|| type.equals("257")) {
dmlUrl = Util.null2String(fieldBean.getFieldTypeBean().getOtherParam());
}
}
String isUse = Util.null2String(fieldBean.getEnable(),"0");
String isMand = Util.null2String(fieldBean.getRequired(),"0");
String fieldOrder = Util.null2String(fieldBean.getKey());
int temId = Util.getIntValue(fieldId,-1);
//int lableid = hrmUtil.getFieldLabelId(fieldLabel);
int lableid = new LabelUtil().getLabelId(fieldLabel);
if(Util.null2String(fieldId).length()==0){
FieldParam fp = new FieldParam();
if(fieldHtmlType.equals("1")){
fp.setSimpleText(Util.getIntValue(type,-1),typeDetial);
}else if(fieldHtmlType.equals("2")){
fp.setText();
}else if(fieldHtmlType.equals("3")){
fp.setBrowser(Util.getIntValue(type,-1));
}else if(fieldHtmlType.equals("4")){
fp.setCheck();
}else if(fieldHtmlType.equals("5")){
fp.setSelect();
}else if(fieldHtmlType.equals("6")){
fp.setAttach();
}
temId = hfm.addField(fieldName, fp.getFielddbtype(), fieldHtmlType, type, ""+lableid, fieldOrder, isMand, isUse, groupId, dmlUrl);
}else{
//只允许更改显示属性,数据库层面的不允许修改
hfm.editField(fieldId, ""+lableid, fieldOrder, isMand, isUse, groupId);
}
if(fieldHtmlType.equals("5")){
List<FieldSelectOptionBean> lsSelectOption = fieldBean.getFieldTypeBean().getLsSelectOption();
hfm.checkSelectField(temId, lsSelectOption);
}
}catch (Exception e) {
writeLog(e);
}
}
@Override
public BizLogContext getLogContext() {
return null;
}
@Override
public List<BizLogContext> getLogContexts() {
return logger.getBizLogContexts();
}
}

View File

@ -0,0 +1,199 @@
package com.engine.hrm.cmd.organization;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import weaver.bokang.xiao.tbxc.mapper.FormFieldMapper;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.definedfield.HrmDeptFieldManager;
import weaver.hrm.definedfield.HrmDeptFieldManagerE9;
import weaver.hrm.definedfield.HrmFieldComInfo;
import weaver.hrm.definedfield.HrmFieldGroupComInfo;
import weaver.systeminfo.SystemEnv;
import com.api.browser.bean.SearchConditionItem;
import com.api.hrm.bean.HrmFieldBean;
import com.api.hrm.util.HrmFieldSearchConditionComInfo;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.hrm.util.HrmOrganizationUtil;
public class GetDepartmentFormFieldCmd extends AbstractCommonCommand<Map<String, Object>> {
private final FormFieldMapper formFieldMapper = aiyh.utils.Util.getMapper(FormFieldMapper.class);
public GetDepartmentFormFieldCmd(Map<String, Object> params, User user) {
this.user = user;
this.params = params;
}
@Override
public Map<String, Object> execute(CommandContext commandContext) {
Map<String, Object> retmap = new HashMap<String, Object>();
List<Map<String, Object>> grouplist = new ArrayList<Map<String, Object>>();
Map<String, Object> groupitem = null;
List<Object> itemlist = null;
try {
String id = Util.null2String(params.get("id"));
int viewattr = Util.getIntValue((String)params.get("viewattr"),1);
String nodeType = Util.null2String(params.get("type"));
String addType = Util.null2String(params.get("addType"));
DepartmentComInfo departmentComInfo = new DepartmentComInfo();
String subcompanyid1 = "";
String supdepid = "";
if(addType.equals("normal")){
if(nodeType.equals("subcompany")){
subcompanyid1 = id;
}else{
subcompanyid1 = departmentComInfo.getSubcompanyid1(id);
}
}else if(addType.equals("sibling")){
subcompanyid1 = departmentComInfo.getSubcompanyid1(id);
supdepid = departmentComInfo.getDepartmentsupdepid(id);
}else if(addType.equals("child")){
subcompanyid1 = departmentComInfo.getSubcompanyid1(id);
supdepid = id;
}
HrmFieldGroupComInfo HrmFieldGroupComInfo = new HrmFieldGroupComInfo();
HrmFieldComInfo HrmFieldComInfo = new HrmFieldComInfo();
HrmFieldSearchConditionComInfo hrmFieldSearchConditionComInfo = new HrmFieldSearchConditionComInfo();
SearchConditionItem searchConditionItem = null;
HrmFieldBean hrmFieldBean = null;
HrmDeptFieldManagerE9 hfm = new HrmDeptFieldManagerE9(5);
hfm.isReturnDecryptData(true);
hfm.getCustomData(Util.getIntValue(id));
List lsGroup = hfm.getLsGroup();
for (int tmp = 0; lsGroup != null && tmp < lsGroup.size(); tmp++) {
String groupid = (String) lsGroup.get(tmp);
List lsField = hfm.getLsField(groupid);
//if (lsField.size() == 0) continue;
//if (hfm.getGroupCount(lsField) == 0) continue;
//if(!Util.null2String(HrmFieldGroupComInfo.getIsShow(groupid)).equals("1"))continue;
boolean groupHide = lsField.size() == 0 || hfm.getGroupCount(lsField) == 0 || !Util.null2String(HrmFieldGroupComInfo.getIsShow(groupid)).equals("1");
String grouplabel = HrmFieldGroupComInfo.getLabel(groupid);
itemlist = new ArrayList<Object>();
groupitem = new HashMap<String, Object>();
groupitem.put("title", SystemEnv.getHtmlLabelNames(grouplabel, user.getLanguage()));
groupitem.put("hide", groupHide);
groupitem.put("defaultshow", true);
for (int j = 0; lsField != null && j < lsField.size(); j++) {
String fieldid = (String) lsField.get(j);
//分部或部门时查询对应是否可编辑字段,若不可编辑则直接不展示此字段 update by bokang.xiao
String isEdit = formFieldMapper.queryIsEdit(fieldid, Util.getIntValue(groupid));
if("0".equals(isEdit) || "".equals(isEdit)){
continue;
}
String fieldname = HrmFieldComInfo.getFieldname(fieldid);
String isuse = HrmFieldComInfo.getIsused(fieldid);
if (!isuse.equals("1"))continue;
int tmpViewattr = viewattr;
String rules = "";
String fieldlabel = HrmFieldComInfo.getLabel(fieldid);
String fieldhtmltype = HrmFieldComInfo.getFieldhtmltype(fieldid);
String type = HrmFieldComInfo.getFieldType(fieldid);
String dmlurl = Util.null2String(HrmFieldComInfo.getFieldDmlurl(fieldid));
String fieldValue = "";
if(addType.length()>0) {
}else {
if (HrmFieldComInfo.getIssystem(fieldid).equals("1")) {
fieldValue = hfm.getData(fieldname);
} else {
fieldValue = hfm.getData("hrmdepartmentdefined", fieldname);
}
}
if(!groupHide && tmpViewattr==2&&HrmFieldComInfo.getIsmand(fieldid).equals("1")){
tmpViewattr=3;
if("1".equals(fieldhtmltype) && "2".equals(type)){
rules = "required|integer";
}else{
rules = "required|string";
}
}
if(subcompanyid1.length()>0 && fieldname.equals("subcompanyid1")){
fieldValue = subcompanyid1;
}
if(supdepid.length()>0 && fieldname.equals("supdepid")){
fieldValue = supdepid;
}
if(fieldname.equals("showid")){
if(addType.length()>0){
continue;
}else{
fieldValue = id;
tmpViewattr = 1;
}
}
hrmFieldBean = new HrmFieldBean();
hrmFieldBean.setFieldid(fieldid);
hrmFieldBean.setFieldname(fieldname);
hrmFieldBean.setFieldlabel(fieldlabel);
hrmFieldBean.setFieldhtmltype(fieldhtmltype);
hrmFieldBean.setType(type);
hrmFieldBean.setIsFormField(true);
hrmFieldBean.setIssystem("1");
hrmFieldBean.setFieldvalue(fieldValue);
hrmFieldBean.setDmlurl(dmlurl);
hrmFieldBean.setViewAttr(tmpViewattr);
hrmFieldBean.setRules(rules);
if(hrmFieldBean.getFieldname().equals("subcompanyid1")||hrmFieldBean.getFieldname().equals("supdepid")){
hrmFieldBean.setHideVirtualOrg(true);
}
if(hrmFieldBean.getFieldname().equals("departmentcode")){
hrmFieldBean.setMultilang(false);
}
searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user);
if(searchConditionItem!=null){
searchConditionItem.setLabelcol(8);
searchConditionItem.setFieldcol(16);
}
if(fieldname.equals("showorder")){
searchConditionItem.setPrecision(2);
}
if(fieldname.equals("showid")){
Map<String, Object> otherParams = new HashMap<String, Object>();
otherParams.put("hasBorder", true);
searchConditionItem.setOtherParams(otherParams);
}
if("6".equals(fieldhtmltype)){//附件
Map<String, Object> otherParams1 = new HashMap<String, Object>();
otherParams1.put("showOrder", false);
searchConditionItem.setOtherParams(otherParams1);
}
itemlist.add(searchConditionItem);
}
groupitem.put("items", itemlist);
grouplist.add(groupitem);
}
retmap.put("status", "1");
retmap.put("id", id);
retmap.put("titleInfo", HrmOrganizationUtil.getTitleInfo(id, "department", user));
retmap.put("formField", grouplist);
} 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;
}
}

View File

@ -0,0 +1,195 @@
package com.engine.hrm.cmd.organization;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import weaver.bokang.xiao.tbxc.mapper.FormFieldMapper;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.company.SubCompanyComInfo;
import weaver.hrm.definedfield.HrmDeptFieldManager;
import weaver.hrm.definedfield.HrmDeptFieldManagerE9;
import weaver.hrm.definedfield.HrmFieldComInfo;
import weaver.hrm.definedfield.HrmFieldGroupComInfo;
import weaver.systeminfo.SystemEnv;
import com.api.browser.bean.SearchConditionItem;
import com.api.hrm.bean.HrmFieldBean;
import com.api.hrm.util.HrmFieldSearchConditionComInfo;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.hrm.util.HrmOrganizationUtil;
public class GetSubCompanyFormFieldCmd extends AbstractCommonCommand<Map<String, Object>> {
private final FormFieldMapper formFieldMapper = aiyh.utils.Util.getMapper(FormFieldMapper.class);
public GetSubCompanyFormFieldCmd(Map<String, Object> params, User user) {
this.user = user;
this.params = params;
}
@Override
public Map<String, Object> execute(CommandContext commandContext) {
Map<String, Object> retmap = new HashMap<String, Object>();
List<Map<String, Object>> grouplist = new ArrayList<Map<String, Object>>();
Map<String, Object> groupitem = null;
List<Object> itemlist = null;
try {
String id = Util.null2String(params.get("id"));
int viewattr = Util.getIntValue((String)params.get("viewattr"),1);
String addType = Util.null2String(params.get("addType"));
SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo();
String supsubcomid = "";
if(addType.equals("sibling")){
supsubcomid = subCompanyComInfo.getSupsubcomid(id);
}else if(addType.equals("child")){
supsubcomid = id;
}
if(addType.length()>0){
id = "";
}
HrmFieldGroupComInfo HrmFieldGroupComInfo = new HrmFieldGroupComInfo();
HrmFieldComInfo HrmFieldComInfo = new HrmFieldComInfo();
HrmFieldSearchConditionComInfo hrmFieldSearchConditionComInfo = new HrmFieldSearchConditionComInfo();
SearchConditionItem searchConditionItem = null;
HrmFieldBean hrmFieldBean = null;
HrmDeptFieldManagerE9 hfm = new HrmDeptFieldManagerE9(4);
hfm.isReturnDecryptData(true);
hfm.getCustomData(Util.getIntValue(id));
List lsGroup = hfm.getLsGroup();
for (int tmp = 0; lsGroup != null && tmp < lsGroup.size(); tmp++) {
String groupid = (String) lsGroup.get(tmp);
List lsField = hfm.getLsField(groupid);
//if (lsField.size() == 0) continue;
//if (hfm.getGroupCount(lsField) == 0) continue;
//if(!Util.null2String(HrmFieldGroupComInfo.getIsShow(groupid)).equals("1"))continue;
boolean groupHide = lsField.size() == 0 || hfm.getGroupCount(lsField) == 0 || !Util.null2String(HrmFieldGroupComInfo.getIsShow(groupid)).equals("1");
String grouplabel = HrmFieldGroupComInfo.getLabel(groupid);
itemlist = new ArrayList<Object>();
groupitem = new HashMap<String, Object>();
groupitem.put("title", SystemEnv.getHtmlLabelNames(grouplabel, user.getLanguage()));
groupitem.put("hide", groupHide);
groupitem.put("defaultshow", true);
for (int j = 0; lsField != null && j < lsField.size(); j++) {
String fieldid = (String) lsField.get(j);
//分部或部门时查询对应是否可编辑字段,若不可编辑则直接不展示此字段 update by bokang.xiao
String isEdit = formFieldMapper.queryIsEdit(fieldid, Util.getIntValue(groupid));
if("0".equals(isEdit) || "".equals(isEdit)){
continue;
}
String fieldname = HrmFieldComInfo.getFieldname(fieldid);
String isuse = HrmFieldComInfo.getIsused(fieldid);
if (!isuse.equals("1"))continue;
int tmpViewattr = viewattr;
String rules = "";
String fieldlabel = HrmFieldComInfo.getLabel(fieldid);
String fieldhtmltype = HrmFieldComInfo.getFieldhtmltype(fieldid);
String type = HrmFieldComInfo.getFieldType(fieldid);
String dmlurl = Util.null2String(HrmFieldComInfo.getFieldDmlurl(fieldid));
String fieldValue = "";
if(addType.length()>0) {
}else{
if (HrmFieldComInfo.getIssystem(fieldid).equals("1")) {
fieldValue = hfm.getData(fieldname);
} else {
fieldValue = hfm.getData("hrmsubcompanydefined", fieldname);
}
}
if(!groupHide && tmpViewattr==2&&HrmFieldComInfo.getIsmand(fieldid).equals("1")){
tmpViewattr=3;
if("1".equals(fieldhtmltype) && "2".equals(type)){
rules = "required|integer";
}else{
rules = "required|string";
}
}
if ("84".equals(fieldid)) {
if (user.getUID() != 1)
continue;
fieldValue = fieldValue.equals("0") ? "" : fieldValue;
}
if(supsubcomid.length()>0 && fieldname.equals("supsubcomid")){
fieldValue = supsubcomid;
}
if(fieldname.equals("subshowid")){
if(addType.length()>0){
continue;
}else{
fieldValue = id;
tmpViewattr = 1;
}
}
hrmFieldBean = new HrmFieldBean();
hrmFieldBean.setFieldid(fieldid);
hrmFieldBean.setFieldname(fieldname);
hrmFieldBean.setFieldlabel(fieldlabel);
hrmFieldBean.setFieldhtmltype(fieldhtmltype);
hrmFieldBean.setType(type);
hrmFieldBean.setIsFormField(true);
hrmFieldBean.setFieldvalue(fieldValue);
hrmFieldBean.setDmlurl(dmlurl);
hrmFieldBean.setViewAttr(tmpViewattr);
hrmFieldBean.setRules(rules);
hrmFieldBean.setIssystem("1");
if(hrmFieldBean.getFieldname().equals("supsubcomid")){
hrmFieldBean.setHideVirtualOrg(true);
}
if(hrmFieldBean.getFieldname().equals("subcompanycode")) {
hrmFieldBean.setMultilang(false);
}
searchConditionItem = hrmFieldSearchConditionComInfo.getSearchConditionItem(hrmFieldBean, user);
if(searchConditionItem!=null){
searchConditionItem.setLabelcol(8);
searchConditionItem.setFieldcol(16);
}
if(hrmFieldBean.getFieldname().equals("showorder")){
searchConditionItem.setPrecision(2);
}
if(fieldname.equals("subshowid")){
Map<String, Object> otherParams = new HashMap<String, Object>();
otherParams.put("hasBorder", true);
searchConditionItem.setOtherParams(otherParams);
}
if("6".equals(fieldhtmltype)){//附件
Map<String, Object> otherParams1 = new HashMap<String, Object>();
otherParams1.put("showOrder", false);
searchConditionItem.setOtherParams(otherParams1);
}
itemlist.add(searchConditionItem);
}
groupitem.put("items", itemlist);
grouplist.add(groupitem);
}
retmap.put("status", "1");
retmap.put("id", id);
retmap.put("titleInfo", HrmOrganizationUtil.getTitleInfo(id, "subcompany", user));
retmap.put("formField", grouplist);
} 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;
}
}

View File

@ -0,0 +1,325 @@
package com.engine.hrm.cmd.subcompanyfielddefined;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.cloudstore.dev.api.util.TextUtil;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.biz.EncryptConfigBiz;
import com.engine.common.entity.BizLogContext;
import com.engine.common.entity.EncryptFieldEntity;
import com.engine.common.enums.EncryptMould;
import com.engine.core.interceptor.CommandContext;
import org.apache.log4j.Logger;
import weaver.bokang.xiao.tbxc.mapper.FormFieldMapper;
import weaver.conn.RecordSet;
import weaver.general.LabelUtil;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.hrm.definedfield.HrmDeptFieldManagerE9;
import weaver.hrm.definedfield.HrmFieldComInfo;
import weaver.matrix.MatrixUtil;
import weaver.systeminfo.SystemEnv;
import weaver.workflow.field.BrowserComInfo;
/**
*
* @author lvyi
*
*/
public class GetFieldDefinedCmd extends AbstractCommonCommand<Map<String, Object>> {
private final FormFieldMapper formFieldMapper = aiyh.utils.Util.getMapper(FormFieldMapper.class);
private final Logger log = aiyh.utils.Util.getLogger();
public GetFieldDefinedCmd(Map<String, Object> params, User user) {
this.user = user;
this.params = params;
}
@Override
public Map<String, Object> execute(CommandContext commandContext) {
Map<String, Object> retmap = new HashMap<String, Object>();
List<Map<String, Object>> lsFieldInfo = new ArrayList<Map<String, Object>>();
Map<String, Object> fieldInfo = null;
Map<String, Object> recordInfo = null;
Map<String, Object> propsInfo = null;
Map<String, Object> comInfo = null;
List<Object> fieldTypeInfo = null;
List<Object> lsComDetialInfo = null;
Map<String, Object> comDetialInfo = null;
try {
if (!HrmUserVarify.checkUserRight("SubCompanyDefineInfo1:SubMaintain1", user)) {
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage()));
return retmap;
}
int groupId = Util.getIntValue((String)params.get("groupId"));
boolean encryptEnable = EncryptConfigBiz.getEncryptEnable(EncryptMould.HRM.getCode());
int scopeId = 4;
BrowserComInfo BrowserComInfo = new BrowserComInfo();
HrmFieldComInfo HrmFieldComInfo = new HrmFieldComInfo();
HrmDeptFieldManagerE9 hfm = new HrmDeptFieldManagerE9(scopeId);
List lsGroup = hfm.getLsGroup();
lsGroup = hfm.getLsGroup();
int idx = 0;
boolean canDel = false;
for (int i = 0; lsGroup != null && i < lsGroup.size(); i++) {
String groupid = (String) lsGroup.get(i);
List lsField = hfm.getLsField(groupid);
if(!groupid.equals(""+groupId)){
continue;
}
if (lsField.size() == 0)
continue;
for (int j = 0; lsField != null && j < lsField.size(); j++) {
String fieldid = (String) lsField.get(j);
String issystem = HrmFieldComInfo.getIssystem(fieldid);
String fieldname = HrmFieldComInfo.getFieldname(fieldid);
boolean isUsed = false;
if (issystem.equals("1")) {
isUsed = true;
} else {
isUsed = hfm.getIsUsed(fieldid, fieldname);
}
String fieldlabel = HrmFieldComInfo.getLabel(fieldid);
String fieldfdbtype = HrmFieldComInfo.getFielddbtype(fieldid);
String fieldhtmltype = HrmFieldComInfo.getFieldhtmltype(fieldid);
String fieldtype = HrmFieldComInfo.getFieldType(fieldid);
String fielddmlurl = HrmFieldComInfo.getFieldDmlurl(fieldid);
String fieldstrlength = hfm.getStrLength(fieldfdbtype, fieldhtmltype, fieldtype);
String allowhide = HrmFieldComInfo.getAllowhide(fieldid);
String isUse = HrmFieldComInfo.getIsused(fieldid);
String isMand = HrmFieldComInfo.getIsmand(fieldid);
String dsporder = HrmFieldComInfo.getDsporder(fieldid);
String textheight = ""+HrmFieldComInfo.getTextheight(fieldid);
//判断人力资源类型 字段是否通过矩阵被流程引用
boolean isUsed_ = false;
if (fieldtype.equals("1") || fieldtype.equals("17")) {
isUsed_ = MatrixUtil.isUsed(fieldname, "1");
if (isUsed_)
isUsed = isUsed_;
}
List<Object> fieldTypeObj = new ArrayList<Object>();
String fieldType = "";
if (fieldhtmltype.equals("1")) {
fieldTypeObj.add("input");
fieldType = SystemEnv.getHtmlLabelName(688, user.getLanguage());
if (fieldhtmltype.equals("1")) {
if (fieldtype.equals("1")) {
fieldTypeObj.add("text");
fieldType += " " + SystemEnv.getHtmlLabelName(608, user.getLanguage());
fieldType += " " + SystemEnv.getHtmlLabelName(608, user.getLanguage()) + ":" + fieldstrlength;
fieldTypeObj.add(fieldstrlength);
} else if (fieldtype.equals("2")) {
fieldTypeObj.add("int");
fieldType += " " + SystemEnv.getHtmlLabelName(696, user.getLanguage());
} else if (fieldtype.equals("3")) {
fieldTypeObj.add("float");
fieldType += " " + SystemEnv.getHtmlLabelName(697, user.getLanguage());
}
}
} else if (fieldhtmltype.equals("2")) {
fieldTypeObj.add("textarea");
fieldType = SystemEnv.getHtmlLabelName(689, user.getLanguage());
//fieldType += " " + SystemEnv.getHtmlLabelName(689, user.getLanguage())+textheight+" "+(fieldtype.equals("1")?"":"");
} else if (fieldhtmltype.equals("3")) {
fieldTypeObj.add("browser");
List<Object> replaceDatas = new ArrayList<Object>();
Map<String, Object> tmp = new HashMap<String, Object>();
tmp.put("value", fieldtype);
tmp.put("valueSpan", SystemEnv.getHtmlLabelName(Util.getIntValue(BrowserComInfo.getBrowserlabelid(fieldtype), 0), user.getLanguage()));
Map<String, Object> tmp1 = new HashMap<String, Object>();
tmp1.put("id", fieldtype);
tmp1.put("name", SystemEnv.getHtmlLabelName(Util.getIntValue(BrowserComInfo.getBrowserlabelid(fieldtype), 0), user.getLanguage()));
replaceDatas.add(tmp1);
tmp.put("replaceDatas", replaceDatas);
fieldTypeObj.add(tmp);
if(fieldtype.equals("161")||fieldtype.equals("162") || fieldtype.equals("256") || fieldtype.equals("257")){
tmp = new HashMap<String, Object>();
tmp.put("value", fielddmlurl);
tmp.put("valueSpan", getName(fielddmlurl));
fieldTypeObj.add(tmp);
}
fieldType = SystemEnv.getHtmlLabelName(695, user.getLanguage());
fieldType += " " + SystemEnv.getHtmlLabelName(Util.getIntValue(BrowserComInfo.getBrowserlabelid(fieldtype), 0), user.getLanguage());
if ("emptyVal".equals(fielddmlurl) || "".equals(fielddmlurl)) {
} else {
fieldType += " " + getName(fielddmlurl);
}
} else if (fieldhtmltype.equals("4")) {
fieldTypeObj.add("check");
fieldType = SystemEnv.getHtmlLabelName(691, user.getLanguage());
} else if (fieldhtmltype.equals("5")) {
fieldTypeObj.add("select");
fieldTypeObj.add("select");
List<Object> datas = new ArrayList<Object>();
Map<String, Object> tmp = new HashMap<String, Object>();
Map<String, Object> data = null;
RecordSet rs = new RecordSet();
rs.executeSql("select selectvalue, selectname, isdefault, cancel from hrm_selectitem where fieldid=" + fieldid + " order by listorder");
int key = 0;
while (rs.next()) {
data = new HashMap<String, Object>();
data.put("option", rs.getString("selectname"));
data.put("default", rs.getString("isdefault"));
data.put("unuse", rs.getString("cancel"));
datas.add(data);
}
tmp.put("datas", datas);
tmp.put("sort", "horizontal");
fieldTypeObj.add(tmp);
fieldType = SystemEnv.getHtmlLabelName(690, user.getLanguage());
} else if (fieldhtmltype.equals("6")) {
fieldTypeObj.add("upload");
fieldTypeObj.add("file");
fieldType = SystemEnv.getHtmlLabelName(17616, user.getLanguage());
fieldType += " " + SystemEnv.getHtmlLabelName(20798, user.getLanguage());
//fieldType += " " + (fieldtype.equals("1") ? SystemEnv.getHtmlLabelName(20798, user.getLanguage()) : SystemEnv.getHtmlLabelName(20001, user.getLanguage()));
}
fieldInfo = new HashMap<String, Object>();
recordInfo = new HashMap<String, Object>();
recordInfo.put("id", fieldid);
recordInfo.put("fieldlabel", TextUtil.toBase64ForMultilang(new LabelUtil().getMultiLangLabel(fieldlabel)));
recordInfo.put("fieldname", fieldname);
recordInfo.put("fieldType", fieldType);
recordInfo.put("fieldTypeObj", fieldTypeObj);
recordInfo.put("enable", isUse);
recordInfo.put("required", isMand);
recordInfo.put("viewAttr", isUsed || issystem.equals("1") ? 1 : 2);
recordInfo.put("key", dsporder);
//分部或部门时查询对应是否可编辑字段 update by bokang.xiao
log.info(String.format("查询对应字段信息 ==> groupId:%s fieldId:%s",groupId,fieldid));
if(groupId == 6 || groupId == 7) {
recordInfo.put("isEdit", formFieldMapper.queryIsEdit(fieldid, groupId));
}
log.info("recordInfo ==>"+ JSON.toJSONString(recordInfo));
if (encryptEnable && ((fieldhtmltype.equals("1")||fieldhtmltype.equals("2")) && !issystem.equals("1")) ) {
//只支持单行文本,多行文本
String tablename = "hrmsubcompanydefined";
EncryptFieldEntity encryptFieldEntity = EncryptConfigBiz.getFieldEncryptConfig(tablename,fieldname);
recordInfo.put("encryptId", encryptFieldEntity!=null?encryptFieldEntity.getId():"");
recordInfo.put("tablename", tablename);
recordInfo.put("canEncrypt", "1");
}
fieldInfo.put("record", recordInfo);
propsInfo = new HashMap<String, Object>();
Map<String, Object> checkPropsInfo = new HashMap<String, Object>();
Map<String, Object> checkPropsDetialInfo = null;
checkPropsDetialInfo = new HashMap<String, Object>();
checkPropsDetialInfo.put("viewAttr", allowhide.equals("1") ? 2 : 1);
checkPropsInfo.put("enable", checkPropsDetialInfo);
checkPropsInfo.put("required", checkPropsDetialInfo);
propsInfo.put("checkProps", checkPropsInfo);
fieldInfo.put("props", propsInfo);
comInfo = new HashMap<String, Object>();
lsComDetialInfo = new ArrayList<Object>();
comDetialInfo = new HashMap<String, Object>();
comDetialInfo.put("label", "");
comDetialInfo.put("type", "INPUT");
comDetialInfo.put("width", "15%");
comDetialInfo.put("key", "fieldlabel");
comDetialInfo.put("viewAttr", 3);
lsComDetialInfo.add(comDetialInfo);
comInfo.put("fieldlabel", lsComDetialInfo);
lsComDetialInfo = new ArrayList<Object>();
comDetialInfo = new HashMap<String, Object>();
comDetialInfo.put("label", "");
comDetialInfo.put("type", "TEXT");
comDetialInfo.put("width", "15%");
comDetialInfo.put("key", "fieldname");
comDetialInfo.put("viewAttr", 3);
lsComDetialInfo.add(comDetialInfo);
comInfo.put("fieldname", lsComDetialInfo);
lsComDetialInfo = new ArrayList<Object>();
comDetialInfo = new HashMap<String, Object>();
comDetialInfo.put("label", "");
comDetialInfo.put("type", fieldhtmltype.equals("5") ? "CUSTOMFIELD" : "TEXT");
comDetialInfo.put("width", "60%");
comDetialInfo.put("key", "fieldType");
lsComDetialInfo.add(comDetialInfo);
comInfo.put("fieldType", lsComDetialInfo);
fieldInfo.put("com", comInfo);
fieldTypeInfo = new ArrayList<Object>();
fieldTypeInfo.add("select");
fieldTypeInfo.add("select");
Map<String, Object> fieldTypeParamInfo = new HashMap<String, Object>();
List<Object> lsFieldTypeParamDetialInfo = new ArrayList<Object>();
Map<String, Object> fieldTypeParamDetialInfo = null;
if (fieldhtmltype.equals("5")) {
//hfm.getSelectItem(fieldid);
RecordSet rs = new RecordSet();
rs.executeSql("select selectvalue, selectname, isdefault, cancel from hrm_selectitem where fieldid=" + fieldid + " order by listorder");
int key = 0;
while (rs.next()) {
fieldTypeParamDetialInfo = new HashMap<String, Object>();
fieldTypeParamDetialInfo.put("key", key++);
fieldTypeParamDetialInfo.put("id", rs.getString("selectvalue"));
fieldTypeParamDetialInfo.put("option", rs.getString("selectname"));
fieldTypeParamDetialInfo.put("default", rs.getString("isdefault"));
fieldTypeParamDetialInfo.put("unuse", rs.getString("cancel"));
lsFieldTypeParamDetialInfo.add(fieldTypeParamDetialInfo);
}
fieldTypeParamInfo.put("datas", lsFieldTypeParamDetialInfo);
fieldTypeParamInfo.put("sort", "horizontal");
fieldTypeInfo.add(fieldTypeParamInfo);
fieldInfo.put("fieldType", fieldTypeInfo);
}
lsFieldInfo.add(fieldInfo);
}
}
retmap.put("status", "1");
retmap.put("data", lsFieldInfo);
retmap.put("encryptEnable",encryptEnable);
} catch (Exception e) {
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(382661, user.getLanguage()));
writeLog(e);
}
return retmap;
}
private String getName(String showname) {
RecordSet rs = new RecordSet();
if (showname != null && !"".equals(showname)) {
//兼容老数据如果id有moduleid则去掉
int index = showname.indexOf(".");
if (index > 0) {
showname = showname.substring(index + 1);
}
String sql = "select name from datashowset where showname='" + showname + "'";
rs.executeSql(sql);
if (rs.next()) {
return Util.null2String(rs.getString("name"));
}
}
return "";
}
@Override
public BizLogContext getLogContext() {
// TODO Auto-generated method stub
return null;
}
}

View File

@ -0,0 +1,300 @@
package com.engine.hrm.cmd.subcompanyfielddefined;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.biz.SimpleBizLogger;
import com.engine.common.constant.BizLogSmallType4Hrm;
import com.engine.common.constant.BizLogType;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.hrm.entity.FieldBean;
import com.engine.hrm.entity.FieldSelectOptionBean;
import com.engine.hrm.util.HrmUtil;
import org.apache.log4j.Logger;
import weaver.bokang.xiao.tbxc.mapper.FormFieldMapper;
import weaver.conn.RecordSet;
import weaver.docs.docs.FieldParam;
import weaver.general.LabelUtil;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.hrm.common.database.dialect.DialectUtil;
import weaver.hrm.definedfield.HrmDeptFieldManagerE9;
import weaver.hrm.definedfield.HrmFieldComInfo;
import weaver.matrix.MatrixUtil;
import weaver.systeminfo.SystemEnv;
/**
*
* @author lvyi
*
*/
public class SaveFieldDefinedCmd extends AbstractCommonCommand<Map<String, Object>>{
private final FormFieldMapper formFieldMapper = aiyh.utils.Util.getMapper(FormFieldMapper.class);
private final Logger log = aiyh.utils.Util.getLogger();
private SimpleBizLogger logger;
public SaveFieldDefinedCmd(Map<String, Object> params, User user) {
this.user = user;
this.params = params;
RecordSet rs = new RecordSet();
String sql = "";
String data = Util.null2String(params.get("data"));
JSONObject jsonObj = JSON.parseObject(data);
String groupId = Util.null2String(jsonObj.get("groupId"));
this.logger = new SimpleBizLogger();
BizLogContext bizLogContext = new BizLogContext();
bizLogContext.setLogType(BizLogType.HRM_ENGINE);//模块类型
bizLogContext.setBelongType(BizLogSmallType4Hrm.HRM_ENGINE_SUBCOMPANYFIELDDEFINED);//所属大类型
bizLogContext.setLogSmallType(BizLogSmallType4Hrm.HRM_ENGINE_SUBCOMPANYFIELDDEFINED);//当前小类型
bizLogContext.setParams(params);//当前request请求参数
logger.setUser(user);//当前操作人
String mainSql = "SELECT a.*, b.labelname FROM hrm_fieldgroup a, htmllabelinfo b WHERE a.grouplabel= b.indexid and a.id= "+groupId+" and b.languageid="+user.getLanguage();
logger.setMainSql(mainSql,"id");//主表sql
logger.setMainPrimarykey("id");//主日志表唯一key
logger.setMainTargetNameColumn("labelname");//当前targetName对应的列对应日志中的对象名
SimpleBizLogger.SubLogInfo subLogInfo = logger.getNewSubLogInfo();
String subSql = "SELECT * FROM hrm_formfield WHERE groupid = "+groupId;
subLogInfo.setSubSql(subSql,"fieldid");
logger.addSubLogInfo(subLogInfo);
logger.before(bizLogContext);
}
@Override
public Map<String, Object> execute(CommandContext commandContext) {
Map<String, Object> retmap = new HashMap<String, Object>();
RecordSet rs = new RecordSet();
HrmFieldComInfo HrmFieldComInfo = new HrmFieldComInfo();
String sql = "";
try {
if(!HrmUserVarify.checkUserRight("SubCompanyDefineInfo1:SubMaintain1",user)) {
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(2012, user.getLanguage()));
return retmap;
}
String data = Util.null2String(params.get("data"));
JSONObject jsonObj = JSON.parseObject(data);
String groupId = Util.null2String(jsonObj.get("groupId"));
String groupType = "";
sql = "SELECT grouptype FROM hrm_fieldgroup WHERE id="+groupId;
rs.executeSql(sql);
if(rs.next()){
groupType = rs.getString("groupType");
}
List<String> listFieldLabel = new ArrayList<String>();
List<String> listFieldName = new ArrayList<String>();
sql = " SELECT fieldlabel FROM hrm_formfield WHERE groupid IN (SELECT id FROM hrm_fieldgroup WHERE grouptype = "+groupType+") and groupid not in("+groupId+")";
rs.executeQuery(sql);
while(rs.next()){
listFieldLabel.add(SystemEnv.getHtmlLabelNames(rs.getString("fieldlabel"), user.getLanguage()));
}
sql = " SELECT fieldname FROM hrm_formfield WHERE groupid IN (SELECT id FROM hrm_fieldgroup WHERE grouptype = "+groupType+") and groupid not in("+groupId+")";
rs.executeQuery(sql);
while(rs.next()){
listFieldName.add(rs.getString("fieldname").toLowerCase());
}
JSONArray records = (JSONArray)jsonObj.get("records");
for(int i=0; i<records.size();i++){
FieldBean fieldBean = (FieldBean) JSONObject.toJavaObject((JSONObject)records.get(i), FieldBean.class);
listFieldLabel.add(Util.formatMultiLang(Util.null2String(fieldBean.getFieldlabel()),""+user.getLanguage()));
listFieldName.add(Util.null2String(fieldBean.getFieldname()).toLowerCase());
}
System.out.print(listFieldLabel.toString());
if(listFieldLabel.size() != new HashSet<String>(listFieldLabel).size()||
listFieldName.size() != new HashSet<String>(listFieldName).size()){
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(383055, user.getLanguage()));
return retmap;
}
for(int i=0; i<records.size();i++){
FieldBean fieldBean = (FieldBean) JSONObject.toJavaObject((JSONObject)records.get(i), FieldBean.class);
fieldBean.initFieldType("subcompany");
//部门和分部添加自定义字段时多一个列属性 update by bokang.xiao
log.info("save subCompany groupId ==>"+groupId);
if("6".equals(groupId) || "7".equals(groupId)){
this.save(fieldBean,groupId,records.getJSONObject(i));
}else {
this.save(fieldBean, groupId);
}
}
HrmFieldComInfo.removeFieldCache();
//同步分部数据到矩阵
MatrixUtil.sysSubcompayData();
retmap.put("status", "1");
} catch (Exception e) {
retmap.put("status", "-1");
retmap.put("message", SystemEnv.getHtmlLabelName(382661,user.getLanguage()));
writeLog(e);
}
return retmap;
}
/**
* <h2></h2>
* @author bokang.xiao
* @param fieldBean
* @param groupId id
* @param fieldJson JSON
*/
private void save(FieldBean fieldBean, String groupId,JSONObject fieldJson){
try {
HrmUtil hrmUtil = new HrmUtil();
HrmDeptFieldManagerE9 hfm = new HrmDeptFieldManagerE9(4);
String fieldId = Util.null2String(fieldBean.getId());
String fieldLabel = Util.null2String(fieldBean.getFieldlabel());
String fieldName = Util.null2String(fieldBean.getFieldname());
String fieldHtmlType = "";
String type = "";
String typeDetial = "";
String dmlUrl = "";
if(fieldBean.getFieldTypeBean()!=null){
fieldHtmlType = Util.null2String(fieldBean.getFieldTypeBean().getFieldHtmlType());
type = Util.null2String(fieldBean.getFieldTypeBean().getFieldType());
if(fieldHtmlType.equals("1")||fieldHtmlType.equals("2")){
typeDetial = Util.null2String(fieldBean.getFieldTypeBean().getOtherParam());
} else if(fieldHtmlType.equals("66") || fieldHtmlType.equals("67")){
dmlUrl = Util.null2String(fieldBean.getFieldTypeBean().getOtherParam());
} else if (type.equals("161") || type.equals("162") || type.equals("256")|| type.equals("257")) {
dmlUrl = Util.null2String(fieldBean.getFieldTypeBean().getOtherParam());
}
}
String isUse = Util.null2String(fieldBean.getEnable(),"0");
String isMand = Util.null2String(fieldBean.getRequired(),"0");
String fieldOrder = Util.null2String(fieldBean.getKey());
int temId = Util.getIntValue(fieldId,-1);
//int lableid = hrmUtil.getFieldLabelId(fieldLabel);
int lableid = new LabelUtil().getLabelId(fieldLabel);
if(Util.null2String(fieldId).length()==0){
FieldParam fp = new FieldParam();
if(fieldHtmlType.equals("1")){
fp.setSimpleText(Util.getIntValue(type,-1),typeDetial);
}else if(fieldHtmlType.equals("2")){
fp.setText();
}else if(fieldHtmlType.equals("3")){
fp.setBrowser(Util.getIntValue(type,-1));
}else if(fieldHtmlType.equals("4")){
fp.setCheck();
}else if(fieldHtmlType.equals("5")){
fp.setSelect();
}else if(fieldHtmlType.equals("6")){
fp.setAttach();
}
temId = hfm.addField(fieldName, fp.getFielddbtype(), fieldHtmlType, type, ""+lableid, fieldOrder, isMand, isUse, groupId, dmlUrl);
//添加字段值isEdit
String isEdit = Util.null2String(fieldJson.getString("isEdit"),"1");
formFieldMapper.updateHrmFormField(isEdit,temId+"",groupId);
}else{
//只允许更改显示属性,数据库层面的不允许修改
hfm.editField(fieldId, ""+lableid, fieldOrder, isMand, isUse, groupId);
//添加字段值isEdit
String isEdit = Util.null2String(fieldJson.getString("isEdit"),"1");
formFieldMapper.updateHrmFormField(isEdit,fieldId,groupId);
}
if(fieldHtmlType.equals("5")){
List<FieldSelectOptionBean> lsSelectOption = fieldBean.getFieldTypeBean().getLsSelectOption();
hfm.checkSelectField(temId, lsSelectOption);
}
}catch (Exception e) {
writeLog(e);
}
}
private void save(FieldBean fieldBean, String groupId){
try {
HrmUtil hrmUtil = new HrmUtil();
HrmDeptFieldManagerE9 hfm = new HrmDeptFieldManagerE9(4);
String fieldId = Util.null2String(fieldBean.getId());
String fieldLabel = Util.null2String(fieldBean.getFieldlabel());
String fieldName = Util.null2String(fieldBean.getFieldname());
String fieldHtmlType = "";
String type = "";
String typeDetial = "";
String dmlUrl = "";
if(fieldBean.getFieldTypeBean()!=null){
fieldHtmlType = Util.null2String(fieldBean.getFieldTypeBean().getFieldHtmlType());
type = Util.null2String(fieldBean.getFieldTypeBean().getFieldType());
if(fieldHtmlType.equals("1")||fieldHtmlType.equals("2")){
typeDetial = Util.null2String(fieldBean.getFieldTypeBean().getOtherParam());
} else if(fieldHtmlType.equals("66") || fieldHtmlType.equals("67")){
dmlUrl = Util.null2String(fieldBean.getFieldTypeBean().getOtherParam());
} else if (type.equals("161") || type.equals("162") || type.equals("256")|| type.equals("257")) {
dmlUrl = Util.null2String(fieldBean.getFieldTypeBean().getOtherParam());
}
}
String isUse = Util.null2String(fieldBean.getEnable(),"0");
String isMand = Util.null2String(fieldBean.getRequired(),"0");
String fieldOrder = Util.null2String(fieldBean.getKey());
int temId = Util.getIntValue(fieldId,-1);
//int lableid = hrmUtil.getFieldLabelId(fieldLabel);
int lableid = new LabelUtil().getLabelId(fieldLabel);
if(Util.null2String(fieldId).length()==0){
FieldParam fp = new FieldParam();
if(fieldHtmlType.equals("1")){
fp.setSimpleText(Util.getIntValue(type,-1),typeDetial);
}else if(fieldHtmlType.equals("2")){
fp.setText();
}else if(fieldHtmlType.equals("3")){
fp.setBrowser(Util.getIntValue(type,-1));
}else if(fieldHtmlType.equals("4")){
fp.setCheck();
}else if(fieldHtmlType.equals("5")){
fp.setSelect();
}else if(fieldHtmlType.equals("6")){
fp.setAttach();
}
temId = hfm.addField(fieldName, fp.getFielddbtype(), fieldHtmlType, type, ""+lableid, fieldOrder, isMand, isUse, groupId, dmlUrl);
}else{
//只允许更改显示属性,数据库层面的不允许修改
hfm.editField(fieldId, ""+lableid, fieldOrder, isMand, isUse, groupId);
}
if(fieldHtmlType.equals("5")){
List<FieldSelectOptionBean> lsSelectOption = fieldBean.getFieldTypeBean().getLsSelectOption();
hfm.checkSelectField(temId, lsSelectOption);
}
}catch (Exception e) {
writeLog(e);
}
}
@Override
public BizLogContext getLogContext() {
return null;
}
@Override
public List<BizLogContext> getLogContexts() {
return logger.getBizLogContexts();
}
}

View File

@ -0,0 +1,38 @@
package weaver.bokang.xiao.tbxc.mapper;
import aiyh.utils.annotation.recordset.ParamMapper;
import aiyh.utils.annotation.recordset.Select;
import aiyh.utils.annotation.recordset.SqlMapper;
import aiyh.utils.annotation.recordset.Update;
/**
* @ClassName FormFieldMapper
* @Author
* @Date 2023/4/26 17:22
* @Description <h1></h1>
**/
@SqlMapper
public interface FormFieldMapper {
/**
* <h2></h2>
* @param isEdit
* @param formFieldId id
* @param groupId id
* @return
*/
@Update("update hrm_formfield set is_edit = #{isEdit} where fieldid = #{formFieldId} and groupid = #{groupId}")
boolean updateHrmFormField(@ParamMapper("isEdit") String isEdit,
@ParamMapper("formFieldId") String formFieldId,
@ParamMapper("groupId") String groupId);
/**
* <h2>isEdit</h2>
* @param formFieldId id
* @param groupId id
* @return
*/
@Select("select is_edit from hrm_formfield where fieldid = #{formFieldId} and groupid = #{groupId}")
String queryIsEdit(@ParamMapper("formFieldId") String formFieldId,
@ParamMapper("groupId") int groupId);
}

View File

@ -1,5 +1,6 @@
package weaver.bokang.xiao.zscq.config.entity;
import aiyh.utils.annotation.recordset.SqlOracleDbFieldAnn;
import lombok.Data;
/**
@ -12,20 +13,26 @@ import lombok.Data;
public class AssignmentEntity {
/** 赋值字段 */
@SqlOracleDbFieldAnn("ASSIGNMENT_FIELD")
private String assignmentField;
/** 值选择 */
@SqlOracleDbFieldAnn("VALUE_SELECT")
private Integer valueSelect;
/** 源字段 */
@SqlOracleDbFieldAnn("SOURCE_FIELD")
private String sourceField;
/** 赋值字段名 */
@SqlOracleDbFieldAnn("ASSIGNMENT_FIELD_NAME")
private String assignmentFieldName;
/** 源字段名 */
@SqlOracleDbFieldAnn("SOURCE_FIELD_NAME")
private String sourceFieldName;
/** 文本框 */
private String context;
@SqlOracleDbFieldAnn("CUS_CONTEXT")
private String cusContext;
}

View File

@ -1,5 +1,6 @@
package weaver.bokang.xiao.zscq.config.entity;
import aiyh.utils.annotation.recordset.SqlOracleDbFieldAnn;
import lombok.Data;
/**
@ -12,26 +13,34 @@ import lombok.Data;
public class ConditionEntity {
/** 条件类型 */
@SqlOracleDbFieldAnn("CONDITION_TYPE")
private Integer conditionType;
/** 条件 */
@SqlOracleDbFieldAnn("CONDITION_VALUE")
private Integer conditionValue;
/** 源字段 */
@SqlOracleDbFieldAnn("CONDITION_SOURCE_FIELD")
private String conditionSourceField;
/** 值类型 */
@SqlOracleDbFieldAnn("VALUE_TYPE")
private Integer valueType;
/** 目标字段 */
@SqlOracleDbFieldAnn("CONDITION_TARGET_FIELD")
private String conditionTargetField;
/** 源字段名 */
@SqlOracleDbFieldAnn("CONDITION_SOURCE_FIELD_NAME")
private String conditionSourceFieldName;
/** 目标字段名 */
@SqlOracleDbFieldAnn("CONDITION_TARGET_FIELD_NAME")
private String conditionTargetFieldName;
/** 文本框 */
@SqlOracleDbFieldAnn("CUS_TEXT")
private String cusText;
}

View File

@ -1,5 +1,6 @@
package weaver.bokang.xiao.zscq.config.entity;
import aiyh.utils.annotation.recordset.SqlOracleDbFieldAnn;
import lombok.Data;
import java.util.List;
@ -14,30 +15,39 @@ import java.util.List;
public class UpdateModeConf {
/** 源建模 */
@SqlOracleDbFieldAnn("SOURCE_MODE")
private String sourceMode;
/** 触发建模 */
@SqlOracleDbFieldAnn("TARGET_MODE")
private String targetMode;
/** 说明 */
@SqlOracleDbFieldAnn("DESCRIPTION")
private String description;
/** 唯一标识 */
@SqlOracleDbFieldAnn("UNIQUE_CODE")
private String uniqueCode;
/** 源表名 */
@SqlOracleDbFieldAnn("SOURCE_TABLE_NAME")
private String sourceTableName;
/** 触发表名 */
@SqlOracleDbFieldAnn("TARGET_TABLE_NAME")
private String targetTableName;
/** 数据写入方式 */
@SqlOracleDbFieldAnn("DATA_IN_TYPE")
private Integer dataInType;
/** 自定义操作类全路径 */
@SqlOracleDbFieldAnn("OPERATE_PATH")
private String operatePath;
/** 无条件触发 */
@SqlOracleDbFieldAnn("NO_RULE")
private Integer noRule;
/** 条件列表 */

View File

@ -29,6 +29,17 @@ public interface UpdateModeMapper {
})
List<UpdateModeConf> queryUpdateModeConfByFormId(@ParamMapper("formId")String formId);
/**
* <h2>formId</h2>
* @return
*/
@Select("select * from uf_update_mode_conf")
@CollectionMappings({
@CollectionMapping(property = "conditionList", column = "id", id = @Id(value = Integer.class, methodId = 1)),
@CollectionMapping(property = "assignmentList", column = "id", id = @Id(value = Integer.class, methodId = 2)),
})
List<UpdateModeConf> queryUpdateModeConf();
/**
* <h2></h2>
* @param mainId id

View File

@ -71,13 +71,61 @@ public class ConditionTargetProcess {
*/
@MethodRuleNo(value = 1, desc = "不等于")
public static String noEquals(Map<String,Object> whereParam,Map<String,Object> param,String whereSql) {
String sourceFieldName = Util.null2String(param.get("sourceValue"));
String conditionValue = Util.null2String(param.get("conditionValue"));
String targetFieldName = Util.null2String(param.get("targetFieldName"));
String targetStr = " and "+sourceFieldName+" <> #{whereParam."+targetFieldName+"}";
String targetStr = " and "+targetFieldName+" <> #{whereParam."+targetFieldName+"}";
whereSql += targetStr;
whereParam.put(targetFieldName,conditionValue);
return whereSql;
}
/**
* <h2></h2>
* @param whereParam
* @param param
* @param whereSql sql
* @return sql
*/
@MethodRuleNo(value = 6, desc = "in")
public static String in(Map<String,Object> whereParam,Map<String,Object> param,String whereSql) {
String conditionValue = Util.null2String(param.get("conditionValue"));
String targetFieldName = Util.null2String(param.get("targetFieldName"));
String targetStr = " and "+targetFieldName+" in ( $t{whereParam."+targetFieldName+"})";
whereSql += targetStr;
whereParam.put(targetFieldName,conditionValue);
return whereSql;
}
/**
* <h2></h2>
* @param whereParam
* @param param
* @param whereSql sql
* @return sql
*/
@MethodRuleNo(value = 7, desc = "not in")
public static String notIn(Map<String,Object> whereParam,Map<String,Object> param,String whereSql) {
String conditionValue = Util.null2String(param.get("conditionValue"));
String targetFieldName = Util.null2String(param.get("targetFieldName"));
String targetStr = " and "+targetFieldName+" not in ( $t{whereParam."+targetFieldName+"})";
whereSql += targetStr;
whereParam.put(targetFieldName,conditionValue);
return whereSql;
}
/**
* <h2></h2>
* @param whereParam
* @param param
* @param whereSql sql
* @return sql
*/
@MethodRuleNo(value = 8, desc = "自定义sql")
public static String cusSql(Map<String,Object> whereParam,Map<String,Object> param,String whereSql) {
String conditionValue = Util.null2String(param.get("conditionValue"));
String targetStr = " and "+Util.sbc2dbcCase(conditionValue);
whereSql += targetStr;
return whereSql;
}
}

View File

@ -67,5 +67,32 @@ public class ConditionValueProcess {
return !sourceValue.equals(value);
}
/**
* <h2></h2>
* @param sourceValue
* @param value
* @return
*/
@MethodRuleNo(value = 6, desc = "in")
public static boolean in(String sourceValue, String value) {
if("".equals(sourceValue) || "".equals(value)){
return false;
}
String tempStr = ","+value+",";
sourceValue = "," + sourceValue + ",";
return tempStr.contains(sourceValue);
}
/**
* <h2></h2>
* @param sourceValue
* @param value
* @return
*/
@MethodRuleNo(value = 7, desc = "not in")
public static boolean notIn(String sourceValue, String value) {
return !in(sourceValue, value);
}
}

View File

@ -69,7 +69,7 @@ public class DataTypeProcess {
whereSql = whereSql.replaceFirst(" and "," where ");
}
updateSql = updateSql + whereSql;
logger.info("updateSql ==>"+updateSql);
logger.info(String.format("updateSql ==> %s updateParam ==> %s whereParam ==> %s",updateSql,updateParam,whereParam));
return UPDATE_MODE_MAPPER.executeUpdateCusSql(updateSql, updateParam, whereParam);
}
@ -90,7 +90,7 @@ public class DataTypeProcess {
String updateSql = buildUpdateSql(tableName, updateParam);
String whereSql = DataTypeProcess.buildWhereSql(whereParam);
updateSql = updateSql + " " + whereSql;
logger.info("updateSql ==>"+updateSql);
logger.info(String.format("updateSql ==> %s updateParam ==> %s whereParam ==> %s",updateSql,updateParam,whereParam));
return UPDATE_MODE_MAPPER.executeUpdateCusSql(updateSql,updateParam,whereParam);
}
@ -142,6 +142,30 @@ public class DataTypeProcess {
return insert(updateParam,whereParam,param) && cusOperate(updateParam,whereParam,param);
}
/**
* <h2></h2>
* @param updateParam
* @param whereParam
* @param param
* @return
*/
@MethodRuleNo(value = 5,desc = "执行自定义操作并更新")
public static boolean updateAndCus(Map<String,Object> updateParam, Map<String,Object> whereParam,Map<String,String> param) {
return cusOperate(updateParam,whereParam,param) && update(updateParam,whereParam,param);
}
/**
* <h2></h2>
* @param updateParam
* @param whereParam
* @param param
* @return
*/
@MethodRuleNo(value = 6,desc = "执行自定义操作并插入")
public static boolean insertAndCus(Map<String,Object> updateParam, Map<String,Object> whereParam,Map<String,String> param) {
return cusOperate(updateParam,whereParam,param) && insert(updateParam,whereParam,param);
}
/**
* <h2>sql</h2>
* @param tableName

View File

@ -60,7 +60,7 @@ public class ValueSelectProcess {
*/
@MethodRuleNo(value = 0, desc = "默认值")
public static String defaultValue(Map<String,Object> modeMap,AssignmentEntity assignment) {
return assignment.getContext();
return assignment.getCusContext();
}
/**
@ -82,7 +82,7 @@ public class ValueSelectProcess {
*/
@MethodRuleNo(value = 2, desc = "自定义sql")
public static String cusSql(Map<String,Object> modeMap,AssignmentEntity assignment) {
String cusSqlStr = Util.null2String(assignment.getContext());
String cusSqlStr = Util.null2String(assignment.getCusContext());
cusSqlStr = Util.dbc2sbcCase(cusSqlStr);
if(StringUtils.isBlank(cusSqlStr)){
throw new CustomerException("选择自定义sql时sql字符串不能为空");

View File

@ -9,6 +9,7 @@ import weaver.bokang.xiao.zscq.config.entity.UpdateModeConf;
import weaver.bokang.xiao.zscq.config.function.ConditionFunction;
import weaver.bokang.xiao.zscq.config.mapper.UpdateModeMapper;
import weaver.bokang.xiao.zscq.config.process.*;
import weaver.bokang.xiao.zscq.store.TableNameStore;
import java.util.HashMap;
import java.util.List;
@ -33,23 +34,39 @@ public class ModeChangeService {
* <h2></h2>
* @param modeMap
* @param formId id
* @param triggerType 0:; 1:; 2:
*/
public void changeOtherMode(Map<String,Object> modeMap, String formId){
List<UpdateModeConf> updateModeConfList = updateModeMapper.queryUpdateModeConfByFormId(formId);
public void changeOtherMode(Map<String,Object> modeMap, String formId,int triggerType){
Map<String, List<UpdateModeConf>> triggerStore = TableNameStore.getInstance().getTriggerStore();
List<UpdateModeConf> updateModeConfList = triggerStore.get(formId);
if(Objects.isNull(updateModeConfList) || updateModeConfList.isEmpty()){
logger.error(String.format("此表单建模[%s] 未配置相关更新信息,请检查!!!",formId));
return;
}
logger.info("配置信息 updateModeConfList==>"+ JSON.toJSONString(updateModeConfList));
List<UpdateModeConf> collect = updateModeConfList.stream().filter(item -> item.getNoRule() == triggerType).collect(Collectors.toList());
if(collect.isEmpty()){
logger.error(String.format("此表单建模[%s] 未配置相关更新信息,请检查!!!",formId));
return;
}
doChange(modeMap,collect);
}
/**
* <h2></h2>
* @param modeMap
* @param updateModeConfList
*/
private void doChange(Map<String,Object> modeMap,List<UpdateModeConf> updateModeConfList){
for (UpdateModeConf updateModeConf : updateModeConfList) {
List<ConditionEntity> conditionList = updateModeConf.getConditionList();
List<AssignmentEntity> assignmentList = updateModeConf.getAssignmentList();
Integer dataInType = updateModeConf.getDataInType();
Integer noRule = updateModeConf.getNoRule();
if(noRule == 0 && conditionList.isEmpty()){
if(noRule == 1 && conditionList.isEmpty()){
logger.error(String.format("没有条件设置,不允许建模 %s 更新",updateModeConf.getTargetTableName()));
continue;
}
logger.info(String.format("处理配置 deal config [%s - %s]",updateModeConf.getUniqueCode(),updateModeConf.getDescription()));
//条件sql
String whereSql = "";
//条件数据
@ -71,12 +88,13 @@ public class ModeChangeService {
String sourceValue = Util.null2String(modeMap.get(sourceCondition.getConditionSourceFieldName()));
String conditionValue = valueFunction.apply(modeMap, sourceCondition);
Boolean result = conditionFunction.apply(sourceValue, conditionValue);
if (result) {
if (!result) {
flag = true;
break;
}
}
if (flag) {
logger.info("源建模条件判断不通过,此条数据跳过 sourceMode condition fail !!! "+JSON.toJSONString(modeMap));
continue;
}
}
@ -113,4 +131,6 @@ public class ModeChangeService {
logger.info("更新结果 executeFlag ==>"+executeFlag);
}
}
}

View File

@ -97,7 +97,7 @@ public class DataControlExpand extends AbstractModeExpandJavaCodeNew {
queryParam.put("fieldValue",dataId);
Map<String, Object> modeData = modeMapper.queryModeDataInfo(tableName, queryParam);
if(Objects.nonNull(modeData)){
modeChangeService.changeOtherMode(modeData,formId);
modeChangeService.changeOtherMode(modeData,formId,1);
}
}

View File

@ -3,6 +3,7 @@ package weaver.bokang.xiao.zscq.fun;
import aiyh.utils.Util;
import weaver.bokang.xiao.zscq.config.function.CusOperateInterface;
import weaver.bokang.xiao.zscq.config.mapper.UpdateModeMapper;
import weaver.bokang.xiao.zscq.mapper.StatusMapper;
import weaver.hrm.User;
import weaver.workflow.workflow.WfForceOver;
@ -21,6 +22,8 @@ public class WorkflowOverOperate implements CusOperateInterface {
private final UpdateModeMapper updateModeMapper = Util.getMapper(UpdateModeMapper.class);
private final StatusMapper statusMapper = Util.getMapper(StatusMapper.class);
@Override
public void execute(Map<String, Object> whereParam, Map<String, String> param, Map<String, String> pathParam) {
logger.info(String.format("WorkflowOverOperate 自定义处理 whereParam[%s],param:[%s],pathParam:[%s]",whereParam,param,pathParam));
@ -35,6 +38,11 @@ public class WorkflowOverOperate implements CusOperateInterface {
if(Objects.nonNull(modeData)){
String workflowField = Util.null2String(pathParam.get("workflowField"));
String requestId = Util.null2String(modeData.get(workflowField));
int status = statusMapper.queryWorkflowStatus(requestId);
if(status == 3){
logger.error(String.format("此流程已归档,不再执行强制归档操作 this workflow is over!!! requestId:%s ",requestId));
return;
}
logger.info("流程强制归档 ==>"+requestId);
//流程强制归档
WfForceOver wfForceOver = new WfForceOver();

View File

@ -0,0 +1,100 @@
package weaver.bokang.xiao.zscq.fun;
import aiyh.utils.Util;
import com.api.bokang.xiao.zscq.service.impl.ReserveServiceImpl;
import weaver.bokang.xiao.zscq.config.function.CusOperateInterface;
import weaver.bokang.xiao.zscq.config.mapper.UpdateModeMapper;
import weaver.conn.RecordSet;
import weaver.hrm.User;
import weaver.workflow.workflow.RequestForceDrawBack;
import weaver.workflow.workflow.WfForceDrawBack;
import weaver.workflow.workflow.WfFunctionManageUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/**
* @ClassName WorkflowRepossessedSign
* @Author
* @Date 2023/4/24 11:11
* @Description <h1></h1>
**/
public class WorkflowRepossessedSign implements CusOperateInterface {
private final UpdateModeMapper updateModeMapper = Util.getMapper(UpdateModeMapper.class);
private final ReserveServiceImpl reserveService = new ReserveServiceImpl();
@Override
public void execute(Map<String, Object> whereParam, Map<String, String> param, Map<String, String> pathParam) {
logger.info(String.format("WorkflowRepossessedSign 自定义处理 whereParam[%s],param:[%s],pathParam:[%s]",whereParam,param,pathParam));
String tableName = Util.null2String(param.get("tableName"));
String whereSql = Util.null2String(param.get("whereSql"));
if(!"".equals(whereSql)){
whereSql = whereSql.replaceFirst(" and "," where ");
}
String querySql = "select * from " + tableName +whereSql;
Map<String, Object> modeData = updateModeMapper.executeCusSqlMap(querySql, whereParam,new HashMap<>());
logger.info("modeData ==>"+modeData);
if(Objects.nonNull(modeData)){
String workflowField = Util.null2String(pathParam.get("workflowField"));
String requestId = Util.null2String(modeData.get(workflowField));
logger.info("流程强制收回 ==>"+requestId);
//流程强制收回
reserveService.doRepossessedSign(Util.getIntValue(requestId),new User(1));
//this.doRepossessedSign2(Util.getIntValue(requestId),new User(1));
}
}
/**
* <h2></>
* @param requestId id
* @param user
* @return
*/
public boolean doRepossessedSign2(int requestId,User user){
WfFunctionManageUtil wfFunctionManageUtil = new WfFunctionManageUtil();
//初始化
RequestForceDrawBack requestForceDrawBack = new RequestForceDrawBack();
WfForceDrawBack wfForceDrawBack = new WfForceDrawBack();
if(requestId != -1){
RecordSet recordSet = new RecordSet();
//从日志中去找最后一个操作者
recordSet.executeSql("select max(logid), operator,operatortype from workflow_requestlog where requestId=" + requestId + " and (logtype='2' or logtype='0' or logtype='3' or logtype='e') and exists(select 1 from workflow_currentoperator where requestId=workflow_requestlog.requestId and userid=workflow_requestlog.operator and usertype=workflow_requestlog.operatortype and isremark='2' and preisremark='0' and operatedate is not null and operatedate>' ') group by operator,operatortype order by max(logid) desc");
int tempUser = -1;
int tempUserType = -1;
if (recordSet.next()) {
tempUser = Util.getIntValue(recordSet.getString("operator"));
tempUserType = Util.getIntValue(recordSet.getString("operatortype"), 0);
}else{
recordSet.executeSql("select userid,usertype from workflow_currentoperator where requestId = " + requestId + " and isremark = '2' and preisremark='0' and operatedate is not null and operatedate>' ' order by operatedate desc ,operatetime desc");
if (recordSet.next()) {
tempUser = recordSet.getInt("userid");
tempUserType = recordSet.getInt("usertype");
}
}
if(tempUser == -1 && tempUserType == -1){
logger.error(String.format("流程 requestId:[%s] 操作者 operateInfo no find 流程可能未归档 !!!",requestId));
return false;
}
//提交时针对流程再作一次权限判断
boolean canForceDrawBack = RequestForceDrawBack.isHavePurview(user.getUID(), requestId, true);
if (canForceDrawBack && wfFunctionManageUtil.haveOtherOperationRight(requestId)) {
//int result = requestForceDrawBack.foreceDrawBack(user, requestId, true, tempUser, tempUserType);
ArrayList<String> requestIds = new ArrayList<>();
requestIds.add(requestId+"");
wfForceDrawBack.doForceDrawBack(requestIds,new User(1),-1,-1);
logger.info(String.format("流程 requestId:[%s] 撤回结果 drawBack result:[%d] message:[%s]",requestId,111,requestForceDrawBack.getMessage()));
//return result == 1;
return true;
}else{
return false;
}
}else{
return false;
}
}
}

View File

@ -1,6 +1,7 @@
package weaver.bokang.xiao.zscq.mapper;
import aiyh.utils.annotation.recordset.ParamMapper;
import aiyh.utils.annotation.recordset.Select;
import aiyh.utils.annotation.recordset.SqlMapper;
import aiyh.utils.annotation.recordset.Update;
@ -19,8 +20,16 @@ public interface StatusMapper {
* @param userIds id
* @return
*/
@Update("update workflow_currentoperator set viewtype = -2,isremark = 2 " +
@Update("update workflow_currentoperator set isremark = 2 " +
"where REQUESTID = #{requestId} and userid in ($t{userIds}) and isremark = 8")
boolean changeWorkflowStatus(@ParamMapper("requestId")String requestId,@ParamMapper("userIds") String userIds);
/**
* <h2></h2>
* @param requestId id
* @return
*/
@Select("select currentnodetype from workflow_requestbase where requestid = #{requestId}")
int queryWorkflowStatus(@ParamMapper("requestId")String requestId);
}

View File

@ -6,6 +6,8 @@ import lombok.Getter;
import org.apache.log4j.Logger;
import weaver.bokang.xiao.xhny_report.entity.pojo.CompanyEntity;
import weaver.bokang.xiao.xhny_report.mapper.VendorMapper;
import weaver.bokang.xiao.zscq.config.entity.UpdateModeConf;
import weaver.bokang.xiao.zscq.config.mapper.UpdateModeMapper;
import weaver.general.StaticObj;
import weaver.interfaces.datasource.DataSource;
@ -30,9 +32,31 @@ public class TableNameStore {
private final Map<String,String> tableNameStore = new HashMap<>();
private final Map<String,List<UpdateModeConf>> triggerStore = new HashMap<>();
private final UpdateModeMapper updateModeMapper = Util.getMapper(UpdateModeMapper.class);
private static final Logger logger = Util.getLogger();
private TableNameStore(){}
private TableNameStore(){init();}
private void init(){
try {
triggerStore.clear();
List<UpdateModeConf> updateModeConfList = updateModeMapper.queryUpdateModeConf();
if (Objects.nonNull(updateModeConfList) && !updateModeConfList.isEmpty()) {
Map<String, List<UpdateModeConf>> collect = updateModeConfList.stream().collect(Collectors.groupingBy(UpdateModeConf::getSourceMode));
triggerStore.putAll(collect);
}
logger.info(String.format("TableNameStore init success!!! triggerStore:%s updateModeConfList:%s", JSON.toJSONString(triggerStore), JSON.toJSONString(updateModeConfList)));
}catch (Exception e){
logger.error("TableNameStore init error "+Util.getErrString(e));
}
}
public void refresh(){
this.init();
}
public static TableNameStore getInstance(){
return VendorStoreHolder.VENDOR_STORE;

View File

@ -112,4 +112,13 @@ public interface CommonMapper {
@Update("update meeting set meetingstatus = 4 where requestid in (${requestIds})")
boolean cancelMeeting(@ParamMapper("requestIds") List<String> requestIds);
@Select(custom = true)
String selectCustomerSql(@SqlString String sql, Map<String, Object> map);
@Update(custom = true)
boolean updateModelInfo(@SqlString String sql, Map<String, Object> params);
@BatchUpdate(custom = true)
boolean updateModelInfoList(@SqlString String sql, @BatchSqlArgs List<Map<String, Object>> params);
}

View File

@ -10,6 +10,9 @@ import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import weaver.conn.RecordSet;
import weaver.formmode.data.ModeDataApproval;
import weaver.formmode.data.ModeDataIdUpdate;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.TimeUtil;
import weaver.hrm.User;
import weaver.xiao.commons.config.entity.RequestMappingConfig;
import weaver.xiao.commons.config.service.DealWithMapping;
@ -60,6 +63,9 @@ public class CommonUtil {
**/
private static final CommonMapper commonMapper = Util.getMapper(CommonMapper.class);
private static final ModeDataIdUpdate modeDataIdUpdate = ModeDataIdUpdate.getInstance();
private static final ModeRightInfo moderightinfo = new ModeRightInfo();
public CommonUtil(){
}
@ -655,6 +661,52 @@ public class CommonUtil {
return commonMapper.queryMeetingIdByRequestId(requestId);
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2022/11/23 21:02
* @param modelId id
* @param ids
* @return
**/
public static boolean deleteModelDataByIds(String modelId, List<String> ids){
String tableName = commonMapper.getModelNameByModelId(modelId);
return commonMapper.deleteModelDataByIds(tableName, ids);
}
/**
* <h1>id</h1>
* @author xuanran.wang
* @dateTime 2022/12/15 10:56
* @param modelTableName
* @param modelId id
* @return id
**/
private static Integer getNewIdByModelInfo(String modelTableName, int modelId){
String currentDateTime = TimeUtil.getCurrentTimeString();
//日期
String currentDate = currentDateTime.substring(0, 10);
//时间
String currentTime = currentDateTime.substring(11);
return modeDataIdUpdate.getModeDataNewId(modelTableName, modelId, 1, 0, currentDate, currentTime);
}
/**
* <h1>id </h1>
* @author xuanran.wang
* @dateTime 2023/2/9 11:18
* @param modelId id
* @return
**/
public static String checkModelId(int modelId){
if(modelId < 0){
throw new RuntimeException("建模模块id不能小于0!");
}
String tableName = commonMapper.getModelNameByModelId(String.valueOf(modelId));
if(StringUtils.isBlank(tableName)){
throw new CustomerException("模块id为 " + modelId + ", 在系统中暂没查询到对应表单!");
}
return tableName;
}
}

View File

@ -0,0 +1,99 @@
package weaver.xuanran.wang.common.util;
import aiyh.utils.Util;
import aiyh.utils.annotation.recordset.BatchUpdate;
import aiyh.utils.excention.CustomerException;
import org.apache.axis2.databinding.types.xsd._float;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import weaver.formmode.data.ModeDataIdUpdate;
import weaver.formmode.setup.ModeRightInfo;
import weaver.xuanran.wang.common.mapper.CommonMapper;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* <h1>oa</h1>
*
* @author xuanran.wang
* @date 2023/4/19 16:24
*/
public class CusData2OA {
private static final CommonMapper commonMapper = Util.getMapper(CommonMapper.class);
private static final Logger log = Util.getLogger();
private static final String TABLE_NAME_PLACEHOLDER = "#\\{tableName}";
public static String writeToModel(String modelId, String uniqueSql, Map<String, Object> params){
return baseExecute(modelId, uniqueSql, Collections.singletonList(params)).get(0);
}
public static String writeToModel(String modelId, Map<String, Object> params){
return baseExecute(modelId, "", Collections.singletonList(params)).get(0);
}
public static List<String> batchWriteToModel(String modelId, List<Map<String, Object>> params){
return baseExecute(modelId, "", params);
}
public static List<String> batchWriteToModel(String modelId, String uniqueSql, List<Map<String, Object>> params){
return baseExecute(modelId, uniqueSql, params);
}
@BatchUpdate
public static List<String> baseExecute(String modelId, String uniqueSql, List<Map<String, Object>> params){
int modelIdInt = Util.getIntValue(modelId, -1);
String tableName = CommonUtil.checkModelId(modelIdInt);
if(modelIdInt < 0 || StringUtils.isBlank(tableName)){
throw new CustomerException("modelId can not < 0 or modelTableName can not empty!");
}
uniqueSql = Util.sbc2dbcCase(uniqueSql);
uniqueSql = uniqueSql.replaceAll(TABLE_NAME_PLACEHOLDER, tableName);
String modelDataId = "";
List<String> delList = new ArrayList<>();
List<String> modelDataList = new ArrayList<>();
String updateSql = "";
for (Map<String, Object> param : params) {
if(StringUtils.isNotBlank(uniqueSql)){
modelDataId = commonMapper.selectCustomerSql(uniqueSql, param);
}
if(StringUtils.isBlank(modelDataId)){
modelDataId = Util.null2DefaultStr(Util.getModeDataId(tableName, modelIdInt, 1),"");
delList.add(modelDataId);
Util.rebuildModeDataShare(1, tableName, Util.getIntValue(modelDataId, -1));
}
if(StringUtils.isBlank(updateSql)){
updateSql = buildUpdateSql(tableName, param);
}
param.put("id",modelDataId);
modelDataList.add(modelDataId);
}
try {
if (!commonMapper.updateModelInfoList(updateSql, params)) {
throw new CustomerException("update model data sql execute error!");
}
}catch (Exception e){
CommonUtil.deleteDataByIds(delList, tableName);
throw new CustomerException(e);
}
return modelDataList;
}
public static String buildUpdateSql(String tableName, Map<String, Object> params) {
StringBuilder sqlSb = new StringBuilder("update ")
.append(tableName)
.append(" set ");
for (Map.Entry<String, Object> entry : params.entrySet()) {
sqlSb.append(entry.getKey())
.append(" = #{item.")
.append(entry.getKey())
.append("},");
}
sqlSb.deleteCharAt(sqlSb.length() - 1);
sqlSb.append(" where id = #{item.id}");
return sqlSb.toString();
}
}

View File

@ -0,0 +1,153 @@
package weaver.xuanran.wang.cssc.cms;
import aiyh.utils.Util;
import aiyh.utils.action.SafeCusBaseAction;
import aiyh.utils.annotation.ActionDesc;
import aiyh.utils.annotation.ActionOptionalParam;
import aiyh.utils.annotation.PrintParamMark;
import aiyh.utils.annotation.RequiredMark;
import weaver.hrm.User;
import weaver.soa.workflow.request.RequestInfo;
import weaver.xuanran.wang.cssc.cms.entity.CusSuccess;
import weaver.xuanran.wang.cssc.cms.service.WorkflowToCmsService;
import weaver.xuanran.wang.cssc.cms.service.impl.WorkFlowToCmsServiceImpl;
/**
* <h1></h1>
*
* @author xuanran.wang
* @date 2023/4/26 10:52
*/
@ActionDesc(value = "中国船舶研究所流程数据推送到科研综合管理系统", author = "xuanran.wang")
public class WorkflowToCms extends SafeCusBaseAction {
private final WorkflowToCmsService workflowToCmsService = new WorkFlowToCmsServiceImpl();
@PrintParamMark
@RequiredMark("建模配置文件唯一标识")
private String onlyMark;
@PrintParamMark
private String tokenOnlyMark;
@PrintParamMark
private String tokenSuccessField;
@PrintParamMark
private String tokenSuccessVal;
@PrintParamMark
private String tokenMsg;
@PrintParamMark
private String tokenDataKey;
@PrintParamMark
@ActionOptionalParam(value = "code", desc = "接口成功标识字段")
private String successField;
@PrintParamMark
@ActionOptionalParam(value = "successVal", desc = "接口成功标识默认200")
private String successVal;
@PrintParamMark
@ActionOptionalParam(value = "message", desc = "报错返回信息字段")
private String msg;
@PrintParamMark
private String dataKey;
@Override
public void doSubmit(String requestId, String billTable, int workflowId, User user, RequestInfo requestInfo) {
log.info("-------------- " + requestId + " begin --------------");
CusSuccess cmsResponseVoField = CusSuccess
.builder()
.successField(Util.null2DefaultStr(successField, "success"))
.successValue(Util.null2DefaultStr(successVal, "true"))
.errorMsg(Util.null2DefaultStr(msg, "error"))
.dataKey(Util.null2DefaultStr(dataKey, "result.accessToken"))
.build();
log.info("");
CusSuccess tokenSuccess = CusSuccess
.builder()
.successField(Util.null2DefaultStr(tokenSuccessField, "success"))
.successValue(Util.null2DefaultStr(tokenSuccessVal, "true"))
.errorMsg(Util.null2DefaultStr(tokenMsg, "error"))
.dataKey(Util.null2DefaultStr(tokenDataKey,""))
.build();
workflowToCmsService.workflowToCms(onlyMark,tokenOnlyMark, billTable, requestId,cmsResponseVoField, tokenSuccess);
}
public String getOnlyMark() {
return onlyMark;
}
public void setOnlyMark(String onlyMark) {
this.onlyMark = onlyMark;
}
public String getSuccessField() {
return successField;
}
public void setSuccessField(String successField) {
this.successField = successField;
}
public String getSuccessVal() {
return successVal;
}
public void setSuccessVal(String successVal) {
this.successVal = successVal;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getTokenOnlyMark() {
return tokenOnlyMark;
}
public void setTokenOnlyMark(String tokenOnlyMark) {
this.tokenOnlyMark = tokenOnlyMark;
}
public String getTokenSuccessField() {
return tokenSuccessField;
}
public void setTokenSuccessField(String tokenSuccessField) {
this.tokenSuccessField = tokenSuccessField;
}
public String getTokenSuccessVal() {
return tokenSuccessVal;
}
public void setTokenSuccessVal(String tokenSuccessVal) {
this.tokenSuccessVal = tokenSuccessVal;
}
public String getTokenMsg() {
return tokenMsg;
}
public void setTokenMsg(String tokenMsg) {
this.tokenMsg = tokenMsg;
}
public String getTokenDataKey() {
return tokenDataKey;
}
public void setTokenDataKey(String tokenDataKey) {
this.tokenDataKey = tokenDataKey;
}
public String getDataKey() {
return dataKey;
}
public void setDataKey(String dataKey) {
this.dataKey = dataKey;
}
}

View File

@ -0,0 +1,27 @@
package weaver.xuanran.wang.cssc.cms.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import weaver.xuanran.wang.sh_bigdata.common.service.CusDataDecipher;
/**
* <h1></h1>
*
* @author xuanran.wang
* @date 2023/4/6 19:34
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class CusSuccess {
private String successField;
private Object successValue;
private String errorMsg;
private String dataKey;
private Object response;
private CusDataDecipher cusDataDecipher;
}

View File

@ -0,0 +1,14 @@
package weaver.xuanran.wang.cssc.cms.service;
import weaver.xuanran.wang.cssc.cms.entity.CusSuccess;
/**
* <h1></h1>
*
* @author xuanran.wang
* @date 2023/4/26 10:53
*/
public interface WorkflowToCmsService {
String getToken(String onlyMark, String billTable, String requestId, CusSuccess cusSuccess);
void workflowToCms(String onlyMark,String tokenMark,String billTable, String requestId, CusSuccess cusSuccess, CusSuccess tokenSuccess);
}

View File

@ -0,0 +1,73 @@
package weaver.xuanran.wang.cssc.cms.service.impl;
import aiyh.utils.Util;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import weaver.conn.RecordSet;
import weaver.xiao.commons.config.entity.RequestMappingConfig;
import weaver.xiao.commons.config.service.DealWithMapping;
import weaver.xuanran.wang.common.util.CommonUtil;
import weaver.xuanran.wang.cssc.cms.entity.CusSuccess;
import weaver.xuanran.wang.cssc.cms.service.WorkflowToCmsService;
import weaver.xuanran.wang.cssc.cms.util.RequestMasterPlate;
import java.util.HashMap;
import java.util.Map;
/**
* <h1>vms</h1>
*
* @Author xuanran.wang
* @Date 2022/12/1 10:58
*/
public class WorkFlowToCmsServiceImpl implements WorkflowToCmsService {
private final DealWithMapping dealWithMapping = new DealWithMapping();
private final Logger log = Util.getLogger(); // 获取日志对象
private final RequestMasterPlate requestMasterPlate = new RequestMasterPlate();
@Override
public String getToken(String onlyMark,String billTable,
String requestId, CusSuccess cusSuccess) {
RequestMappingConfig requestMappingConfig = dealWithMapping.treeDealWithUniqueCode(onlyMark); // 将配置参数通过唯一标识查询处理成树形结构
RecordSet recordSet = initRs(requestMappingConfig, billTable, requestId);
String url = requestMappingConfig.getRequestUrl();
dealWithMapping.setMainTable(billTable);
Map<String, Object> param = dealWithMapping.getRequestParam(recordSet, requestMappingConfig);
return requestMasterPlate.apiPost(url, param, new HashMap<>(), cusSuccess);
}
/**
* <h1></h1>
*
* @param onlyMark
* @param billTable
* @param requestId id
* @author xuanran.wang
* @dateTime 2022/12/5 17:05
**/
@Override
public void workflowToCms(String onlyMark,String tokenMark, String billTable,
String requestId, CusSuccess cusSuccess, CusSuccess tokenSuccess) {
Map<String, String> headers = new HashMap<>();
if(StringUtils.isNotBlank(tokenMark)) {
String token = getToken(tokenMark, billTable, requestId, tokenSuccess);
headers.put("Authorization", "Bearer " + token);
}
RequestMappingConfig requestMappingConfig = dealWithMapping.treeDealWithUniqueCode(onlyMark); // 将配置参数通过唯一标识查询处理成树形结构
RecordSet recordSet = initRs(requestMappingConfig, billTable, requestId);
String url = requestMappingConfig.getRequestUrl();
dealWithMapping.setMainTable(billTable);
Map<String, Object> param = dealWithMapping.getRequestParam(recordSet, requestMappingConfig);
requestMasterPlate.apiPost(url, param, headers, cusSuccess);
}
public RecordSet initRs( RequestMappingConfig requestMappingConfig, String billTable, String requestId){
String selectMainSql = CommonUtil.getSelectSql(requestMappingConfig, billTable);
log.info(Util.logStr("查询主表数据sql : {}, requestId : {}", selectMainSql, requestId));
RecordSet recordSet = new RecordSet();
recordSet.executeQuery(selectMainSql, requestId);
recordSet.next();
return recordSet;
}
}

View File

@ -0,0 +1,80 @@
package weaver.xuanran.wang.cssc.cms.util;
import aiyh.utils.Util;
import aiyh.utils.excention.CustomerException;
import aiyh.utils.httpUtil.ResponeVo;
import aiyh.utils.httpUtil.util.HttpUtils;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import weaver.xuanran.wang.cssc.cms.entity.CusSuccess;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.util.Map;
/**
* <h1></h1>
*
* @author xuanran.wang
* @date 2023/4/4 11:51
*/
public class RequestMasterPlate {
private final Logger log = Util.getLogger();
private final HttpUtils httpUtils = new HttpUtils();
private static final int HTTP_SUCCESS_CODE = 200;
public <T> T apiGet(String url, Map<String, Object> params, Map<String, String> headers, CusSuccess cusSuccess){
ResponeVo responeVo;
try {
responeVo = httpUtils.apiGet(url, params, headers);
} catch (IOException e) {
throw new CustomerException(Util.logStr("发送请求发生异常! : {}", e.getMessage())); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串
}
return parseResponse(url, responeVo, params, cusSuccess);
}
public <T> T apiPost(String url, Object o, Map<String, String> headers, CusSuccess cusSuccess){
ResponeVo responeVo;
try {
headers.put("Content-Type", MediaType.APPLICATION_JSON);
responeVo = httpUtils.apiPostObject(url, o, headers);
} catch (IOException e) {
throw new CustomerException(Util.logStr("发送请求发生异常! : {}", e.getMessage())); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串
}
return parseResponse(url, responeVo, o, cusSuccess);
}
public <T> T parseResponse(String url, ResponeVo responseVo, Object o, CusSuccess cusSuccess){
if (responseVo.getCode() != HTTP_SUCCESS_CODE) { // 相应状态码
log.error(Util.logStr("can not fetch [{}]this request params is [{}]" + // 构建日志字符串
"this request heard is [{}]but response status code is [{}]" +
"this response is [{}]", url, JSON.toJSON(o), JSON.toJSONString(httpUtils.getGlobalCache().header), responseVo.getCode(), // 相应状态码
responseVo.getEntityString())); // 相应内容
throw new CustomerException(Util.logStr("can not fetch [{}]", url)); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串
}
Map<String, Object> response;
if(cusSuccess.getCusDataDecipher() != null){
response = cusSuccess.getCusDataDecipher().decoder(responseVo);
}else {
response = responseVo.getResponseMap(); // 根据相应结果转化为map集合
}
cusSuccess.setResponse(response);
String responseValue = Util.null2DefaultStr(response.get(cusSuccess.getSuccessField()), "");
if (!cusSuccess.getSuccessValue().equals(responseValue)) {
throw new CustomerException(Util.logStr("接口地址:[{}], 接口响应码不为: [{}], 接口响应信息: {}", url, cusSuccess.getSuccessValue(), Util.null2DefaultStr(response.get(cusSuccess.getErrorMsg()), ""))); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串
}
String[] split = Util.null2DefaultStr(cusSuccess.getDataKey(),"").split("\\.");
int len = split.length;
if(len == 0 || StringUtils.isBlank(cusSuccess.getDataKey())){
return (T)response;
}
for (int i = 0; i < len - 1; i++) {
response = (Map) response.get(split[i]);
}
return (T) response.get(split[len - 1]);
}
}

View File

@ -0,0 +1,53 @@
package weaver.xuanran.wang.eighty_five_degreec.sap.action;
import aiyh.utils.ThreadPoolConfig;
import aiyh.utils.action.SafeCusBaseAction;
import aiyh.utils.annotation.ActionDesc;
import aiyh.utils.annotation.PrintParamMark;
import aiyh.utils.annotation.RequiredMark;
import weaver.hrm.User;
import weaver.soa.workflow.request.RequestInfo;
import weaver.xuanran.wang.eighty_five_degreec.sap.entity.eneity.MainRequestConfig;
import weaver.xuanran.wang.eighty_five_degreec.sap.service.WorkflowToSapService;
import weaver.xuanran.wang.eighty_five_degreec.sap.service.impl.WorkflowToSapServiceImpl;
import java.util.concurrent.ExecutorService;
/**
* <h1>sap</h1>
*
* @author xuanran.wang
* @date 2023/4/14 16:30
*/
@ActionDesc(value = "流程数据推送到SAP",author = "xuanran.wang")
public class WorkflowToSap extends SafeCusBaseAction {
private final WorkflowToSapService service = new WorkflowToSapServiceImpl();
private final ExecutorService pool = ThreadPoolConfig.createThreadPoolInstance();
@PrintParamMark
@RequiredMark("配置表唯一标识")
private String uniqueCode;
@PrintParamMark
@RequiredMark("日志表模块id")
private String modelId;
@Override
public void doSubmit(String requestId, String billTable, int workflowId, User user, RequestInfo requestInfo) {
try {
MainRequestConfig config = service.getRequestConfig(uniqueCode, billTable);
String xml = service.convertXml(config, requestId, billTable);
String response = service.sendToSap();
pool.execute(()->{
try {
service.logToOA(modelId, config.getRequestUrl(), requestId, xml, response);
}catch (Exception e){
log.error("日志数据写入建模失败! " + e.getMessage());
}
});
}catch (Exception e){
log.error("流程数据推送SAP error : " + e.getMessage());
}
}
}

View File

@ -0,0 +1,41 @@
package weaver.xuanran.wang.eighty_five_degreec.sap.entity.eneity;
import aiyh.utils.annotation.recordset.SqlDbFieldAnn;
import aiyh.utils.annotation.recordset.SqlOracleDbFieldAnn;
import lombok.Data;
/**
* @Author xuanran.wang
* @Date 2022/6/18 16:47
*/
@Data
public class DetailRequestConfig {
@SqlDbFieldAnn("paramName")
@SqlOracleDbFieldAnn("PARAMNAME")
private String paramName;
@SqlDbFieldAnn("paramType")
@SqlOracleDbFieldAnn("PARAMTYPE")
private String paramType;
@SqlDbFieldAnn("getValueType")
@SqlOracleDbFieldAnn("GETVALUETYPE")
private String getValueType;
@SqlDbFieldAnn("valueContext")
@SqlOracleDbFieldAnn("VALUECONTEXT")
private String valueContext;
@SqlDbFieldAnn("tableName")
@SqlOracleDbFieldAnn("TABLENAME")
private String tableName;
@SqlDbFieldAnn("workFlowField")
@SqlOracleDbFieldAnn("WORKFLOWFIELD")
private String workFlowField;
@SqlDbFieldAnn("fieldName")
@SqlOracleDbFieldAnn("FIELDNAME")
private String fieldName;
@SqlDbFieldAnn("detailId")
@SqlOracleDbFieldAnn("DETAILID")
private String detailId;
@SqlDbFieldAnn("parentName")
@SqlOracleDbFieldAnn("PARENTNAME")
private String parentName;
}

View File

@ -0,0 +1,47 @@
package weaver.xuanran.wang.eighty_five_degreec.sap.entity.eneity;
import aiyh.utils.annotation.recordset.SqlDbFieldAnn;
import aiyh.utils.annotation.recordset.SqlOracleDbFieldAnn;
import lombok.Data;
import java.util.List;
/**
* @Author xuanran.wang
* @Date 2022/6/18 15:43
*/
@Data
public class MainRequestConfig {
@SqlDbFieldAnn("id")
@SqlOracleDbFieldAnn("ID")
private String id;
@SqlDbFieldAnn("uniqueCode")
@SqlOracleDbFieldAnn("UNIQUECODE")
private String uniqueCode;
@SqlDbFieldAnn("workflow")
@SqlOracleDbFieldAnn("WORKFLOW")
private String workflow;
@SqlDbFieldAnn("requestUrl")
@SqlOracleDbFieldAnn("REQUESTURL")
private String requestUrl;
@SqlDbFieldAnn("dataSource")
@SqlOracleDbFieldAnn("DATASOURCE")
private String dataSource;
@SqlDbFieldAnn("detailIndex")
@SqlOracleDbFieldAnn("DETAILINDEX")
private String detailIndex;
@SqlDbFieldAnn("cusSql")
@SqlOracleDbFieldAnn("CUSSQL")
private String cusSql;
@SqlDbFieldAnn("configFilePath")
@SqlOracleDbFieldAnn("CONFIGFILEPATH")
private String configFilePath;
@SqlDbFieldAnn("enable")
@SqlOracleDbFieldAnn("ENABLE")
private String enable;
@SqlDbFieldAnn("methodParameterClassName")
@SqlOracleDbFieldAnn("METHODPARAMETERCLASSNAME")
private String methodParameterClassName;
private List<DetailRequestConfig> detailRequestConfigList;
}

View File

@ -0,0 +1,16 @@
package weaver.xuanran.wang.eighty_five_degreec.sap.service;
import weaver.xuanran.wang.eighty_five_degreec.sap.entity.eneity.MainRequestConfig;
/**
* <h1>sap</h1>
*
* @author xuanran.wang
* @date 2023/4/19 15:15
*/
public interface WorkflowToSapService {
MainRequestConfig getRequestConfig(String uniqueCode, String tableName);
String convertXml(MainRequestConfig config, String requestId, String tableName);
String sendToSap();
void logToOA(String modelId, String url, String requestId, String requestXml, String response);
}

View File

@ -0,0 +1,49 @@
package weaver.xuanran.wang.eighty_five_degreec.sap.service.impl;
import aiyh.utils.Util;
import weaver.xuanran.wang.common.util.CusInfoToOAUtil;
import weaver.xuanran.wang.eighty_five_degreec.sap.entity.eneity.MainRequestConfig;
import weaver.xuanran.wang.eighty_five_degreec.sap.service.WorkflowToSapService;
import weaver.xuanran.wang.eighty_five_degreec.sap.util.ReadConfigUtil;
import java.util.Collections;
import java.util.HashMap;
/**
* <h1>sap</h1>
*
* @author xuanran.wang
* @date 2023/4/19 15:17
*/
public class WorkflowToSapServiceImpl implements WorkflowToSapService {
private final ReadConfigUtil configUtil = new ReadConfigUtil();
@Override
public MainRequestConfig getRequestConfig(String uniqueCode, String tableName) {
return configUtil.getConfigByUniqueCode(uniqueCode, tableName);
}
@Override
public String convertXml(MainRequestConfig config, String requestId, String tableName) {
return configUtil.getXml(config, requestId, tableName);
}
@Override
public String sendToSap() {
// TODO sap接口调用方式暂时搞不了
return "";
}
@Override
public void logToOA(String modelId, String url, String requestId,
String requestXml, String response) {
HashMap<String, Object> params = new HashMap<>();
params.put("requestUrlAndFunName", url);
params.put("reqId", requestId);
params.put("requestXml", requestXml);
params.put("responseCode","");
params.put("erpResponse", response);
CusInfoToOAUtil.getDataId(Util.getIntValue(modelId, -1), params, "select id from #{tableName} where reqId = ?", Collections.singletonList(requestId));
}
}

View File

@ -0,0 +1,565 @@
package weaver.xuanran.wang.eighty_five_degreec.sap.util;
import com.google.common.base.Strings;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import weaver.conn.RecordSet;
import weaver.general.GCONST;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.xuanran.wang.eighty_five_degreec.sap.entity.eneity.DetailRequestConfig;
import weaver.xuanran.wang.eighty_five_degreec.sap.entity.eneity.MainRequestConfig;
import weaver.zwl.common.ToolUtil;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* @Author xuanran.wang
* @Date 2022/11/14 11:33
*
*/
public class ReadConfigUtil extends ToolUtil {
private static final int enable = 0;
private final Logger log = aiyh.utils.Util.getLogger();
/**
* <h1></h1>
* @param uniqueCode
* @param mainTableName
* @return
*/
public MainRequestConfig getConfigByUniqueCode(String uniqueCode, String mainTableName){
MainRequestConfig res = new MainRequestConfig();
RecordSet queryRs = new RecordSet();
String sql = "select * from uf_memsic_createXml where uniqueCode = ? and enable = ?";
if (queryRs.executeQuery(sql, uniqueCode,enable)) {
if (queryRs.next()) {
res = getInstance(queryRs, MainRequestConfig.class);
}
}
if (res == null || StringUtils.isBlank(res.getId()) || (-1 == Util.getIntValue(res.getId(), -1))) {
throw new RuntimeException("配置不存在");
}
int mainId = Util.getIntValue(res.getId());
// 配置明细表
sql = "select paramName,paramType,parentName,getValueType,workflowField,valueContext,fv.tableName," +
" fv.id fieldId,fv.fieldname,fv.indexdesc " +
" from uf_memsic_createXml_dt1 config " +
" left join workflow_field_table_view fv on config.workflowField = fv.id " +
" where mainid = ? and enable = ?";
if (queryRs.executeQuery(sql, mainId,enable)) {
ArrayList<DetailRequestConfig> detailConfigs = new ArrayList<>();
while (queryRs.next()) {
DetailRequestConfig detailConfig = getInstance(queryRs, DetailRequestConfig.class);
String tableName = detailConfig.getTableName();
// 主表默认0
String detailId = "0";
// 明细id替换
if(!mainTableName.equals(detailConfig.getTableName())){
detailId = tableName.replaceAll(mainTableName + "_dt", "");
}
detailConfig.setDetailId(detailId);
detailConfigs.add(detailConfig);
}
res.setDetailRequestConfigList(detailConfigs);
}
return res;
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2022/11/15 22:20
* @param queryRs
* @param clazz class
* @return
**/
public static <T> T getInstance(RecordSet queryRs, Class<T> clazz) {
T res = null;
try {
res = clazz.newInstance();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
// 判断字段类型
if (field.getType().isAssignableFrom(List.class) || field.getType().isAssignableFrom(Map.class)) {
continue;
}
field.setAccessible(true);
String fieldName = field.getName();
if ("oracle".equals(queryRs.getDBType())) {
fieldName = fieldName.toUpperCase();
}
String value = Util.null2String(queryRs.getString(fieldName));
field.set(res, value);
}
} catch (Exception e) {
throw new RuntimeException("实体类生成异常");
}
return res;
}
/**
* <h1></h1>
* @param detailRequestConfig
* @param mainRs recordSet
* @param detailRs recordSet
* @return
*/
public Object getParamValue(DetailRequestConfig detailRequestConfig,
RecordSet mainRs, RecordSet detailRs, int count){
Object value = "";
try {
// 参数类型
String paramType = detailRequestConfig.getParamType();
// 取值方式
String getValueType = detailRequestConfig.getGetValueType();
// 明细id
String detailId = detailRequestConfig.getDetailId();
// 自定义文本
String valueContext = detailRequestConfig.getValueContext();
// 接口参数名称
String paramName = detailRequestConfig.getParamName();
// 父级参数名称
String parentName = detailRequestConfig.getParentName();
switch (getValueType){
// 流程字段
case "0":{
String fieldName = detailRequestConfig.getFieldName();
if("0".equals(detailId)){
value = Util.null2String(mainRs.getString(fieldName));
}else{
value = Util.null2String(detailRs.getString(fieldName));
}
break;
}
// 固定值
case "1":{
value = Util.null2String(detailRequestConfig.getValueContext());
break;
}
// 当前时间
case "3":{
// 当前时间
value = TimeUtil.getCurrentTimeString();
break;
}
// 自定义sql
case "4":{
String fieldName = detailRequestConfig.getFieldName();
String tempValue;
if("0".equals(detailId)){
tempValue = Util.null2String(mainRs.getString(fieldName));
}else{
tempValue = Util.null2String(detailRs.getString(fieldName));
}
String requestId = Util.null2String(mainRs.getString("requestid"));
value = getValueByChangeRule(detailRequestConfig.getValueContext(), tempValue, requestId);
break;
}
// 请求id
case "5" : {
value = Util.null2String(mainRs.getString("requestid"));
}break;
// 主数据id
case "6": {
if ("mainRecord".equals(parentName)) {
value = Util.null2String(mainRs.getString("id"));
} else {
value = Util.null2String(detailRs.getString("id"));
}
}break;
// 随机数
case "7": {
int bit = Util.getIntValue(valueContext, 10);
value = this.getGUID(bit);
}break;
case "9":{
value = count;
}break;
default:break;
}
// 参数类型
switch (paramType){
// String
case "0":{
value = Util.null2String(value);
value = String.valueOf(value).replaceAll("&nbsp;", " ")
.replaceAll("<br>", " ")
.replaceAll("&", "&amp;")
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;")
.replaceAll("\"", "&quot;")
.replaceAll("'", "&apos;");
break;
}
// Int
case "1":{
value = Util.getIntValue(String.valueOf(value),0);
break;
}
// Double
case "2":{
value = Util.getDoubleValue(String.valueOf(value),0);
break;
}
//日期类型
case "3" : {
if (null == value || Strings.isNullOrEmpty(String.valueOf(value))) {
value = "";
break;
}
try {
Date date = value instanceof Date ? (Date) value : parseDate(String.valueOf(value));
value = this.diyDateFortMat(date, "yyyy-MM-dd");
} catch (Exception e) {
throw new RuntimeException("时间处理异常:参数>>" + paramName);
}
}break;
// 时间日期类型
case "4": {
if (null == value || Strings.isNullOrEmpty(String.valueOf(value))) {
value = "";
break;
}
try {
Date date = value instanceof Date ? (Date) value : parseDate(String.valueOf(value));
value = this.diyDateFortMat(date, "yyyy-MM-dd HH:mm:ss");
} catch (Exception e) {
throw new RuntimeException("时间处理异常:参数>>" + paramName + " 异常信息:" + e);
}
}
break;
// 自定义时间格式化类型
case "7": {
if (null == value || Strings.isNullOrEmpty(String.valueOf(value))) {
value = "";
break;
}
try {
Date date = value instanceof Date ? (Date) value : parseDate(String.valueOf(value));
value = this.diyDateFortMat(date, valueContext);
} catch (Exception e) {
throw new RuntimeException("时间处理异常:参数>>" + paramName + " 异常信息:" + e.getMessage());
}
}
break;
// 时间戳类型
case "8": {
if (null == value || Strings.isNullOrEmpty(String.valueOf(value))) {
value = "";
break;
}
try {
Date date = value instanceof Date ? (Date) value : parseDate(String.valueOf(value));
value = date.getTime();
} catch (Exception e) {
throw new RuntimeException("时间处理异常:参数>>" + paramName + " 异常信息:" + e.getMessage());
}
}break;
default:break;
}
}catch (Exception e){
throw new RuntimeException("执行setCommonParamValue发生异常 : " + e.getMessage());
}
return value;
}
/**
* <h1></h1>
* @param dateStr
* @return
*/
public static Date parseDate(String dateStr) {
ThreadLocal<SimpleDateFormat> SIMPLE_DATE_FORMAT = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd"));
if (dateStr == null || dateStr.length() == 0) {
return null;
}
String regex = "\\/|\\.|年|月|日";
Date date = null;
try {
date = SIMPLE_DATE_FORMAT.get().parse(dateStr.replaceAll(regex, "-"));
return date;
} catch (ParseException e) {
throw new RuntimeException("无法将" + dateStr + "转换为日期对象!", e);
}
}
/**
* <h1></h1>
* @param date
* @param tempStr
* @return
*/
private static String diyDateFortMat(Date date,String tempStr){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(tempStr);
return simpleDateFormat.format(date);
}
/**
* <h1>xml</h1>
* @param config
* @param requestId id
* @param tableName
* @return xml
*/
public String getXml(MainRequestConfig config, String requestId,String tableName){
try {
String configFilePath = config.getConfigFilePath();
if(StringUtils.isBlank(configFilePath)){
throw new RuntimeException("建模主表配置文件不能为空!");
}
String requestUrl = config.getRequestUrl();
if(StringUtils.isBlank(requestUrl)){
throw new RuntimeException("获取配置文件明细表为空!");
}
List<DetailRequestConfig> requestConfigList = config.getDetailRequestConfigList();
if(CollectionUtils.isEmpty(requestConfigList)){
throw new RuntimeException("获取配置文件明细表为空!");
}
String sql = "select * from " + tableName + " where requestid = ?";
if(StringUtils.isNotBlank(config.getCusSql())){
sql += config.getCusSql();
}
String dataSource = config.getDataSource();
RecordSet mainRs = new RecordSet();
RecordSet detailRs = new RecordSet();
mainRs.executeQuery(sql, requestId);
log.info("执行主表查询SQL[ " + sql + " ], 参数 [ " + requestId + " ]");
if (mainRs.next()) {
String mainId = mainRs.getString("id");
String mainXml = "";
String detailXml = "";
// 主表
if ("0".equals(dataSource)) {
mainXml = getMainXml(requestConfigList, mainRs, detailRs);
} else if("1".equals(dataSource)) {
// 仅明细
detailXml = getDetailXml(requestConfigList, mainRs, detailRs, config.getDetailIndex(), tableName, mainId);
}else {
// 主表-明细
mainXml = getMainXml(requestConfigList, mainRs, detailRs);
detailXml = getDetailXml(requestConfigList, mainRs, detailRs, config.getDetailIndex(), tableName, mainId);
}
StringBuilder xml = new StringBuilder();
try {
String filePath = parseConfigPath(configFilePath);
log.info("模板配置文件路径 [ " + filePath + " ]");
FileInputStream in = new FileInputStream(filePath);
InputStreamReader inReader = new InputStreamReader(in, StandardCharsets.UTF_8);
BufferedReader bufReader = new BufferedReader(inReader);
String line;
while ((line = bufReader.readLine()) != null) {
if(line.contains("{mainRecord}")){
line = mainXml;
xml.append(line);
}else if(line.contains("{detailRecord}")){
line = detailXml;
xml.append(line);
}else {
if(StringUtils.isNotBlank(line)){
String pattern = "(?<=\\{).+(?=})";
Pattern compile = Pattern.compile(pattern);
Matcher matcher = compile.matcher(line);
while (matcher.find()){
String field = matcher.group();
if(StringUtils.isNotBlank(field)){
if(field.startsWith("main.")){
String mainField = field.replace("main.", "");
line = line.replaceAll("#\\{.+}",Util.null2String(mainRs.getString(mainField)));
}else if(field.startsWith("sql.")){
String selectSql = field.replace("sql.", "");
Matcher matcherSql = compile.matcher(selectSql);
while (matcherSql.find()){
String sqlField = matcherSql.group();
String value = Util.null2String(mainRs.getString(sqlField));
String replaceAllSql = selectSql.replaceAll("#\\{.+}", "\\?");
line = line.replaceAll("#\\{.+}",Util.null2String(getValueByChangeRule(replaceAllSql,value, requestId)));
}
}
}
}
}
xml.append(line).append("\n");
}
}
bufReader.close();
inReader.close();
in.close();
} catch (Exception e) {
throw new RuntimeException("读取配置文件失败!文件路径=> " + configFilePath + " error => " + e.getMessage());
}
return xml.toString();
}
}catch (Exception e){
throw new RuntimeException("生成xml发生异常, " + e.getMessage());
}
return "";
}
/**
* <h1>xml</h1>
* @param requestConfigList
* @param mainRs recordSet
* @param detailRs recordSet
* @return xml
*/
public String getMainXml(List<DetailRequestConfig> requestConfigList,
RecordSet mainRs,
RecordSet detailRs){
List<DetailRequestConfig> collect = requestConfigList.stream()
.filter(item -> "mainRecord".equals(item.getParentName()))
.collect(Collectors.toList());
StringBuilder mainSb = new StringBuilder();
appendXml(mainSb, collect, mainRs, detailRs,1);
return mainSb.toString();
}
/**
* <h1>xml</h1>
* @param requestConfigList
* @param mainRs recordSet
* @param detailRs recordSet
* @param detailIndex
* @param tableName
* @param mainId id
* @return xml
*/
public String getDetailXml(List<DetailRequestConfig> requestConfigList,
RecordSet mainRs, RecordSet detailRs, String detailIndex,
String tableName, String mainId){
// 明细
String[] detailIdArr = detailIndex.split(",");
StringBuilder detailSb = new StringBuilder();
for (String detailId : detailIdArr) {
List<DetailRequestConfig> detailCollect = requestConfigList.stream()
.filter(item -> "detailRecord".equals(item.getParentName())
).collect(Collectors.toList());
String detailSql = "select * from " + tableName + "_dt" + detailId + " where mainid = ?";
if (detailRs.executeQuery(detailSql, mainId)) {
int count = 1;
while (detailRs.next()) {
appendXml(detailSb, detailCollect, mainRs, detailRs, count++);
}
}
}
return detailSb.toString();
}
/**
* <h1>xml</h1>
* @param xml xml
* @param configList
* @param mainRs recordSet
* @param detailRs recordSet
* @param count
*/
public void appendXml(StringBuilder xml, List<DetailRequestConfig> configList,
RecordSet mainRs, RecordSet detailRs, int count){
for (DetailRequestConfig requestConfig : configList) {
String paramName = requestConfig.getParamName();
xml.append("<")
.append(paramName)
.append(">")
.append(getParamValue(requestConfig, mainRs, detailRs,count))
.append("<")
.append(paramName)
.append(">")
.append("\n");
}
}
/**
* <h1>xml</h1>
* wxr.memsic.test.xml = /wxr/memsic/test.xml
* @param configFilePath
* @return
*/
public String parseConfigPath(String configFilePath){
StringBuilder filePath = new StringBuilder(GCONST.getSysFilePath());
int beginIndex = configFilePath.indexOf(".");
int endIndex = configFilePath.lastIndexOf(".");
if(beginIndex == endIndex){
filePath.append(configFilePath);
}else {
String[] pathArr = configFilePath.split("\\.");
for (int i = 0; i < pathArr.length - 2; i++) {
if(i != 0){
filePath.append(File.separator);
}
filePath.append(pathArr[i]);
}
filePath.append(File.separator)
.append(pathArr[pathArr.length - 2])
.append(".")
.append(pathArr[pathArr.length - 1]);
}
return filePath.toString();
}
private String getGUID(int bit) {
StringBuilder uid = new StringBuilder();
// 产生16位的强随机数
Random rd = new SecureRandom();
for (int i = 0; i < bit; i++) {
// 产生0-2的3位随机数
int type = rd.nextInt(3);
switch (type) {
case 0:
// 0-9的随机数
uid.append(rd.nextInt(10));
break;
case 1:
// ASCII在65-90之间为大写,获取大写随机
uid.append((char) (rd.nextInt(25) + 65));
break;
case 2:
// ASCII在97-122之间为小写获取小写随机
uid.append((char) (rd.nextInt(25) + 97));
break;
default:
break;
}
}
return uid.toString();
}
/**
* <h1></h1>
* @param responseMap map
* @param responseField map Response.Execution
* @return
*/
public String parseMap(Map<String, Object> responseMap, String responseField){
String[] strArr = responseField.split("\\.");
int i = 0;
while (i < strArr.length - 1){
Object o = responseMap.get(strArr[i]);
if(o instanceof Map){
responseMap = (Map<String, Object>) o;
}else if(o instanceof List){
List<Map<String, Object>> list = (List<Map<String, Object>>) o;
if(CollectionUtils.isEmpty(list)){
return "";
}
responseMap = list.get(0);
}
i++;
}
return Util.null2String(responseMap.get(strArr[strArr.length - 1]));
}
}

View File

@ -13,14 +13,18 @@ import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.apache.log4j.Logger;
import weaver.conn.RecordSet;
import weaver.general.GCONST;
import weaver.xiao.commons.config.entity.RequestMappingConfig;
import weaver.xiao.commons.config.service.DealWithMapping;
import weaver.xuanran.wang.common.util.CommonUtil;
import weaver.xuanran.wang.immc.entity.VmsResponseVoField;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.io.*;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* <h1>vms</h1>
@ -115,32 +119,41 @@ public class WorkFlowToVmsAndMQService {
**/
public void sendToMQ(String kafkaConfig, Map<String, Object> message){
KafkaProducer<String, String> producer = null;
InputStream inputStream = null;
try {
Map<String, Object> configMap = Util.getProperties2Map(kafkaConfig);
if(MapUtils.isEmpty(configMap)){
String path = GCONST.getPropertyPath() + "prop2map" + File.separator + kafkaConfig + ".properties";
File configFile = new File(path);
if(!configFile.exists()){
throw new CustomerException("please check /web-inf/prop2map has " + kafkaConfig + ".properties");
}
log.info("kafkaConfig : " + JSONObject.toJSONString(configMap));
String topic = Util.null2DefaultStr(configMap.get("topic"),"");
Properties prop = new Properties();
inputStream= new BufferedInputStream(Files.newInputStream(configFile.toPath()));
prop.load(inputStream);
log.info("prop => " + JSONObject.toJSONString(prop));
log.info("msg => " + JSONObject.toJSONString(message));
String topic = Util.null2DefaultStr(prop.getProperty("topic"),"");
if(StringUtils.isBlank(topic)){
throw new CustomerException("kafka properties topic can not null!");
}
producer = new KafkaProducer<>(configMap);
producer = new KafkaProducer<>(prop);
// 发送消息到指定主题
ProducerRecord<String, String> record = new ProducerRecord<>(topic, JSONObject.toJSONString(message));
try {
RecordMetadata recordMetadata = producer.send(record).get();
log.info(Util.logStr("send mq recordMetadata: {}", JSONObject.toJSONString(recordMetadata)));
producer.send(record).get();
}catch (Exception e){
throw new CustomerException(Util.logStr("producer send error: {}!", e.getMessage()));
}
}catch (Exception e){
throw new CustomerException(Util.logStr("send to kafka error!: {}", e.getMessage()));
log.error(Util.getErrString(e));
throw new CustomerException(Util.logStr("send to kafka error!: [{}]", e.getMessage()));
}finally {
// 关闭Kafka生产者实例
if(producer != null){
producer.close();
}
if(inputStream != null){
try {
inputStream.close();
}catch (Exception e){
log.error("inputStream close error! " + e.getMessage());
}
}
}
}

View File

@ -4,8 +4,8 @@ import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import weaver.xuanran.wang.sh_bigdata.common.service.CusDataDecipher;
import java.util.function.Consumer;
/**
* <h1></h1>
@ -23,4 +23,5 @@ public class CusSuccess {
private String errorMsg;
private String dataKey;
private Object response;
private CusDataDecipher cusDataDecipher;
}

View File

@ -0,0 +1,15 @@
package weaver.xuanran.wang.sh_bigdata.common.service;
import aiyh.utils.httpUtil.ResponeVo;
import java.util.Map;
/**
* <h1></h1>
*
* @author xuanran.wang
* @date 2023/4/10 13:20
*/
public interface CusDataDecipher {
Map<String, Object> decoder(ResponeVo responeVo);
}

View File

@ -5,7 +5,6 @@ import aiyh.utils.excention.CustomerException;
import aiyh.utils.httpUtil.ResponeVo;
import aiyh.utils.httpUtil.util.HttpUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import weaver.xuanran.wang.sh_bigdata.common.entity.CusSuccess;
@ -52,11 +51,16 @@ public class RequestMasterPlate{
responseVo.getEntityString())); // 相应内容
throw new CustomerException(Util.logStr("can not fetch [{}]", url)); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串
}
Map<String, Object> response = responseVo.getResponseMap(); // 根据相应结果转化为map集合
Map<String, Object> response;
if(cusSuccess.getCusDataDecipher() != null){
response = cusSuccess.getCusDataDecipher().decoder(responseVo);
}else {
response = responseVo.getResponseMap(); // 根据相应结果转化为map集合
}
cusSuccess.setResponse(response);
int responseValue = Util.getIntValue(Util.null2DefaultStr(response.get(cusSuccess.getSuccessField()), ""),-1);
if (cusSuccess.getSuccessValue() != responseValue) {
throw new CustomerException(Util.logStr("接口响应码不为: [{}], 接口响应信息: {}", cusSuccess.getSuccessValue(), Util.null2DefaultStr(response.get(cusSuccess.getErrorMsg()), ""))); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串
throw new CustomerException(Util.logStr("接口地址:[{}], 接口响应码不为: [{}], 接口响应信息: {}", url, cusSuccess.getSuccessValue(), Util.null2DefaultStr(response.get(cusSuccess.getErrorMsg()), ""))); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串
}
String[] split = Util.null2DefaultStr(cusSuccess.getDataKey(),"").split("\\.");
int len = split.length;

View File

@ -26,7 +26,7 @@ import java.util.stream.Collectors;
public class SendTodoTaskUtil {
private final SendTodoTaskMapper mapper = Util.getMapper(SendTodoTaskMapper.class);
private final CommonMapper commonMapper = Util.getMapper(CommonMapper.class);
private String appId;
private String agentId;
private String oaAddress;
private Logger log = Util.getLogger();
@ -71,11 +71,11 @@ public class SendTodoTaskUtil {
int requestId = obj.getRequestid();
int userId = obj.getUser().getUID();
todoTask.setTaskNum(taskId);
todoTask.setAppId(appId);
todoTask.setAgentid(agentId);
todoTask.setTaskName(obj.getRequestnamenew());
todoTask.setTaskDesc(obj.getRequestnamenew());
todoTask.setLinkUrl(oaAddress + "/spa/workflow/static4form/index.html?#/main/workflow/req?requestid="+requestId);
todoTask.setMobileLinkUrl(oaAddress + "/spa/workflow/static4mobileform/index.html?#/req?requestid="+requestId);
todoTask.setLinkUrl(Util.null2DefaultStr(ShBigDataUtil.getPropertiesValByKey("taskPcUrl"), oaAddress) + "/spa/workflow/static4form/index.html?#/main/workflow/req?requestid="+requestId);
todoTask.setMobileLinkUrl(Util.null2DefaultStr(ShBigDataUtil.getPropertiesValByKey("taskMobileUrl"), oaAddress) + "/spa/workflow/static4mobileform/index.html?#/req?requestid="+requestId);
todoTask.setSender(getConvertHrm(0, obj, obj.getCreator().getUID() + ""));
todoTask.setReceiver(getConvertHrm(1, obj,userId + ""));
res.add(todoTask);
@ -99,7 +99,7 @@ public class SendTodoTaskUtil {
CusDoneTask doneTask = new CusDoneTask();
doneTask.setTaskNum(num);
doneTask.setStatus(1);
doneTask.setAppId(appId);
doneTask.setAgentid(agentId);
res.add(doneTask);
}
}
@ -156,11 +156,10 @@ public class SendTodoTaskUtil {
* @return OA
**/
public String getOAAddress(){
String address = mapper.queryOAAddress();
if(StringUtils.isBlank(address)){
throw new CustomerException("OAAddress can not null!");
}
return address;
// if(StringUtils.isBlank(address)){
// throw new CustomerException("OAAddress can not null!");
// }
return Util.null2DefaultStr(mapper.queryOAAddress(),"");
}

View File

@ -2,11 +2,9 @@ package weaver.xuanran.wang.sh_bigdata.common.util;
import aiyh.utils.Util;
import aiyh.utils.excention.CustomerException;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import weaver.xuanran.wang.sh_bigdata.common.entity.CusSuccess;
import weaver.xuanran.wang.sh_bigdata.common.entity.CusToken;
import weaver.general.TimeUtil;
import weaver.xuanran.wang.sh_bigdata.org_hrm_async.annotations.CusDbEntityMapping;
import java.lang.reflect.Field;
@ -28,6 +26,15 @@ public class ShBigDataUtil {
static {
WHILTE_LIST.add("hrmSenderConvertRuleSql");
WHILTE_LIST.add("hrmReceiveConvertRuleSql");
WHILTE_LIST.add("maxLevel");
WHILTE_LIST.add("orgNoFetchChild");
WHILTE_LIST.add("orgUpdateTime");
WHILTE_LIST.add("hrmUpdateTime");
WHILTE_LIST.add("orgHrmAsyncLogModelId");
WHILTE_LIST.add("loginSuccessSendRedirectUrl");
WHILTE_LIST.add("loginErrorSendRedirectUrl");
WHILTE_LIST.add("getUserIdDebug");
WHILTE_LIST.add("getUserIdDebugOutKey");
}
/**
@ -37,7 +44,18 @@ public class ShBigDataUtil {
* @return token
**/
public static String getToken(){
return TokenUtil.getToken();
return TokenUtil.getToken(ShBigDataUtil.getPropertiesValByKey("corpSecret"));
}
/**
* <h1>token</h1>
* @author xuanran.wang
* @dateTime 2023/4/6 19:59
* @param secret
* @return token
**/
public static String getToken(String secret){
return TokenUtil.getToken(secret);
}
/**
@ -51,6 +69,18 @@ public class ShBigDataUtil {
return url + "?access_token=" + getToken();
}
/**
* <h1>posturltoken</h1>
* @author xuanran.wang
* @dateTime 2023/4/6 20:11
* @param url
* @param secret
* @return tokenurl
**/
public static String addToken2Url(String url, String secret){
return url + "?access_token=" + getToken(secret);
}
/**
* <h1></h1>
* @author xuanran.wang
@ -90,6 +120,19 @@ public class ShBigDataUtil {
* @return
**/
public static LinkedHashMap<String, Object> parseCusDbEntityMapping(int type, Object o) throws IllegalAccessException {
return parseCusDbEntityMapping(type, 0, false);
}
/**
* <h1>map</h1>
* @author xuanran.wang
* @dateTime 2023/4/6 12:27
* @param type 0: , 1:
* @param o
* @param addSysParam
* @return
**/
public static LinkedHashMap<String, Object> parseCusDbEntityMapping(int type, Object o, boolean addSysParam) throws IllegalAccessException {
Class<?> clazz = o.getClass();
LinkedHashMap<String, Object> params = new LinkedHashMap<>();
Field[] fields = clazz.getDeclaredFields();
@ -103,18 +146,28 @@ public class ShBigDataUtil {
if(cusDbEntityMapping != null){
String[] dbFields = cusDbEntityMapping.dbFiled();
String dbField;
if(dbFields.length == 0 || type == -1){
dbField = field.getName();
if(dbFields.length <= 1 || type == -1){
dbField = dbFields[0];
}else {
int index = Math.min(dbFields.length, type);
dbField = dbFields[index - 1];
dbField = dbFields[type];
}
if(StringUtils.isBlank(dbField)){
continue;
}
field.setAccessible(true);
params.put(dbField, field.get(o));
}
}
if(addSysParam){
String dateTime = TimeUtil.getCurrentTimeString();
params.put("creater",1);
params.put("created", dateTime);
params.put("modifier", 1);
params.put("modified", dateTime);
}
return params;
}
}

View File

@ -10,6 +10,7 @@ import weaver.xuanran.wang.sh_bigdata.common.entity.CusToken;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* <h1>token </h1>
@ -19,39 +20,43 @@ import java.util.Map;
*/
public class TokenUtil {
private static final Logger log = Util.getLogger();
private static volatile CusToken cusToken = null;
// private static volatile CusToken cusToken = null;
private static final CusSuccess tokenCusSuccess = CusSuccess.builder()
.successField("errcode")
.successValue(0)
.errorMsg("msg")
.errorMsg("errmsg")
.dataKey("")
.build();
private static final RequestMasterPlate requestMasterPlate = new RequestMasterPlate();
private static final Map<String, CusToken> TOKEN_MAP = new ConcurrentHashMap<>();
/**
* <h1>token</h1>
* @author xuanran.wang
* @dateTime 2023/4/6 19:59
* @return token
* @param secret
**/
public static String getToken() {
if(cusToken == null){
public static String getToken(String secret) {
CusToken token = TOKEN_MAP.get(secret);
if(token == null){
synchronized (TokenUtil.class){
if(cusToken == null){
return getTokenByHTTP();
token = TOKEN_MAP.get(secret);
if(token == null){
return getTokenByHTTP(secret);
}
}
}
long expiryTime = cusToken.getExpiryTime();
long expiryTime = token.getExpiryTime();
if(new Date().getTime() >= expiryTime){
synchronized (TokenUtil.class){
expiryTime = cusToken.getExpiryTime();
expiryTime = token.getExpiryTime();
if(new Date().getTime() >= expiryTime){
return getTokenByHTTP();
return getTokenByHTTP(secret);
}
}
}
return cusToken.getAccess_token();
return token.getAccess_token();
}
/**
@ -60,19 +65,20 @@ public class TokenUtil {
* @dateTime 2023/4/7 23:49
* @return token
**/
private static String getTokenByHTTP(){
private static String getTokenByHTTP(String secret){
log.info("getTokenByHTTP secret : " + secret);
HashMap<String, Object> params = new HashMap<>();
// 接口调用地址
String tokenUrl = ShBigDataUtil.getPropertiesValByKey("tokenUrl");
// 密钥
String corpSecret = ShBigDataUtil.getPropertiesValByKey("corpSecret");
params.put("corpsecret", corpSecret);
params.put("corpsecret", secret);
Map<String, Object> tokenMap = requestMasterPlate.apiGet(tokenUrl, params, new HashMap<>(), tokenCusSuccess);
cusToken = JSONObject.parseObject(JSONObject.toJSONString(tokenMap), CusToken.class);
CusToken token = JSONObject.parseObject(JSONObject.toJSONString(tokenMap), CusToken.class);
long expiryBeforeTime = Util.getIntValue(ShBigDataUtil.getPropertiesValByKey("expiryBeforeTime"), 5);
// 默认少5分钟过期
cusToken.setExpiryTime(new Date().getTime() + (cusToken.getExpires_in() * 1000) - (60 * expiryBeforeTime * 1000));
log.info("http token => " + JSONObject.toJSONString(cusToken));
return cusToken.getAccess_token();
token.setExpiryTime(new Date().getTime() + (token.getExpires_in() * 1000) - (60 * expiryBeforeTime * 1000));
TOKEN_MAP.put(secret, token);
log.info("token maps : " + JSONObject.toJSONString(TOKEN_MAP));
return token.getAccess_token();
}
}

View File

@ -1,9 +1,16 @@
package weaver.xuanran.wang.sh_bigdata.org_hrm_async;
import aiyh.utils.Util;
import com.alibaba.fastjson.JSONObject;
import org.apache.log4j.Logger;
import weaver.hrm.resource.HrmSynDAO;
import weaver.interfaces.hrm.*;
import weaver.xuanran.wang.sh_bigdata.org_hrm_async.service.OrgHrmAsyncService;
import weaver.xuanran.wang.sh_bigdata.org_hrm_async.service.impl.OrgHrmAsyncServiceImpl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
@ -15,17 +22,29 @@ import java.util.Map;
public class OrganizationHrmSyncFromOtherSys implements HrmSynService {
private HashMap<String, Object> synResult;
private final OrgHrmAsyncService asyncService = new OrgHrmAsyncServiceImpl();
private final Logger log = Util.getLogger();
public OrganizationHrmSyncFromOtherSys(){
this.removeSynResult();
}
@Override
public String SynTimingToOASubCompany() {
List<Map<String, Object>> subCompany = asyncService.asyncOrgDep(0);
List<Map<String, Object>> list = buildItemList(subCompany);
this.synResult.put("1", list);
log.info("subCompany : \n" + JSONObject.toJSONString(list));
return null;
}
@Override
public String SynTimingToOADepartment() {
List<Map<String, Object>> subCompany = asyncService.asyncOrgDep(1);
List<Map<String, Object>> list = buildItemList(subCompany);
this.synResult.put("2", list);
log.info("department : \n" + JSONObject.toJSONString(list));
return null;
}
@ -36,6 +55,10 @@ public class OrganizationHrmSyncFromOtherSys implements HrmSynService {
@Override
public String SynTimingToOAHrmResource() {
List<Map<String, Object>> hrmList = asyncService.asyncHrm();
List<Map<String, Object>> list = buildItemList(hrmList);
this.synResult.put("4", list);
log.info("hrmresource : \n" + JSONObject.toJSONString(list));
return null;
}
@ -93,6 +116,18 @@ public class OrganizationHrmSyncFromOtherSys implements HrmSynService {
this.synResult = new HashMap<>();
}
private List<Map<String, Object>> buildItemList(List<Map<String, Object>> list){
List<Map<String, Object>> synResultlist = new ArrayList<>();
for (Map<String, Object> map : list) {
String id = Util.null2DefaultStr(map.get("id"), "");
String name = Util.null2DefaultStr(map.get("name"), "");
String code = Util.null2DefaultStr(map.get("code"), "");
String msg = Util.null2DefaultStr(map.get("msg"), "");
synResultlist.add(buildItemMap(id, id, name, code, msg));
}
return synResultlist;
}
private Map<String, Object> buildItemMap(String pkCode, String pk, String memo, String success, String error) {
//保存结果
Map<String, Object> res = new HashMap<>();
@ -103,4 +138,6 @@ public class OrganizationHrmSyncFromOtherSys implements HrmSynService {
res.put(HrmSynDAO.ErrorMessage, error);
return res;
}
}

View File

@ -0,0 +1,16 @@
package weaver.xuanran.wang.sh_bigdata.org_hrm_async.annotations;
import weaver.xuanran.wang.sh_bigdata.org_hrm_async.entity.OrgHrmAsyncCache;
import weaver.xuanran.wang.sh_bigdata.org_hrm_async.entity.OrgHrmAsyncConfigDetail;
import java.util.Map;
/**
* <h1></h1>
*
* @author xuanran.wang
* @date 2023/4/11 16:49
*/
public interface CusOrgHrmAsyncConvert {
Object cusConvert(OrgHrmAsyncConfigDetail detail, OrgHrmAsyncCache cache, Map<String, String> pathParam);
}

View File

@ -0,0 +1,43 @@
package weaver.xuanran.wang.sh_bigdata.org_hrm_async.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.HashMap;
import java.util.Map;
/**
* <h1></h1>
*
* @author xuanran.wang
* @date 2023/4/11 17:19
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class OrgHrmAsyncCache {
/**
* <h2></h2>
**/
private Map<String, Integer> subCompanyCache;
/**
* <h2></h2>
**/
private Map<String, Integer> departmentCache;
/**
* <h2></h2>
**/
private Map<String, Object> interfaceVal;
/**
* <h2></h2>
**/
private Map<String, Integer> hrmCache;
/**
* <h2></h2>
**/
private Map<String, Integer> jobTitleCache;
private int arrIndex;
}

View File

@ -0,0 +1,30 @@
package weaver.xuanran.wang.sh_bigdata.org_hrm_async.entity;
import aiyh.utils.annotation.recordset.SqlDbFieldAnn;
import aiyh.utils.annotation.recordset.SqlOracleDbFieldAnn;
import lombok.Data;
/**
* <h1>-</h1>
*
* @author xuanran.wang
* @date 2023/4/11 15:08
*/
@Data
public class OrgHrmAsyncConfigDetail {
@SqlDbFieldAnn("interfaceField")
@SqlOracleDbFieldAnn("INTERFACEFIELD")
private String interfaceField;
@SqlDbFieldAnn("oaField")
@SqlOracleDbFieldAnn("OAFIELD")
private String oaField;
@SqlDbFieldAnn("fieldType")
@SqlOracleDbFieldAnn("FIELDTYPE")
private int fieldType;
@SqlDbFieldAnn("convertType")
@SqlOracleDbFieldAnn("CONVERTTYPE")
private int convertType;
@SqlDbFieldAnn("cusText")
@SqlOracleDbFieldAnn("CUSTEXT")
private String cusText;
}

View File

@ -0,0 +1,39 @@
package weaver.xuanran.wang.sh_bigdata.org_hrm_async.entity;
import aiyh.utils.annotation.recordset.SqlDbFieldAnn;
import aiyh.utils.annotation.recordset.SqlOracleDbFieldAnn;
import lombok.Data;
import java.util.List;
/**
* <h1></h1>
*
* @author xuanran.wang
* @date 2023/4/11 15:05
*/
@Data
public class OrgHrmAsyncConfigMain {
@SqlDbFieldAnn("asyncType")
@SqlOracleDbFieldAnn("ASYNCTYPE")
private int asyncType;
@SqlDbFieldAnn("updateTableName")
@SqlOracleDbFieldAnn("UPDATETABLENAME")
private String updateTableName;
@SqlDbFieldAnn("cusWhere")
@SqlOracleDbFieldAnn("CUSWHERE")
private String cusWhere;
@SqlDbFieldAnn("primaryKey")
@SqlOracleDbFieldAnn("PRIMARYKEY")
private String primaryKey;
@SqlDbFieldAnn("foreignKey")
@SqlOracleDbFieldAnn("FOREIGNKEY")
private String foreignKey;
@SqlDbFieldAnn("cusDepartment")
@SqlOracleDbFieldAnn("CUSDEPARTMENT")
private String cusDepartment;
@SqlDbFieldAnn("cudSubCompany")
@SqlOracleDbFieldAnn("CUDSUBCOMPANY")
private String cudSubCompany;
private List<OrgHrmAsyncConfigDetail> orgHrmAsyncConfigDetailList;
}

View File

@ -1,7 +1,9 @@
package weaver.xuanran.wang.sh_bigdata.org_hrm_async.entity;
import aiyh.utils.annotation.recordset.SqlDbFieldAnn;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import weaver.xuanran.wang.sh_bigdata.org_hrm_async.annotations.CusDbEntityMapping;
import java.util.List;
@ -14,6 +16,8 @@ import java.util.List;
* @date 2023/4/4 11:03
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class OtherSysDepartment {
/**
* <h2>id</h2>
@ -37,17 +41,26 @@ public class OtherSysDepartment {
**/
@CusDbEntityMapping(dbFiled = {"showorder"})
private int order;
/**
* <h2>id</h2>
**/
@CusDbEntityMapping(dbFiled = {"supsubcomid","supsubcomid1"})
private int subCompanyId;
/**
* <h2>
* ,0:,1:
* </h2>
**/
private int hasChild;
/**
* <h2></h2>
**/
@CusDbEntityMapping(dbFiled = {"tlevel"})
private int level;
/**
* <h2> 0</h2>
**/
private int isDeleted;
/**
* <h2></h2>
**/
@CusDbEntityMapping(dbFiled = {"","subcompanyid1"})
private int division;
private List<OtherSysDepartment> childList;
}

View File

@ -0,0 +1,146 @@
package weaver.xuanran.wang.sh_bigdata.org_hrm_async.job;
import aiyh.utils.ThreadPoolConfig;
import aiyh.utils.Util;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import weaver.interfaces.schedule.BaseCronJob;
import weaver.xuanran.wang.common.util.CusInfoToOAUtil;
import weaver.xuanran.wang.sh_bigdata.common.util.ShBigDataUtil;
import weaver.xuanran.wang.sh_bigdata.org_hrm_async.service.OrgHrmAsyncService;
import weaver.xuanran.wang.sh_bigdata.org_hrm_async.service.impl.OrgHrmAsyncServiceImpl;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.function.Function;
/**
* <h1>- </h1>
*
* @author xuanran.wang
* @date 2023/4/14 11:51
*/
public class OrganizationHrmSyncJob extends BaseCronJob {
private final OrgHrmAsyncService asyncService = new OrgHrmAsyncServiceImpl();
private final Logger log = Util.getLogger();
private String orgHrmAsyncLogModelId;
private final ExecutorService executorService = ThreadPoolConfig.createThreadPoolInstance();
private String asyncType;
private static final String ALL_ASYNC = "";
private static final String ORG_COMPANY_ASYNC = "1";
private static final String HRMRESOURCE_ASYNC = "2";
private final Map<String, Function<String, String>> maps = new HashMap<>();
{
try {
orgHrmAsyncLogModelId = ShBigDataUtil.getPropertiesValByKey("orgHrmAsyncLogModelId");
}catch (Exception e){
log.error("orgHrmAsyncLogModelId init error!");
}
maps.put(ORG_COMPANY_ASYNC, (o)->{
orgAsync();
return "";
});
maps.put(ALL_ASYNC, (o)->{
orgAsync();
hrmAsync();
return "";
});
maps.put(HRMRESOURCE_ASYNC, (o)->{
hrmAsync();
return "";
});
}
@Override
public void execute() {
if(StringUtils.isNotBlank(orgHrmAsyncLogModelId)){
try {
asyncType = Util.null2DefaultStr(asyncType, "");
log.info("asyncType : [ " + asyncType + " ]");
Function<String, String> function = maps.get(asyncType);
if(function != null){
function.apply("");
}
}catch (Exception e){
log.error("OrganizationHrmSyncJob execute error! " + e.getMessage());
log.info(Util.getErrString(e));
}
}
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2023/4/14 16:12
**/
private void orgAsync(){
List<Map<String, Object>> subCompanyList = asyncService.asyncOrgDep(0);
poolExecute(subCompanyList, 0);
List<Map<String, Object>> departmentList = asyncService.asyncOrgDep(1);
poolExecute(departmentList, 1);
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2023/4/14 16:12
**/
private void hrmAsync(){
List<Map<String, Object>> hrmList = asyncService.asyncHrm();
poolExecute(hrmList, 2);
}
/**
* <h1>线</h1>
* @author xuanran.wang
* @dateTime 2023/4/14 14:11
* @param list
**/
private void poolExecute(List<Map<String, Object>> list, int type){
executorService.execute(()->{
try {
log.info("subCompanyList : \n" + JSONObject.toJSONString(list));
List<LinkedHashMap<String, Object>> convert = convert(list, type);
CusInfoToOAUtil.executeBatch(Util.getIntValue(this.orgHrmAsyncLogModelId, -1), convert);
}catch (Exception e){
log.info("写入日志建模异常! " + e.getMessage());
}
});
}
/**
* <h1>map</h1>
* @author xuanran.wang
* @dateTime 2023/4/14 14:12
* @param dataList
* @param type
* @return
**/
private List<LinkedHashMap<String, Object>> convert(List<Map<String, Object>> dataList, int type){
List<LinkedHashMap<String, Object>> res = new ArrayList<>();
for (Map<String, Object> map : dataList) {
LinkedHashMap<String, Object> linkedHashMap = new LinkedHashMap<>();
linkedHashMap.put("asyncType", type);
// 0 是失败 1是插入 2 是更新
int success = Util.getIntValue(Util.null2DefaultStr(map.get("code"), ""), 0);
// 建模表 数据同步状态 成功是0 1是失败
linkedHashMap.put("status", success == 0 ? 1 : 0);
// 建模表 更新/插入 更新是0 插入是1
linkedHashMap.put("updateOrInsert", success == 2 ? 0 : 1);
linkedHashMap.put("msg", Util.null2DefaultStr(map.get("msg"), ""));
linkedHashMap.put("outPk", Util.null2DefaultStr(map.get("id"), ""));
linkedHashMap.put("dataName", Util.null2DefaultStr(map.get("name"), ""));
res.add(linkedHashMap);
}
return res;
}
public String getAsyncType() {
return asyncType;
}
public void setAsyncType(String asyncType) {
this.asyncType = asyncType;
}
}

View File

@ -1,11 +1,10 @@
package weaver.xuanran.wang.sh_bigdata.org_hrm_async.mapper;
import aiyh.utils.annotation.recordset.Select;
import aiyh.utils.annotation.recordset.SqlMapper;
import aiyh.utils.annotation.recordset.SqlString;
import aiyh.utils.annotation.recordset.Update;
import io.swagger.models.auth.In;
import aiyh.utils.annotation.recordset.*;
import weaver.xuanran.wang.sh_bigdata.org_hrm_async.entity.OrgHrmAsyncConfigDetail;
import weaver.xuanran.wang.sh_bigdata.org_hrm_async.entity.OrgHrmAsyncConfigMain;
import java.util.List;
import java.util.Map;
/**
@ -17,9 +16,80 @@ import java.util.Map;
@SqlMapper
public interface OrgHrmAsyncMapper {
@Select("select outkey, id from HrmSubCompany where outkey != '' and outkey is not null")
Map<Integer, Integer> selectSubCompany();
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2023/3/1 16:39
* @return
**/
@Select("select * from uf_org_hrm_async where asyncType = #{asyncType}")
@CollectionMappings({
@CollectionMapping(property = "orgHrmAsyncConfigDetailList",
column = "id",
id = @Id(value = Integer.class, methodId = 1))
})
List<OrgHrmAsyncConfigMain> selectSubCompanyAsyncConfig(@ParamMapper("asyncType") int asyncType);
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2023/3/1 16:39
* @param mainId id
* @return
**/
@Select("select * from uf_org_hrm_async_dt1 where mainid = #{mainId}")
@CollectionMethod(1)
List<OrgHrmAsyncConfigDetail> selectSubCompanyAsyncConfigDetail(@ParamMapper("mainId") int mainId);
@Select("select outkey, id from HrmSubCompany where outkey <> '' and outkey is not null")
List<Map<String, Integer>> selectSubCompanyAll();
@Select("select outkey, id from hrmdepartment where outkey <> '' and outkey is not null")
List<Map<String, Integer>> selectDepartmentAll();
@Select("select outkey, id, tlevel from HrmSubCompany where outkey <> '' and outkey is not null and canceled <> 1")
List<Map<String, Integer>> selectSubCompanyActive();
@Select("select outkey, id from hrmdepartment where outkey <> '' and outkey is not null and canceled <> 1")
List<Map<String, Integer>> selectDepartmentActive();
@Select("select jobtitlename,id from hrmjobtitles")
List<Map<String, Integer>> selectJobTitle();
@Select("select id from hrmjobtitles where jobtitlename = #{jobTitleName}")
String selectJobTitleByName(@ParamMapper("jobTitleName") String jobTitleName);
@Insert("insert into hrmjobtitles(jobtitlemark, jobtitlename, creater, created) values(#{position}, #{position}, 1, #{jobCreateTime})")
boolean insertJobTitle(Map<String, Object> params);
@Update(custom = true)
boolean updateSubInfo(@SqlString String sql, Map<String, Object> params);
boolean updateOrgInfo(@SqlString String sql, Map<String, Object> params);
@Select("select interfaceDataId from uf_depart_or_sub where depOrSub = 0")
List<String> selectCusSubCompany();
@Select("select interfaceDataId from uf_depart_or_sub where depOrSub = 1")
List<String> selectCusDepart();
@Select(custom = true)
String selectCustomerSql(@SqlString String sql, Map<String, Object> map);
@Select(custom = true)
List<String> selectCustomerSqlArr(@SqlString String sql, Map<String, Object> map);
@Update("update HrmSubCompany set canceled = 1 where outkey in (${outKeys})")
boolean updateHrmSubCompanyCanceled(List<String> outKeys);
@Update("update hrmdepartment set canceled = 1 where outkey in (${outKeys})")
boolean updateHrmDepartmentCanceled(List<String> outKeys);
@Select("select min(outkey) from hrmsubcompany where outkey <> '' and outkey is not null")
String selectTopLevelOutKey();
@Select("select outkey, id from hrmresource ")
List<Map<String, Integer>> selectHrmIdAndOutKey();
@Insert(custom = true)
boolean insertHrmInfo(@SqlString String sql, Map<String, Object> params);
@Select("select 1 from hrmresource where departmentid = (select id from hrmdepartment where outkey = #{outKey})")
int selectDepartHasUser(@ParamMapper("outKey") String outKey);
}

View File

@ -1,8 +1,10 @@
package weaver.xuanran.wang.sh_bigdata.org_hrm_async.service;
import com.icbc.api.internal.apache.http.impl.cookie.S;
import weaver.xuanran.wang.sh_bigdata.org_hrm_async.entity.OtherSysDepartment;
import java.util.List;
import java.util.Map;
/**
* <h1>/ </h1>
@ -14,12 +16,13 @@ public interface OrgHrmAsyncApiService {
/**
* <h1></h1>
* <h1> id </h1>
* @author xuanran.wang
* @dateTime 2023/4/4 11:13
* @param topLevelId id
* @return
**/
List<Object> getUserInfo();
List<Map<String, Object>> getUserInfo(int topLevelId);
/**
* <h1></h1>
@ -29,4 +32,12 @@ public interface OrgHrmAsyncApiService {
**/
List<OtherSysDepartment> getDepartmentInfo();
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2023/4/4 11:13
* @return
**/
List<Map<String, Object>> getDepartmentInfoMap();
}

View File

@ -1,6 +1,5 @@
package weaver.xuanran.wang.sh_bigdata.org_hrm_async.service;
import io.swagger.models.auth.In;
import weaver.xuanran.wang.sh_bigdata.org_hrm_async.entity.OtherSysDepartment;
import java.util.List;
@ -14,13 +13,6 @@ import java.util.Map;
*/
public interface OrgHrmAsyncService {
/**
* <h1> outKey idmap</h1>
* @author xuanran.wang
* @dateTime 2023/4/6 13:44
* @return outKey idmap
**/
Map<Integer, Integer> initSubCompany();
/**
* <h1></h1>
* @author xuanran.wang
@ -28,4 +20,13 @@ public interface OrgHrmAsyncService {
**/
List<OtherSysDepartment> asyncDepartment();
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2023/4/6 13:44
**/
List<Map<String, Object>> asyncOrgDep(int type);
List<Map<String, Object>> asyncHrm();
}

View File

@ -1,6 +1,8 @@
package weaver.xuanran.wang.sh_bigdata.org_hrm_async.service.impl;
import aiyh.utils.Util;
import com.alibaba.fastjson.JSONObject;
import com.engine.common.service.impl.ThemeServiceImpl;
import weaver.xuanran.wang.sh_bigdata.common.entity.CusSuccess;
import weaver.xuanran.wang.sh_bigdata.org_hrm_async.entity.OtherSysDepartment;
import weaver.xuanran.wang.sh_bigdata.org_hrm_async.service.OrgHrmAsyncApiService;
@ -22,23 +24,30 @@ import java.util.Map;
*/
public class OrgHrmAsyncApiServiceImpl implements OrgHrmAsyncApiService {
private final RequestMasterPlate requestMasterPlate = new RequestMasterPlate();
@Override
public List<Object> getUserInfo() {
return null;
}
@Override
public List<OtherSysDepartment> getDepartmentInfo() {
String departmentInfoUrl = ShBigDataUtil.getPropertiesValByKey("departmentInfoUrl");
public List<Map<String, Object>> getUserInfo(int topLevelId) {
String departmentInfoUrl = ShBigDataUtil.getPropertiesValByKey("userInfoUrl");
HashMap<String, Object> params = new HashMap<>();
params.put("access_token", ShBigDataUtil.getToken());
params.put("department_id", topLevelId);
params.put("no_fetch_child", 1);
// 如果hrmUpdateTime则获取增量数据
if(1 == Util.getIntValue(ShBigDataUtil.getPropertiesValByKey("hrmUpdateTime"),0)){
params.put("updateTime", System.currentTimeMillis());
}
CusSuccess cusSuccess = CusSuccess.builder()
.successField("code")
.successValue(0)
.errorMsg("msg")
.dataKey("data.department")
.dataKey("data.userList")
.build();
List<Map<String, Object>> list = requestMasterPlate.apiGet(departmentInfoUrl, params, new HashMap<>(), cusSuccess);
return requestMasterPlate.apiGet(departmentInfoUrl, params, new HashMap<>(), cusSuccess);
}
@Override
public List<OtherSysDepartment> getDepartmentInfo() {
List<Map<String, Object>> list = getDepartmentInfoMap();
List<OtherSysDepartment> res = new ArrayList<>();
for (Object o : list) {
res.add(JSONObject.parseObject(JSONObject.toJSONString(o), OtherSysDepartment.class));
@ -46,4 +55,24 @@ public class OrgHrmAsyncApiServiceImpl implements OrgHrmAsyncApiService {
return res;
}
@Override
public List<Map<String, Object>> getDepartmentInfoMap() {
String departmentInfoUrl = ShBigDataUtil.getPropertiesValByKey("departmentInfoUrl");
HashMap<String, Object> params = new HashMap<>();
params.put("access_token", ShBigDataUtil.getToken());
params.put("no_fetch_child", Util.getIntValue(ShBigDataUtil.getPropertiesValByKey("orgNoFetchChild"),0));
// orgUpdateTime = 1 进行增量数据同步
if(1 == Util.getIntValue(ShBigDataUtil.getPropertiesValByKey("orgUpdateTime"),0)){
params.put("updateTime", System.currentTimeMillis());
}
CusSuccess cusSuccess = CusSuccess.builder()
.successField("code")
.successValue(0)
.errorMsg("msg")
.dataKey("data.department")
.build();
return requestMasterPlate.apiGet(departmentInfoUrl, params, new HashMap<>(), cusSuccess);
}
}

View File

@ -0,0 +1,265 @@
package weaver.xuanran.wang.sh_bigdata.org_hrm_async.service.impl;
import aiyh.utils.Util;
import aiyh.utils.excention.CustomerException;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import weaver.conn.RecordSet;
import weaver.hrm.company.SubCompanyComInfo;
import weaver.matrix.MatrixUtil;
import weaver.xuanran.wang.sh_bigdata.common.util.ShBigDataUtil;
import weaver.xuanran.wang.sh_bigdata.org_hrm_async.entity.OtherSysDepartment;
import weaver.xuanran.wang.sh_bigdata.org_hrm_async.mapper.OrgHrmAsyncMapper;
import weaver.xuanran.wang.sh_bigdata.org_hrm_async.service.OrgHrmAsyncApiService;
import weaver.xuanran.wang.sh_bigdata.org_hrm_async.service.OrgHrmAsyncService;
import weaver.xuanran.wang.sh_bigdata.org_hrm_async.util.OrgHrmAsyncUtil;
import java.util.*;
import java.util.stream.Collectors;
/**
* <h1></h1>
*
* @author xuanran.wang
* @date 2023/4/6 10:10
*/
public class OrgHrmAsyncEntityServiceImpl implements OrgHrmAsyncService {
private final Logger log = Util.getLogger();
private final OrgHrmAsyncApiService orgHrmAsyncApiService = new OrgHrmAsyncApiServiceImpl();
private final OrgHrmAsyncMapper orgHrmAsyncMapper = Util.getMapper(OrgHrmAsyncMapper.class);
private final SubCompanyComInfo sci = new SubCompanyComInfo();
/**
* <h2></h2>
**/
private final List<String> departmentWhiteList;
/**
* <h2></h2>
**/
private final List<String> subCompanyWhiteList;
/**
* <h2></h2>
**/
private Map<String, Integer> subCompanyCache = new HashMap<>();
/**
* <h2></h2>
**/
private Map<String, Integer> departmentCache = new HashMap<>();
/**
* <h2></h2>
**/
int maxLevel;
/**
* <h2> </h2>
**/
private String interfaceSupSubCompany;
{
departmentWhiteList = orgHrmAsyncMapper.selectCusDepart();
subCompanyWhiteList = orgHrmAsyncMapper.selectCusSubCompany();
List<Map<String, Integer>> subCompany = orgHrmAsyncMapper.selectSubCompanyAll();
subCompanyCache = OrgHrmAsyncUtil.parseListMap2Map(subCompany);
List<Map<String, Integer>> department = orgHrmAsyncMapper.selectDepartmentAll();
departmentCache = OrgHrmAsyncUtil.parseListMap2Map(department);
maxLevel = Util.getIntValue(ShBigDataUtil.getPropertiesValByKey("maxLevel"), 3);
}
@Override
public List<OtherSysDepartment> asyncDepartment() {
List<OtherSysDepartment> departmentInfo = orgHrmAsyncApiService.getDepartmentInfo();
// 将部门信息转换成树
List<OtherSysDepartment> convetList = Util.listToTree(departmentInfo,
OtherSysDepartment::getId, OtherSysDepartment::getParentid,
OtherSysDepartment::getChildList, OtherSysDepartment::setChildList,
parentid -> parentid == -1);
// 进行部门分部解析
List<OtherSysDepartment> hrmSubCompany = new ArrayList<>();
List<OtherSysDepartment> hrmDepartment = new ArrayList<>();
// 解析是部门还是分部
parseSubCompanyAndDepartment(convetList, 0, maxLevel, hrmSubCompany, hrmDepartment);
// 进行顺序排序
hrmSubCompany = hrmSubCompany.stream().sorted(Comparator.comparingInt(OtherSysDepartment::getId)).collect(Collectors.toList());
hrmDepartment = hrmDepartment.stream().sorted(Comparator.comparingInt(OtherSysDepartment::getId)).collect(Collectors.toList());
System.out.println("hrmSubCompany => " + JSONObject.toJSONString(hrmSubCompany));
System.out.println("hrmDepartment => " + JSONObject.toJSONString(hrmDepartment));
// 同步
addHrmSubCompany(hrmSubCompany);
addHrmDepartment(hrmDepartment);
return departmentInfo;
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2023/4/6 13:37
* @param departmentList
**/
public void addHrmSubCompany(List<OtherSysDepartment> departmentList){
char separator = weaver.general.Util.getSeparator();
RecordSet rsSch = new RecordSet();
for (OtherSysDepartment department : departmentList) {
int subId = Util.getIntValue(Util.null2DefaultStr(subCompanyCache.get(department.getId()),""),-1);
if(subId < 0){
String para = department.getName() + separator + department.getName() + separator + "1" + separator
+ department.getId()+ separator + "" + separator +department.getOrder();
rsSch.executeProc("HrmSubCompany_Insert", para);
if (rsSch.next()) {
subId = rsSch.getInt(1);
}
subCompanyCache.put(department.getId() + "", subId);
}
department.setParentid(Util.getIntValue(Util.null2DefaultStr(subCompanyCache.get(department.getParentid()),""),0));
updateTable("HrmSubCompany", subId, 0, department);
}
//清除全部分部缓存
sci.removeCompanyCache();
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2023/4/6 13:37
* @param departmentList
**/
public void addHrmDepartment(List<OtherSysDepartment> departmentList){
char separator = weaver.general.Util.getSeparator();
RecordSet rsSch = new RecordSet();
for (OtherSysDepartment department : departmentList) {
int id = Util.getIntValue(Util.null2DefaultStr(departmentCache.get(department.getId()), ""),-1);
if(id < 0){
String para = department.getName() + separator + department.getName() + separator +
"" + separator + "" + separator + department.getParentid() + separator + department.getOrder() + separator + "";
rsSch.executeProc("HrmDepartment_Insert", para);
if (rsSch.next()) {
id = rsSch.getInt(1);
}
departmentCache.put(department.getId() + "", id);
}
System.out.println("departmentCache => " + JSONObject.toJSONString(departmentCache));
System.out.println("subCompanyCache => " + JSONObject.toJSONString(subCompanyCache));
System.out.println("department => " + JSONObject.toJSONString(department));
int parentid = department.getParentid();
department.setParentid(Util.getIntValue(Util.null2DefaultStr(departmentCache.get(parentid),""),0));
// 如果一个分部从 分部变成了部门 那么他下面所有的都是部门 在设置所属分部的时候要将 分部的所属分部替换
int division = Util.getIntValue(Util.null2DefaultStr(subCompanyCache.get(parentid), ""), -1);
department.setDivision(division);
updateTable("HrmDepartment", id, 1, department);
}
//清除全部分部缓存
sci.removeCompanyCache();
}
/**
* <h1>or</h1>
* @author xuanran.wang
* @dateTime 2023/4/10 12:13
* @param list
* @param n
* @param hrmSubCompany
* @param hrmDepartment
**/
public void parseSubCompanyAndDepartment(List<OtherSysDepartment> list, int n, int maxLevel,List<OtherSysDepartment> hrmSubCompany, List<OtherSysDepartment> hrmDepartment){
n++;
for (OtherSysDepartment department : list) {
department.setLevel(n);
List<OtherSysDepartment> childList = department.getChildList();
String departmentId = department.getId() + "";
if(CollectionUtils.isNotEmpty(childList)){
List<String> collect = department.getChildList().stream().map(item -> Util.null2DefaultStr(item.getId(), "")).collect(Collectors.toList());
if(departmentWhiteList.contains(departmentId)){
departmentWhiteList.addAll(collect);
}else if(subCompanyWhiteList.contains(departmentId)){
subCompanyWhiteList.addAll(collect);
}
parseSubCompanyAndDepartment(childList, n, maxLevel, hrmSubCompany, hrmDepartment);
department.setChildList(new ArrayList<>());
}
if(n > maxLevel || departmentWhiteList.contains(departmentId)){
hrmDepartment.add(department);
}else{
hrmSubCompany.add(department);
}
}
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2023/4/6 13:35
* @param tableName
* @param id id
* @param type
* @param o
**/
public void updateTable(String tableName, int id, int type, Object o){
StringBuilder sb = new StringBuilder("update ");
sb.append(tableName).append(" set ");
Map<String, Object> params;
try {
params = ShBigDataUtil.parseCusDbEntityMapping(type, o, true);
}catch (Exception e){
throw new CustomerException("parseCusDbEntityMapping error!" + e.getMessage());
}
for (Map.Entry<String, Object> entry : params.entrySet()) {
sb.append(entry.getKey())
.append(" = #{")
.append(entry.getKey())
.append("},");
}
sb.deleteCharAt(sb.length() - 1);
sb.append(" where id = ").append(id);
boolean success = orgHrmAsyncMapper.updateOrgInfo(sb.toString(), params);
if(!success){
log.error(Util.logStr("update {} sql error!", tableName));
}
//同步分部数据到矩阵
MatrixUtil.updateSubcompayData(String.valueOf(id));
}
@Override
public List<Map<String, Object>> asyncOrgDep(int type) {
return new ArrayList<>();
}
@Override
public List<Map<String, Object>> asyncHrm() {
return null;
}
/**
* <h1>or</h1>
* @author xuanran.wang
* @dateTime 2023/4/10 12:13
* @param list
* @param n
* @param hrmSubCompany
* @param hrmDepartment
**/
// public void parseSubCompanyAndDepartment(List<OtherSysDepartment> list, int n, int maxLevel,List<OtherSysDepartment> hrmSubCompany, List<OtherSysDepartment> hrmDepartment){
// n++;
// for (OtherSysDepartment department : list) {
// department.setLevel(n);
// List<OtherSysDepartment> childList = department.getChildList();
// if(CollectionUtils.isNotEmpty(childList)){
// parseSubCompanyAndDepartment(childList, n, maxLevel, hrmSubCompany, hrmDepartment);
// department.setChildList(null);
// }
// String departmentId = department.getId() + "";
// if(n > maxLevel || departmentWhiteList.contains(departmentId)){
// hrmDepartment.add(department);
// }else if(n < maxLevel || subCompanyWhiteList.contains(departmentId)){
// hrmSubCompany.add(department);
// }
// }
// }
}

View File

@ -1,21 +1,33 @@
package weaver.xuanran.wang.sh_bigdata.org_hrm_async.service.impl;
import aiyh.utils.ThreadPoolConfig;
import aiyh.utils.Util;
import aiyh.utils.excention.CustomerException;
import com.alibaba.fastjson.JSONObject;
import com.engine.common.service.impl.ThemeServiceImpl;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import weaver.conn.RecordSet;
import weaver.general.TimeUtil;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.company.SubCompanyComInfo;
import weaver.hrm.resource.ResourceComInfo;
import weaver.matrix.MatrixUtil;
import weaver.xuanran.wang.sh_bigdata.org_hrm_async.entity.OrgHrmAsyncCache;
import weaver.xuanran.wang.sh_bigdata.org_hrm_async.entity.OrgHrmAsyncConfigMain;
import weaver.xuanran.wang.sh_bigdata.org_hrm_async.entity.OtherSysDepartment;
import weaver.xuanran.wang.sh_bigdata.org_hrm_async.mapper.OrgHrmAsyncMapper;
import weaver.xuanran.wang.sh_bigdata.org_hrm_async.service.OrgHrmAsyncApiService;
import weaver.xuanran.wang.sh_bigdata.org_hrm_async.service.OrgHrmAsyncService;
import weaver.xuanran.wang.sh_bigdata.common.util.ShBigDataUtil;
import weaver.xuanran.wang.sh_bigdata.org_hrm_async.util.OrgHrmAsyncUtil;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.function.Function;
import java.util.stream.Collectors;
import ln.LN;
/**
* <h1></h1>
@ -24,65 +36,346 @@ import java.util.stream.Collectors;
* @date 2023/4/6 10:10
*/
public class OrgHrmAsyncServiceImpl implements OrgHrmAsyncService {
private final Logger log = Util.getLogger();
private final OrgHrmAsyncApiService orgHrmAsyncApiService = new OrgHrmAsyncApiServiceImpl();
private final OrgHrmAsyncMapper orgHrmAsyncMapper = Util.getMapper(OrgHrmAsyncMapper.class);
private final SubCompanyComInfo sci = new SubCompanyComInfo();
private final DepartmentComInfo departmentComInfo = new DepartmentComInfo();
private ResourceComInfo comInfo = null;
/**
* <h2></h2>
**/
private final List<String> departmentWhiteList;
/**
* <h2></h2>
**/
private final List<String> subCompanyWhiteList;
/**
* <h2></h2>
**/
private final Map<String, Integer> subCompanyCache;
/**
* <h2></h2>
**/
private final Map<String, Integer> departmentCache;
/**
* <h2></h2>
**/
private final Map<String, Integer> jobTitleCache;
/**
* <h2></h2>
**/
private final Map<String, Integer> hrmCache;
/**
* <h2></h2>
**/
int maxLevel;
/**
* <h2></h2>
**/
private final List<OrgHrmAsyncConfigMain> subCompanyConfig;
/**
* <h2></h2>
**/
private final List<OrgHrmAsyncConfigMain> departmentConfig;
/**
* <h2></h2>
**/
private final List<OrgHrmAsyncConfigMain> hrmReSourceConfig;
/**
* <h2></h2>
**/
private final List<Map<String, Object>> asyncHrmSubCompany = new ArrayList<>();
/**
* <h2></h2>
**/
private final List<Map<String, Object>> asyncHrmDepartment = new ArrayList<>();
private final Map<Integer, String> typeTableName = new HashMap<>();
private final HashMap<Integer, Function<Object, Integer>> getNextIdTypeMap = new HashMap<>();
private final Map<String, Integer> subCompanyLevelCache;
@Override
public Map<Integer, Integer> initSubCompany() {
return orgHrmAsyncMapper.selectSubCompany();
// 创建按order值进行排序的比较器
Comparator<Map<String, Object>> orderByOrder = (o1, o2) -> {
int order1 = (int) o1.get("order");
int order2 = (int) o2.get("order");
if (order1 != order2) {
return Integer.compare(order2, order1);
} else {
int id1 = (int) o1.get("id");
int id2 = (int) o2.get("id");
return Integer.compare(id1, id2);
}
};
// 创建按id值进行排序的比较器
Comparator<Map<String, Object>> orderById = (o1, o2) -> {
int id1 = (int) o1.get("id");
int id2 = (int) o2.get("id");
return Integer.compare(id1, id2);
};
private RecordSet procRs = new RecordSet();
ExecutorService threadPoolInstance = ThreadPoolConfig.createThreadPoolInstance();
private final ThemeServiceImpl themeService = new ThemeServiceImpl();
{
// ========================= 白名单初始化 =========================
// departmentWhiteList = orgHrmAsyncMapper.selectCusDepart();
departmentWhiteList = new ArrayList<>();
// subCompanyWhiteList = orgHrmAsyncMapper.selectCusSubCompany();
subCompanyWhiteList = new ArrayList<>();
// ================================================================
// ========================= 部门&分部&岗位&用户 缓存初始化 =========================
List<Map<String, Integer>> subCompany = orgHrmAsyncMapper.selectSubCompanyActive();
subCompanyCache = OrgHrmAsyncUtil.parseListMap2Map(subCompany);
subCompanyLevelCache = OrgHrmAsyncUtil.parseListMap2Map("outkey","tlevel", subCompany);
List<Map<String, Integer>> department = orgHrmAsyncMapper.selectDepartmentActive();
departmentCache = OrgHrmAsyncUtil.parseListMap2Map(department);
List<Map<String, Integer>> jobTitle = orgHrmAsyncMapper.selectJobTitle();
jobTitleCache = OrgHrmAsyncUtil.parseListMap2Map("jobtitlename","id", jobTitle);
List<Map<String, Integer>> hrm = orgHrmAsyncMapper.selectHrmIdAndOutKey();
hrmCache = OrgHrmAsyncUtil.parseListMap2Map(hrm);
// =======================================================================
maxLevel = Util.getIntValue(ShBigDataUtil.getPropertiesValByKey("maxLevel"), 3);
// ======================部门-分部-人员 同步配置表初始化 =====================
subCompanyConfig = orgHrmAsyncMapper.selectSubCompanyAsyncConfig(0);
if(subCompanyConfig == null || CollectionUtils.isEmpty(subCompanyConfig.get(0).getOrgHrmAsyncConfigDetailList())){
throw new CustomerException("subCompanyConfig can not be null!");
}
departmentConfig = orgHrmAsyncMapper.selectSubCompanyAsyncConfig(1);
if(departmentConfig == null || CollectionUtils.isEmpty(departmentConfig.get(0).getOrgHrmAsyncConfigDetailList())){
throw new CustomerException("departmentConfig can not be null!");
}
hrmReSourceConfig = orgHrmAsyncMapper.selectSubCompanyAsyncConfig(2);
// =======================================================================
typeTableName.put(0, "hrmsubcompany");
typeTableName.put(1, "hrmdepartment");
typeTableName.put(2, "hrmresource");
getNextIdTypeMap.put(0, (o)-> getNextHrmSubCompanyId());
getNextIdTypeMap.put(1, (o)-> getNextHrmDepartmentId());
getNextIdTypeMap.put(2, (o)-> getNextHrmId());
try {
comInfo = new ResourceComInfo();
}catch (Exception e){
log.error("init ResourceComInfo error : " + e.getMessage());
}
}
private final OrgHrmAsyncCache orgHrmAsyncCache = OrgHrmAsyncCache.builder()
.departmentCache(departmentCache)
.subCompanyCache(subCompanyCache)
.hrmCache(hrmCache)
.jobTitleCache(jobTitleCache)
.arrIndex(0)
.build();
@Override
public List<OtherSysDepartment> asyncDepartment() {
List<OtherSysDepartment> departmentInfo = orgHrmAsyncApiService.getDepartmentInfo();
//TODO 分部(条件待确认)
List<OtherSysDepartment> subList = departmentInfo
.stream()
.filter(item -> -1 == item.getParentid())
.sorted(Comparator.comparing(OtherSysDepartment::getId))
.collect(Collectors.toList());
addHrmSubCompany(subList);
// 过滤出父节点并根据id进行升序排序
List<OtherSysDepartment> rootDepList = departmentInfo
.stream()
.filter(item -> 0 == item.getHasChild() && -1 != item.getParentid())
.sorted(Comparator.comparing(OtherSysDepartment::getId))
.collect(Collectors.toList());
return null;
}
@Override
public synchronized List<Map<String, Object>> asyncOrgDep(int type) {
if(CollectionUtils.isEmpty(asyncHrmSubCompany) || CollectionUtils.isEmpty(asyncHrmDepartment)){
initWhiteList();
List<Map<String, Object>> departmentInfoMap = orgHrmAsyncApiService.getDepartmentInfoMap();
// 解析成树形
List<Map<String, Object>> tree = convertListToTree(departmentInfoMap);
if(CollectionUtils.isEmpty(tree)){
subDepIncrementDataAsync(departmentInfoMap, asyncHrmSubCompany, asyncHrmDepartment);
}else {
asyncOrDepByTree(tree,0, maxLevel, asyncHrmSubCompany, asyncHrmDepartment);
}
asyncOrgExtraData();
}
threadPoolInstance.execute(()->{
departmentComInfo.removeCache();
sci.removeCompanyCache();
});
return type == 0 ? asyncHrmSubCompany : asyncHrmDepartment;
}
@Override
public List<Map<String, Object>> asyncHrm() {
if(CollectionUtils.isEmpty(hrmReSourceConfig) ){
throw new CustomerException("hrmReSourceConfig can not be null!");
}
int topLevelOutKey = Util.getIntValue(orgHrmAsyncMapper.selectTopLevelOutKey(), -1);
if(topLevelOutKey < 0){
return new ArrayList<>();
}
List<Map<String, Object>> userInfo = orgHrmAsyncApiService.getUserInfo(topLevelOutKey);
try {
List<String> oaCacheOutKeys = new ArrayList<>(hrmCache.keySet());
LN ln = new LN();
int licenseNum = ln.CkHrmnum();
log.info("当前可用license : " + licenseNum);
log.info("当前接口数据条数 : " + userInfo.size());
log.info("当前oa缓存outKey条数 : " + oaCacheOutKeys.size());
if(CollectionUtils.isEmpty(oaCacheOutKeys)){
if(licenseNum < userInfo.size()){
log.error("当前接口条数大于可用license!本次同步跳过!");
return new ArrayList<>();
}
}else {
List<Map<String, Object>> notContains = userInfo.stream().filter(item -> !oaCacheOutKeys.contains(Util.null2DefaultStr(item.get("id"), ""))).collect(Collectors.toList());
log.info("接口中存在oa中不存在数据条数 : " + notContains.size());
if(oaCacheOutKeys.size() + notContains.size() > licenseNum){
log.error("当前接口条数+oa人员数量大于可用license!本次同步跳过!");
return new ArrayList<>();
}
}
}catch (Exception e){
log.error("校验可用license数量失败! " + e.getMessage());
}
addHrmResourceMap(userInfo);
List<OrgHrmAsyncConfigMain> hrmExtraConfig = hrmReSourceConfig.stream()
.filter(item -> StringUtils.isNotBlank(item.getUpdateTableName())
&& !"hrmresource".equalsIgnoreCase(item.getUpdateTableName()))
.collect(Collectors.toList());
threadPoolInstance.execute(()-> asyncExtraData(userInfo, hrmExtraConfig));
return userInfo;
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2023/4/14 15:14
* @param list
* @param hrmSubCompany
* @param hrmDepartment
**/
public void subDepIncrementDataAsync(List<Map<String, Object>> list, List<Map<String, Object>> hrmSubCompany, List<Map<String, Object>> hrmDepartment){
for (Map<String, Object> data : list) {
int parentid = Util.getIntValue(Util.null2DefaultStr(data.get("parentid"), ""), -1);
int parentLevel = Util.getIntValue(Util.null2DefaultStr(subCompanyLevelCache.get(parentid + ""),""), -1);
data.put("msg","success!");
String departmentId = Util.null2DefaultStr(data.get("id"),"");
// 如果分部中不存在并且父节点的层级等于最大的层级
boolean isDep = parentLevel < 0 || parentLevel == maxLevel;
if(departmentWhiteList.contains(departmentId)){
isDep = true;
}
if(subCompanyWhiteList.contains(departmentId)){
isDep = false;
}
if(isDep){
try {
addHrmDepartmentMap(Collections.singletonList(data));
hrmDepartment.add(data);
orgHrmAsyncMapper.updateHrmSubCompanyCanceled(Collections.singletonList(departmentId));
}catch (Exception e){
log.error(Util.logStr("async depart error!: {}, json: \n{}",e.getMessage(),JSONObject.toJSONString(data)));
data.put("code",0);
data.put("msg","async department error! " + e.getMessage());
}
}else {
try {
addHrmSubCompanyMap(Collections.singletonList(data));
hrmSubCompany.add(data);
orgHrmAsyncMapper.updateHrmDepartmentCanceled(Collections.singletonList(departmentId));
}catch (Exception e){
log.error(Util.logStr("async depart error!: {}, json: \n{}",e.getMessage(),JSONObject.toJSONString(data)));
data.put("code",0);
data.put("msg","async department error! " + e.getMessage());
}
}
}
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2023/4/14 15:17
**/
public void asyncOrgExtraData(){
List<OrgHrmAsyncConfigMain> subCompanyAsyncOtherConfig = subCompanyConfig.stream()
.filter(item -> StringUtils.isNotBlank(item.getUpdateTableName()) && !"hrmsubcompany".equalsIgnoreCase(item.getUpdateTableName()))
.collect(Collectors.toList());
List<OrgHrmAsyncConfigMain> departOtherAsyncConfig = subCompanyConfig.stream()
.filter(item -> StringUtils.isNotBlank(item.getUpdateTableName()) && !"hrmdepartment".equalsIgnoreCase(item.getUpdateTableName()))
.collect(Collectors.toList());
threadPoolInstance.execute(()->{
// 同步部门其他表数据
asyncExtraData(asyncHrmSubCompany, subCompanyAsyncOtherConfig);
// 同步分部其他表数据
asyncExtraData(asyncHrmDepartment, departOtherAsyncConfig);
});
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2023/4/13 13:20
* @param data
* @param configs
**/
public void asyncExtraData(List<Map<String, Object>> data, List<OrgHrmAsyncConfigMain> configs){
for (OrgHrmAsyncConfigMain config : configs) {
for (Map<String, Object> map : data) {
String updateTableName = config.getUpdateTableName();
String primaryKey = config.getPrimaryKey();
String cusWhere = config.getCusWhere();
if(StringUtils.isNotBlank(cusWhere)){
cusWhere = Util.sbc2dbcCase(cusWhere);
}
orgHrmAsyncCache.setInterfaceVal(map);
String id = orgHrmAsyncMapper.selectCustomerSql(cusWhere, map);
Map<String, Object> param = OrgHrmAsyncUtil.convertInterfaceValToOA(orgHrmAsyncCache, config, false);
if(StringUtils.isNotBlank(id)){
executeSql(updateTableName, Util.getIntValue(id, -1), param, 0, primaryKey);
}else {
executeSql(updateTableName, Util.getIntValue(id, -1), param, 1);
}
}
}
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2023/4/14 15:16
**/
public void initWhiteList(){
// 解析白名单数据
subCompanyConfig.forEach(item->{
String cudSubCompany = item.getCudSubCompany();
if(StringUtils.isNotBlank(cudSubCompany)){
subCompanyWhiteList.addAll(Arrays.asList(cudSubCompany.split(",")));
}
});
departmentConfig.forEach(item->{
String cusDepartment = item.getCusDepartment();
if(StringUtils.isNotBlank(cusDepartment)){
departmentWhiteList.addAll(Arrays.asList(cusDepartment.split(",")));
}
});
log.info("departmentWhiteList : \n" + JSONObject.toJSONString(departmentWhiteList));
log.info("subCompanyWhiteList : \n" + JSONObject.toJSONString(subCompanyWhiteList));
}
/**
* <h1></h1>
*
* @param departmentList
* @author xuanran.wang
* @dateTime 2023/4/6 13:37
* @param departmentList
**/
public void addHrmSubCompany(List<OtherSysDepartment> departmentList){
//新增的分部id
int subId;
char separator = weaver.general.Util.getSeparator();
RecordSet rsSch = new RecordSet();
// 分部数据
Map<Integer, Integer> subCompany = initSubCompany();
for (OtherSysDepartment department : departmentList) {
subId = Util.getIntValue(Util.null2DefaultStr(subCompany.get(department.getId()),""),-1);
if(subId < 0){
String para = department.getName() + separator + department.getName() + separator + "1" + separator
+ department.getId()+ separator + "" + separator +department.getOrder();
rsSch.executeProc("HrmSubCompany_Insert", para);
if (rsSch.next()) {
subId = rsSch.getInt(1);
}
}
updateTable("HrmSubCompany", subId, 0, department);
}
//清除全部分部缓存
sci.removeCompanyCache();
public void addHrmSubCompanyMap(List<Map<String, Object>> departmentList) {
List<OrgHrmAsyncConfigMain> collect = subCompanyConfig.stream().filter(item -> StringUtils.isBlank(item.getUpdateTableName())).collect(Collectors.toList());
baseAddOrgDepByMap(departmentList, 0, subCompanyCache, collect.get(0));
}
/**
@ -91,73 +384,361 @@ public class OrgHrmAsyncServiceImpl implements OrgHrmAsyncService {
* @dateTime 2023/4/6 13:37
* @param departmentList
**/
public void addHrmDepartment(List<OtherSysDepartment> departmentList){
//新增的分部id
int id = 0;
char separator = weaver.general.Util.getSeparator();
RecordSet rsSch = new RecordSet();
for (OtherSysDepartment department : departmentList) {
String para = department.getName() + separator + department.getName() + separator + "1" + separator
+ department.getParentid() + separator + "" + separator +department.getOrder();
rsSch.executeProc("HrmSubCompany_Insert", para);
if (rsSch.next()) {
id = rsSch.getInt(1);
updateTable("HrmSubCompany", id, 0, department);
}
}
//清除全部分部缓存
sci.removeCompanyCache();
public void addHrmDepartmentMap(List<Map<String, Object>> departmentList){
List<OrgHrmAsyncConfigMain> collect = departmentConfig.stream().filter(item -> StringUtils.isBlank(item.getUpdateTableName())).collect(Collectors.toList());
baseAddOrgDepByMap(departmentList, 1, departmentCache, collect.get(0));
}
/**
* <h1></h1>
* <h1></h1>
* @author xuanran.wang
* @dateTime 2023/4/6 13:35
* @dateTime 2023/4/6 13:37
* @param hrmList
**/
public void addHrmResourceMap(List<Map<String, Object>> hrmList){
List<OrgHrmAsyncConfigMain> hrmAsyncConf = hrmReSourceConfig.stream()
.filter(item -> StringUtils.isBlank(item.getUpdateTableName()) || !"hrmresource".equalsIgnoreCase(item.getUpdateTableName()))
.collect(Collectors.toList());
baseAddOrgDepByMap(hrmList, 2, hrmCache, hrmAsyncConf.get(0));
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2023/4/12 10:36
* @param dataList
* @param type 0 1
**/
public void baseAddOrgDepByMap(List<Map<String, Object>> dataList,
int type, Map<String, Integer> cache,
OrgHrmAsyncConfigMain config){
for (Map<String, Object> data : dataList) {
int interfaceId = Util.getIntValue(Util.null2DefaultStr(data.get("id"), ""), -1);
int oaId = Util.getIntValue(Util.null2DefaultStr(cache.get(interfaceId + ""),""), -1);
boolean insert = false;
// 如果不存在则需要新增
if(oaId < 0){
oaId = getNextIdTypeMap.get(type).apply(null);
if(oaId < 0){
log.error("create " + typeTableName.get(type) + " id fail!");
continue;
}
cache.put(interfaceId + "", oaId);
insert = true;
}
orgHrmAsyncCache.setInterfaceVal(data);
Map<String, Object> map = OrgHrmAsyncUtil.convertInterfaceValToOA(orgHrmAsyncCache, config, true);
if(insert){
map.put("creater",1);
map.put("created", TimeUtil.getCurrentTimeString());
}
if(type == 2 && insert){
map.put("id", oaId);
executeSql(typeTableName.get(type), oaId, map, 1);
try {
int subcompanyid1 = Util.getIntValue(Util.null2DefaultStr(map.get("subcompanyid1"), ""), -1);
if(subcompanyid1 > 0){
themeService.createSubCompanyMenu(oaId, subcompanyid1);
}
}catch (Exception e){
log.error("为新员工创建默认的菜单权限 error " + e.getMessage());
}
try {
comInfo.addResourceInfoCache(oaId + "");
}catch (Exception e){
log.error("添加人员缓存 error " + e.getMessage());
}
}else {
if(type == 2){
try {
comInfo.updateResourceInfoCache(oaId + "");
}catch (Exception e){
log.error("更新人员缓存 error " + e.getMessage());
}
}
executeSql(typeTableName.get(type), oaId, map, 0);
}
if(insert){
data.put("code", 1);
}else {
data.put("code", 2);
}
if(type == 0){
//同步分部数据到矩阵
MatrixUtil.updateSubcompayData(String.valueOf(oaId));
}
}
}
/**
* <h1>id</h1>
* @author xuanran.wang
* @dateTime 2023/4/12 13:25
* @return id
**/
public int getNextHrmSubCompanyId(){
char separator = weaver.general.Util.getSeparator();
String uuid = UUID.randomUUID().toString();
String para = uuid + separator + uuid + separator + "1" + separator
+ 1 + separator + "" + separator + 1;
return executeProc("HrmSubCompany_Insert", para);
}
/**
* <h1>id</h1>
* @author xuanran.wang
* @dateTime 2023/4/12 13:24
* @return id
**/
public int getNextHrmDepartmentId(){
char separator = weaver.general.Util.getSeparator();
String uuid = UUID.randomUUID().toString();
String para = uuid + separator +uuid + separator +
"" + separator + "" + separator + 1+ separator + 1 + separator + "";
return executeProc("HrmDepartment_Insert", para);
}
/**
* <h1>id</h1>
* @author xuanran.wang
* @dateTime 2023/4/12 13:24
* @return id
**/
public int getNextHrmId(){
procRs.executeProc("HrmResourceMaxId_Get", "");
if (procRs.next()) {
return procRs.getInt(1);
}
return -1;
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2023/4/12 16:12
* @param name
* @param para
* @return id
**/
public int executeProc(String name, String para){
if(procRs == null){
procRs = new RecordSet();
}
procRs.executeProc(name, para);
if (procRs.next()) {
return procRs.getInt(1);
}
return -1;
}
/**
* <h1></h1>
*
* @param tableName
* @param id id
* @param type
* @param o
* @param params
* @param type 0: 1:
* @author xuanran.wang
* @dateTime 2023/4/6 13:35
**/
public void updateTable(String tableName, int id, int type, Object o){
StringBuilder sb = new StringBuilder("update ");
sb.append(tableName).append(" set ");
Map<String, Object> params;
try {
params = ShBigDataUtil.parseCusDbEntityMapping(type, o);
}catch (Exception e){
throw new CustomerException("parseCusDbEntityMapping error!");
public boolean executeSql(String tableName, int id, Map<String, Object> params, int type) {
return executeSql(tableName, id, params, type, "id");
}
/**
* <h1></h1>
*
* @param tableName
* @param id id
* @param params
* @param type 0: 1:
* @param primaryKey where
* @author xuanran.wang
* @dateTime 2023/4/6 13:35
**/
public boolean executeSql(String tableName, int id, Map<String, Object> params, int type, String primaryKey) {
String operationType = "update ";
if(type == 1){
operationType = "insert ";
}
StringBuilder sqlSb = new StringBuilder(operationType)
.append(tableName)
.append(" set ");
for (Map.Entry<String, Object> entry : params.entrySet()) {
sb.append(entry.getKey())
sqlSb.append(entry.getKey())
.append(" = #{")
.append(entry.getKey())
.append("},");
}
sb.deleteCharAt(sb.length() - 1);
sb.append(" where id = ").append(id);
boolean success = orgHrmAsyncMapper.updateSubInfo(sb.toString(), params);
sqlSb.deleteCharAt(sqlSb.length() - 1);
if(type == 0){
sqlSb.append(" where ")
.append(primaryKey)
.append(" = ")
.append(id);
}
boolean success;
if(type == 1){
success = orgHrmAsyncMapper.insertHrmInfo(sqlSb.toString(), params);
}else {
success = orgHrmAsyncMapper.updateOrgInfo(sqlSb.toString(), params);
}
if (!success) {
throw new CustomerException(Util.logStr("update {} sql error!", tableName));
throw new CustomerException(operationType + tableName + " fail!");
}
//同步分部数据到矩阵
MatrixUtil.updateSubcompayData(String.valueOf(id));
return true;
}
public void setChildList(List<OtherSysDepartment> departmentList){
if(departmentList.size() == 0){
return;
/**
* <h1>or</h1>
*
* @param list
* @param n
* @author xuanran.wang
* @dateTime 2023/4/10 12:13
**/
public void asyncOrDepByTree(List<Map<String, Object>> list, int n, int maxLevel, List<Map<String, Object>> hrmSubCompany, List<Map<String, Object>> hrmDepartment) {
n++;
for (Map<String, Object> department : list) {
department.put("level", n);
List<Map<String, Object>> childList = (List<Map<String, Object>>) department.get("childList");
String departmentId = Util.null2DefaultStr(department.get("id"), "");
boolean dep = n > maxLevel;
if(departmentWhiteList.contains(departmentId)){
dep = true;
}
if(subCompanyWhiteList.contains(departmentId)){
dep = false;
}
department.put("msg","success!");
if(dep){
try {
addHrmDepartmentMap(Collections.singletonList(department));
orgHrmAsyncMapper.updateHrmSubCompanyCanceled(Collections.singletonList(departmentId));
}catch (Exception e){
log.error(Util.logStr("async depart error!: {}, json: \n{}",e.getMessage(),JSONObject.toJSONString(department)));
department.put("code",0);
department.put("msg","async department error! " + e.getMessage());
}
hrmDepartment.add(department);
}else {
try {
if(subCompanyWhiteList.contains(departmentId) && orgHrmAsyncMapper.selectDepartHasUser(departmentId) > 0){
String error = "该部门下存在人员,无法同步成分部.本次同步不做更新请手动同步! json:\n" + JSONObject.toJSONString(department);
throw new CustomerException(error);
}
addHrmSubCompanyMap(Collections.singletonList(department));
orgHrmAsyncMapper.updateHrmDepartmentCanceled(Collections.singletonList(departmentId));
}catch (Exception e){
log.error(Util.logStr("async subCompany error!: {}, json: \n{}",e.getMessage(),JSONObject.toJSONString(department)));
department.put("code",0);
department.put("msg","async subCompany error! " + e.getMessage());
}
hrmSubCompany.add(department);
}
for (OtherSysDepartment department : departmentList) {
List<OtherSysDepartment> childList = departmentList
.stream()
.filter(item -> department.getId() == item.getParentid())
.collect(Collectors.toList());
department.setChildList(childList);
if (CollectionUtils.isNotEmpty(childList)) {
setChildList(childList);
childList.sort(orderByOrder.thenComparing(orderById));
List<String> childIds = childList
.stream()
.map(item -> Util.null2DefaultStr(item.get("id"), ""))
.collect(Collectors.toList());
if (departmentWhiteList.contains(departmentId)) {
departmentWhiteList.addAll(childIds);
// childIds.add(departmentId);
// if (!orgHrmAsyncMapper.updateHrmSubCompanyCanceled(childIds)) {
// log.error("updateHrmSubCompanyCanceled error!");
// }
}
// else if (subCompanyWhiteList.contains(departmentId)) {
// orgHrmAsyncMapper.updateHrmDepartmentCanceled(Collections.singletonList(departmentId));
// }
asyncOrDepByTree(childList, n, maxLevel, hrmSubCompany, hrmDepartment);
department.put("childList", new ArrayList<>());
}
}
}
/**
* <h1>or()</h1>
*
* @param list
* @param n
* @param hrmSubCompany
* @param hrmDepartment
* @author xuanran.wang
* @dateTime 2023/4/10 12:13
**/
@Deprecated
public void parseSubCompanyAndDepartmentMap(List<Map<String, Object>> list, int n, int maxLevel, List<Map<String, Object>> hrmSubCompany, List<Map<String, Object>> hrmDepartment) {
n++;
for (Map<String, Object> department : list) {
department.put("level", n);
List<Map<String, Object>> childList = (List<Map<String, Object>>) department.get("childList");
String departmentId = Util.null2DefaultStr(department.get("id"), "");
if (CollectionUtils.isNotEmpty(childList)) {
List<String> collect = childList.stream()
.map(item -> Util.null2DefaultStr(item.get("id"), ""))
.collect(Collectors.toList());
// 分部变成了部门则把子节点都变成部门 并将 当前数据和子数据以前是分部的全部封存
if (departmentWhiteList.contains(departmentId)) {
departmentWhiteList.addAll(collect);
collect.add(departmentId);
if (!orgHrmAsyncMapper.updateHrmSubCompanyCanceled(collect)) {
log.error("updateHrmSubCompanyCanceled error!");
}
}
// 如果部门变成了分部那么 把当前部门变成分部 然后把部门表中相应的数据进行封存
else if (subCompanyWhiteList.contains(departmentId)) {
// subCompanyWhiteList.addAll(collect);
orgHrmAsyncMapper.updateHrmDepartmentCanceled(Collections.singletonList(departmentId));
}
parseSubCompanyAndDepartmentMap(childList, n, maxLevel, hrmSubCompany, hrmDepartment);
department.put("childList", new ArrayList<>());
}
if (n > maxLevel || departmentWhiteList.contains(departmentId)) {
hrmDepartment.add(department);
} else {
hrmSubCompany.add(department);
}
}
}
/**
* <h1>parentId</h1>
*
* @param list
* @return
* @author xuanran.wang
* @dateTime 2023/4/11 13:26
**/
public List<Map<String, Object>> convertListToTree(List<Map<String, Object>> list) {
Map<Integer, Map<String, Object>> map = new HashMap<>();
for (Map<String, Object> item : list) {
map.put((Integer) item.get("id"), item);
}
// 构建树形结构
List<Map<String, Object>> tree = new ArrayList<>();
for (Map<String, Object> item : list) {
int parentId = (Integer) item.get("parentid");
if (parentId == -1) {
// 添加根节点
tree.add(item);
} else {
// 添加子节点
Map<String, Object> parent = map.get(parentId);
if (parent != null) {
List<Map<String, Object>> childList = (List<Map<String, Object>>) parent.get("childList");
if (childList == null) {
childList = new ArrayList<>();
parent.put("childList", childList);
}
childList.add(item);
}
}
}
return tree;
}
}

View File

@ -0,0 +1,102 @@
package weaver.xuanran.wang.sh_bigdata.org_hrm_async.util;
import aiyh.utils.Util;
import io.swagger.models.auth.In;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import weaver.general.TimeUtil;
import weaver.xuanran.wang.sh_bigdata.org_hrm_async.entity.OrgHrmAsyncCache;
import weaver.xuanran.wang.sh_bigdata.org_hrm_async.entity.OrgHrmAsyncConfigDetail;
import weaver.xuanran.wang.sh_bigdata.org_hrm_async.entity.OrgHrmAsyncConfigMain;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* <h1>-</h1>
*
* @author xuanran.wang
* @date 2023/4/11 15:48
*/
public class OrgHrmAsyncUtil {
/**
* <h1>map</h1>
* @author xuanran.wang
* @dateTime 2023/4/11 18:21
* @param orgHrmAsyncCache
* @param hrmAsyncConfig
* @return map
**/
public static Map<String, Object> convertInterfaceValToOA(OrgHrmAsyncCache orgHrmAsyncCache, OrgHrmAsyncConfigMain hrmAsyncConfig){
return convertInterfaceValToOA(orgHrmAsyncCache, hrmAsyncConfig, false);
}
/**
* <h1>map</h1>
* @author xuanran.wang
* @dateTime 2023/4/11 18:21
* @param orgHrmAsyncCache
* @param hrmAsyncConfig
* @return map
**/
public static Map<String, Object> convertInterfaceValToOA(OrgHrmAsyncCache orgHrmAsyncCache, OrgHrmAsyncConfigMain hrmAsyncConfig, boolean addSystemParam){
List<OrgHrmAsyncConfigDetail> configDetailList = hrmAsyncConfig.getOrgHrmAsyncConfigDetailList();
LinkedHashMap<String, Object> res = new LinkedHashMap<>();
for (OrgHrmAsyncConfigDetail detail : configDetailList) {
String oaField = detail.getOaField();
Object value = ValueRuleMethod.VALUE_RULE_FUNCTION.get(detail.getConvertType()).apply(detail, orgHrmAsyncCache);
int fieldType = detail.getFieldType();
if(0 == fieldType){
value = Util.null2DefaultStr(value, "");
}else {
value = Util.getIntValue(Util.null2DefaultStr(value, ""),0);
}
res.put(oaField, value);
}
if(addSystemParam){
addSysParam(res);
}
return res;
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2023/4/10 18:33
* @param listMap
**/
public static HashMap<String, Integer> parseListMap2Map( List<Map<String, Integer>> listMap){
return parseListMap2Map("outkey","id", listMap);
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2023/4/10 18:33
* @param listMap
**/
public static HashMap<String, Integer> parseListMap2Map(String key, String value, List<Map<String, Integer>> listMap){
if(CollectionUtils.isEmpty(listMap)){
return new HashMap<>();
}
HashMap<String, Integer> res = new HashMap<>();
listMap.forEach(map -> {
String outKey = Util.null2DefaultStr(map.get(key),"");
if(StringUtils.isNotBlank(outKey)){
int id = Util.getIntValue(Util.null2DefaultStr(map.get(value),""),-1);
res.put(outKey, id);
}
});
return res;
}
public static void addSysParam(Map<String, Object> res){
String dateTime = TimeUtil.getCurrentTimeString();
res.put("modifier", 1);
res.put("modified", dateTime);
}
}

View File

@ -0,0 +1,178 @@
package weaver.xuanran.wang.sh_bigdata.org_hrm_async.util;
import aiyh.utils.Util;
import aiyh.utils.excention.CustomerException;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import weaver.general.TimeUtil;
import weaver.xuanran.wang.sh_bigdata.org_hrm_async.annotations.CusOrgHrmAsyncConvert;
import weaver.xuanran.wang.sh_bigdata.org_hrm_async.entity.OrgHrmAsyncCache;
import weaver.xuanran.wang.sh_bigdata.org_hrm_async.entity.OrgHrmAsyncConfigDetail;
import weaver.xuanran.wang.sh_bigdata.org_hrm_async.mapper.OrgHrmAsyncMapper;
import weaver.youhong.ai.haripijiu.action.sapdocking.config.mapper.SapConfigMapper;
import weaver.youhong.ai.haripijiu.action.sapdocking.config.pojo.SapConfigDetail;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import java.util.function.BiFunction;
/**
* <h1></h1>
*
* <p>create: 2023-02-02 15:15</p>
*
* @author youHong.ai
*/
public class ValueRuleMethod {
public static final Map<Integer, BiFunction<OrgHrmAsyncConfigDetail, OrgHrmAsyncCache, Object>> VALUE_RULE_FUNCTION = new HashMap<>();
private final OrgHrmAsyncMapper orgHrmAsyncMapper = Util.getMapper(OrgHrmAsyncMapper.class);
private final Logger log = Util.getLogger();
static {
Class<ValueRuleMethod> valueRuleMethodClass = ValueRuleMethod.class;
Method[] methods = valueRuleMethodClass.getMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(ValueRuleMethodNo.class)) {
ValueRuleMethodNo annotation = method.getAnnotation(ValueRuleMethodNo.class);
int value = annotation.value();
VALUE_RULE_FUNCTION.put(value, (OrgHrmAsyncConfigDetail, orgHrmAsyncCache) -> {
try {
ValueRuleMethod valueRuleMethod = new ValueRuleMethod();
return method.invoke(valueRuleMethod, OrgHrmAsyncConfigDetail, orgHrmAsyncCache);
} catch (IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
}
});
}
}
}
@ValueRuleMethodNo(value = 0, desc = "不转换")
public Object getFixValue(OrgHrmAsyncConfigDetail configDetail,OrgHrmAsyncCache cache) {
return cache.getInterfaceVal().get(configDetail.getInterfaceField());
}
@ValueRuleMethodNo(value = 1, desc = "默认值")
public Object getCusText(OrgHrmAsyncConfigDetail configDetail, OrgHrmAsyncCache cache) {
return configDetail.getCusText();
}
@ValueRuleMethodNo(value = 2, desc = "自定义sql")
public Object getCustomerSqlValue(OrgHrmAsyncConfigDetail configDetail, OrgHrmAsyncCache cache) {
Map<String, Object> interfaceVal = cache.getInterfaceVal();
String cusText = configDetail.getCusText();
cusText = Util.sbc2dbcCase(cusText);
if (Strings.isNullOrEmpty(cusText)) {
return null;
}
if (!cusText.startsWith("select")) {
return null;
}
// 接口字段值判断
String interfaceField = configDetail.getInterfaceField();
String interfaceFieldVal = Util.null2DefaultStr(interfaceVal.get(interfaceField),"");
if(StringUtils.isBlank(interfaceFieldVal)){
return "";
}
Object val = interfaceVal.get(configDetail.getInterfaceField());
// 如果接口参数是集合则转成'1,2'形式 放到参数中
if(val instanceof List && ((List<?>) val).size() > 0){
ArrayList<String> temp = new ArrayList<>();
for (int i = 0; i < ((List<?>) val).size(); i++) {
interfaceVal.put(interfaceField + "_" + i, ((List<?>) val).get(i));
temp.add("'" + ((List<?>) val).get(i) + "'");
}
interfaceVal.put(interfaceField,StringUtils.join(temp,","));
}
String oaField = configDetail.getOaField();
// 先从缓存中找数据
int cacheVal = convertFromCache(interfaceVal, cache, oaField, interfaceFieldVal);
if(cacheVal > 0){
return cacheVal;
}
if(StringUtils.isNotBlank(interfaceFieldVal)){
cusText = cusText.replace("?", interfaceFieldVal);
}
List<String> strings = orgHrmAsyncMapper.selectCustomerSqlArr(cusText, interfaceVal);
if(CollectionUtils.isNotEmpty(strings)){
return StringUtils.join(strings,",");
}
return "";
}
@ValueRuleMethodNo(value = 3, desc = "自定义接口")
public Object getCusConvertInterface(OrgHrmAsyncConfigDetail configDetail, OrgHrmAsyncCache cache) {
String cusText = configDetail.getCusText();
if(Strings.isNullOrEmpty(cusText)){
return null;
}
try {
Class<?> clazz = Class.forName(cusText);
if(!CusOrgHrmAsyncConvert.class.isAssignableFrom(clazz)){
throw new CustomerException(cusText + " not implements weaver.xuanran.wang.sh_bigdata.org_hrm_async.annotations.CusOrgHrmAsyncConvert");
}
CusOrgHrmAsyncConvert o = (CusOrgHrmAsyncConvert) clazz.newInstance();
Map<String, String> pathParam = Util.parseCusInterfacePathParam(cusText);
return o.cusConvert(configDetail, cache, pathParam);
}catch (Exception e){
log.error("getCusConvertInterface error! " + e.getMessage());
return null;
}
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2023/4/13 13:44
* @param interfaceVal map
* @param cache
* @param oaField oa
* @param interfaceFieldVal
* @return id
**/
public int convertFromCache(Map<String, Object> interfaceVal, OrgHrmAsyncCache cache, String oaField, String interfaceFieldVal){
Map<String, Integer> subCompanyCache = cache.getSubCompanyCache();
Map<String, Integer> departmentCache = cache.getDepartmentCache();
Integer value = Util.getIntValue(Util.null2DefaultStr(interfaceVal.get("parentid"), ""),-1);
// 特殊处理 先从缓存中拿如果缓存中没有在执行sql
if("subcompanyid1".equalsIgnoreCase(oaField) || "supsubcomid".equalsIgnoreCase(oaField)){
value = subCompanyCache.get(value + "");
} else if("supdepId".equalsIgnoreCase(oaField)){
value = departmentCache.get(value + "");
}
if("jobtitle".equalsIgnoreCase(oaField)){
Map<String, Integer> jobTitleCache = cache.getJobTitleCache();
value = Util.getIntValue(Util.null2DefaultStr(jobTitleCache.get(interfaceFieldVal), ""), -1);
if(value < 0){
interfaceVal.put("jobCreateTime", TimeUtil.getCurrentTimeString());
boolean success = orgHrmAsyncMapper.insertJobTitle(interfaceVal);
if(!success){
log.error("insertJobTitle fail!");
}
int id = Util.getIntValue(orgHrmAsyncMapper.selectJobTitleByName(interfaceFieldVal), -1);
if(id > 0){
jobTitleCache.put(interfaceFieldVal, id);
}
}
}
if(!Objects.isNull(value) && value > 0){
return value;
}
return -1;
}
}

View File

@ -0,0 +1,19 @@
package weaver.xuanran.wang.sh_bigdata.org_hrm_async.util;
import java.lang.annotation.*;
/**
* <h1></h1>
*
* <p>create: 2023-02-02 15:18</p>
*
* @author youHong.ai
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ValueRuleMethodNo {
int value();
String desc();
}

View File

@ -19,5 +19,5 @@ public class CusDoneTask {
@SqlFieldMapping
private String taskNum;
private int status;
private String appId;
private String agentid;
}

View File

@ -18,7 +18,7 @@ import weaver.xuanran.wang.common.annocation.SqlUpdateWhereField;
public class CusTodoTask {
@SqlFieldMapping
protected String taskNum;
protected String appId;
protected String agentid;
@SqlFieldMapping
protected String taskName;
protected String taskDesc;

View File

@ -33,7 +33,6 @@ import java.util.*;
@Data
public class SendTodoTaskServiceImpl implements SendTodoTaskService {
private final Logger log = Util.getLogger();
private String appId;
private final SendTodoTaskUtil sendTodoTaskUtil = new SendTodoTaskUtil();
private String addTodoTaskUrl;
private String updateTodoTaskUrl;
@ -45,7 +44,7 @@ public class SendTodoTaskServiceImpl implements SendTodoTaskService {
{
sendTodoTaskUtil.setAppId(ShBigDataUtil.getPropertiesValByKey("appId"));
sendTodoTaskUtil.setAgentId(ShBigDataUtil.getPropertiesValByKey("agentId"));
modelId = Util.getIntValue(ShBigDataUtil.getPropertiesValByKey("modelId"),-1);
addTodoTaskUrl = ShBigDataUtil.getPropertiesValByKey("addTodoTaskUrl");
updateTodoTaskUrl = ShBigDataUtil.getPropertiesValByKey("updateTodoTaskUrl");

View File

@ -33,4 +33,6 @@ public class StudentClass {
**/
@SqlFieldMapping()
private int belongYear;
@SqlFieldMapping()
private String teacherId;
}

View File

@ -2,13 +2,12 @@ package weaver.xuanran.wang.shyl.dataasync.job;
import aiyh.utils.Util;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.log4j.Logger;
import weaver.interfaces.schedule.BaseCronJob;
import weaver.xuanran.wang.common.annocation.ParamNotNull;
import weaver.xuanran.wang.common.annocation.ParamPrint;
import weaver.xuanran.wang.common.util.CommonUtil;
import weaver.xuanran.wang.shyl.dataasync.entity.Student;
import weaver.xuanran.wang.shyl.dataasync.entity.StudentClass;
import weaver.xuanran.wang.shyl.dataasync.service.CusDataAsyncService;
import java.util.HashMap;
@ -19,7 +18,6 @@ import java.util.HashMap;
* @author xuanran.wang
* @date 2023/2/9 10:02
*/
@Data
public class CusDataAsyncJob extends BaseCronJob {
/**
@ -63,18 +61,42 @@ public class CusDataAsyncJob extends BaseCronJob {
private final CusDataAsyncService dataAsyncService = new CusDataAsyncService();
// private final Logger logger = Util.getLogger();
private final Logger logger = Util.getLogger();
@Override
public void execute() {
try {
CommonUtil.checkParamNotNull(this);
// 数据同步
dataAsyncService.asyncData(baseAddr + queryClassUrl, classModelId, StudentClass.class, updateClassSql,"data");
dataAsyncService.asyncData(baseAddr + queryClassUrl, classModelId, updateClassSql,"data");
}catch (Exception e){
// logger.error(Util.logStr("CusDataAsyncJob execute error! the error is :{}, " +
// "error stack trace msg is: \n{}", e.getMessage(), Util.getErrString(e)));
}
logger.error(Util.logStr("CusDataAsyncJob execute error! the error is :{}, " +
"error stack trace msg is: \n{}", e.getMessage(), Util.getErrString(e)));
}
}
public String getBaseAddr() {
return baseAddr;
}
public void setBaseAddr(String baseAddr) {
this.baseAddr = baseAddr;
}
public String getQueryClassUrl() {
return queryClassUrl;
}
public void setQueryClassUrl(String queryClassUrl) {
this.queryClassUrl = queryClassUrl;
}
public String getClassModelId() {
return classModelId;
}
public void setClassModelId(String classModelId) {
this.classModelId = classModelId;
}
}

View File

@ -11,7 +11,9 @@ import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import weaver.conn.RecordSet;
import weaver.xuanran.wang.common.util.CusInfoToOAUtil;
import weaver.xuanran.wang.shyl.dataasync.entity.StudentClass;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
@ -59,13 +61,49 @@ public class CusDataAsyncService {
return;
}
ArrayList<Object> dataList = new ArrayList<>();
ArrayList<String> ids = new ArrayList<>();
for (Object o : array) {
Object temp = JSONObject.parseObject(o.toString(), clazz);
dataList.add(temp);
}
CusInfoToOAUtil.executeBatchByEntity(Util.getIntValue(modelId, -1), dataList, updateSql);
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2023/2/9 10:10
* @param url
* @param modelId id
* @param updateSql sql
**/
public void asyncData(String url, String modelId, String updateSql, String key){
Object data = getResponseDataByGet(url, new HashMap<>(), new HashMap<>(), key);
JSONArray array = JSONObject.parseArray(JSONObject.toJSONString(data));
log.info("data : " + array);
if(CollectionUtils.isEmpty(array)){
log.error("array is empty!");
return;
}
ArrayList<Object> dataList = new ArrayList<>();
ArrayList<String> ids = new ArrayList<>();
for (Object o : array) {
StudentClass temp = JSONObject.parseObject(o.toString(), StudentClass.class);
dataList.add(temp);
ids.add("'" + temp.getId() + "'");
}
CusInfoToOAUtil.executeBatchByEntity(Util.getIntValue(modelId, -1), dataList, updateSql);
RecordSet updateRs = new RecordSet();
if(CollectionUtils.isNotEmpty(ids)){
String updateDelStatus = "update " + CusInfoToOAUtil.checkModelId(Util.getIntValue(modelId, -1)) + " set delStatus = 1 where " +
weaver.general.Util.getSubINClause(StringUtils.join(ids,","),"classId","not in");
if (!updateRs.executeUpdate(updateDelStatus)) {
throw new CustomerException("更新删除状态失败!");
}
}
}
/**
* <h1>token</h1>
* @author xuanran.wang

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