ic_excellent 2023-05-06 13:51:48 +08:00
commit e3a1a7060e
817 changed files with 145151 additions and 373 deletions

11
.gitignore vendored
View File

@ -26,7 +26,7 @@ log
/log/
.DS_Store
/src/main/resources/WEB-INF/prop/weaver.properties
/lib/classbean
/file/
/src/test/resources/application.properties
/src/test/resources/application.xml
@ -36,7 +36,7 @@ DirectoryV2.xml
/lib/classbeanLib/ecology-dev-lib.jar
/lib/classbeanLib/web-inf-class-lib.jar
/lib/weaverLib/
/lib/jitulib/
*.groovy
*.log
*.iml
@ -47,5 +47,8 @@ src/test/resources/font
src/main/resources/WEB-INF/vm/outFile
target/
*.back
src/main/aiyh_old_src/
src/main/jitu_src/
# 老项目代码
#/lib/jitulib/
#/lib/classbean
#src/main/youhong_ai_old_src/
#src/main/youhong_ai_jitu_src/

View File

@ -113,9 +113,12 @@
```properties
serverName=ecology
rootPath=/Users/aoey.oct.22/company/Fan_wei/code/idea/ecology9-project/src/main/resources/ # 修改为实际的地址
systemFilePath=/Users/aoey.oct.22/company/Fan_wei/code/idea/ecology9-project/file # 修改为实际的地址这里可以是你实际ecology的文件地址即.../ecolog/web-inf/systemfile 绝对路径
logPath=/Users/aoey.oct.22/company/Fan_wei/code/idea/ecology9-project/log # 修改为实际的地址
# 修改为实际的地址
rootPath=/Users/aoey.oct.22/company/Fan_wei/code/idea/ecology9-project/src/main/resources/
# 修改为实际的地址这里可以是你实际ecology的文件地址即.../ecolog/web-inf/systemfile 绝对路径
systemFilePath=/Users/aoey.oct.22/company/Fan_wei/code/idea/ecology9-project/file
# 修改为实际的地址
logPath=/Users/aoey.oct.22/company/Fan_wei/code/idea/ecology9-project/log
```
### 测试

Binary file not shown.

BIN
lib/jitulib/jjwt-0.6.0.jar Normal file

Binary file not shown.

View File

@ -17,6 +17,7 @@ import aiyh.utils.sqlUtil.builderSql.impl.BuilderSqlImpl;
import aiyh.utils.sqlUtil.whereUtil.Where;
import aiyh.utils.sqlUtil.whereUtil.impl.PrepWhereImpl;
import aiyh.utils.sqlUtil.whereUtil.impl.WhereImpl;
import aiyh.utils.tool.cn.hutool.core.util.StrUtil;
import aiyh.utils.zwl.common.ToolUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
@ -28,6 +29,7 @@ import com.weaver.general.TimeUtil;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.log4j.*;
import org.h2.util.StringUtils;
import org.jetbrains.annotations.NotNull;
import weaver.common.util.string.StringUtil;
import weaver.conn.RecordSet;
import weaver.docs.docs.DocImageManager;
@ -61,6 +63,9 @@ import java.lang.reflect.*;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.ParseException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
@ -3952,4 +3957,41 @@ public class Util extends weaver.general.Util {
supportLanuage.append("`~`~");
return supportLanuage.toString();
}
/**
* <h2></h2>
*
* @param dir
* @param prefix
* @return
*/
@NotNull
public static String getTempFilePath(String dir, String prefix) {
if (StrUtil.isBlank(dir)) {
dir = "temp";
}
if (StrUtil.isBlank(prefix)) {
throw new CustomerException("this prefix can not be null!");
}
String sysFilePath = GCONST.getSysFilePath();
String filePath = "";
if (sysFilePath.endsWith(File.separator)) {
filePath = sysFilePath + "cus_temp" + File.separator + dir + File.separator +
System.currentTimeMillis() + "-" + dir + "-" + UUID.randomUUID() + prefix;
} else {
filePath = sysFilePath + File.separator + "cus_temp" + File.separator + dir + File.separator +
System.currentTimeMillis() + "-" + dir + "-" + UUID.randomUUID() + prefix;
}
Path path = Paths.get(filePath);
if (!Files.exists(path)) {
Path parent = path.getParent();
try {
Files.createDirectories(parent);
} catch (IOException e) {
throw new CustomerException(Util.logStr("can not create file [{}]", filePath));
}
}
return filePath;
}
}

View File

@ -2,6 +2,7 @@ package aiyh.utils.fileUtil.pdf;
import aiyh.utils.Util;
import aiyh.utils.excention.CustomerException;
import aiyh.utils.tool.cn.hutool.core.collection.CollectionUtil;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfContentByte;
@ -107,6 +108,9 @@ public class PdfUtil {
}
InputStream inputStream = ImageFileManager.getInputStreamById(pdfImageFileId);
List<PdfPointItem> keywordPoints = findKeywordPoints(inputStream, keyword);
if (CollectionUtil.isEmpty(keywordPoints)) {
throw new CustomerException("关键字定位异常,未发现关键字!");
}
PdfReader pdfReader = null;
Image image = null;
try {

View File

@ -41,6 +41,7 @@ public class FloatTypeHandler implements TypeHandler {
}
return 0.0F;
}
return Float.parseFloat(string);
}
@ -55,6 +56,7 @@ public class FloatTypeHandler implements TypeHandler {
}
return 0.0F;
}
return Float.parseFloat(string);
}
@ -69,6 +71,7 @@ public class FloatTypeHandler implements TypeHandler {
}
return 0.0F;
}
return Float.parseFloat(string);
}

View File

@ -473,15 +473,15 @@ public class ResultMapper {
}
if ("FLOAT".equalsIgnoreCase(columnType) || "DOUBLE".equalsIgnoreCase(columnType) || "DECIMAL".equalsIgnoreCase(columnType)) {
if (enable) {
((Map<? super Object, ? super Object>) o).put(Util.toCamelCase(columnName[i]), rs.getFloat(i + 1));
((Map<? super Object, ? super Object>) o).put(Util.toCamelCase(columnName[i]), rs.getString(i + 1));
continue;
}
if (DBConstant.DB_TYPE_ORACLE.equals(rs.getDBType())) {
((Map<? super Object, ? super Object>) o).put(Util.toCamelCase(columnName[i]), rs.getFloat(i + 1));
((Map<? super Object, ? super Object>) o).put(Util.toCamelCase(columnName[i]), rs.getString(i + 1));
}
((Map<? super Object, ? super Object>) o).put(columnName[i].toLowerCase(), rs.getFloat(i + 1));
((Map<? super Object, ? super Object>) o).put(columnName[i].toUpperCase(), rs.getFloat(i + 1));
((Map<? super Object, ? super Object>) o).put(columnName[i], rs.getFloat(i + 1));
((Map<? super Object, ? super Object>) o).put(columnName[i].toLowerCase(), rs.getString(i + 1));
((Map<? super Object, ? super Object>) o).put(columnName[i].toUpperCase(), rs.getString(i + 1));
((Map<? super Object, ? super Object>) o).put(columnName[i], rs.getString(i + 1));
continue;
}
if (method.isAnnotationPresent(Associations.class)) {

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

@ -26,4 +26,8 @@ public class RequestLogAuthority {
/** 权限组成员 */
@SqlOracleDbFieldAnn("AUTHORITY_MEMBER")
private String authorityMember;
/** */
@SqlOracleDbFieldAnn("DEFAULT_VALUE")
private String defaultValue;
}

View File

@ -30,13 +30,22 @@ public class RequestLogAuthorityService {
result.put("show", false);
return result;
}
if (StrUtil.isBlank(requestId) || "-1".equals(requestId)) {
if ("1".equals(requestLogAuthority.getDefaultValue())) {
result.put("enable", true);
} else {
result.put("enable", false);
}
return result;
}
Integer id = mapper.selectRequestLogId(requestId, nodeId, String.valueOf(user.getUID()));
if (id <= 0) {
if ("1".equals(requestLogAuthority.getDefaultValue())) {
result.put("enable", true);
} else {
result.put("enable", false);
}
} else {
result.put("enable", true);
}

View File

@ -0,0 +1,38 @@
package com.api.youhong.ai.yashilandai.openbill.controller;
import aiyh.utils.ApiResult;
import aiyh.utils.Util;
import com.api.youhong.ai.yashilandai.openbill.service.OpenThenBillService;
import org.apache.log4j.Logger;
import javax.ws.rs.Consumes;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
/**
* <h1>api</h1>
*
* <p>create: 2023/4/25 10:09</p>
*
* @author youHong.ai
*/
@Path("/ayh/estee-Lauder/open-bill")
public class OpenThenBillController {
private final OpenThenBillService service = new OpenThenBillService();
private final Logger log = Util.getLogger();
@Path("/data/get")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public String dataGet() {
try {
return ApiResult.success(service.getOpenBillListData());
} catch (Exception e) {
log.error("get open the bill data error!" + Util.getErrString(e));
return ApiResult.error("system error!");
}
}
}

View File

@ -0,0 +1,26 @@
package com.api.youhong.ai.yashilandai.openbill.mapper;
import aiyh.utils.annotation.recordset.Select;
import aiyh.utils.annotation.recordset.SqlMapper;
import java.util.List;
import java.util.Map;
/**
* <h1></h1>
*
* <p>create: 2023/4/25 10:15</p>
*
* @author youHong.ai
*/
@SqlMapper
public interface OpenThenBillMapper {
/**
* <h2></h2>
*
* @return
*/
@Select("select * from v_online")
List<Map<String, Object>> selectList();
}

View File

@ -0,0 +1,30 @@
package com.api.youhong.ai.yashilandai.openbill.service;
import aiyh.utils.Util;
import com.api.youhong.ai.yashilandai.openbill.mapper.OpenThenBillMapper;
import java.util.List;
import java.util.Map;
/**
* <h1></h1>
*
* <p>create: 2023/4/25 10:12</p>
*
* @author youHong.ai
*/
public class OpenThenBillService {
private final OpenThenBillMapper mapper = Util.getMapper(OpenThenBillMapper.class);
public Object getOpenBillListData() {
return null;
}
public List<Map<String, Object>> getData() {
List<Map<String, Object>> dataList = mapper.selectList();
return null;
}
}

View File

@ -12,7 +12,6 @@ import com.engine.workflow.cmd.requestForm.remind.GetEmailRemindUrlCmd;
import com.engine.workflow.constant.RemindTypeEnum;
import com.engine.workflow.util.GetCustomLevelUtil;
import com.engine.workflow.util.WfToDocUtil;
import com.engine.youhong.ai.taibao.email.BlackListExpansion;
import com.engine.youhong.ai.taibao.email.BlackListRegister;
import com.google.common.base.Strings;
import weaver.conn.RecordSet;
@ -1747,11 +1746,14 @@ public class RequestRemindBiz {
}
}
/* ******************* youhong.ai 添加发送邮箱的黑名单拓展start ******************* */
for (BlackListExpansion blackListExpansion : BlackListRegister.getExpansionList()) {
Set<String> mailAddress1 = blackListExpansion.sendEmailHandler(mailAddress);
if (Objects.nonNull(mailAddress1)) {
mailAddress = mailAddress1;
try {
Set<String> expansionList = BlackListRegister.getExpansionList(mailAddress);
if (Objects.nonNull(expansionList)) {
mailAddress = expansionList;
}
} catch (Exception e) {
aiyh.utils.Util.getLogger().error("过滤黑名单日志失败:" + aiyh.utils.Util.getErrString(e));
}
/* ******************* youhong.ai 添加发送邮箱的黑名单拓展 end ******************* */
if (mailAddress.isEmpty()) return;
@ -1784,11 +1786,13 @@ public class RequestRemindBiz {
}
}
/* ******************* youhong.ai 添加发送邮箱的黑名单拓展start ******************* */
for (BlackListExpansion blackListExpansion : BlackListRegister.getExpansionApproveList()) {
Set<String> mailAddress1 = blackListExpansion.sendEmailHandler(mailAddress);
if (Objects.nonNull(mailAddress1)) {
mailAddress = mailAddress1;
try {
Set<String> expansionList = BlackListRegister.getExpansionApproveList(mailAddress);
if (Objects.nonNull(expansionList)) {
mailAddress = expansionList;
}
} catch (Exception e) {
aiyh.utils.Util.getLogger().error("过滤黑名单日志失败:" + aiyh.utils.Util.getErrString(e));
}
/* ******************* youhong.ai 添加发送邮箱的黑名单拓展 end ******************* */
EmailApprovalRunnable.threadModeReminder(String.join(",", mailAddress), title, content, String.valueOf(requestId), allAttchment);

View File

@ -1,21 +0,0 @@
package com.engine.youhong.ai.taibao.email;
import java.util.Set;
/**
* <h1></h1>
*
* <p>create: 2023/4/14 17:07</p>
*
* @author youHong.ai
*/
public interface BlackListExpansion {
/**
* <h2></h2>
*
* @param mailAddress
* @return
*/
Set<String> sendEmailHandler(Set<String> mailAddress);
}

View File

@ -1,8 +1,14 @@
package com.engine.youhong.ai.taibao.email;
import java.util.ArrayList;
import aiyh.utils.Util;
import aiyh.utils.tool.cn.hutool.core.collection.CollectionUtil;
import com.engine.youhong.ai.taibao.email.mapper.InitBlackEmailListMapper;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
/**
* <h1></h1>
@ -13,26 +19,40 @@ import java.util.Objects;
*/
public class BlackListRegister {
private static final List<BlackListExpansion> EXPANSION_LIST = new ArrayList<>();
private static final List<BlackListExpansion> EXPANSION_APPROVE_LIST = new ArrayList<>();
public static void registerExpansion(BlackListExpansion blackListExpansion) {
if (Objects.nonNull(blackListExpansion)) {
EXPANSION_LIST.add(blackListExpansion);
private static final InitBlackEmailListMapper mapper = Util.getMapper(InitBlackEmailListMapper.class);
public static Set<String> getExpansionList(Set<String> set) {
if (Objects.isNull(set)) {
return null;
}
List<String> hrmList = mapper.selectWorkflowBlackEmailList();
return getBlackListEamil(set, hrmList);
}
public static void registerAPPROVEExpansion(BlackListExpansion blackListExpansion) {
if (Objects.nonNull(blackListExpansion)) {
EXPANSION_APPROVE_LIST.add(blackListExpansion);
public static Set<String> getExpansionApproveList(Set<String> set) {
if (Objects.isNull(set)) {
return null;
}
List<String> hrmList = mapper.selectWorkflowApproveBlackEmailList();
return getBlackListEamil(set, hrmList);
}
public static List<BlackListExpansion> getExpansionList() {
return EXPANSION_LIST;
@Nullable
private static Set<String> getBlackListEamil(Set<String> set, List<String> hrmList) {
if (CollectionUtil.isEmpty(hrmList)) {
return null;
}
public static List<BlackListExpansion> getExpansionApproveList() {
return EXPANSION_APPROVE_LIST;
String ids = Util.join(hrmList, ",");
List<String> blackEmailList = mapper.selectEmailListByHrmIds(ids);
if (CollectionUtil.isEmpty(blackEmailList)) {
return null;
}
Set<String> collect = set.stream()
.filter(item -> !blackEmailList.contains(item))
.collect(Collectors.toSet());
Util.getLogger().info("拦截后邮箱:" + collect);
return collect;
}
}

View File

@ -1,64 +0,0 @@
package com.engine.youhong.ai.taibao.email.impl;
import aiyh.utils.Util;
import aiyh.utils.tool.cn.hutool.core.collection.CollectionUtil;
import com.engine.youhong.ai.taibao.email.BlackListRegister;
import com.engine.youhong.ai.taibao.email.mapper.InitBlackEmailListMapper;
import com.weaverboot.frame.ioc.anno.classAnno.WeaSysInitComponent;
import com.weaverboot.frame.ioc.anno.methodAnno.WeaSysInit;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* <h1></h1>
*
* <p>create: 2023/4/14 17:15</p>
*
* @author youHong.ai
*/
@WeaSysInitComponent("注册email黑名单拦截器")
public class InitBlackListServiceImpl {
private final InitBlackEmailListMapper mapper = Util.getMapper(InitBlackEmailListMapper.class);
@WeaSysInit(order = 1, description = "注册拦截邮箱黑名单")
public void init() {
Util.getLogger().info("注册拦截邮箱黑名单,init");
BlackListRegister.registerExpansion(set -> {
if (Objects.isNull(set)) {
return null;
}
List<String> hrmList = mapper.selectWorkflowBlackEmailList();
String ids = Util.join(hrmList, ",");
List<String> blackEmailList = mapper.selectEmailListByHrmIds(ids);
if (CollectionUtil.isEmpty(blackEmailList)) {
return set;
}
return set.stream()
.filter(item -> !blackEmailList.contains(item))
.collect(Collectors.toSet());
});
}
@WeaSysInit(order = 2, description = "注册拦截邮箱黑名单")
public void initApprove() {
Util.getLogger().info("注册拦截邮箱黑名单,initApprove");
BlackListRegister.registerAPPROVEExpansion(set -> {
if (Objects.isNull(set)) {
return null;
}
String ids = mapper.selectWorkflowApproveBlackEmailList();
List<String> blackEmailList = mapper.selectEmailListByHrmIds(ids);
if (CollectionUtil.isEmpty(blackEmailList)) {
return set;
}
return set.stream()
.filter(item -> !blackEmailList.contains(item))
.collect(Collectors.toSet());
});
}
}

View File

@ -29,8 +29,8 @@ public interface InitBlackEmailListMapper {
*
* @return email
*/
@Select("select email from uf_black_email_conf where type = 1")
String selectWorkflowApproveBlackEmailList();
@Select("select black_hrm from uf_black_email_conf where type = 0")
List<String> selectWorkflowApproveBlackEmailList();
/**

View File

@ -414,7 +414,6 @@ public class DealWithMapping extends ToolUtil {
}
// 6为List类型
else if (ParamTypeEnum.LIST == anEnum) {
String childType = mappingDetail.getChildType();
List<MappingDetail> childList = mappingDetail.getChildList();
List<Object> list = new ArrayList<>();
requestParam.put(paramName, list);
@ -466,8 +465,7 @@ public class DealWithMapping extends ToolUtil {
}
tempList.add(map);
}
}
else {
} else {
tempList.add(o);
}
}
@ -560,8 +558,7 @@ public class DealWithMapping extends ToolUtil {
}
tempList.add(map);
}
}
else{
} else {
tempList.add(o);
}
}
@ -628,17 +625,21 @@ public class DealWithMapping extends ToolUtil {
String fieldName = fieldMassage.getFieldName();
String fieldNameLowe = fieldName.toLowerCase();
if ("1".equals(childSource)) {
if (Objects.nonNull(detailMap)) {
workFlowVal = Util.null2String(detailMap.get(fieldNameLowe));
if ("".equals(workFlowVal)) {
workFlowVal = Util.null2String(detailMap.get(fieldName));
}
}
} else if ("0".equals(childSource)) {
if (Objects.nonNull(mainMap)) {
workFlowVal = Util.null2String(mainMap.get(fieldNameLowe));
if ("".equals(workFlowVal)) {
workFlowVal = Util.null2String(mainMap.get(fieldName));
}
}
}
}
value = Util.null2String(valueContext)
.replace("{?requestid}", String.valueOf(mainMap.get("requestid")))
.replace("{?}", workFlowVal);
@ -750,12 +751,15 @@ public class DealWithMapping extends ToolUtil {
if ("".equals(value)) {
value = Util.null2String(detailMap.get(fieldNameLower));
}
} else if ("".equals(childSource)) {
value = valueContext;
} else {
value = Util.null2String(mainMap.get(fieldName));
if ("".equals(value)) {
value = Util.null2String(detailMap.get(fieldNameLower));
}
}
}
value = o.execute(mainMap, detailMap, String.valueOf(value == null ? "" : value), pathParamMap);
}
@ -1243,6 +1247,7 @@ public class DealWithMapping extends ToolUtil {
*/
private void listValueDeal(Map<String, Object> mainMap, List<MappingDetail> childList, List<Object> list, MappingDetail detail) throws ValueDealException {
String childSource = detail.getDataSource();
String childType = detail.getChildType();
if ("1".equals(childSource)) {
int mainId = Util.getIntValue(Util.null2String(mainMap.get("id")));

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

View File

@ -50,7 +50,7 @@ public interface ConsumerMapper {
* @param outKey id
* @return map key : id, val : id
**/
@Select("select id departmentId, subcompanyid1 subCompanyId from hrmdepartment where outkey = #{outKey} and canceled != 1")
@Select("select id departmentId, subcompanyid1 subCompanyId from hrmdepartment where outkey = #{outKey} and ifnull(canceled,0) <> 1")
Map<String, Integer> getDepInfoByOutKey(@ParamMapper("outKey") String outKey);
/**
@ -70,7 +70,7 @@ public interface ConsumerMapper {
* @param outKey id
* @return id
**/
@Select("select id from hrmdepartment where outkey = #{outKey} and canceled != 1")
@Select("select id from hrmdepartment where outkey = #{outKey} and ifnull(canceled,0) <> 1")
String getDepIdByOutKey(@ParamMapper("outKey") String outKey);
/**

View File

@ -42,7 +42,7 @@ public class OrgServiceImpl extends CusInfoActionService {
**/
@Override
public ConsumeConcurrentlyStatus cusCreateAction(MQMessage message) {
int depId = 0;
int depId;
try {
String content = message.getContent();
Org org = JSONObject.parseObject(content, Org.class);

View File

@ -122,6 +122,7 @@ public class RocketConsumerUtil {
log.error(Util.logStr("MQMessageId: {}, Already consumed!",mqMessageId));
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
log.info("mqMessage : " + JSONObject.toJSONString(mqMessage));
// 业务类型
String actionType = mqMessage.getActionType();
switch (actionType){

View File

@ -5,6 +5,7 @@ import aiyh.utils.action.SafeCusBaseAction;
import aiyh.utils.annotation.*;
import aiyh.utils.excention.CustomerException;
import aiyh.utils.tool.cn.hutool.core.lang.Assert;
import aiyh.utils.tool.cn.hutool.core.util.StrUtil;
import lombok.Setter;
import org.jetbrains.annotations.NotNull;
import weaver.general.GCONST;
@ -21,10 +22,7 @@ import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.*;
import java.util.stream.Collectors;
/**
@ -56,47 +54,60 @@ public class VoucherPayableNewAction extends SafeCusBaseAction {
@PrintParamMark
@RequiredMark("凭证类型1- 应付凭证; 2- 付款凭证")
@ActionDefaultTestValue("1")
private String voucherType;
@PrintParamMark
@RequiredMark("应付凭证远程路径")
@ActionDefaultTestValue("/test")
private String pavRemotePath;
@PrintParamMark
@RequiredMark("付款凭证远程路径")
@ActionDefaultTestValue("/test")
private String pmvRemotePath;
@PrintParamMark
@RequiredMark("用户名")
@ActionDefaultTestValue("userName")
private String userName;
@PrintParamMark
@RequiredMark("密码")
@ActionDefaultTestValue("password")
private String password;
@PrintParamMark
@RequiredMark("ip")
@ActionDefaultTestValue("127.0.0.1")
private String ip;
@PrintParamMark
@RequiredMark("应付凭证远程文件名称前缀")
@ActionDefaultTestValue("test")
private String pavFileName;
@PrintParamMark
@RequiredMark("付款凭证远程文件名称前缀")
@ActionDefaultTestValue("test")
private String pmvFileName;
@PrintParamMark
@ActionOptionalParam(desc = "是否删除生成的临时本地文件,true - 删除 false - 不删除", value = "false")
private String deleteTemp = "false";
@PrintParamMark
@ActionOptionalParam(value = "", desc = "过滤字段字段名称,接口参数配置中的接口参数名,也就是序号")
@ActionDefaultTestValue("100")
private String filterField;
@Override
public void doSubmit(String requestId, String billTable, int workflowId, User user, RequestInfo requestInfo) {
try {
@ -136,7 +147,8 @@ public class VoucherPayableNewAction extends SafeCusBaseAction {
private String getFile(String billTable, RequestInfo requestInfo) {
dealWithMapping.setMainTable(billTable);
RequestMappingConfig requestMappingConfig = dealWithMapping.treeDealWithUniqueCode(onlyMark);
Map<String, Object> requestParam = dealWithMapping.getRequestParam(getObjMainTableValue(requestInfo), requestMappingConfig);
Map<String, Object> objMainTableValue = getObjMainTableValue(requestInfo);
Map<String, Object> requestParam = dealWithMapping.getRequestParam(objMainTableValue, requestMappingConfig);
Assert.notEmpty(requestParam, "query config error, can not query result by onlyMark:[{}],Please check the configuration table", onlyMark);
// 借方
List<Object> debit = (List<Object>) requestParam.get("debit");
@ -164,10 +176,13 @@ public class VoucherPayableNewAction extends SafeCusBaseAction {
}
sb.deleteCharAt(sb.lastIndexOf("\t"));
sb.append("\r\n");
log.info("头写入的数据:" + sb);
// 写入借方信息
writeList(debit, sb);
log.info("debit写入的数据:" + sb);
// 写入贷方信息
writeList(creditSide, sb);
log.info("creditSide写入的数据:" + sb);
String filePath = getFilePath();
try {
OutputStreamWriter out = new OutputStreamWriter(
@ -200,6 +215,17 @@ public class VoucherPayableNewAction extends SafeCusBaseAction {
keys = sortKey(keys);
for (Object o : list) {
Map<String, Object> map = (Map<String, Object>) o;
if (!StrUtil.isBlank(filterField)) {
if (map.containsKey(filterField)) {
try {
String value = Util.null2String(map.get(filterField));
if (Double.parseDouble(value) == 0.0) {
continue;
}
} catch (Exception ignore) {
}
}
}
for (String key : keys) {
if (map.containsKey(key)) {
sb.append(map.get(key))
@ -212,11 +238,43 @@ public class VoucherPayableNewAction extends SafeCusBaseAction {
}
private List<String> sortKey(List<String> list) {
return list.stream()
.map(Integer::parseInt)
.sorted()
.map(Util::null2String)
.collect(Collectors.toList());
List<Entry> entryList = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
Entry entry = new Entry();
entry.setIndex(i);
entry.setValue(list.get(i));
entryList.add(entry);
}
List<Entry> collect = entryList.stream()
.sorted(
Comparator.comparing(Entry::getValue)
).collect(Collectors.toList());
List<String> result = new ArrayList<>();
for (Entry entry : collect) {
result.add(list.get(entry.getIndex()));
}
return result;
}
class Entry {
private Integer index;
private String value;
public Integer getIndex() {
return index;
}
public void setIndex(Integer index) {
this.index = index;
}
public Double getValue() {
return Double.parseDouble(value);
}
public void setValue(String value) {
this.value = value;
}
}
@NotNull

View File

@ -2,7 +2,6 @@ package weaver.youhong.ai.haripijiu.action.sapdocking.service;
import aiyh.utils.Util;
import aiyh.utils.excention.CustomerException;
import com.alibaba.fastjson.JSON;
import org.apache.log4j.Logger;
import org.jetbrains.annotations.NotNull;
import weaver.general.GCONST;
@ -74,16 +73,14 @@ public class VoucherPayableService {
public String sendSapVoucher(String onlyMark, String requestId, String billTable) {
SapVoucher voucherData = configService.getVoucherData(onlyMark, requestId, billTable);
logger.info("查询的凭证配置数据: " + JSON.toJSONString(voucherData));
/* ******************* 整理数据 ******************* */
StringBuilder voucherHeadBuilder = new StringBuilder();
List<VoucherItem> voucherHead = voucherData.getVoucherHead();
for (VoucherItem voucherItem : voucherHead) {
voucherHeadBuilder.append(voucherItem.getValue())
voucherHeadBuilder.append(Util.null2String(voucherItem.getValue()).replace("&nbsp;", " "))
.append("\t");
}
String voucherHeadStr = voucherHeadBuilder.substring(0, voucherHeadBuilder.lastIndexOf("\t")) + "\r\n";
logger.info("凭证头:" + voucherHeadStr);
StringBuilder voucherDetailBuilder = new StringBuilder();
List<List<VoucherItem>> voucherDetail = voucherData.getVoucherDetail();
for (List<VoucherItem> voucherItems : voucherDetail) {
@ -91,7 +88,6 @@ public class VoucherPayableService {
.append("\r\n");
}
String voucherDetailStr = voucherDetailBuilder.substring(0, voucherDetailBuilder.lastIndexOf("\r\n"));
logger.info("凭证数据:" + voucherHeadStr);
String filePath = getFilePath();
try {
// BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
@ -115,7 +111,6 @@ public class VoucherPayableService {
public String sendReceiptVoucher(String onlyMark, String requestId, String billTable) {
SapVoucher voucherData = configService.getReceiptPaymentData(onlyMark, requestId, billTable);
logger.info("查询的凭证配置数据: " + JSON.toJSONString(voucherData));
/* ******************* 整理数据 ******************* */
StringBuilder voucherHeadBuilder = new StringBuilder();
List<List<VoucherItem>> voucherDetail = voucherData.getVoucherDetail();
@ -143,7 +138,6 @@ public class VoucherPayableService {
}
}
String voucherHaredStr = voucherHeadBuilder.toString();
logger.info("凭证数据:" + voucherHaredStr);
String filePath = getFilePath();
try {
OutputStreamWriter out = new OutputStreamWriter(
@ -166,27 +160,25 @@ public class VoucherPayableService {
public List<String> sendPaymentVoucher(String onlyMark, String requestId, String billTable) {
SapVoucher voucherData = configService.getReceiptPaymentData(onlyMark, requestId, billTable);
logger.info("配置数据:" + JSON.toJSONString(voucherData));
List<String> filePathList = new ArrayList<>();
/* ******************* 整理数据 ******************* */
StringBuilder voucherHeadBuilder = new StringBuilder();
List<List<VoucherItem>> voucherDetail = voucherData.getVoucherDetail();
for (List<VoucherItem> voucherItems : voucherDetail) {
for (VoucherItem voucherItem : voucherItems) {
voucherHeadBuilder.append(voucherItem.getName())
voucherHeadBuilder.append(Util.null2String(voucherItem.getName()).replace("&nbsp;", " "))
.append("\t");
}
voucherHeadBuilder = new StringBuilder(voucherHeadBuilder
.substring(0, voucherHeadBuilder.lastIndexOf("\t")) + "\r\n");
for (VoucherItem voucherItem : voucherItems) {
voucherHeadBuilder.append(voucherItem.getValue())
voucherHeadBuilder.append(Util.null2String(voucherItem.getValue()).replace("&nbsp;", " "))
.append("\t");
}
voucherHeadBuilder = new StringBuilder(voucherHeadBuilder
.substring(0, voucherHeadBuilder.lastIndexOf("\t")) + "");
String voucherHeadStr = voucherHeadBuilder.toString();
logger.info("凭证数据:" + voucherHeadStr);
String filePath = getFilePath();
try {
// BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
@ -220,9 +212,9 @@ public class VoucherPayableService {
private String appendVoucherItems(List<VoucherItem> voucherItems) {
StringBuilder result = new StringBuilder();
for (VoucherItem voucherItem : voucherItems) {
result.append(voucherItem.getValue())
result.append(Util.null2String(voucherItem.getValue()).replace("&nbsp;", " "))
.append("\t");
}
return result.toString();
return result.substring(0, result.lastIndexOf("\t"));
}
}

View File

@ -0,0 +1,30 @@
package weaver.youhong.ai.intellectualproperty.cusgetvalue;
import aiyh.utils.excention.CustomerException;
import weaver.xiao.commons.config.interfacies.CusInterfaceGetValue;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
/**
* <h1>urlecode</h1>
*
* <p>create: 2023/4/19 15:33</p>
*
* @author youHong.ai
*/
public class ContentUrlEncodeGetValue implements CusInterfaceGetValue {
@Override
public Object execute(Map<String, Object> mainMap,
Map<String, Object> detailMap,
String currentValue,
Map<String, String> pathParam) {
try {
String content = pathParam.get("content");
return URLEncoder.encode(content, "utf-8");
} catch (UnsupportedEncodingException e) {
throw new CustomerException("关键字内容url编码错误", e);
}
}
}

View File

@ -3,6 +3,7 @@ package weaver.youhong.ai.intellectualproperty.cusgetvalue;
import aiyh.utils.Util;
import aiyh.utils.entity.DocImageInfo;
import aiyh.utils.excention.CustomerException;
import aiyh.utils.tool.cn.hutool.core.util.StrUtil;
import org.apache.log4j.Logger;
import weaver.file.ImageFileManager;
import weaver.xiao.commons.config.interfacies.CusInterfaceGetValue;
@ -26,6 +27,12 @@ public class FileToBase64CusGetValue implements CusInterfaceGetValue {
public Object execute(Map<String, Object> mainMap, Map<String, Object> detailMap,
String currentValue, Map<String, String> pathParam) {
try {
if (StrUtil.isBlank(currentValue)) {
throw new CustomerException("签章文件必填,不能为空!");
}
if (currentValue.split(",").length > 1) {
throw new CustomerException("签章文件有且只能有一个文件!");
}
DocImageInfo docImageInfo = Util.selectImageInfoByDocId(currentValue);
InputStream inputStream = ImageFileManager.getInputStreamById(docImageInfo.getImageFileId());
byte[] src = new byte[inputStream.available()];

View File

@ -1,24 +1,54 @@
# ???????
# 应用的凭证密钥
corpSecret=5eab6957b4944d75acfa9cfcc8feff5a
agentId=10000060
corpId=wwdbb6b075752cc1b9
# ??token???
# 获取token的地址
tokenUrl=http://ramos-develop.shdata.com:11080/uranus/cgi-bin/gettoken
# ??????
# 人员信息接口
userInfoUrl=http://ramos-develop.shdata.com:11080/uranus/cgi-bin/request/user/get
# ??????
# 部门信息接口
departmentInfoUrl=http://ramos-develop.shdata.com:11080/uranus/cgi-bin/request/department/list
# ??????
# 新增待办接口
addTodoTaskUrl=http://ramos-develop.shdata.com:11080/uranus/cgi-bin/request/task/create
# ??????
# 更新待办接口
updateTodoTaskUrl=http://ramos-develop.shdata.com:11080/uranus/cgi-bin/request/task/update
# ?????????appId
# 新增待办接口的appId
appId=wwdbb6b075752cc1b9
# ????????????ID
# 统一待办推送日志记录模块ID
modelId=112
# ???????????sql ????????outkey ??sql?? select outkey from hrmresource where id in (${ids}) ??
# 新增待办接口发送人转换sql 如果后面要改成传outkey 则将sql改为 select outkey from hrmresource where id in (${ids}) 即可
hrmSenderConvertRuleSql=select lastname from hrmresource where id in (${ids})
# ?????
# 与上面同理
hrmReceiveConvertRuleSql=select lastname from hrmresource where id in (${ids})
# oa token??????????
# 统一待办pc端链接地址
taskPcUrl=
# 统一待办移动端链接地址
taskMobileUrl=
# oa token缓存对象提前过期时间
expiryBeforeTime=5
# ================ 组织架构同步新增 ================
# 分部最大的层级
maxLevel=3
# 组织结架构同步时是否递归获取 0递归 1非递归
orgNoFetchChild=0
# 组织结架构同步时同步增量数据 0 全量 1增量
orgUpdateTime=0
# 人员同步时同步增量数据 0 全量 1增量
hrmUpdateTime=0
# 组织架构同步日志模块id
orgHrmAsyncLogModelId=115
# ================ sso ================
# 根据code获取用户信息接口地址
getUserInfoByCodeUrl=
# 人员校验成功后oa跳转地址
loginSuccessSendRedirectUrl=/wui/index.html#/main
# 人员校验失败后oa跳转地址
loginErrorSendRedirectUrl=/login/login.jsp
#debug
getUserIdDebug=
#debug key
getUserIdDebugOutKey=

View File

@ -0,0 +1,48 @@
package com.api.company;
import com.alibaba.fastjson.JSONObject;
import com.engine.common.util.ParamUtil;
import jntchina.service.oa.util.ModifyDetailInfo;
import weaver.general.Util;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import java.util.HashMap;
import java.util.Map;
@Path("/jnt/company")
public class CompanyInfo {
@GET
@Path("/test")
@Produces({"text/plain"})
public String test(@Context HttpServletRequest request, @Context HttpServletResponse response){
Map<String, Object> apidatas = new HashMap<String, Object>();
System.out.println("de");
String mess="";
String path="";
boolean api_status=true;
try {
//String field,String fromtableName,String totableName,int modeid,int billid,String qyid 608 9175
/** /api/jnt/company/test?field=djgd,cgbl,cgfs,gfzl&fromtableName=uf_jnqyxxbgb_dt1&totableName=uf_jnqyxxbgb_dt2&modeid=35001&billid=608&qyid=9175& **/
Map<String, Object> param= ParamUtil.request2Map(request);
String field=(String)param.get("field");
String fromtableName=(String)param.get("fromtableName");
String totableName=(String)param.get("totableName");
int modeid= Util.getIntValue((String)param.get("modeid"),0);
int billid=Util.getIntValue((String)param.get("billid"),0);;
String qyid=(String)param.get("qyid");
ModifyDetailInfo modifyDetailInfo=new ModifyDetailInfo(field, fromtableName, totableName, modeid, billid, qyid);
modifyDetailInfo.setDtailJson();
} catch (Exception e) {
mess="异常"+e.getMessage();
e.printStackTrace();
apidatas.put("status", false);
apidatas.put("msg", "catch exception : " + e.getMessage());
}
return JSONObject.toJSONString(apidatas);
}
}

View File

@ -0,0 +1,56 @@
package com.api.dys.wdzxys.controller;
import aiyh.utils.Util;
import com.alibaba.fastjson.JSON;
import com.api.dys.wdzxys.service.WdzxysWorkflowService;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import org.apache.log4j.Logger;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.HashMap;
import java.util.Map;
/**
* @Author DYS
* @Date 2023/3/21 23:15
* @description controller
* create at weaver
*/
@Path("/dys")
public class WdzxysWorkflowController {
private final Logger log = Util.getLogger();
private final WdzxysWorkflowService wdzxysWorkflowService = new WdzxysWorkflowService();
/**
*
*
* @param map
* @return
*/
@Path("/getSsdlq")
@POST
@Produces(MediaType.APPLICATION_JSON)
public String getSsdlq(@RequestBody Map<String, Object> map) {
log.info("网点装修验收流程的controller:" + map.toString());
String ssdlqId = (String) map.get("ssdlqId");//所属代理区id
String ssdlqName = (String) map.get("ssdlqName");//所属代理区name
log.info("所属代理区id:[" + ssdlqId + "], 所属代理区name:[" + ssdlqName + "]");
//根据代理区name查询代理区的网点编码然后根据网点编码查所属代理区的个数
int ssdlqNum = wdzxysWorkflowService.getssdlqName(ssdlqName);
Map<String, Object> result = new HashMap<>();
result.put("code", "200");
result.put("msg", "查询成功");
//查询验收数量 验收数量需要单独设置一个建模表,从建模表里面查询 如果是第一次的话就给一个默认值0
int dlqyssl = wdzxysWorkflowService.getdlqysNum(ssdlqName);
Map<String, Integer> dataMap = new HashMap<>();
dataMap.put("ssdlqNum", ssdlqNum);
dataMap.put("dlqyssl", dlqyssl);
result.put("data", dataMap);
log.info("代理区个数以及代理区验收数量:[" + dataMap.toString() + "]");
log.info("返回结果:[" + result.toString() + "]");
return JSON.toJSONString(result);
}
}

View File

@ -0,0 +1,26 @@
package com.api.dys.wdzxys.mapper;
import aiyh.utils.annotation.recordset.ParamMapper;
import aiyh.utils.annotation.recordset.Select;
import aiyh.utils.annotation.recordset.SqlMapper;
/**
* @Author DYS
* @Date 2023/3/21 23:21
* @description mapper
* create at weaver
*/
@SqlMapper
public interface WdzxysWorkflowMapper {
@Select("select count(1) from uf_netsiteinfo " +
"group by belong_area having belong_area = " +
"(select net_code from uf_netsiteinfo u where u.net_name = #{ssdlqName})")
int getssdlqName(@ParamMapper("ssdlqName") String ssdlqName);
@Select("select dlqyssl from uf_dlqyssl where dlqmc = #{ssdlqName}")
int getdlqysNum(@ParamMapper("ssdlqName") String ssdlqName);
@Select("select count(1) from uf_dlqyssl where dlqmc = #{ssdlqName}")
int getIfHasdlqmc(@ParamMapper("ssdlqName") String ssdlqName);
}

View File

@ -0,0 +1,39 @@
package com.api.dys.wdzxys.service;
import aiyh.utils.Util;
import com.api.dys.wdzxys.mapper.WdzxysWorkflowMapper;
import weaver.conn.RecordSet;
/**
* @Author DYS
* @Date 2023/3/21 23:22
* @description
* create at weaver
*/
public class WdzxysWorkflowService {
private final WdzxysWorkflowMapper wdzxysWorkflowMapper = Util.getMapper(WdzxysWorkflowMapper.class);
/**
*
*
* @param ssdlqName
* @return
*/
public int getssdlqName(String ssdlqName) {
return wdzxysWorkflowMapper.getssdlqName(ssdlqName);
}
/**
*
*
* @param ssdlqName
* @return
*/
public int getdlqysNum(String ssdlqName) {
int ifHasdlq = wdzxysWorkflowMapper.getIfHasdlqmc(ssdlqName);
if (ifHasdlq == 0) {
return 0;
}
return wdzxysWorkflowMapper.getdlqysNum(ssdlqName);
}
}

View File

@ -0,0 +1,323 @@
package com.api.lh.action;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.api.lh.config.DemoConfig;
import com.api.lh.util.CreateProcessUtil;
import selfdev.util.base.BaseUtil;
import selfdev.util.log.LogTool;
import weaver.conn.RecordSet;
import weaver.file.Prop;
import weaver.general.Util;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.*;
import weaver.workflow.workflow.WorkflowVersion;
import java.util.Arrays;
/**
* @ClassName CreateSubprocessAction
* @Description 01--J&T(NCC)
* @Author louh
* @Date 2022/4/6 13:53
* @Version 1.0
*/
public class CreateSubprocessAction implements Action, DemoConfig {
LogTool log = new LogTool("/log/lh/CreateSubprocessAction", false);
//当前环境
String mode = Prop.getPropValue("DevToProcess_jntchina", "mode");
//付款申请流程id
String fk_workflowid = Prop.getPropValue("DevToProcess_jntchina", mode + "_fk_workflowid");
@Override
public String execute(RequestInfo ri) {
RecordSet rs = new RecordSet();
RecordSet rs1 = new RecordSet();
String requestid = ri.getRequestid();
String workflowid = ri.getWorkflowid();
try {
WorkflowVersion workflowVersion = new WorkflowVersion(fk_workflowid);
String newFid = workflowVersion.getActiveVersionWFID();
//获取表名
String tablename = BaseUtil.getBaseInfoByParm("tablename", "workflow_bill", "1", "1", " and id in (select formid from workflow_base where id=" + workflowid + ")");
log.writeLog("requestid---> " + requestid + "对应表名tablename---> " + tablename);
//主表数据id
String id = BaseUtil.getBaseInfoByParm("id", tablename, "requestid", requestid, "");
//主表申请日期
String sqrq = BaseUtil.getBaseInfoByParm("sqrq", tablename, "requestid", requestid, "");
//获取明细表不同批次号数据
String sql = "select distinct pch,sfsczlccg from " + tablename + "_dt1 where mainid = " + id;
log.writeLog("获取明细表数据sql----> " + sql);
rs.execute(sql);
while (rs.next()) {
//实际付款金额
double sum = 0.00;
//批次号
String pch = Util.null2String(rs.getString("pch")).trim();
if ("".equals(pch)) {
ri.getRequestManager().setMessagecontent("批次号不允许为空!");
return FAILURE_AND_CONTINUE;
}
//是否生成子流程成功
String sfsczlccg = Util.null2String(rs.getString("sfsczlccg"));
//成功生成子流程则不再生成
if ("0".equals(sfsczlccg)) {
continue;
}
//生成子流程
RequestService requestService = new RequestService();
RequestInfo requestInfo = new RequestInfo();
//流程workflowid
requestInfo.setWorkflowid(newFid);
//提醒
requestInfo.setRemindtype("0");
//紧急程度
requestInfo.setRequestlevel("0");
//是否自动流转
requestInfo.setIsNextFlow("0");
/* 根据批次号查询该批次号有多少条数据 */
String pchSql = "select * from " + tablename + "_dt1 where mainid = " + id + " and pch = " + pch;
log.writeLog("根据批次号查询该批次号有多少条数据---> " + pchSql);
rs1.execute(pchSql);
//流程创建人id
String peopleId = "";
//流程标题
String bt = "";
//公司名称
String gsmc = "";
//申请人部门id
String departmentid = "";
//申请人分部id
String subcompanyid1 = "";
//是否有合同
String sfyht = "";
//预计付款日期
String yjfkrq = "";
//供应商名称
String gysmc = "";
//账户名称
String khmc = "";
//银行账号
String yxzh = "";
//开户行
String khx = "";
//发票号码
String fphm = "";
//发票类型
String fplx = "";
//发票日期
String fprq = "";
//付款说明
String fksm = "";
//付款类型
String fklx = "";
//拼接明细表数据
DetailTableInfo dti = new DetailTableInfo();
DetailTable[] dt = new DetailTable[0];
int i = 0;
while (rs1.next()) {
String sqrgh = Util.null2String(rs1.getString("sqrgh")); /* 申请人工号 */
/* 根据人员工号获取人员id */
peopleId = BaseUtil.getBaseInfoByParm("id", "hrmresource", "workcode", sqrgh, "");
if ("".equals(peopleId)) {
ri.getRequestManager().setMessagecontent("当前明细表申请人工号【" + sqrgh + "】未找到对应人员,请确认工号是否正确!");
return FAILURE_AND_CONTINUE;
}
//标题
bt = Util.null2String(rs1.getString("bt"));
//公司名称
gsmc = Util.null2String(rs1.getString("gsmc"));
//申请人部门id
departmentid = BaseUtil.getBaseInfoByParm("departmentid", "hrmresource", "workcode", sqrgh, "");
//申请人分部id
subcompanyid1 = BaseUtil.getBaseInfoByParm("subcompanyid1", "hrmresource", "workcode", sqrgh, "");
//是否有合同
sfyht = Util.null2String(rs1.getString("sfyht")).trim();
//预计付款日期
yjfkrq = Util.null2String(rs1.getString("yjfkrq"));
//供应商名称
gysmc = Util.null2String(rs1.getString("gysmc"));
//账户名称
khmc = Util.null2String(rs1.getString("khmc"));
//银行账号
yxzh = Util.null2String(rs1.getString("yxzh"));
//开户行
khx = Util.null2String(rs1.getString("khx"));
//发票号码
fphm = Util.null2String(rs1.getString("fphm"));
//发票类型
fplx = Util.null2String(rs1.getString("fplx"));
//发票日期
fprq = Util.null2String(rs1.getString("fprq"));
//付款说明
fksm = Util.null2String(rs1.getString("fksm"));
//付款类型
fklx = Util.null2String(rs1.getString("fklx"));
//行数据
Row[] row = new Row[0];
//添加单元格到行
Cell[] c = new Cell[0];
//添加子表数据
row = Arrays.copyOf(row, (row.length + 1));
row[row.length - 1] = new Row();
row[row.length - 1].setId((i + 1) + "");
//费用承担部门
String fycdbmbm = Util.null2String(rs1.getString("fycdbmbm")); /* 费用承担部门编码 */
String bmid = BaseUtil.getBaseInfoByParm("id", "hrmdepartment", "departmentcode", fycdbmbm, "");
c = CreateProcessUtil.setCell(c, "fycdbm", bmid);
//不含税金额
String bhsje = Util.null2String(rs1.getString("bhsje"));
if (!"".equals(bhsje)) {
bhsje = bhsje.replaceAll(",", "");
} else {
bhsje = "0.00";
}
c = CreateProcessUtil.setCell(c, "bhsje", bhsje);
//税率
c = CreateProcessUtil.setCell(c, "sl", Util.null2String(rs1.getString("sl")));
//税额
String se = Util.null2String(rs1.getString("se"));
if (!"".equals(se)) {
se = se.replaceAll(",", "");
} else {
se = "0.00";
}
c = CreateProcessUtil.setCell(c, "se", se);
//价税合计
String jshj = Util.null2String(rs1.getString("jshj"));
if (!"".equals(jshj)) {
jshj = jshj.replaceAll(",", "");
} else {
jshj = "0.00";
}
sum += Double.parseDouble(jshj);
c = CreateProcessUtil.setCell(c, "jshj", jshj);
//添加一行
row[row.length - 1].setCell(c);
dt = Arrays.copyOf(dt, (dt.length + 1));
dt[dt.length - 1] = new DetailTable();
dt[dt.length - 1].setId("1");//明细表 dt1 后面的1
dt[dt.length - 1].setRow(row);
++i;
}
dti.setDetailTable(dt);
log.writeLog("明细表数据: " + JSON.toJSONString(dti));
requestInfo.setDetailTableInfo(dti);
/* 流程创建人id */
requestInfo.setCreatorid(peopleId);
//流程标题
requestInfo.setDescription(bt);
//设置主表字段
Property[] p = new Property[0];
//公司名称
p = CreateProcessUtil.setProperty(p, "gsmc", gsmc);
//创建日期
p = CreateProcessUtil.setProperty(p, "cjrq", sqrq);
//申请人部门id
p = CreateProcessUtil.setProperty(p, "fygsbm", departmentid);
p = CreateProcessUtil.setProperty(p, "zz", subcompanyid1);
//姓名
p = CreateProcessUtil.setProperty(p, "xm", peopleId);
//是否有合同
sfyht = getSelectValue(sfyht, requestInfo.getWorkflowid(), "sfyht", "");
//sfyht = getSelectValue(sfyht_fieldid, sfyht);
p = CreateProcessUtil.setProperty(p, "sfyht", sfyht);
//预计付款日期
p = CreateProcessUtil.setProperty(p, "yjfkrq", yjfkrq);
//供应商名称
p = CreateProcessUtil.setProperty(p, "gysmc", gysmc);
//账户名称
p = CreateProcessUtil.setProperty(p, "yzhm", khmc);
//银行账号
p = CreateProcessUtil.setProperty(p, "yxhm", yxzh);
//开户行
p = CreateProcessUtil.setProperty(p, "yxmz", khx);
//发票号码
p = CreateProcessUtil.setProperty(p, "fphm", fphm);
//发票类型
fplx = getSelectValue(fplx, requestInfo.getWorkflowid(), "fplx", "");
//fplx = getSelectValue(fplx_fieldid, fplx);
p = CreateProcessUtil.setProperty(p, "fplx", fplx);
//发票日期
p = CreateProcessUtil.setProperty(p, "fprq", fprq);
//付款说明
p = CreateProcessUtil.setProperty(p, "fksm", fksm);
//实际付款金额大写
p = CreateProcessUtil.setProperty(p, "sjfkje2", sum + "");
//付款方式 默认 银行汇款
p = CreateProcessUtil.setProperty(p, "fkfs", "0");
//币种 默认RMB
p = CreateProcessUtil.setProperty(p, "bz", "1");
//付款类型 默认航空费
p = CreateProcessUtil.setProperty(p, "fklx1", fklx);
//区域
String fbid = BaseUtil.getBaseInfoByParm("subcompanyid1", "hrmresource", "id", peopleId, "");
p = CreateProcessUtil.setProperty(p, "qy", fbid);
/**********************************新加字段*****************************************/
//是否杭百费用 0:是 1:否 为否则显示付款类型值
p = CreateProcessUtil.setProperty(p, "sfhbfy", "1");
//添加主表数据
MainTableInfo mti = new MainTableInfo();
mti.setProperty(p);
log.writeLog("主表数据: " + JSON.toJSONString(mti));
requestInfo.setMainTableInfo(mti);
//创建流程
String request = requestService.createRequest(requestInfo);
JSONObject judge = CreateProcessUtil.judge(request);
if ("1".equals(judge.getString("status"))) {
ri.getRequestManager().setMessagecontent("流程创建失败!");
//修改明细表数据
String updSql = "update " + tablename + "_dt1 set sfsczlccg = '" + judge.getString("status") + "', cfzlcxx = '" + judge.getString("msg") + "', cfrequestid = '" + judge.getString("requestid") + "' where mainid = " + id + " and pch = '" + pch + "'";
log.writeLog("修改明细表数据sql----> " + updSql);
rs.execute(updSql);
return FAILURE_AND_CONTINUE;
}
//修改明细表数据
String updSql = "update " + tablename + "_dt1 set sfsczlccg = '" + judge.getString("status") + "', cfzlcxx = '" + judge.getString("msg") + "', cfrequestid = '" + judge.getString("requestid") + "' where mainid = " + id + " and pch = '" + pch + "'";
log.writeLog("修改明细表数据sql----> " + updSql);
rs.execute(updSql);
}
} catch (Exception e) {
log.writeLog("出现异常---> " + e);
ri.getRequestManager().setMessagecontent("内部出错,联系管理员查看问题!");
return FAILURE_AND_CONTINUE;
}
return SUCCESS;
}
/**
* id
*
* @param fieldid
* @param selectname
* @return
*/
public String getSelectValue(String fieldid, String selectname) {
RecordSet rs = new RecordSet();
String selectValue = "";
String sql = "select selectvalue from workflow_selectitem where fieldid = " + fieldid + " and convtomultilang(selectname,7) = '" + selectname + "'";
rs.execute(sql);
if (rs.next()) {
selectValue = Util.null2String(rs.getString("selectvalue"));
}
return selectValue;
}
}

View File

@ -0,0 +1,125 @@
package com.api.lh.action;
import com.api.lh.config.DemoConfig;
import selfdev.util.log.LogTool;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.Util;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
/**
* @ClassName CurrencyModifyAccountAction
* @Description ---
* @Author louh
* @Date 2022/4/27 16:04
* @Version 1.0
*/
public class CurrencyModifyAccountAction implements Action, DemoConfig {
@Override
public String execute(RequestInfo ri) {
String requestid = ri.getRequestid();
String workflowid = ri.getWorkflowid();
RecordSet rs = new RecordSet();
RecordSet rs1 = new RecordSet();
RecordSet rs2 = new RecordSet();
RecordSet rs3 = new RecordSet();
RecordSetTrans rst = new RecordSetTrans();
rst.setAutoCommit(false);
try{
String tableName = getTableName(workflowid);
log.writeLog("requestid---> " + requestid + "对应表名tablename---> " + tableName);
String id = getId(tableName, requestid);
String sql = "select yfkqptzmxid, count(yfkqptzmxid) as sum from " + tableName + "_dt1 where mainid = " + id + " group by yfkqptzmxid having count(yfkqptzmxid) > 1";
log.writeLog("根据主表数据id查询当前明细表数据是否有多次选择同一个预付款欠票台账明细id【yfkqptzmxid】sql---->" + sql);
rs.execute(sql);
if(rs.next()){
ri.getRequestManager().setMessagecontent("同一张单据不允许多次选择相同的【预付款欠票台账明细id】,请重新选择抵扣明细表不同的【预付款欠票台账明细id】数据。");
return FAILURE_AND_CONTINUE;
}
sql = "select * from "+ tableName + "_dt1 where mainid = "+ id;
log.writeLog("查询当前单据抵扣明细详细信息sql------> " + sql);
rs.execute(sql);
while(rs.next()){
String yfkqptzmxid = Util.null2String(rs.getString("yfkqptzmxid")); /* 预付款欠票台账明细id */
// double yfje = Double.parseDouble(Util.null2String(rs.getString("yfje")) == "" ? "0.00" : Util.null2String(rs.getString("yfje"))); /* 预付金额 */
double bcdjje = Double.parseDouble(Util.null2String(rs.getString("bcdjje")) == "" ? "0.00" : Util.null2String(rs.getString("bcdjje"))); /* 本次抵扣金额 */
String bz = Util.null2String(rs.getString("bz"));/* 备注 */
String nccdh = Util.null2String(rs.getString("nccdh")); /* ncc单号 */
String xgyflc = Util.null2String(rs.getString("xgyflc")); //相关预付流程
String sql1 = "select * from uf_fksqyfb_dt1 where id = " + yfkqptzmxid;
log.writeLog("查询台账本次抵扣流程信息sql----> " + sql1);
rs1.execute(sql1);
//已核销金额
double yhxje = 0.00;
//剩余未核销金额
double sywhxje = 0.00;
//预付款金额
double fkje = 0.00;
//相关核销流程
String xghxlc = "";
if(rs1.next()){
xghxlc = Util.null2String(rs1.getString("xghxlc"));
yhxje = Double.parseDouble(Util.null2String(rs1.getString("yhxje")) == "" ? "0.00" : Util.null2String(rs1.getString("yhxje")));
sywhxje = Double.parseDouble(Util.null2String(rs1.getString("sywhxje")) == "" ? "0.00" : Util.null2String(rs1.getString("sywhxje")));
fkje = Double.parseDouble(Util.null2String(rs1.getString("fkje")) == "" ? "0.00" : Util.null2String(rs1.getString("fkje")));
}
if(bcdjje > sywhxje){
ri.getRequestManager().setMessagecontent("当前抵扣明细本次抵扣金额【" + bcdjje + "】大于剩余未核销金额【" + sywhxje + "】,请确认金额是否正确。");
return FAILURE_AND_CONTINUE;
}
yhxje = bcdjje + yhxje;
if(yhxje > fkje){
ri.getRequestManager().setMessagecontent("当前抵扣明细本次抵扣金额与历史抵扣金额共【" + yhxje + "】大于借款总金额【" + fkje + "】,请确认金额是否正确。");
return FAILURE_AND_CONTINUE;
}
sywhxje = fkje - yhxje;
if(sywhxje < 0.00){
ri.getRequestManager().setMessagecontent("当前抵扣明细单据总金额【"+ fkje + "】,核销总金额【" + yhxje + "】相减,则剩余未核销金额小于0.00元,请确认金额是否正确。");
return FAILURE_AND_CONTINUE;
}
if("".equals(xghxlc)){
xghxlc = requestid;
}else {
xghxlc += "," + requestid;
}
String updSql = "update uf_fksqyfb_dt1 set " +
"yhxje = '" + yhxje + "', " +
"sywhxje = '" + sywhxje + "'," +
" xghxlc ='" + xghxlc + "' where id = '" + yfkqptzmxid + "'";
log.writeLog("修改台账信息sql-----> " + updSql);
rst.executeSql(updSql);
sql1 = "select * from uf_fksqyfb where qqid = '" + xgyflc + "'" ;
log.writeLog("查询主表总预付金额及核销金额sql----> " + sql1);
rs2.execute(sql1);
double fkje1 = 0.00;
double yhxje1 = 0.00;
double sywhxje1 = 0.00;
if (rs2.next()){
fkje1 = Double.parseDouble(Util.null2String(rs2.getString("fkje"))==""?"0.00":Util.null2String(rs2.getString("fkje")));//付款金额
yhxje1 = Double.parseDouble(Util.null2String(rs2.getString("yhxje"))==""?"0.00":Util.null2String(rs2.getString("yhxje")));//已核销金额
sywhxje1 = Double.parseDouble(Util.null2String(rs2.getString("sywhxje"))==""?"0.00":Util.null2String(rs2.getString("sywhxje")));//剩余金额
}
double bchxje = bcdjje + yhxje1;
sywhxje1 = fkje1 - bchxje;
updSql = "update uf_fksqyfb set yhxje = '" + bchxje + "'," +
" sywhxje ='" + sywhxje1 + "' where ncclcdh = '" + nccdh + "' and qqid = '" + xgyflc + "'" ;
log.writeLog("修改本次台账主表信息sql-----> " + updSql);
//rst.executeSql(updSql);
rs3.execute(updSql);
}
rst.commit();
}catch (Exception e){
rst.rollback();
log.writeLog("出现异常-----> " + e);
ri.getRequestManager().setMessagecontent("系统内部出错----> " + e);
return FAILURE_AND_CONTINUE;
}
return SUCCESS;
}
}

View File

@ -0,0 +1,123 @@
package com.api.lh.action;
import com.api.lh.config.DemoConfig;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.Util;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
/**
* @ClassName CurrencyModifyAccountAction
* @Description ---
* @Author ycf
* @Date 2022/4/27 16:04
* @Version 1.0
*/
public class CurrencyModifyAccountActionYY implements Action, DemoConfig {
@Override
public String execute(RequestInfo ri) {
String requestid = ri.getRequestid();
String workflowid = ri.getWorkflowid();
RecordSet rs = new RecordSet();
RecordSet rs1 = new RecordSet();
RecordSet rs2 = new RecordSet();
RecordSet rs3 = new RecordSet();
RecordSetTrans rst = new RecordSetTrans();
rst.setAutoCommit(false);
try{
String tableName = getTableName(workflowid);
log.writeLog("requestid---> " + requestid + "对应表名tablename---> " + tableName);
String id = getId(tableName, requestid);
String sql = "select yfkqptzmxid, count(yfkqptzmxid) as sum from " + tableName + "_dt1 where mainid = " + id + " group by yfkqptzmxid having count(yfkqptzmxid) > 1";
log.writeLog("根据主表数据id查询当前明细表数据是否有多次选择同一个预付款欠票台账明细id【yfkqptzmxid】sql---->" + sql);
rs.execute(sql);
if(rs.next()){
ri.getRequestManager().setMessagecontent("同一张单据不允许多次选择相同的【预付款欠票台账明细id】,请重新选择抵扣明细表不同的【预付款欠票台账明细id】数据。");
return FAILURE_AND_CONTINUE;
}
sql = "select * from "+ tableName + "_dt1 where mainid = "+ id;
log.writeLog("查询当前单据抵扣明细详细信息sql------> " + sql);
rs.execute(sql);
while(rs.next()){
String yfkqptzmxid = Util.null2String(rs.getString("yfkqptzmxid")); /* 预付款欠票台账明细id */
// double yfje = Double.parseDouble(Util.null2String(rs.getString("yfje")) == "" ? "0.00" : Util.null2String(rs.getString("yfje"))); /* 预付金额 */
double bcdjje = Double.parseDouble(Util.null2String(rs.getString("bcdjje")) == "" ? "0.00" : Util.null2String(rs.getString("bcdjje"))); /* 本次抵扣金额 */
String bz = Util.null2String(rs.getString("bz"));/* 备注 */
String nccdh = Util.null2String(rs.getString("nccdh")); /* ncc单号 */
String xgyflc = Util.null2String(rs.getString("xgyflc")); //相关预付流程
String sql1 = "select * from uf_gysqktzyy_dt1 where id = " + yfkqptzmxid;
log.writeLog("查询台账本次抵扣流程信息sql----> " + sql1);
rs1.execute(sql1);
//已核销金额
double yhxje = 0.00;
//剩余未核销金额
double sywhxje = 0.00;
//预付款金额
double fkje = 0.00;
//相关核销流程
String xghxlc = "";
if(rs1.next()){
xghxlc = Util.null2String(rs1.getString("xghxlc"));
yhxje = Double.parseDouble(Util.null2String(rs1.getString("yhxje")) == "" ? "0.00" : Util.null2String(rs1.getString("yhxje")));
sywhxje = Double.parseDouble(Util.null2String(rs1.getString("sywhxje")) == "" ? "0.00" : Util.null2String(rs1.getString("sywhxje")));
fkje = Double.parseDouble(Util.null2String(rs1.getString("fkje")) == "" ? "0.00" : Util.null2String(rs1.getString("fkje")));
}
if(bcdjje > sywhxje){
ri.getRequestManager().setMessagecontent("当前抵扣明细本次抵扣金额【" + bcdjje + "】大于剩余未核销金额【" + sywhxje + "】,请确认金额是否正确。");
return FAILURE_AND_CONTINUE;
}
yhxje = bcdjje + yhxje;
if(yhxje > fkje){
ri.getRequestManager().setMessagecontent("当前抵扣明细本次抵扣金额与历史抵扣金额共【" + yhxje + "】大于借款总金额【" + fkje + "】,请确认金额是否正确。");
return FAILURE_AND_CONTINUE;
}
sywhxje = fkje - yhxje;
if(sywhxje < 0.00){
ri.getRequestManager().setMessagecontent("当前抵扣明细单据总金额【"+ fkje + "】,核销总金额【" + yhxje + "】相减,则剩余未核销金额小于0.00元,请确认金额是否正确。");
return FAILURE_AND_CONTINUE;
}
if("".equals(xghxlc)){
xghxlc = requestid;
}else {
xghxlc += "," + requestid;
}
String updSql = "update uf_gysqktzyy_dt1 set " +
"yhxje = '" + yhxje + "', " +
"sywhxje = '" + sywhxje + "'," +
" xghxlc ='" + xghxlc + "' where id = '" + yfkqptzmxid + "'";
log.writeLog("修改台账信息sql-----> " + updSql);
rst.executeSql(updSql);
sql1 = "select * from uf_gysqktzyy where qqid = '" + xgyflc + "'" ;
rs2.execute(sql1);
double fkje1 = 0.00;
double yhxje1 = 0.00;
double sywhxje1 = 0.00;
if (rs2.next()){
fkje1 = Double.parseDouble(Util.null2String(rs2.getString("fkje"))==""?"0.00":Util.null2String(rs2.getString("fkje")));//付款金额
yhxje1 = Double.parseDouble(Util.null2String(rs2.getString("yhxje"))==""?"0.00":Util.null2String(rs2.getString("yhxje")));//已核销金额
sywhxje1 = Double.parseDouble(Util.null2String(rs2.getString("sywhxje"))==""?"0.00":Util.null2String(rs2.getString("sywhxje")));//剩余金额
}
double bchxje = bcdjje + yhxje1;
sywhxje1 = fkje1 - bchxje;
updSql = "update uf_gysqktzyy set yhxje = '" + bchxje + "'," +
" sywhxje ='" + sywhxje1 + "' where ncclcdh = '" + nccdh + "' and qqid = '" + xgyflc + "'" ;
log.writeLog("修改本次台账主表信息sql-----> " + updSql);
//rst.executeSql(updSql);
rs3.execute(updSql);
}
rst.commit();
}catch (Exception e){
rst.rollback();
log.writeLog("出现异常-----> " + e);
ri.getRequestManager().setMessagecontent("系统内部出错----> " + e);
return FAILURE_AND_CONTINUE;
}
return SUCCESS;
}
}

View File

@ -0,0 +1,191 @@
package com.api.lh.action;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.api.lh.port.AddJournal;
import com.api.lh.port.Items;
import com.api.lh.port.StuData;
import com.api.lh.util.DUtil;
import jntchina.util.HttpClientToDC;
import selfdev.util.base.BaseUtil;
import selfdev.util.log.LogTool;
import weaver.conn.RecordSet;
import weaver.file.Prop;
import weaver.general.Util;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* @ClassName NCCAdvanceTossAction
* @Description NCC
* @Author louh
* @Date 2022/3/9 11:06
* @Version 1.0
*/
public class NCCAdvanceTossAction implements Action {
LogTool log = new LogTool("/log/lh/action/NCCAdvanceTossAction", false);
static final String mode = Prop.getPropValue("DevToDC_jntchina","mode");
static final String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl");
@Override
public String execute(RequestInfo ri) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date = dateFormat.format(new Date());
String startDate = date.substring(0, 10);
String endDate = date.substring(11);
date = getNewDate(startDate, endDate);
JSONObject json = new JSONObject();
RecordSet rs = new RecordSet();
String xrnccsbcsfts = "";
String s= "";
//单据属性
String djsx = "";
String requestid = ri.getRequestid();
String workflowid = ri.getWorkflowid();
try{
//获取表名
String tablename = BaseUtil.getBaseInfoByParm("tablename", "workflow_bill", "1", "1", " and id in (select formid from workflow_base where id=" + workflowid + ")");
log.writeLog("requestid---> " + requestid + "对应表名tablename---> " + tablename);
/* 主表数据id */
String id = BaseUtil.getBaseInfoByParm("id", tablename, "requestid", requestid, "");
/* 流程编号 */
String lcbh = BaseUtil.getBaseInfoByParm("lcbh", tablename, "requestid", requestid, "");
/* 供应商名称 */
String gysmc = BaseUtil.getBaseInfoByParm("gysmc", tablename, "requestid", requestid, "");
/* 付款金额 */
String fkje = BaseUtil.getBaseInfoByParm("jshjje", tablename, "requestid", requestid, "");
/* 公司名称(NCC财务组织编码) */
String gsmc = BaseUtil.getBaseInfoByParm("gsmc", tablename, "requestid", requestid, "");
/* 制单人 */
String zdr = BaseUtil.getBaseInfoByParm("zdr", tablename, "requestid", requestid, "");
/* 制单人编码 */
String workcode = BaseUtil.getBaseInfoByParm("workcode", "hrmresource", "id", zdr, "");
/* 部门 */
String bm = BaseUtil.getBaseInfoByParm("fygsbm", tablename, "requestid", requestid, "");
/* 部门编码 */
String departmentcode = BaseUtil.getBaseInfoByParm("departmentcode", "hrmdepartment", "id", bm, "");
/* 银行账号 */
String yxhm = BaseUtil.getBaseInfoByParm("yxhm", tablename, "requestid", requestid, "");
//是否提示报错信息
xrnccsbcsfts = BaseUtil.getBaseInfoByParm("xrnccsbcsfts", tablename, "requestid", requestid, "");
//银行付款备注
String yxfkbz = BaseUtil.getBaseInfoByParm("yxfkbz", tablename, "requestid", requestid, "");
double je = Double.parseDouble(fkje.replaceAll(",", ""));
String sql = "select * from " + tablename + "_dt2 where mainid = " + id;
log.writeLog("查询应付单明细数据sql-----> " + sql);
rs.execute(sql);
List<Items> list = new ArrayList<>();
while(rs.next()){
/* 本次付款金额 */
String je1 = Util.null2String(rs.getString("bcfkje"));
double v = Double.parseDouble(je1.replaceAll(",", ""));
/* 付款计划唯一id */
String fkjhwyid = Util.null2String(rs.getString("fkjhwyid"));
/* 采购订单明细id */
String cgddmxid = Util.null2String(rs.getString("cgddmxid"));
/* 采购订单号 */
String cgddh = Util.null2String(rs.getString("cgddh"));
/* 摘要 */
String zy = Util.null2String(rs.getString("zy"));
/* 成本中心 */
String wd = Util.null2String(rs.getString("wd"));
djsx = Util.null2String(rs.getString("fkdbm"));
s = djsx == "F3-Cxx-06" ? "" : djsx;
Items items = new Items("1", gysmc,departmentcode, "", "1","CNY",v + "",
"1",v + "","1",v + "","1",
v + "","1",v + "",cgddmxid,cgddh,fkjhwyid,"",
zy, s, "", departmentcode, yxhm, "", wd);
list.add(items);
}
StuData stuData = new StuData(gsmc,s,date,"1","CNY",yxhm,je + "",
"1",je + "","1",je + "","1",je + "",
workcode,requestid,lcbh,gysmc,list,departmentcode, "", yxfkbz);
json = (JSONObject) JSONObject.toJSON(stuData);
log.writeLog("json-----> " + json);
/* 调用NCC付款单接口 */
//获取token
String token = HttpClientToDC.getToken();
log.writeLog("获取中台的数据token----》 " + token);
if ("".equals(weaver.general.Util.null2String(token))) {
ri.getRequestManager().setMessagecontent("未获取到中台token请联系管理员查看问题");
return FAILURE_AND_CONTINUE;
}
String result = HttpClientToDC.sendPostApi(baseUrl + "/dcoaapi/ncc/sendPreBill", token, json.toJSONString());
//String result = NCCUtils.sendApi(baseUrl + "/dcoaapi/ncc/sendPreBill", json.toJSONString());
log.writeLog("result----> " + result);
JSONObject parse = (JSONObject) JSONObject.parse(result);
String success = parse.getString("succ");
String msg = parse.getString("msg");
if(success.equals("true")) {
JSONObject data = parse.getJSONObject("data");
String billno = data.getString("billno"); /* ncc单据号 */
String pk_bill = data.getString("pk_bill");/* ncc单据主键 */
String billmaker = data.getString("billmaker"); /* 制单人 */
String pk_org = data.getString("pk_org"); /* 财务组织编码 */
String updSql = "update " + tablename + " set nccdjzj = '" + pk_bill + "', ncczdr = '" + billmaker + "', nccfkdh ='" + billno + "',ncccwzzbm = '" + pk_org + "',nccfhxx = '" + msg + "',sfcgscnccfkd = 0 where requestid = " + requestid;
log.writeLog("修改当前单据NCC回传信息sql----> " + updSql);
rs.execute(updSql);
//获取回传的明细表付款单id
JSONArray items = data.getJSONArray("items");
for (int i = 0; i < items.size(); i++) {
JSONObject resultData = items.getJSONObject(i);
String itemid = resultData.getString("itemid");/* 采购订单明细id */
String pk_payitem = resultData.getString("pk_payitem"); /* 付款单id */
String payplanid = resultData.getString("payplanid");/* 付款计划id */
String upddelSql = "update " + tablename + "_dt2 set fkdid = '" + pk_payitem + "' where cgddmxid = '" + itemid + "' and fkjhwyid = '" + payplanid + "' and mainid = " + id ;
log.writeLog("修改明细表的明细数据sql---->" + upddelSql);
rs.execute(upddelSql);
}
}else{
String updSql = "update " + tablename + " set sfcgscnccfkd = 1,nccfhxx = '" + msg + "' where requestid = " + requestid;
rs.execute(updSql);
AddJournal.addInfo("抛转预付单数据到NCC", json, result, "1", requestid);
if("yes".equals(xrnccsbcsfts)) {
ri.getRequestManager().setMessagecontent(msg);
return FAILURE_AND_CONTINUE;
}else{
return SUCCESS;
}
}
AddJournal.addInfo("抛转预付单数据到NCC", json, result, "0", requestid);
}catch (Exception e){
AddJournal.addInfo("抛转预付单数据到NCC", json, "出现异常---> " + e, "1", requestid);
if("yes".equals(xrnccsbcsfts)) {
ri.getRequestManager().setMessagecontent("数据传递出错-----> " + e.getMessage());
return FAILURE_AND_CONTINUE;
}else{
return SUCCESS;
}
}
return SUCCESS;
}
public static void main(String[] args) {
System.out.println(getNewDate("2022-06-30", "18:00:00"));
}
public static String getNewDate(String startDate, String endDate){
if(DUtil.getLastDayOfMonth(startDate).equals(startDate)){
int i = endDate.compareTo("18:00:00");
if (i >= 0){
startDate = DUtil.getFirstDayOfNextMonth(startDate);
endDate = "00:30:00";
}
}
return startDate + " " + endDate;
}
}

View File

@ -0,0 +1,114 @@
package com.api.lh.action;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.api.lh.port.AddJournal;
import com.wbi.util.Util;
import jntchina.util.HttpClientToDC;
import jntchina.util.NCCUtils;
import selfdev.util.base.BaseUtil;
import selfdev.util.log.LogTool;
import weaver.conn.RecordSet;
import weaver.file.Prop;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
/**
* @ClassName NCCPayableValidationAction
* @Description NCC,
* @Author louh
* @Date 2022/3/1 14:01
* @Version 1.0
*/
public class NCCAdvanceValidationAction implements Action {
static final String mode = Prop.getPropValue("DevToDC_jntchina","mode");
static final String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl");
LogTool log = new LogTool("/log/lh/NCCAdvanceValidationAction", false);
@Override
public String execute(RequestInfo ri) {
JSONObject json = new JSONObject();
JSONArray jsonArray = new JSONArray();
RecordSet rs = new RecordSet();
/* 流程requestid */
String requestid = ri.getRequestid();
/* 流程id */
String workflowid = ri.getWorkflowid();
try {
//获取表名
String tablename = BaseUtil.getBaseInfoByParm("tablename", "workflow_bill", "1", "1", " and id in (select formid from workflow_base where id=" + workflowid + ")");
log.writeLog("requestid---> " + requestid + "对应表名tablename---> " + tablename);
/* 主表数据id */
String id = BaseUtil.getBaseInfoByParm("id", tablename, "requestid", requestid, "");
String sql = "select * from " + tablename + "_dt2 where mainid = " + id;
log.writeLog("查询明细表预付单数据sql-----> " + sql);
rs.execute(sql);
while (rs.next()) {
JSONObject jsonObject = new JSONObject();
/* 预付单付款计划唯一id */
jsonObject.put("pk_item", Util.null2String(rs.getString("fkjhwyid")));
/* 本次付款金额 */
jsonObject.put("mny", Util.null2String(rs.getString("bcfkje")));
jsonArray.add(jsonObject);
}
json.put("request", jsonArray);
log.writeLog("request: " + json);
//获取token
String token = HttpClientToDC.getToken();
log.writeLog("获取中台的数据token----》 " + token);
if ("".equals(weaver.general.Util.null2String(token))) {
ri.getRequestManager().setMessagecontent("未获取到中台token请联系管理员查看问题");
return FAILURE_AND_CONTINUE;
}
String result = HttpClientToDC.sendPostApi(baseUrl + "/dcoaapi/ncc/payApplication", token, json.toJSONString());
//result = NCCUtils.sendApi(baseUrl + "/nccloud/api/jitu/arap/busi/mnycheck", json.toJSONString());
/* 解析返回的数据 */
JSONObject result_json = (JSONObject) JSONObject.parse(result);
String allmsg = "";
String success = result_json.getString("succ");
String msg = result_json.getString("msg");
if("true".equals(success)) {
JSONArray data = result_json.getJSONArray("data");
for (int i = 0; i < data.size(); i++) {
JSONObject item = data.getJSONObject(i);
String flag = item.getString("flag"); /* 是否正确 */
if (!"Y".equals(flag)) { //数据不一致
String pk_item = item.getString("pk_item");
/* 根据预付单付款计划唯一id去查询表单对应数据 */
String podb_sql = "select * from " + tablename + "_dt2 where fkjhwyid = '" + pk_item +"' and mainid = " + id;
log.writeLog("根据预付单明细行唯一id去查询表单对应数据sql-----> " + podb_sql);
rs.execute(podb_sql);
if(rs.next()){
/* 采购订单号 */
String cgddh = Util.null2String(rs.getString("cgddh"));
allmsg += cgddh + ",";
}
}
}
}else{
ri.getRequestManager().setMessagecontent(msg);
AddJournal.addInfo("效验预付单据数据是否正确", json, result, "1", requestid);
return FAILURE_AND_CONTINUE;
}
if(!"".equals(allmsg)){
allmsg += "数据效验不通过请删除当前单据重新获取NCC数据并选择";
ri.getRequestManager().setMessagecontent(allmsg);
AddJournal.addInfo("效验预付单据数据是否正确", json, result, "1", requestid);
return FAILURE_AND_CONTINUE;
}
AddJournal.addInfo("效验预付单据数据是否正确", json, result, "0", requestid);
}catch (Exception e) {
AddJournal.addInfo("效验预付单据数据是否正确", json, "出现异常" + e, "1", requestid);
ri.getRequestManager().setMessagecontent("数据传递出错----> " + e.getMessage());
return FAILURE_AND_CONTINUE;
}
return SUCCESS;
}
}

View File

@ -0,0 +1,166 @@
package com.api.lh.action;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.api.lh.config.DemoConfig;
import com.api.lh.port.AddJournal;
import com.api.lh.port.Billdata;
import com.api.lh.port.ErBxcontrast;
import jntchina.util.HttpClientToDC;
import selfdev.util.base.BaseUtil;
import selfdev.util.log.LogTool;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @ClassName NCCAdvanceWriteOffAction
* @Description NCC
* @Author louh
* @Date 2022/4/13 14:06
* @Version 1.0
*/
public class NCCAdvanceWriteOffAction implements Action, DemoConfig {
LogTool log = new LogTool("/log/lh/NCCAdvanceWriteOffAction", false);
@Override
public String execute(RequestInfo ri) {
String requestid = ri.getRequestid(); //requestid
String workflowid = ri.getWorkflowid(); //workflowid
RecordSet rs = new RecordSet();
Billdata billdata = null; //存储主表数据
List<ErBxcontrast> bxcontrasts = new ArrayList<>(); //存储明细数据
JSONObject json = null; //传递数据
try {
//获取表名
String tablename = BaseUtil.getBaseInfoByParm("tablename", "workflow_bill", "1", "1", " and id in (select formid from workflow_base where id=" + workflowid + ")");
log.writeLog("requestid---> " + requestid + "对应表名tablename---> " + tablename);
//主表数据id
String id = BaseUtil.getBaseInfoByParm("id", tablename, "requestid", requestid, "");
String sql = "select xgyflc, count(xgyflc) as sum from " + tablename + "_dt1 where mainid = " + id + " group by xgyflc having count(xgyflc) > 1";
log.writeLog("根据主表数据id查询当前明细表数据是否有多次选择同一个相关预付流程【requestid】sql---->" + sql);
rs.execute(sql);
if(rs.next()){
ri.getRequestManager().setMessagecontent("同一张单据不允许多次选择相同的【相关预付流程】,请重新选择明细表不同的【相关预付流程】数据。");
return FAILURE_AND_CONTINUE;
}
sql = "select * from " + tablename + "_dt1 where mainid = " + id;
log.writeLog("根据主表数据id查询当前明细数据sql----> " + sql);
rs.execute(sql);
while(rs.next()){
//已核销金额
double yhxje = Double.parseDouble(Util.null2String(rs.getString("yhxje")) == "" ? "0.00": Util.null2String(rs.getString("yhxje")));
//剩余未核销金额
double sywhxje = Double.parseDouble(Util.null2String(rs.getString("sywhxje")));
//预付金额
double yfje = Double.parseDouble(Util.null2String(rs.getString("yfje")));
//本次核销金额
double bchxje = Double.parseDouble(Util.null2String(rs.getString("bchxje")) == "" ? "0.00" : Util.null2String(rs.getString("bchxje")));
//相关预付流程
String xgyflc = Util.null2String(rs.getString("xgyflc"));
//本次核销金额大于剩余未核销金额
if(bchxje > sywhxje){
ri.getRequestManager().setMessagecontent("【相关预付流程 " + xgyflc + "】 剩余未核销金额【" + sywhxje + "】元、本次核销金额【" + bchxje + "】、大于【剩余未核销金额】,请重新填写【本次核销金额】");
return FAILURE_AND_CONTINUE;
}
//当前条数共计合计金额
double money = yhxje + bchxje;
if(money > yfje){
ri.getRequestManager().setMessagecontent("【相关预付流程 " + xgyflc + "】 已核销金额【" + yhxje + "】元、本次核销金额【" + bchxje + "】、合计【" + money + "】元!大于预付金额,请重新填写【本次核销金额】");
return FAILURE_AND_CONTINUE;
}
//ncc借款单号
String nccdh = Util.null2String(rs.getString("nccdh"));
ErBxcontrast bxcontrast = new ErBxcontrast(nccdh,"",bchxje + "");
bxcontrasts.add(bxcontrast);
}
sql = "select * from " + tablename + " where requestid = " + requestid;
log.writeLog("查询当前主表数据sql------> " + sql);
rs.execute(sql);
if(rs.next()){
String sqr = Util.null2String(rs.getString("sqr"));//申请人
//申请人工号
String workcode = BaseUtil.getBaseInfoByParm("workcode", "hrmresource", "id", sqr, "");
String sqbm = Util.null2String(rs.getString("sqbm")); //申请部门
//申请部门编码
String departmentcode = BaseUtil.getBaseInfoByParm("departmentcode", "hrmdepartment", "id", sqbm, "");
String gsmc = Util.null2String(rs.getString("gsmc"));
billdata = new Billdata(gsmc, //公司名称
"",
"",
"",
Util.null2String(rs.getString("sqrq")), //申请日期
Util.null2String(rs.getString("hxje")), //核销金额
gsmc,
"",
workcode,
"",
"",
requestid,
Util.null2String(rs.getString("lcbh")), //流程编号
"",
departmentcode, //申请部门
Util.null2String(rs.getString("sm")), //说明
bxcontrasts
);
}
String result = JSON.toJSONString(billdata, SerializerFeature.DisableCircularReferenceDetect);
json = (JSONObject) JSONObject.toJSON(billdata);
//获取token
String token = HttpClientToDC.getToken();
log.writeLog("获取中台的数据token----》 " + token);
if ("".equals(Util.null2String(token))) {
ri.getRequestManager().setMessagecontent("为获取到中台token,请联系管理员查看问题!");
AddJournal.addInfo("还款单接口", json, "未获取到中台token请联系管理员查看问题", "1", requestid);
return FAILURE_AND_CONTINUE;
}
//调用中台还款单接口
log.writeLog("开始调用中台还款单接口--------");
result = HttpClientToDC.sendPostApi( baseUrl + "/dcoaapi/ncc/repaymentBill", token, result);
JSONObject parse = (JSONObject) JSONObject.parse(result);
log.writeLog("返回数据----- " + parse.toJSONString());
String success = parse.getString("succ");
String msg = parse.getString("msg");
if(success.equals("true")) {
JSONObject data = parse.getJSONObject("data");
String pk_bill = data.getString("pk_bill");/* ncc单据id */
String billno = data.getString("billno"); /* ncc单据号 */
String updSql = "update " + tablename + " set nccdjzj = '" + pk_bill + "', nccfkdh ='" + billno + "', nccfhxx = '" + msg + "',sfcgscnccfkd = 0 where requestid = " + requestid;
log.writeLog("修改当前单据NCC回传信息sql----> " + updSql);
rs.execute(updSql);
}else{
String updSql = "update " + tablename + " set sfcgscnccfkd = 1,nccfhxx = '" + msg + "' where requestid = " + requestid;
rs.execute(updSql);
AddJournal.addInfo("还款单接口", json, result, "1", requestid);
ri.getRequestManager().setMessagecontent(msg);
return FAILURE_AND_CONTINUE;
}
AddJournal.addInfo("还款单接口", json, result, "0", requestid);
}catch (Exception e){
ri.getRequestManager().setMessagecontent("数据传递NCC出错----->" + e);
AddJournal.addInfo("还款单接口",json, "出现异常+++" + e, "1", requestid);
return FAILURE_AND_CONTINUE;
}
return SUCCESS;
}
public static void main(String[] args) {
double yhxje = Double.parseDouble("" == "" ? "0.00": "");
System.out.println(yhxje);
}
}

View File

@ -0,0 +1,180 @@
package com.api.lh.action;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.api.lh.port.AddJournal;
import jntchina.util.HttpClientToDC;
import jntchina.util.NCCUtils;
import selfdev.util.log.LogTool;
import weaver.file.Prop;
import weaver.general.Util;
import weaver.interfaces.workflow.action.Action;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import java.util.HashMap;
import java.util.Map;
/**
* @ClassName NCCPayableDataAction
* @Description ncc
* @Author louh
* @Date 2022/2/24 10:17
* @Version 1.0
*/
@Path("/Data")
public class NCCPayableDataAction {
LogTool log = new LogTool("/log/lh/action/NCCPayableDataAction", false);
static final String mode = Prop.getPropValue("DevToDC_jntchina","mode");
static final String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl");
/* 应付单查询接口 */
@POST
@Path("/getNCCPayableData")
@Produces({"application/json"})
public String getNCCPayableData(String data){
JSONObject json = null;
log.writeLog("应付单data: " + data);
String result = "";
Map<String, Object> return_map = new HashMap<>();
try {
json = (JSONObject) JSONObject.parse(data);
//获取token
String token = HttpClientToDC.getToken();
log.writeLog("获取中台的数据应付接口token----》 " + token);
if ("".equals(Util.null2String(token))) {
return_map.put("code", 500);
return_map.put("msg", "未获取到中台token请联系管理员查看问题");
return return_map.toString();
}
result = HttpClientToDC.sendPostApi(baseUrl + "/dcoaapi/ncc/payableBillSearch", token, data);
JSONObject parse = (JSONObject) JSONObject.parse(result);
String succ = parse.getString("succ");
JSONArray jsonArray = new JSONArray();
if ("true".equals(succ)){
JSONArray datas = parse.getJSONArray("data");
for (int i = 0; i < datas.size(); i++) {
JSONObject item = datas.getJSONObject(i);
String money = item.getString("money"); //剩余未付金额
double v = Double.parseDouble(money);
if(v > 0){
//获取原对象到账日期
String denddate = item.getString("denddate");
if(!"".equals(denddate)) {
item.remove("denddate");
//生成新的到账日期
denddate = denddate.substring(0, 10);
item.put("denddate", denddate);
}
jsonArray.add(item);
}
}
//删除原有数据
parse.remove("data");
parse.put("data", jsonArray);
}else{
return_map.put("code", 500);
return_map.put("msg", "获取信息失败");
AddJournal.addInfo("应付单查询接口", json, result, "1", "");
return JSON.toJSONString(return_map, SerializerFeature.DisableCircularReferenceDetect);
}
result = parse.toJSONString();
//result = NCCUtils.sendApi(baseUrl + "/nccloud/api/jitu/arap/busi/payablebillquery", data);
log.writeLog("result: " + result);
AddJournal.addInfo("应付单查询接口", json, result, "0", "");
}catch (Exception e){
log.writeLog("出现异常: " + e);
return_map.put("code", 500);
return_map.put("msg", "出现异常 " + e);
AddJournal.addInfo("应付单查询接口", json, "出现异常---> " + e, "1", "");
return JSON.toJSONString(return_map, SerializerFeature.DisableCircularReferenceDetect);
}
return result;
}
/* 预付单付款计划查询接口 */
@POST
@Path("/getNCCAdvanceData")
@Produces({"application/json"})
public String getNCCAdvanceData(String data){
JSONObject json = null;
log.writeLog("预付单data: " + data);
String result = "";
Map<String, Object> return_map = new HashMap<>();
try {
json = (JSONObject) JSONObject.parse(data);
//获取token
String token = HttpClientToDC.getToken();
log.writeLog("获取中台预付单的数据token----》 " + token);
if ("".equals(Util.null2String(token))) {
return_map.put("code", 500);
return_map.put("msg", "未获取到中台token请联系管理员查看问题");
return return_map.toString();
}
result = HttpClientToDC.sendPostApi(baseUrl + "/dcoaapi/ncc/purchasePaymentBillSearch", token, data);
//result = NCCUtils.sendApi(baseUrl + "/nccloud/api/jitu/arap/busi/orderquery", data);
JSONObject parse = (JSONObject) JSONObject.parse(result);
String succ = parse.getString("succ");
JSONArray jsonArray = new JSONArray();
if ("true".equals(succ)){
JSONArray datas = parse.getJSONArray("data");
for (int i = 0; i < datas.size(); i++) {
JSONObject item = datas.getJSONObject(i);
String money = item.getString("money"); //剩余未付金额
double v = Double.parseDouble(money);
if(v > 0){
//获取原对象到账日期
String denddate = item.getString("denddate");
if(!"".equals(denddate)) {
item.remove("denddate");
//生成新的到账日期
denddate = denddate.substring(0, 10);
item.put("denddate", denddate);
}
jsonArray.add(item);
}
}
//删除原有数据
parse.remove("data");
parse.put("data", jsonArray);
}else{
return_map.put("code", 500);
return_map.put("msg", "获取信息失败");
AddJournal.addInfo("预付单计划查询接口", json, result, "1", "");
return JSON.toJSONString(return_map, SerializerFeature.DisableCircularReferenceDetect);
}
result = parse.toJSONString();
log.writeLog("result: " + result);
AddJournal.addInfo("预付单计划查询接口", json, result, "0", "");
}catch (Exception e){
log.writeLog("出现异常: " + e);
return_map.put("code", 500);
return_map.put("msg", "出现异常 " + e);
AddJournal.addInfo("预付单计划查询接口", json, "出现异常---> " + e, "1", "");
return JSON.toJSONString(return_map, SerializerFeature.DisableCircularReferenceDetect);
}
return result;
}
public static void main(String[] args) {
//NCCPayableDataAction nccPayableDataAction = new NCCPayableDataAction();
//String nccPayableData = nccPayableDataAction.getNCCPayableData("{\"pk_org\":\"JTSDCN0001\",\"begindate\":\"2020-03-17\",\"enddate\":\"2022-03-17\",\"pk_supplier\":\"JTSDCN0030\"}");
//System.out.println(nccPayableData);
//String token = HttpClientToDC.getToken();
//System.out.println(token);
// 密码
//final String password = Prop.getPropValue("DevToDC_jntchina", mode+"_password");
//System.out.println("密码:" + password);
String time = "2021-01-01 00:00:00";
System.out.println(time.substring(0,10));
}
}

View File

@ -0,0 +1,182 @@
package com.api.lh.action;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.api.lh.port.AddJournal;
import com.api.lh.port.Items;
import com.api.lh.port.StuData;
import jntchina.util.HttpClientToDC;
import selfdev.util.base.BaseUtil;
import selfdev.util.log.LogTool;
import weaver.conn.RecordSet;
import weaver.file.Prop;
import weaver.general.Util;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* @ClassName NCCPayableTossAction
* @Description NCC
* @Author louh
* @Date 2022/3/1 14:35
* @Version 1.0
*/
public class NCCPayableTossAction implements Action {
LogTool log = new LogTool("/log/lh/action/NCCPayableTossAction", false);
static final String mode = Prop.getPropValue("DevToDC_jntchina","mode");
static final String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl");
@Override
public String execute(RequestInfo ri) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date = dateFormat.format(new Date());
String startDate = date.substring(0, 10);
String endDate = date.substring(11);
date = NCCAdvanceTossAction.getNewDate(startDate, endDate);
JSONObject json = new JSONObject();
RecordSet rs = new RecordSet();
String xrnccsbcsfts = "";
String requestid = ri.getRequestid();
String workflowid = ri.getWorkflowid();
/* 单据属性 */
String djsx = "";
try{
//获取表名
String tablename = BaseUtil.getBaseInfoByParm("tablename", "workflow_bill", "1", "1", " and id in (select formid from workflow_base where id=" + workflowid + ")");
log.writeLog("requestid---> " + requestid + "对应表名tablename---> " + tablename);
/* 主表数据id */
String id = BaseUtil.getBaseInfoByParm("id", tablename, "requestid", requestid, "");
/* 流程编号 */
String lcbh = BaseUtil.getBaseInfoByParm("lcbh", tablename, "requestid", requestid, "");
/* 供应商名称 */
String gysmc = BaseUtil.getBaseInfoByParm("gysmc", tablename, "requestid", requestid, "");
/* 付款金额 */
String fkje = BaseUtil.getBaseInfoByParm("jshjje", tablename, "requestid", requestid, "");
/* 公司名称(NCC财务组织编码) */
String gsmc = BaseUtil.getBaseInfoByParm("gsmc", tablename, "requestid", requestid, "");
/* 制单人 */
String zdr = BaseUtil.getBaseInfoByParm("zdr", tablename, "requestid", requestid, "");
/* 制单人编码 */
String workcode = BaseUtil.getBaseInfoByParm("workcode", "hrmresource", "id", zdr, "");
/* 部门 */
String bm = BaseUtil.getBaseInfoByParm("fygsbm", tablename, "requestid", requestid, "");
/* 部门编码 */
String departmentcode = BaseUtil.getBaseInfoByParm("departmentcode", "hrmdepartment", "id", bm, "");
/* 银行账号 */
String yxhm = BaseUtil.getBaseInfoByParm("yxhm", tablename, "requestid", requestid, "");
//是否提示报错信息
xrnccsbcsfts = BaseUtil.getBaseInfoByParm("xrnccsbcsfts", tablename, "requestid", requestid, "");
//银行付款备注
String yxfkbz = BaseUtil.getBaseInfoByParm("yxfkbz", tablename, "requestid", requestid, "");
double je = Double.parseDouble(fkje.replaceAll(",", ""));
String sql = "select * from " + tablename + "_dt2 where mainid = " + id;
log.writeLog("查询应付单明细数据sql-----> " + sql);
rs.execute(sql);
List<Items> list = new ArrayList<>();
while(rs.next()){
/* 本次付款金额 */
String je1 = Util.null2String(rs.getString("je"));
double v = Double.parseDouble(je1.replaceAll(",", ""));
/* 应付单明细行唯一id */
String yfdmxxwyid = Util.null2String(rs.getString("yfdmxxwyid"));
/* 应付单据号 */
String yfdh = Util.null2String(rs.getString("yfdh"));
/* 摘要 */
String zy = Util.null2String(rs.getString("zy"));
/* 单据属性 */
djsx = Util.null2String(rs.getString("djsx"));
/* 物料 */
String wl = Util.null2String(rs.getString("wl"));
/* 成本中心 */
String wd = Util.null2String(rs.getString("wd"));
//部门编码
String bmbm = Util.null2String(rs.getString("bmbm"));
Items items = new Items("1", gysmc,departmentcode, "", "0",
"CNY",v + "","1",v + "",
"1",v + "","1",v + "","1",
v + "",yfdmxxwyid,"","",yfdh, zy, djsx,
wl, bmbm, yxhm, "", wd);
list.add(items);
}
StuData stuData = new StuData(gsmc,djsx,date,"1","CNY",
yxhm,je + "","1",je + "","1",
je + "","1",je + "",workcode,requestid,lcbh,
gysmc,list,departmentcode, "", yxfkbz);
json = (JSONObject) JSONObject.toJSON(stuData);
log.writeLog("json-----> " + json);
//获取token
String token = HttpClientToDC.getToken();
log.writeLog("获取中台的数据token----》 " + token);
if ("".equals(weaver.general.Util.null2String(token))) {
ri.getRequestManager().setMessagecontent("未获取到中台token请联系管理员查看问题");
return FAILURE_AND_CONTINUE;
}
String result = HttpClientToDC.sendPostApi(baseUrl + "/dcoaapi/ncc/sendPaymentBill", token, json.toJSONString());
/* 调用NCC付款单接口 */
//String result = NCCUtils.sendApi(baseUrl + "/nccloud/api/jitu/arap/fkbill/insert", json.toJSONString());
log.writeLog("result----> " + result);
JSONObject parse = (JSONObject) JSONObject.parse(result);
String success = parse.getString("succ");
String msg = parse.getString("msg");
if(success.equals("true")) {
JSONObject data = parse.getJSONObject("data");
String billno = data.getString("billno"); /* ncc单据号 */
String pk_bill = data.getString("pk_bill");/* ncc单据主键 */
String billmaker = data.getString("billmaker"); /* 制单人 */
String pk_org = data.getString("pk_org"); /* 财务组织编码 */
String updSql = "update " + tablename + " set nccdjzj = '" + pk_bill + "', ncczdr = '" + billmaker + "', nccfkdh ='" + billno + "',ncccwzzbm = '" + pk_org + "', nccfhxx = '" + msg + "',sfcgscnccfkd = 0 where requestid = " + requestid;
log.writeLog("修改当前单据NCC回传信息sql----> " + updSql);
rs.execute(updSql);
//获取回传的明细表付款单id
JSONArray items = data.getJSONArray("items");
for (int i = 0; i < items.size(); i++) {
JSONObject resultData = items.getJSONObject(i);
String itemid = resultData.getString("itemid");/* 应付单明细id */
String pk_payitem = resultData.getString("pk_payitem"); /* 付款单id */
String upddelSql = "update " + tablename + "_dt2 set fkdid = '" + pk_payitem + "' where yfdmxxwyid = '" + itemid + "' and mainid = " + id ;
log.writeLog("修改明细表的明细数据sql---->" + upddelSql);
rs.execute(upddelSql);
}
}else{
String updSql = "update " + tablename + " set sfcgscnccfkd = 1,nccfhxx = '" + msg + "' where requestid = " + requestid;
rs.execute(updSql);
AddJournal.addInfo("抛转应付单数据到NCC", json, result, "1", requestid);
if("yes".equals(xrnccsbcsfts)) {
ri.getRequestManager().setMessagecontent(msg);
return FAILURE_AND_CONTINUE;
}else{
return SUCCESS;
}
}
AddJournal.addInfo("抛转应付单数据到NCC", json, result, "0", requestid);
}catch (Exception e){
AddJournal.addInfo("抛转应付单数据到NCC", json, "出现异常---> " + e, "1", requestid);
if("yes".equals(xrnccsbcsfts)) {
ri.getRequestManager().setMessagecontent("数据传递出错-----> " + e.getMessage());
return FAILURE_AND_CONTINUE;
}else{
return SUCCESS;
}
}
return SUCCESS;
}
public static void main(String[] args) {
System.out.println(NCCAdvanceTossAction.getNewDate("2022-06-29", "18:00:00"));
}
}

View File

@ -0,0 +1,113 @@
package com.api.lh.action;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.api.lh.port.AddJournal;
import com.wbi.util.Util;
import jntchina.util.HttpClientToDC;
import jntchina.util.NCCUtils;
import selfdev.util.base.BaseUtil;
import selfdev.util.log.LogTool;
import weaver.conn.RecordSet;
import weaver.file.Prop;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
/**
* @ClassName NCCPayableValidationAction
* @Description NCC,
* @Author louh
* @Date 2022/3/1 14:01
* @Version 1.0
*/
public class NCCPayableValidationAction implements Action {
static final String mode = Prop.getPropValue("DevToDC_jntchina","mode");
static final String baseUrl = Prop.getPropValue("DevToDC_jntchina", mode + "_baseUrl");
LogTool log = new LogTool("/log/lh/NCCPayableValidationAction", false);
@Override
public String execute(RequestInfo ri) {
JSONObject json = new JSONObject();
JSONArray jsonArray = new JSONArray();
RecordSet rs = new RecordSet();
/* 流程requestid */
String requestid = ri.getRequestid();
/* 流程id */
String workflowid = ri.getWorkflowid();
try {
//获取表名
String tablename = BaseUtil.getBaseInfoByParm("tablename", "workflow_bill", "1", "1", " and id in (select formid from workflow_base where id=" + workflowid + ")");
log.writeLog("requestid---> " + requestid + "对应表名tablename---> " + tablename);
/* 主表数据id */
String id = BaseUtil.getBaseInfoByParm("id", tablename, "requestid", requestid, "");
String sql = "select * from " + tablename + "_dt2 where mainid = " + id;
log.writeLog("查询明细表应付单数据sql-----> " + sql);
rs.execute(sql);
while (rs.next()) {
JSONObject jsonObject = new JSONObject();
/* 应付单明细行唯一id */
jsonObject.put("pk_item", Util.null2String(rs.getString("yfdmxxwyid")));
/* 本次付款金额 */
jsonObject.put("mny", Util.null2String(rs.getString("je")));
jsonArray.add(jsonObject);
}
json.put("request", jsonArray);
log.writeLog("request: " + json);
//获取token
String token = HttpClientToDC.getToken();
log.writeLog("获取中台的数据token----》 " + token);
if ("".equals(weaver.general.Util.null2String(token))) {
ri.getRequestManager().setMessagecontent("未获取到中台token请联系管理员查看问题");
return FAILURE_AND_CONTINUE;
}
String result = HttpClientToDC.sendPostApi(baseUrl + "/dcoaapi/ncc/payApplication", token, json.toJSONString());
//result = NCCUtils.sendApi(baseUrl + "nccloud/api/jitu/arap/busi/mnycheck", json.toJSONString());
/* 解析返回的数据 */
JSONObject result_json = (JSONObject) JSONObject.parse(result);
String allmsg = "";
String success = result_json.getString("succ");
String msg = result_json.getString("msg");
if("true".equals(success)){
JSONArray data = result_json.getJSONArray("data");
for (int i = 0; i < data.size(); i++) {
JSONObject item = data.getJSONObject(i);
String flag = item.getString("flag"); /* 是否正确 */
if(!"Y".equals(flag)) { //数据不一致
String pk_item = item.getString("pk_item"); /* 应付款单号 */
/* 根据应付单明细行唯一id去查询表单对应数据 */
String podb_sql = "select * from " + tablename + "_dt2 where yfdmxxwyid = '" + pk_item +"' and mainid = " + id;
log.writeLog("根据应付单明细行唯一id去查询表单对应数据sql-----> " + podb_sql);
rs.execute(podb_sql);
if(rs.next()){
/* 采购订单号 */
String cgddh = Util.null2String(rs.getString("cgddh"));
allmsg += cgddh + ",";
}
}
}
}else{
ri.getRequestManager().setMessagecontent(msg);
AddJournal.addInfo("效验应付单据数据是否正确", json, result, "1", requestid);
return FAILURE_AND_CONTINUE;
}
if(!"".equals(allmsg)){
allmsg += "数据效验不通过请删除当前单据重新获取NCC数据并选择";
ri.getRequestManager().setMessagecontent(allmsg);
AddJournal.addInfo("效验应付单据数据是否正确", json, result, "1", requestid);
return FAILURE_AND_CONTINUE;
}
AddJournal.addInfo("效验应付单据数据是否正确", json, result, "0", requestid);
}catch (Exception e) {
AddJournal.addInfo("效验应付单据数据是否正确", json, "出现异常" + e, "1", requestid);
ri.getRequestManager().setMessagecontent("数据传递出错----> " + e.getMessage());
return FAILURE_AND_CONTINUE;
}
return SUCCESS;
}
}

View File

@ -0,0 +1,111 @@
package com.api.lh.action;
import com.api.lh.config.DemoConfig;
import selfdev.util.log.LogTool;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.Util;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
/**
* @ClassName UpdPaymentAccountData
* @Description (NCC)
* @Author louh
* @Date 2022/4/21 17:38
* @Version 1.0
*/
public class UpdPaymentAccountAction implements Action, DemoConfig {
@Override
public String execute(RequestInfo ri) {
RecordSet rs = new RecordSet();
RecordSet rs1 = new RecordSet();
RecordSet rs2 = new RecordSet();
RecordSetTrans rst = new RecordSetTrans();
rst.setAutoCommit(false);
String requestid = ri.getRequestid();
String workflowid = ri.getWorkflowid();
try {
//获取表名
String tablename = getTableName(workflowid);
log.writeLog("requestid---> " + requestid + "对应表名tablename---> " + tablename);
//获取当前表单数据id
String id = getId(tablename, requestid);
String sql = "select yfkqptzmxid, " +
"sum(bchxje) as hxje," +
" avg(yfje) as zje," +
" avg(sywhxje) as whxje," +
" avg(xgyflc) as req, avg(yhxje) as yhxje1 " +
"from " + tablename + "_dt1 " +
"where mainid = '" + id + "'" +
"group by yfkqptzmxid having count(yfkqptzmxid) > 0";
log.writeLog("查询明细表1sql-----> " + sql);
rs.execute(sql);
while(rs.next()){
String yfkqptzmxid = Util.null2String(rs.getString("yfkqptzmxid")); //预付款欠票台账明细id
double bchxje = Double.parseDouble(Util.null2String(rs.getString("hxje")) == "" ? "0.00" : Util.null2String(rs.getString("hxje"))); //核销金额
double yfje = Double.parseDouble(Util.null2String(rs.getString("zje"))==""?"0.00":Util.null2String(rs.getString("zje")));//预付金额
double sywhxje = Double.parseDouble(Util.null2String(rs.getString("whxje")) == "" ? "0.00":Util.null2String(rs.getString("whxje"))); //未核销金额
String req = Util.null2String(rs.getString("req")); //相关预付流程requestid
double yhxje = Double.parseDouble(Util.null2String(rs.getString("yhxje1")) == "" ? "0.00" : Util.null2String(rs.getString("yhxje1"))); //核销金额
if (bchxje > yfje){
ri.getRequestManager().setMessagecontent("预付欠票台账明细id【" + yfkqptzmxid + "】本次核销金额【" + bchxje + "】大于预付总金额【" + yfje + "】");
return FAILURE_AND_CONTINUE;
}
//根据供应商预付欠票台账明细id查询该数据为还款金额
String sql1 = "select * from uf_fksqyfb_dt1 where id = '" + yfkqptzmxid + "'";
log.writeLog("获取剩余未核销金额明细sql-----> " + sql1);
rs1.execute(sql1);
String xghxlc = "";
double sywhxje2 = 0.00;
if(rs1.next()){
xghxlc = Util.null2String(rs1.getString("xghxlc")); //相关核销流程
sywhxje2 = Double.parseDouble(Util.null2String(rs1.getString("sywhxje")) == "" ? "0.00":Util.null2String(rs1.getString("sywhxje"))); //剩余未核销金额
}
if ("".equals(xghxlc)){
xghxlc = requestid;
}else{
xghxlc += "," + requestid;
}
yhxje = yhxje + bchxje;
if(sywhxje2 < bchxje){
ri.getRequestManager().setMessagecontent("预付欠票台账明细id【" + yfkqptzmxid + "】本次核销金额【" + bchxje + "】大于剩余未核销金额【" + sywhxje2 + "】,请重新选取抵扣明细数据,获取最新的台账数据!");
return FAILURE_AND_CONTINUE;
}
sywhxje2 = sywhxje2 - bchxje;
String updSql = "update uf_fksqyfb_dt1 set yhxje = '" + yhxje + "', sywhxje = '" + sywhxje2 + "', xghxlc = '" + xghxlc + "' where id = " + yfkqptzmxid;
log.writeLog("修改供应商预付欠票台账明细sql-----> " + updSql);
rst.executeSql(updSql);
//查询主表总预付金额及核销金额
sql1 = "select * from uf_fksqyfb where qqid = '" + req + "'";
log.writeLog("查询主表总预付金额及核销金额sql----> " + sql1);
rs1.execute(sql1);
if(rs1.next()){
double fkje = Double.parseDouble(Util.null2String(rs1.getString("fkje"))==""?"0.00":Util.null2String(rs1.getString("fkje")));//付款金额
double yhxje1 = Double.parseDouble(Util.null2String(rs1.getString("yhxje"))==""?"0.00":Util.null2String(rs1.getString("yhxje")));//已核销金额
double sywhxje1 = Double.parseDouble(Util.null2String(rs1.getString("sywhxje"))==""?"0.00":Util.null2String(rs1.getString("sywhxje")));//剩余金额
if(bchxje > sywhxje1){
ri.getRequestManager().setMessagecontent("本次核销金额【" + bchxje + "】大于剩余为核销金额【" + sywhxje1 + "】");
return FAILURE_AND_CONTINUE;
}
bchxje = bchxje + yhxje1;
sywhxje1 = fkje - bchxje;
updSql = "update uf_fksqyfb set sywhxje = '" + sywhxje1 + "', yhxje = '" + bchxje + "' where qqid = '" + req + "'";
log.writeLog("修改供应商预付欠票台账主数据sql-----> " + updSql);
//rst.executeSql(updSql);
rs2.execute(updSql);
}
}
rst.commit();
} catch (Exception e) {
rst.rollback();
ri.getRequestManager().setMessagecontent("修改台账出现异常-----" + e);
return FAILURE_AND_CONTINUE;
}
return SUCCESS;
}
}

View File

@ -0,0 +1,109 @@
package com.api.lh.action;
import com.api.lh.config.DemoConfig;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.Util;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
/**
* @ClassName UpdPaymentAccountData
* @Description (NCC)
* @Author ycf
* @Date 2022/4/21 17:38
* @Version 1.0
*/
public class UpdPaymentAccountActionYY implements Action, DemoConfig {
@Override
public String execute(RequestInfo ri) {
RecordSet rs = new RecordSet();
RecordSet rs1 = new RecordSet();
RecordSet rs2 = new RecordSet();
RecordSetTrans rst = new RecordSetTrans();
rst.setAutoCommit(false);
String requestid = ri.getRequestid();
String workflowid = ri.getWorkflowid();
try {
//获取表名
String tablename = getTableName(workflowid);
log.writeLog("requestid---> " + requestid + "对应表名tablename---> " + tablename);
//获取当前表单数据id
String id = getId(tablename, requestid);
String sql = "select yfkqptzmxid, " +
"sum(bchxje) as hxje," +
" avg(yfje) as zje," +
" avg(sywhxje) as whxje," +
" avg(xgyflc) as req, avg(yhxje) as yhxje1 " +
"from " + tablename + "_dt1 " +
"where mainid = '" + id + "'" +
"group by yfkqptzmxid having count(yfkqptzmxid) > 0";
log.writeLog("查询明细表1sql-----> " + sql);
rs.execute(sql);
while(rs.next()){
String yfkqptzmxid = Util.null2String(rs.getString("yfkqptzmxid")); //预付款欠票台账明细id
double bchxje = Double.parseDouble(Util.null2String(rs.getString("hxje")) == "" ? "0.00" : Util.null2String(rs.getString("hxje"))); //核销金额
double yfje = Double.parseDouble(Util.null2String(rs.getString("zje"))==""?"0.00":Util.null2String(rs.getString("zje")));//预付金额
double sywhxje = Double.parseDouble(Util.null2String(rs.getString("whxje")) == "" ? "0.00":Util.null2String(rs.getString("whxje"))); //未核销金额
String req = Util.null2String(rs.getString("req")); //相关预付流程requestid
double yhxje = Double.parseDouble(Util.null2String(rs.getString("yhxje1")) == "" ? "0.00" : Util.null2String(rs.getString("yhxje1"))); //核销金额
if (bchxje > yfje){
ri.getRequestManager().setMessagecontent("预付欠票台账明细id【" + yfkqptzmxid + "】本次核销金额【" + bchxje + "】大于预付总金额【" + yfje + "】");
return FAILURE_AND_CONTINUE;
}
//根据供应商预付欠票台账明细id查询该数据为还款金额
String sql1 = "select * from uf_gysqktzyy_dt1 where id = '" + yfkqptzmxid + "'";
rs1.execute(sql1);
String xghxlc = "";
double sywhxje2 = 0.00;
if(rs1.next()){
xghxlc = Util.null2String(rs1.getString("xghxlc")); //相关核销流程
sywhxje2 = Double.parseDouble(Util.null2String(rs1.getString("sywhxje")) == "" ? "0.00":Util.null2String(rs1.getString("sywhxje"))); //剩余未核销金额
}
if ("".equals(xghxlc)){
xghxlc = requestid;
}else{
xghxlc += "," + requestid;
}
yhxje = yhxje + bchxje;
if(sywhxje2 < bchxje){
ri.getRequestManager().setMessagecontent("预付欠票台账明细id【" + yfkqptzmxid + "】本次核销金额【" + bchxje + "】大于剩余未核销金额【" + sywhxje2 + "】,请重新选取抵扣明细数据,获取最新的台账数据!");
return FAILURE_AND_CONTINUE;
}
sywhxje2 = sywhxje2 - bchxje;
String updSql = "update uf_gysqktzyy_dt1 set yhxje = '" + yhxje + "', sywhxje = '" + sywhxje2 + "', xghxlc = '" + xghxlc + "' where id = " + yfkqptzmxid;
log.writeLog("修改供应商预付欠票台账明细sql-----> " + updSql);
rst.executeSql(updSql);
//查询主表总预付金额及核销金额
sql1 = "select * from uf_gysqktzyy where qqid = '" + req + "'";
log.writeLog("查询主表总预付金额及核销金额sql----> " + sql1);
rs1.execute(sql1);
if(rs1.next()){
double fkje = Double.parseDouble(Util.null2String(rs1.getString("fkje"))==""?"0.00":Util.null2String(rs1.getString("fkje")));//付款金额
double yhxje1 = Double.parseDouble(Util.null2String(rs1.getString("yhxje"))==""?"0.00":Util.null2String(rs1.getString("yhxje")));//已核销金额
double sywhxje1 = Double.parseDouble(Util.null2String(rs1.getString("sywhxje"))==""?"0.00":Util.null2String(rs1.getString("sywhxje")));//剩余金额
if(bchxje > sywhxje1){
ri.getRequestManager().setMessagecontent("本次核销金额【" + bchxje + "】大于剩余未核销金额【" + sywhxje1 + "】");
return FAILURE_AND_CONTINUE;
}
bchxje = bchxje + yhxje1;
sywhxje1 = fkje - bchxje;
updSql = "update uf_gysqktzyy set sywhxje = '" + sywhxje1 + "', yhxje = '" + bchxje + "' where qqid = '" + req + "'";
log.writeLog("修改供应商预付欠票台账主数据sql-----> " + updSql);
//rst.executeSql(updSql);
rs2.execute(updSql);
}
}
rst.commit();
} catch (Exception e) {
rst.rollback();
ri.getRequestManager().setMessagecontent("修改台账出现异常-----" + e);
return FAILURE_AND_CONTINUE;
}
return SUCCESS;
}
}

View File

@ -0,0 +1,45 @@
package com.api.lh.action;
import selfdev.util.base.BaseUtil;
import selfdev.util.log.LogTool;
import weaver.conn.RecordSet;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
/**
* @ClassName VaildatePayableDocumentTypeAction
* @Description
* @Author louh
* @Date 2022/3/29 11:40
* @Version 1.0
*/
public class VaildateDocumentTypeAction implements Action {
@Override
public String execute(RequestInfo ri) {
LogTool log = new LogTool("/log/lh/VaildateDocumentTypeAction",false);
String requestid = ri.getRequestid();
RecordSet rs = new RecordSet();
String workflowid = ri.getWorkflowid();
try{
//获取表名
String tablename = BaseUtil.getBaseInfoByParm("tablename", "workflow_bill", "1", "1", " and id in (select formid from workflow_base where id=" + workflowid + ")");
log.writeLog("requestid---> " + requestid + "对应表名tablename---> " + tablename);
//主表id
String id = BaseUtil.getBaseInfoByParm("id", tablename, "requestid", requestid, "");
//根据主表数据id获取明细数据sql
String sql = "select distinct cgddlx from " + tablename + "_dt2 where mainid = " + id;
log.writeLog("根据主表数据id获取明细数据sql---> " + sql);
rs.execute(sql);
int counts = rs.getCounts();
log.writeLog("总行数: " + counts);
if(counts > 1){
ri.getRequestManager().setMessagecontent("同一张付款单,采购类型必须相同,请重新选择要付款的单据!");
return FAILURE_AND_CONTINUE;
}
}catch (Exception e){
ri.getRequestManager().setMessagecontent("内部错误---- > " + e);
return FAILURE_AND_CONTINUE;
}
return SUCCESS;
}
}

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