合并年前保时捷的开发
main
youHong.ai 2023-02-02 10:26:45 +08:00
commit 8204400283
70 changed files with 4392 additions and 308 deletions

View File

@ -0,0 +1,61 @@
/**
* 柏美 施工合同申请js
* 明细表自动添加5行 不允许增删 并校验付款比例是否等于100% 自动计算付款日期
* @author xuanran.wang
*/
// 明细表
const detailTable = "detail_2";
// 主表合同签订日期
const contractSignDateId = WfForm.convertFieldNameToId("htqdrq");
// 明细2付款比例字段
const detail2PayProportionId = WfForm.convertFieldNameToId("fkbl",detailTable);
// 明细2款项类型
const detail2PaymentTypeId = WfForm.convertFieldNameToId("kxlx",detailTable);
// 明细2前后字段
const detail2AroundId = WfForm.convertFieldNameToId("qh",detailTable);
// 明细2天数字段
const detail2DayId = WfForm.convertFieldNameToId("ts",detailTable);
// 明细2预计付款日期
const detail2ComPayDateId = WfForm.convertFieldNameToId("yjfkrq",detailTable);
// 对应日期
const detail2TempDateField = WfForm.convertFieldNameToId("dyrq", detailTable);
// 需要计算的款项类型集合
const computeDatePayType = ['0'];
const DETAIL_MAX_SIZE = 5;
// 款项类型预计对应日期取值
const paymentTypeGetValue = {
0: (index)=>{
WfForm.changeFieldValue(`${detail2TempDateField}_${index}`,{value : WfForm.getFieldValue(contractSignDateId)});
}
}
jQuery().ready(function(){
let configObj = {
'detailPaymentTypeId':detail2PaymentTypeId,
'detailTempDateId': detail2TempDateField,
'around': detail2AroundId,
'detailComPayDateId': detail2ComPayDateId,
'dayId': detail2DayId,
'computeDatePayType': computeDatePayType,
'paymentTypeGetValue': paymentTypeGetValue
}
let rowArr = WfForm.getDetailAllRowIndexStr(detailTable).split(",");
if(rowArr.length !== DETAIL_MAX_SIZE){
// 默认增加5条
for (let i = 0; i < 5; i++) {
WfForm.addDetailRow(detailTable,{ [detail2PaymentTypeId]: {value: i}});
}
}
changeDetailFieldReadOnly(detailTable, detail2ComPayDateId, detail2PaymentTypeId, computeDatePayType)
// 主表字段发生变化
mainFieldChangeDetailCom(contractSignDateId, detailTable, configObj);
// 明细的款项类型字段变化绑定
detailFieldChangeDetailCom(`${detail2PaymentTypeId},${detail2AroundId},${detail2DayId}`, configObj);
submitCallback(detailTable, detail2PayProportionId);
});

View File

@ -0,0 +1,175 @@
const ADD = '1';
const DEL = '0';
const READ_ONLY = '1';
const EDIT = '2';
/**
* 计算日期
* @param date 计算日期
* @param around / 前是0 后是1
* @param day
*/
function computeDate(date, around, day){
let dateTime = new Date(date).getTime();
let mill = 0;
switch (around){
case ADD:{
mill = day * 1;
console.log('add :', mill);
break;
}
case DEL:{
mill = day * -1;
console.log('del :', mill);
break;
}
}
// 转成毫秒数
mill *= (24 * 60 * 60 * 1000);
dateTime += mill;
return getDate(dateTime);
}
/**
* 时间戳转 yyyy-MM-dd
* @param time
* @returns {string}
*/
function getDate(time) {
let date = new Date(time);
y = date.getFullYear();
m = date.getMonth() + 1;
d = date.getDate();
return y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d);
}
/**
* 校验比例是否等于100
* @param detailTable 明细表
* @param detail2PayProportionId 比例字段
*/
function submitCallback(detailTable, detail2PayProportionId){
WfForm.registerCheckEvent(WfForm.OPER_SUBMIT,function(callback){
let rowArr = WfForm.getDetailAllRowIndexStr(detailTable).split(",");
let sum = 0;
for(let i=0; i < rowArr.length; i++){
let rowIndex = rowArr[i];
if(rowIndex !== ""){
let field = `${detail2PayProportionId}_${rowIndex}`;
sum += parseFloat(WfForm.getFieldValue(field));//遍历明细行字段
}
}
sum === 100.00 ? callback() : WfForm.showMessage("明细付款比例总和不等于100,请修改后提交!");
});
}
/**
* 明细表字段发生变化进行日期计算
* @param bindField
* @param configObj
*/
function detailFieldChangeDetailCom(bindField, configObj){
WfForm.bindDetailFieldChangeEvent(bindField,function(id,index,value){
configObj.index = index;
changeDetailPayDate(configObj);
});
}
/**
* 主表字段发生变化进行日期计算
* @param mainField
* @param detailTable
* @param configObj
*/
function mainFieldChangeDetailCom(mainField, detailTable, configObj){
// 主表项目字段变化绑定
WfForm.bindFieldChangeEvent(mainField, function(obj,id,value){
let rowArr = WfForm.getDetailAllRowIndexStr(detailTable).split(",");
for(let i=0; i < rowArr.length; i++){
let index = rowArr[i];
if(index !== ""){
configObj.index = index;
changeDetailPayDate(configObj);
}
}
});
}
/**
* 先进行主表的dml查询日期字段赋值到明细 然后在计算日期
* @param obj 配置对象
*/
function changeDetailPayDate(obj){
console.log('---- changeDetailPayDate obj ----', obj);
// 明细表的款项类型
let detailPaymentTypeId = obj['detailPaymentTypeId'];
// 明细下标
let index = obj['index'];
// 明细表的对应日期
let detailTempDateId = obj['detailTempDateId'];
// 明细表的前/后
let aroundId = obj['around'];
// 明细表的预计付款日期
let detailComPayDateId = obj['detailComPayDateId'];
// 明细表的天数
let dayId = obj['dayId'];
// 需要计算的款项数组
let computeDatePayType = obj['computeDatePayType'];
// 获取主表的字符值转换函数
let paymentTypeGetValue = obj['paymentTypeGetValue'];
// 款项类型
let paymentType = WfForm.getFieldValue(`${detailPaymentTypeId}_${index}`);
// 先进行赋值
if(computeDatePayType.includes(paymentType)){
WfForm.changeFieldAttr(`${detailComPayDateId}_${index}`, READ_ONLY);
// 存在字段联动延时处理
setTimeout(()=>{
if(paymentTypeGetValue){
paymentTypeGetValue[paymentType](index);
}
// 获取对应日期
let tempDate = WfForm.getFieldValue(`${detailTempDateId}_${index}`);
if(tempDate){
// 前/后
let around = WfForm.getFieldValue(`${aroundId}_${index}`);
// 天数
let day = WfForm.getFieldValue(`${dayId}_${index}`);
// 如果明细表三个字段的值都不为空 那么就去计算日期
if(tempDate && around && day){
let comDate = computeDate(tempDate, around, day);
WfForm.changeFieldValue(`${detailComPayDateId}_${index}`,{
value: comDate
});
}
}else {
// 如果对应日期为空就给预计付款赋空值
WfForm.changeFieldValue(`${detailComPayDateId}_${index}`,{
value: ''
});
}
},100);
}else{
// 如果款项类型不需要计算就把预计付款日期属性改成可编辑
WfForm.changeFieldAttr(`${detailComPayDateId}_${index}`, EDIT);
}
}
/**
* 改变明细表字段只读
* @param detailTable
* @param detailComDateField
* @param detailPaymentTypeId
* @param readOnlyArr
*/
function changeDetailFieldReadOnly(detailTable, detailComDateField, detailPaymentTypeId, readOnlyArr){
let rowArr = WfForm.getDetailAllRowIndexStr(detailTable).split(",");
for(let i=0; i < rowArr.length; i++){
let index = rowArr[i];
if(index !== ""){
let paymentType = WfForm.getFieldValue(`${detailPaymentTypeId}_${index}`);
// 先进行赋值
if(readOnlyArr.includes(paymentType)){
WfForm.changeFieldAttr(`${detailComDateField}_${index}`, READ_ONLY);
}
}
}
}

View File

@ -0,0 +1,60 @@
/**
* 柏美 采购合同申请js
* @author xuanran.wang
*/
// 明细表
const detailTable = "detail_3";
// 主表订单编号字段
const mainProjectId = WfForm.convertFieldNameToId("ddh1");
// 主表合同签订日期
const contractSignDateId = WfForm.convertFieldNameToId("htqdrq");
// 主表订单申请日期
const mainPOApplyId = WfForm.convertFieldNameToId("rkdsqrq");
// 明细2付款比例字段
const detailPayProportionId = WfForm.convertFieldNameToId("fkbl",detailTable);
// 明细2款项类型
const detailPaymentTypeId = WfForm.convertFieldNameToId("kxlx",detailTable);
// 明细2前后字段
const detailAroundId = WfForm.convertFieldNameToId("qh",detailTable);
// 明细2天数字段
const detailDayId = WfForm.convertFieldNameToId("ts",detailTable);
// 明细2预计付款日期
const detailComPayDateId = WfForm.convertFieldNameToId("yjfkrq",detailTable);
// 对应日期
const detailTempDateField = WfForm.convertFieldNameToId("dyrq", detailTable);
// 需要计算的款项类型集合
const computeDatePayType = ['0','2','4'];
// 款项类型预计对应日期取值
const paymentTypeGetValue = {
0: (index)=>{
WfForm.changeFieldValue(`${detailTempDateField}_${index}`,{value : WfForm.getFieldValue(contractSignDateId)});
},
2: (index)=>{
WfForm.changeFieldValue(`${detailTempDateField}_${index}`,{value : WfForm.getFieldValue(mainPOApplyId)});
},
4: (index)=>{
WfForm.changeFieldValue(`${detailTempDateField}_${index}`,{value : WfForm.getFieldValue(mainPOApplyId)});
}
}
$(()=>{
init();
});
function init(){
let obj = {
'detailPaymentTypeId':detailPaymentTypeId,
'detailTempDateId': detailTempDateField,
'around': detailAroundId,
'detailComPayDateId': detailComPayDateId,
'dayId': detailDayId,
'computeDatePayType': computeDatePayType,
'paymentTypeGetValue': paymentTypeGetValue
}
changeDetailFieldReadOnly(detailTable, detailComPayDateId, detailPaymentTypeId, computeDatePayType)
// 主表字段发生变化
mainFieldChangeDetailCom(`${mainProjectId},${contractSignDateId}`, detailTable, obj);
// 明细的款项类型字段变化绑定
detailFieldChangeDetailCom(`${detailPaymentTypeId},${detailAroundId},${detailDayId}`, obj);
submitCallback(detailTable, detailPayProportionId);
}

View File

@ -0,0 +1,62 @@
/**
* 柏美 销售合同申请js
* @author xuanran.wang
*/
// 明细表
const detailTable = "detail_2";
// 主表项目字段
const mainProjectId = WfForm.convertFieldNameToId("xmmc");
// 主表流程归档日期
const mainWorkFlowEndId = WfForm.convertFieldNameToId("fhdgdrq");
// 主表实际验收
const mainActualCheckId = WfForm.convertFieldNameToId("sjysrq");
// 明细2付款比例字段
const detail2PayProportionId = WfForm.convertFieldNameToId("fkbl",detailTable);
// 明细2款项类型
const detail2PaymentTypeId = WfForm.convertFieldNameToId("kxlx",detailTable);
// 明细2前后字段
const detail2AroundId = WfForm.convertFieldNameToId("qh",detailTable);
// 明细2天数字段
const detail2DayId = WfForm.convertFieldNameToId("ts",detailTable);
// 明细2预计付款日期
const detail2ComPayDateId = WfForm.convertFieldNameToId("yjfkrq",detailTable);
// 对应日期
const detail2TempDateField = WfForm.convertFieldNameToId("dyrq", detailTable);
// 需要计算的款项类型集合
const computeDatePayType = ['2', '4', '5'];
// 款项类型预计对应日期取值
const paymentTypeGetValue = {
2: (index)=>{
console.log('将主表的 mainWorkFlowEndId : ' + mainWorkFlowEndId + ' val : ' + WfForm.getFieldValue(mainWorkFlowEndId) + ' 赋值给明细 ' + `${detail2TempDateField}_${index}`);
WfForm.changeFieldValue(`${detail2TempDateField}_${index}`,{value : WfForm.getFieldValue(mainWorkFlowEndId)});
},
4: (index)=>{
WfForm.changeFieldValue(`${detail2TempDateField}_${index}`,{value : WfForm.getFieldValue(mainActualCheckId)});
},
5: (index)=>{
WfForm.changeFieldValue(`${detail2TempDateField}_${index}`,{value : WfForm.getFieldValue(mainActualCheckId)});
}
}
$(()=>{
init();
});
function init(){
let obj = {
'detailPaymentTypeId':detail2PaymentTypeId,
'detailTempDateId': detail2TempDateField,
'around': detail2AroundId,
'detailComPayDateId': detail2ComPayDateId,
'dayId': detail2DayId,
'computeDatePayType': computeDatePayType,
'paymentTypeGetValue': paymentTypeGetValue
}
changeDetailFieldReadOnly(detailTable, detail2ComPayDateId, detail2PaymentTypeId, computeDatePayType)
// 主表字段发生变化
mainFieldChangeDetailCom(mainProjectId, detailTable, obj);
// 明细的款项类型字段变化绑定
detailFieldChangeDetailCom(`${detail2PaymentTypeId},${detail2AroundId},${detail2DayId}`, obj);
submitCallback(detailTable, detail2PayProportionId);
}

View File

@ -0,0 +1,151 @@
// 打印盖章
const pritGz = 1;
// 鉴伪盖章
const jwGz = 3;
// 开门盖章
const kmGz = 4;
// 用印方式字段名
const sealTypeId = WfForm.convertFieldNameToId("yyfs");
// 用印方式字段名明细
const detailSealTypeId = WfForm.convertFieldNameToId("yylx","detail_1");
// 是否需要加骑缝章
const detailQfzField = WfForm.convertFieldNameToId("sfjgqfz","detail_1");
// 否
const no = 1;
// 是
const yes = 0;// 组合用印
const zh = 6;
// 取章用印
const qzyy = 7;
// 是否归档
const lastField = WfForm.convertFieldNameToId("sfgd");
// 来源
const source = WfForm.convertFieldNameToId("htspcfyy");
//属于合同
const isht = WfForm.convertFieldNameToId("zyht");
//完成法神
const islaw = WfForm.convertFieldNameToId("wcfs");
// 用印文件字段
const detailFileTypeId = WfForm.convertFieldNameToId("yywj","detail_1");
// 主表
const mainsealtype = WfForm.convertFieldNameToId("yzzl");
// 主表合同专用章次数
const mainht = WfForm.convertFieldNameToId("htzyzcshj");
// 主表公章次数
const maingz = WfForm.convertFieldNameToId("gzcshj");
// 主表法人章次数
const mainfr = WfForm.convertFieldNameToId("frzcshj");
// 必填
const required = 3;
// 只读
const readOnly = 1;
// 可编辑
const edit = 2;
// 默认文件docid
const defaultfile = 85;
// 明细1用印文件
jQuery(document).ready(()=>{
let sourceVal = WfForm.getFieldValue(source);
console.log('sourceVal ', sourceVal)
if(sourceVal == 0){
WfForm.changeSingleField(isht,{value:yes}, {viewAttr:readOnly});
WfForm.changeSingleField(islaw,{value:yes}, {viewAttr:readOnly});
// 明细表用印文件字段做只读
var rowArr = WfForm.getDetailAllRowIndexStr("detail_1").split(",");
for(var i=0; i<rowArr.length; i++){
var rowIndex = rowArr[i];
if(rowIndex !== ""){
WfForm.changeFieldAttr(`${detailFileTypeId}_${rowIndex}`, readOnly);
}
}
// 明细行上+-按钮清除
$('#detail1Btn').empty();
}
WfForm.bindFieldChangeEvent(sealTypeId, function(obj,id,val){ //变更用印方式触发
changeDetailFieldVal();
if(val == qzyy || val == kmGz){
WfForm.delDetailRow("detail_1", "all");
}
if(pritGz == val || jwGz == val || zh == val){
WfForm.changeSingleField(lastField,{value:1}, {viewAttr:readOnly});
} else if (kmGz == val){
WfForm.changeSingleField(lastField,{value:2}, {viewAttr:readOnly});
} else{
WfForm.changeSingleField(lastField,{value:''}, {viewAttr:required});
}
addRow();
});
WfForm.bindFieldChangeEvent(`${mainsealtype}, ${mainfr}, ${maingz}, ${mainht}`, function(obj,id,val){
WfForm.delDetailRow("detail_1", "all");
addRow();
})
WfForm.registerCheckEvent(WfForm.OPER_ADDROW+ "1", function(callback){
callback(); //允许继续添加行调用callback不调用代表阻断添加
let val = WfForm.getFieldValue(sealTypeId);
if(val == zh){
return;
}
changeDetailFieldVal();
});
})
function addRow(){
let val = WfForm.getFieldValue(sealTypeId);
if(val == kmGz || val == qzyy){
// 明细1印章种类
let detail1SealType = WfForm.convertFieldNameToId("yzzl","detail_1");
// 明细1合同专用章次数
let detail1ht = WfForm.convertFieldNameToId("htzyzcs","detail_1");
// 明细1公章次数
let detail1gz = WfForm.convertFieldNameToId("gzcs","detail_1");
// 明细1法人章次数
let detail1fr = WfForm.convertFieldNameToId("frzcs","detail_1");
console.log('detail1SealType ', detail1SealType);
console.log('detail1ht ', detail1SealType);
console.log('detail1SealType ', detail1SealType);
console.log('detail1SealType ', detail1SealType);
let obj = {
detailFileTypeId: {value:defaultfile},
detail1SealType: {value:WfForm.getFieldValue(mainsealtype)},
detail1gz: {value:WfForm.getFieldValue(maingz)},
detail1fr: {value:WfForm.getFieldValue(mainfr)},
detail1ht: {value:WfForm.getFieldValue(mainht)}
};
console.log('obj ', obj)
WfForm.addDetailRow("detail_1",obj);
}
}
function changeDetailFieldVal(){
let val = WfForm.getFieldValue(sealTypeId);
// 必填
let attr = required;
let syqf = '';
if(val == pritGz || val == jwGz){
attr = readOnly;
syqf = no;
}else{
val = '';
}
var rowArr = WfForm.getDetailAllRowIndexStr("detail_1").split(",");
for(var i=0; i<rowArr.length; i++){
var rowIndex = rowArr[i];
if(rowIndex !== ""){
WfForm.changeSingleField(`${detailSealTypeId}_${rowIndex}`,{value:val}, {viewAttr:attr});
WfForm.changeSingleField(`${detailQfzField}_${rowIndex}`,{value:syqf}, {viewAttr:attr});
}
}
}

View File

@ -80,6 +80,14 @@
</dependency>
<dependency>
<groupId>org.apache.rocketmq</groupId>
<artifactId>rocketmq-client</artifactId>
<version>4.4.0</version>
</dependency>
</dependencies>
<repositories>

View File

@ -1010,14 +1010,20 @@ public class HttpUtils {
if (Strings.isNullOrEmpty(contentType)) {
List<NameValuePair> nvps = new ArrayList<>();
for (Map.Entry<String, Object> entry : params.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue())));
//nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue())));
//修复请求form表单提交时参数值被双引号括了起来
nvps.add(new BasicNameValuePair(entry.getKey(), Util.null2String(entry.getValue())));
}
httpPost.setHeader("Content-Type", HttpArgsType.DEFAULT_CONTENT_TYPE);
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
} else if (contentType.toUpperCase().startsWith(HttpArgsType.X_WWW_FORM_URLENCODED.toUpperCase())) {
List<NameValuePair> nvps = new ArrayList<>();
for (Map.Entry<String, Object> entry : params.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue())));
//nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue())));
//修复请求form表单提交时参数值被双引号括了起来
nvps.add(new BasicNameValuePair(entry.getKey(), Util.null2String(entry.getValue())));
}
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
// } else if (contentType.toUpperCase().startsWith(HttpArgsType.APPLICATION_JSON.toUpperCase())) {
@ -1198,14 +1204,18 @@ public class HttpUtils {
if (Strings.isNullOrEmpty(contentType)) {
List<NameValuePair> nvps = new ArrayList<>();
for (Map.Entry<String, Object> entry : paramsMap.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue())));
//nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue())));
//修复请求form表单提交时参数值被双引号括了起来
nvps.add(new BasicNameValuePair(entry.getKey(), Util.null2String(entry.getValue())));
}
httpPut.setHeader("Content-Type", HttpArgsType.DEFAULT_CONTENT_TYPE);
httpPut.setEntity(new UrlEncodedFormEntity(nvps));
} else if (contentType.toUpperCase().startsWith(HttpArgsType.X_WWW_FORM_URLENCODED.toUpperCase())) {
List<NameValuePair> nvps = new ArrayList<>();
for (Map.Entry<String, Object> entry : paramsMap.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue())));
//nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue())));
//修复请求form表单提交时参数值被双引号括了起来
nvps.add(new BasicNameValuePair(entry.getKey(), Util.null2String(entry.getValue())));
}
httpPut.setEntity(new UrlEncodedFormEntity(nvps));
} else if (contentType.toUpperCase().startsWith(HttpArgsType.APPLICATION_JSON.toUpperCase())) {

View File

@ -32,23 +32,8 @@ public class CheckUserController {
String checkContent = request.getParameter("checkContent");
try {
CheckUserService checkUserService = new CheckUserService();
return ApiResult.success(checkUserService.checkADHasUser(checkContent),"ok");
}catch (Exception e){
String error = Util.logStr("AD查询接口发生异常:{}", e.getMessage());
log.error(error);
log.error(Util.getErrString(e));
return ApiResult.error(500, error);
}
}
@Path("logUser")
@GET
@Produces(MediaType.TEXT_PLAIN)
public String logUser(@Context HttpServletRequest request, @Context HttpServletResponse response) {
try {
CheckUserService checkUserService = new CheckUserService();
checkUserService.logAllUser();
return ApiResult.successNoData();
boolean has = checkUserService.checkADHasUser(checkContent);
return ApiResult.success(has,"ok");
}catch (Exception e){
String error = Util.logStr("AD查询接口发生异常:{}", e.getMessage());
log.error(error);

View File

@ -56,7 +56,7 @@ public class CheckUserService {
String searchBase = Util.null2String(ADConfig.get("searchBase"));
// LDAP搜索过滤器类 cn=*name*模糊查询 cn=name 精确查询 String searchFilter = "(objectClass="+type+")";
//查询域帐号
String searchFilter = Util.null2String(ADConfig.get("queryField")) + "=" + checkInfo;
String searchFilter = "(" + Util.null2String(ADConfig.get("queryField")) + "=" + checkInfo + ")";
log.info("searchFilter : " + searchFilter);
// 创建搜索控制器
SearchControls searchControl = new SearchControls();
@ -64,8 +64,15 @@ public class CheckUserService {
searchControl.setSearchScope(SearchControls.SUBTREE_SCOPE);
// 根据设置的域节点、过滤器类和搜索控制器搜索LDAP得到结果
NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchControl);
boolean has = answer.hasMoreElements();
log.info("has " + has);
if(has){
SearchResult sr = (SearchResult) answer.next();
String dn = sr.getName();
log.info("dn " + dn);
}
// 初始化搜索结果数为0
return answer.hasMoreElements();
return has;
} catch (NamingException e) {
throw new CustomerException(Util.logStr("从AD搜索用户异常:[{}]",e.getMessage()));
} finally {

View File

@ -2,10 +2,20 @@ package com.api.xuanran.wang.saic_travel.model_create_workflow.controller;
import aiyh.utils.ApiResult;
import aiyh.utils.Util;
import aiyh.utils.excention.CustomerException;
import com.alibaba.fastjson.JSONObject;
import com.api.xuanran.wang.saic_travel.model_create_workflow.service.CreateWorkFlowService;
import com.icbc.api.internal.apache.http.E;
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.formmode.data.ModeDataApproval;
import weaver.general.TimeUtil;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.xuanran.wang.common.mapper.CommonMapper;
import weaver.xuanran.wang.common.util.CommonUtil; // 工具类
import javax.servlet.http.HttpServletRequest;
@ -13,9 +23,7 @@ import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.*;
import java.util.stream.Collectors;
/**
@ -28,26 +36,75 @@ public class CusCreateWorkFlowController {
private final Logger logger = Util.getLogger(); // 获取日志对象
private final CreateWorkFlowService createWorkFlowService = new CreateWorkFlowService();
@Path("cusCreateWorkFlow")
@POST
@Produces(MediaType.TEXT_PLAIN)
public String createWorkFlow(@Context HttpServletRequest request, @Context HttpServletResponse response) {
User logInUser = HrmUserVarify.getUser(request, response);
if(logInUser == null){
return ApiResult.error(403,"请先登录!");
}
String choiceData = request.getParameter("choiceData");
int modelId = Util.getIntValue(request.getParameter("modelId"), -1);
List<String> dataList = Arrays.stream(choiceData.split(",")).collect(Collectors.toList());
List<String> requestIds = CommonUtil.doCreateWorkFlow(modelId, dataList); // 通过数据审批生成流程
List<String> errorData = new ArrayList<>();
for (int i = 0; i < requestIds.size(); i++) {
if (Util.getIntValue(requestIds.get(i), -1) < 0) {
errorData.add(dataList.get(i));
try {
User logInUser = HrmUserVarify.getUser(request, response);
if(logInUser == null){
return ApiResult.error(403,"请先登录!");
}
String choiceData = request.getParameter("choiceData");
if(StringUtils.isBlank(choiceData)){
return ApiResult.error(403,"请勾选数据!");
}
int modelId = Util.getIntValue(request.getParameter("modelId"), -1);
String triggerWorkflowSetId = Util.null2DefaultStr(request.getParameter("triggerWorkflowSetId"), "");
String createDateField = Util.null2DefaultStr(request.getParameter("createDateField"), "");
if(modelId < 0 || StringUtils.isBlank(triggerWorkflowSetId) || StringUtils.isBlank(createDateField)){
logger.info(Util.logStr("modelId : {}, triggerWorkflowSetId : {}, createDateField : {}", modelId, triggerWorkflowSetId, createDateField));
return ApiResult.error(403,"api必要参数未配置!");
}
return ApiResult.success(JSONObject.toJSONString( createWorkFlowService.hrmCusCreateWorkFlow(choiceData, createDateField, triggerWorkflowSetId, modelId)));
}catch (Exception e){
logger.error(Util.logStr(e.getMessage()));
logger.error(Util.getErrString(e));
return ApiResult.error("接口发生异常!");
}
logger.error(Util.logStr("执行创建流程失败集合: {}",JSONObject.toJSONString(errorData))); // 构建日志字符串
return ApiResult.success(errorData);
}
@Path("gysCusCreateWorkFlow")
@POST
@Produces(MediaType.TEXT_PLAIN)
public String gysCusCreateWorkFlow(@Context HttpServletRequest request, @Context HttpServletResponse response) {
try {
User logInUser = HrmUserVarify.getUser(request, response);
if(logInUser == null){
return ApiResult.error(403,"请先登录!");
}
String choiceData = request.getParameter("choiceData");
if(StringUtils.isBlank(choiceData)){
return ApiResult.error(403,"请勾选数据!");
}
// 执行创建流程数据审批的模块id
int dataApprovalModelId = Util.getIntValue(request.getParameter("dataApprovalModelId"), -1);
// 待合并数据审批id
int createTriggerId = Util.getIntValue(request.getParameter("createTriggerId"), -1);
// 数据同步配置参数
String asyncCode = Util.null2DefaultStr(request.getParameter("asyncCode"), "");
// 带合并模块id
String dataModelId = Util.null2DefaultStr(request.getParameter("dataModelId"), "");
if(createTriggerId < 0 || StringUtils.isBlank(asyncCode) || dataApprovalModelId < 0 || StringUtils.isBlank(dataModelId)){
logger.info(Util.logStr("createTriggerId : {}, asyncCode : {}, dataApprovalModelId : {}", createTriggerId, asyncCode, dataApprovalModelId));
return ApiResult.error(403,"api必要参数未配置!");
}
return ApiResult.success(createWorkFlowService.supplierCusCreateWorkFlow(String.valueOf(createTriggerId), dataModelId, asyncCode, choiceData, dataApprovalModelId));
}catch (Exception e){
logger.error(Util.logStr(e.getMessage()));
logger.error(Util.getErrString(e));
return ApiResult.error("接口发生异常!");
}
}
}

View File

@ -0,0 +1,233 @@
package com.api.xuanran.wang.saic_travel.model_create_workflow.service;
import aiyh.utils.ApiResult;
import aiyh.utils.Util;
import aiyh.utils.excention.CustomerException;
import com.alibaba.fastjson.JSONObject;
import com.icbc.api.internal.apache.http.impl.cookie.S;
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.general.TimeUtil;
import weaver.xuanran.wang.common.mapper.CommonMapper;
import weaver.xuanran.wang.common.util.CommonUtil;
import weaver.xuanran.wang.common.util.CusInfoToOAUtil;
import weaver.xuanran.wang.saic_travel.model_data_async.config.eneity.DataAsyncDetail;
import weaver.xuanran.wang.saic_travel.model_data_async.config.eneity.DataAsyncMain;
import weaver.xuanran.wang.saic_travel.model_data_async.constant.DataAsyncConstant;
import weaver.xuanran.wang.saic_travel.model_data_async.service.DataAsyncConfigService;
import java.util.*;
import java.util.stream.Collectors;
/**
* <h1></h1>
*
* @Author xuanran.wang
* @Date 2022/12/15 14:33
*/
public class CreateWorkFlowService {
private final DataAsyncConfigService dataAsyncConfigService = new DataAsyncConfigService();
private final CommonMapper commonMapper = Util.getMapper(CommonMapper.class);
private final Logger logger = Util.getLogger();
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2022/12/15 17:07
* @param choiceData
* @param createDateField
* @param triggerWorkflowSetId id
* @param modelId id
* @return id
**/
public List<String> hrmCusCreateWorkFlow(String choiceData, String createDateField, String triggerWorkflowSetId, int modelId){
String name = commonMapper.getModelNameByModelId(String.valueOf(modelId));
List<String> dataList = Arrays.stream(choiceData.split(",")).collect(Collectors.toList());
RecordSet rs = new RecordSet();
List<List<String>> splitList = CommonUtil.splitList(dataList);
for (List<String> list : splitList) {
List<Integer> ids = list.stream().map(item -> Util.getIntValue(item, -1)).collect(Collectors.toList());
if(CollectionUtils.isEmpty(ids)){
continue;
}
String updateCreatDateSql = "update " + name + " set " + createDateField + " = '"+ TimeUtil.getCurrentDateString() +"' where id in ( " + StringUtils.join(ids,",") + " )";
if(!rs.executeUpdate(updateCreatDateSql)){
throw new CustomerException(Util.logStr("更新建模表数据失败!, 当前sql : {} ", updateCreatDateSql));
}
}
// 数据审批配置Id
String[] triggerIds = triggerWorkflowSetId.split(",");
logger.info("triggerIds : " + JSONObject.toJSONString(triggerIds));
List<String> errorData = new ArrayList<>();
for (String id : triggerIds) {
String sql = "select id from " + name;
String condition = commonMapper.getConditionByTriggerId(id);
if(StringUtils.isNotBlank(condition)){
sql += " where " + condition;
}
logger.info(Util.logStr("人员创建流程查询数据sql : {}", sql));
List<String> filterIds = filterIds(sql);
List<String> dataIds = dataList.stream().filter(filterIds::contains).collect(Collectors.toList());
if(CollectionUtils.isNotEmpty(dataIds)){
List<String> requestIds = CommonUtil.doCreateWorkFlow(modelId, dataIds, Util.getIntValue(id, -1)); // 通过数据审批生成流程
for (int i = 0; i < requestIds.size(); i++) {
if (Util.getIntValue(requestIds.get(i), -1) < 0) {
errorData.add(dataList.get(i));
}
}
}else {
logger.info("当前数据都不满足触发条件!");
}
logger.error(Util.logStr("人员创建流程执行创建流程失败集合: {}",JSONObject.toJSONString(errorData))); // 构建日志字符串
}
return errorData;
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2022/12/15 17:11
* @param createTriggerId id
* @param dataModelId id
* @param asyncCode
* @param choiceData
* @param dataApprovalModelId id
* @return requestId
**/
public String supplierCusCreateWorkFlow(String createTriggerId, String dataModelId, String asyncCode, String choiceData, int dataApprovalModelId){
// 查询来源数据待合并 数据审批配置
Map<String, String> configByTriggerId = commonMapper.getConfigByTriggerId(String.valueOf(createTriggerId));
if(MapUtils.isEmpty(configByTriggerId)){
return ApiResult.error(403,"请给模块id = [ "+createTriggerId + " ] 配置数据审批!");
}
// 待合并的表名
String dataTable = commonMapper.getModelNameByModelId(dataModelId);
String sql = "select id from " + dataTable;
// 触发条件
String condition = Util.null2DefaultStr(configByTriggerId.get("showcondition"), "");
String successWriteBack = Util.null2DefaultStr(configByTriggerId.get("successwriteback"), "");
if(StringUtils.isNotBlank(condition)){
sql += " where " + condition;
}
List<String> dataList = Arrays.stream(choiceData.split(",")).collect(Collectors.toList());
logger.info(Util.logStr("查询数据sql : {}", sql));
List<String> filterIds = filterIds(sql);
// 过滤之后的数据id
List<String> dataIds = dataList.stream().filter(filterIds::contains).collect(Collectors.toList());
List<String> requestIds = new ArrayList<>();
if(!CollectionUtils.isEmpty(dataIds)){
String dataId = asyncModelData(asyncCode, dataIds, dataApprovalModelId);
requestIds = CommonUtil.doCreateWorkFlow(dataApprovalModelId, Collections.singletonList(dataId));
if(CollectionUtils.isEmpty(requestIds)){
throw new CustomerException("流程创建失败!");
}
if(CollectionUtils.isNotEmpty(requestIds) && !(Util.getIntValue(requestIds.get(0),-1) < 0 && StringUtils.isNotBlank(successWriteBack))){
RecordSet rs = new RecordSet();
sql = "update " + dataTable + " set " + successWriteBack + " where " + Util.getSubINClause(StringUtils.join(dataIds, ","),"id"," in ");
if (!rs.executeUpdate(sql)) {
logger.error(Util.logStr("回写sql : {}", sql));
throw new CustomerException("流程创建成功, 但回写失败!");
}
}
return requestIds.get(0);
}else {
logger.info("当前数据都不满足触发条件!");
}
return "";
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2022/12/2 13:28
* @param configCode
* @param modelId id
**/
public String asyncModelData(String configCode, List<String> dataIds, int modelId) {
DataAsyncMain asyncConfig = dataAsyncConfigService.getDataAsyncConfigByUniqueCode(configCode);
String dataSource = asyncConfig.getDataSource();
String selectSql = dataAsyncConfigService.getSelectSql(asyncConfig);
List<DataAsyncDetail> asyncDetailList = asyncConfig.getDataAsyncDetailList();
selectSql += " where " + Util.getSubINClause(StringUtils.join(dataIds, ","),"id"," in ");
RecordSet rs = new RecordSet();
if (!rs.executeQuery(selectSql)) {
throw new CustomerException(Util.logStr("执行查询数据源sql失败! 当前sql:{}", selectSql));
}
// 主表同步配置条件
List<DataAsyncDetail> mainConfigList = asyncDetailList.stream().filter(item -> !DataAsyncConstant.DETAIL_TABLE.equals(item.getMainOrDetail())).collect(Collectors.toList());
List<DataAsyncDetail> detailConfigList = asyncDetailList.stream().filter(item -> DataAsyncConstant.DETAIL_TABLE.equals(item.getMainOrDetail())).collect(Collectors.toList());
String mainId = "";
if (rs.next()){
// 先把数据同步到主表
LinkedHashMap<String, Object> params = getValue(mainConfigList, rs, dataSource);
mainId = CusInfoToOAUtil.getDataId(modelId, params);
logger.info("生成建模mainId : " + mainId);
}
rs.executeQuery(selectSql);
ArrayList<LinkedHashMap<String, Object>> detailParams = new ArrayList<>();
while (rs.next()){
LinkedHashMap<String, Object> value = getValue(detailConfigList, rs, dataSource);
value.put("mainid", mainId);
detailParams.add(value);
}
CusInfoToOAUtil.executeDetailBatch(asyncConfig.getAsyncTargetModelTableName()+ "_dt" + asyncConfig.getDetailIndex(),detailParams);
return mainId;
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2022/12/15 16:29
* @param asyncDetailList
* @param rs
* @param dataSource
* @return
**/
public LinkedHashMap<String, Object> getValue(List<DataAsyncDetail> asyncDetailList, RecordSet rs, String dataSource){
LinkedHashMap<String, Object> map = new LinkedHashMap<>();
for (DataAsyncDetail dataAsyncDetail : asyncDetailList) {
String field = "";
switch (dataSource){
case DataAsyncConstant.DATA_SOURCE_MODEL:{
field = dataAsyncDetail.getDataSourceModelFiledName();
}break;
case DataAsyncConstant.DATA_SOURCE_CUS_TABLE:{
field = dataAsyncDetail.getCusTableField();
}break;
default:throw new CustomerException("暂不支持的数据来源");
}
// 同步建模字段
String asyncModelTableField = dataAsyncDetail.getAsyncModelTableField();
Object value = dataAsyncConfigService.getFieldValue(rs, field, dataAsyncDetail, 0);
map.put(asyncModelTableField, value);
}
if(MapUtils.isEmpty(map)){
throw new CustomerException("转换配置生成参数map为空!");
}
return map;
}
/**
* <h1>id</h1>
* @author xuanran.wang
* @dateTime 2022/12/15 13:22
* @param sql sql
* @return id
**/
public List<String> filterIds(String sql){
RecordSet rs = new RecordSet();
ArrayList<String> res = new ArrayList<>();
if (rs.executeQuery(sql)) {
while (rs.next()){
res.add(Util.null2DefaultStr(rs.getString(1),""));
}
}
return res;
}
}

View File

@ -1,9 +1,13 @@
package com.api.xuanran.wang.schroeder.download_file.controller;
import aiyh.utils.Util;
import aiyh.utils.excention.CustomerException;
import com.alibaba.fastjson.JSONObject;
import com.api.xuanran.wang.schroeder.download_file.service.DownLoadFileService;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import weaver.docs.docs.DocInfo;
import weaver.file.ImageFileManager;
import javax.servlet.http.HttpServletRequest;
@ -43,6 +47,9 @@ public class DownLoadFileController {
Map<String, Object> fileInfo = downLoadFileService.getFileInfo(docId);
String fileName = Util.null2String(fileInfo.get("fileName"));
int imageFileId = Util.getIntValue(Util.null2DefaultStr(fileInfo.get("imageFileId"),""), -1);
if(StringUtils.isBlank(fileName) || imageFileId < 0){
throw new CustomerException(Util.logStr("文件信息部分字段查询为空!当前查询结果map:[{}]", JSONObject.toJSONString(fileInfo)));
}
InputStream is = ImageFileManager.getInputStreamById(imageFileId);
byte[] bytes = IOUtils.toByteArray(is);
StreamingOutput output = outputStream ->{

View File

@ -1,33 +0,0 @@
package com.api.xuanran.wang.schroeder.download_file.mapper;
import aiyh.utils.annotation.recordset.ParamMapper;
import aiyh.utils.annotation.recordset.Select;
import aiyh.utils.annotation.recordset.SqlMapper;
import java.util.Map;
/**
* <h1>mapper</h1>
*
* @Author xuanran.wang
* @Date 2022/12/7 10:58
*/
@SqlMapper
public interface DownLoadFileMapper {
/**
* <h1>docId</h1>
* @author xuanran.wang
* @dateTime 2022/12/7 11:01
* @param docId docId
* @return imageField
**/
@Select("select t3.imagefileid imageFileId,t3.imagefilename fileName,t3.filerealpath filePath " +
"from DocDetail t1 " +
"left join DocImageFile t2 " +
"on t2.docid = t1.id " +
"left join ImageFile t3 " +
"on t3.imagefileid = t2.imagefileid " +
"where t1.id = #{docId}")
Map<String, Object> selectDocInfoByDocId(@ParamMapper("docId") String docId);
}

View File

@ -2,11 +2,11 @@ package com.api.xuanran.wang.schroeder.download_file.service;
import aiyh.utils.Util;
import aiyh.utils.excention.CustomerException;
import com.alibaba.fastjson.JSONObject;
import com.api.xuanran.wang.schroeder.download_file.mapper.DownLoadFileMapper;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;
import java.util.HashMap;
import java.util.Map;
/**
@ -24,7 +24,6 @@ public class DownLoadFileService {
* <h2>sql</h2>
**/
private static final String SELECT_DOC_LOG_SQL = "select 1 from " + DOC_LOG_TABLE_NAME + " where docId = ? and enable = 0";
private final DownLoadFileMapper downLoadFileMapper = Util.getMapper(DownLoadFileMapper.class);
/**
* <h1>docId</h1>
@ -33,23 +32,29 @@ public class DownLoadFileService {
* @param docId docId
**/
public Map<String, Object> getFileInfo(String docId) {
RecordSet rs = new RecordSet();
if(StringUtils.isBlank(docId)) {
throw new CustomerException(Util.logStr("下载文件失败, 请求路径中不包含指定的docId!当前请求docId:{}", docId));
}
RecordSet rs = new RecordSet();
if (!rs.executeQuery(SELECT_DOC_LOG_SQL, docId) || !rs.next()) {
throw new CustomerException("下载文件失败, 请确认文件记录表中是否存在docId = [ " + docId + " ]的文件!");
}
Map<String, Object> fileInfoMap = downLoadFileMapper.selectDocInfoByDocId(docId);
if(MapUtils.isEmpty(fileInfoMap)){
throw new CustomerException("执行查询文件信息sql失败!");
String sql = " select t3.imagefileid imageFileId,t3.imagefilename fileName " +
" from DocDetail t1 " +
" left join DocImageFile t2 " +
" on t2.docid = t1.id " +
" left join ImageFile t3 " +
" on t3.imagefileid = t2.imagefileid " +
" where t1.id = ?";
HashMap<String, Object> res = new HashMap<>();
if (rs.executeQuery(sql, docId) && rs.next()) {
res.put("imageFileId", rs.getString("imageFileId"));
res.put("fileName", rs.getString("fileName"));
}
String fileName = Util.null2DefaultStr(fileInfoMap.get("fileName"),"");
int imageFileId = Util.getIntValue(Util.null2DefaultStr(fileInfoMap.get("imageFileId"),""), -1);
if(StringUtils.isBlank(fileName) ||imageFileId < 0){
throw new CustomerException(Util.logStr("文件信息部分字段查询为空!当前查询结果map:[{}]", JSONObject.toJSONString(fileInfoMap)));
if(MapUtils.isEmpty(res)){
throw new CustomerException(Util.logStr("执行查询文件信息sql失败! 当前sql : {}", sql));
}
return fileInfoMap;
return res;
}

View File

@ -0,0 +1,92 @@
package weaver.xuanran.wang.bme.action;
import aiyh.utils.Util;
import aiyh.utils.action.SafeCusBaseAction;
import aiyh.utils.annotation.RequiredMark;
import aiyh.utils.excention.CustomerException;
import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSetTrans;
import weaver.hrm.User;
import weaver.soa.workflow.request.RequestInfo;
import java.util.Map;
/**
* <h1>action</h1>
*
* @Author xuanran.wang
* @Date 2022/12/20 11:33
*/
public class ContractApplyComDateAction extends SafeCusBaseAction {
/**
* <h2></h2>
**/
@RequiredMark
private String buildContractProjectField;
/**
* <h2></h2>
**/
@RequiredMark
private String buildContractTable;
/**
* <h2></h2>
**/
@RequiredMark
private String detailContractTable;
/**
* <h2></h2>
**/
@RequiredMark
private String detailContractDateFiled;
/**
* <h2></h2>
**/
@RequiredMark
private String projectField;
/**
* <h2></h2>
**/
@RequiredMark
private String checkDateField;
/**
* <h2></h2>
**/
private String updateWhere;
@Override
public void doSubmit(String requestId, String billTable, int workflowId, User user, RequestInfo requestInfo) {
log.info(Util.logStr("--------------- requestId : {} Begin ---------------", requestId));
RecordSetTrans rs = new RecordSetTrans();
rs.setAutoCommit(false);
try {
Map<String, String> mainTableValue = getMainTableValue(requestInfo);
// 验收流程的实际验收日期
String checkDate = mainTableValue.get(checkDateField);
String project = mainTableValue.get(projectField);
if(StringUtils.isBlank(checkDate) || StringUtils.isBlank(project)){
log.error(Util.logStr("checkDate:{}, project:{}", checkDate, project));
throw new CustomerException("实际验收日期或项目字段字段为空!");
}
String selectSql = "select id from " + buildContractTable + " where " + buildContractProjectField + " = ?";
if(rs.executeQuery(selectSql, project) && rs.next()){
String mainId = rs.getString("id");
String updateSql = "update " + detailContractTable + " set " + detailContractDateFiled + " = ? where mainid = ?";
if(StringUtils.isNotBlank(updateWhere)){
updateSql += " and " + updateWhere;
}
log.info(Util.logStr("更新合同明细表sql:{}, 参数:{}, {}", updateSql, checkDate, mainId));
if(!rs.executeUpdate(updateSql, checkDate, mainId)){
throw new CustomerException("更新合同sql错误!");
}
rs.commit();
}else{
log.error(Util.logStr("查询施工合同关联项目sql暂未查到数据! sql {} ,{}", selectSql, requestId));
}
}catch (Exception e){
rs.rollback();
throw new CustomerException(Util.logStr("更新施工合同实际验收日期发生异常: {} ", e.getMessage()));
}
}
}

View File

@ -0,0 +1,111 @@
package weaver.xuanran.wang.bme.action;
import aiyh.utils.Util;
import aiyh.utils.action.SafeCusBaseAction;
import aiyh.utils.annotation.RequiredMark;
import aiyh.utils.excention.CustomerException;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.hrm.User;
import weaver.soa.workflow.request.RequestInfo;
import weaver.xuanran.wang.common.util.CommonUtil;
import weaver.xuanran.wang.common.util.CusInfoToOAUtil;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* <h1></h1>
* <p>
* + 4 DUJE0101 DUJE0199 => DUJE0201
* </p>
*
* @Author xuanran.wang
* @Date 2022/12/22 13:18
*/
public class CusCreateWaterNoAction extends SafeCusBaseAction {
/**
* <h2></h2>
**/
@RequiredMark
private String invClassificationCode;
/**
* <h2> </h2>
**/
@RequiredMark
private String inventoryCode;
/**
* <h2>id</h2>
**/
private String serialNumberModelId;
private static final String START_NO = "0101";
@Override
public void doSubmit(String requestId, String billTable, int workflowId, User user, RequestInfo requestInfo) {
log.info("----------- CusCreateWaterNoAction Begin " + requestId + "-----------");
RecordSetTrans rsts = new RecordSetTrans();
rsts.setAutoCommit(false);
try {
Map<String, String> mainTableValue = getMainTableValue(requestInfo);
String invClassificationCodeVal = mainTableValue.get(invClassificationCode);
String nextInventoryCode = getNextInventoryCode(invClassificationCodeVal);
String updateSql = "update " + billTable + " set " + inventoryCode + " = ? where requestid = ?";
if(!rsts.executeUpdate(updateSql, nextInventoryCode, requestId)){
log.error(Util.logStr("sql :{}, nextInventoryCode : {}, requestId: {}", updateSql, nextInventoryCode, requestId));
throw new CustomerException("更新表单存货编码字段失败!");
}
}catch (Exception e){
throw new CustomerException(Util.logStr("生成存货编码Action异常: [{}]",e.getMessage()));
}
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2022/12/22 14:08
* @param inventoryCode
* @return +
**/
private synchronized String getNextInventoryCode(String inventoryCode){
RecordSet rs = new RecordSet();
String modelTableName = CommonUtil.getModelTableNameById(Util.getIntValue(serialNumberModelId, -1));
String sql = "select max(serialNumber) serialNumber from " + modelTableName + " where invClassificationCode = ? order by createDateTime";
String res = "";
if(rs.executeQuery(sql, inventoryCode)){
if (!rs.next()) {
res = inventoryCode + START_NO;
}else {
String serialNumber = rs.getString(1);
String front = serialNumber.substring(0,2);
String end = serialNumber.substring(3);
int frontInt = Util.getIntValue(front);
int endInt = Util.getIntValue(end);
String endStr = "";
String frontStr = "";
if(++endInt >= 100){
frontInt += 1;
endInt = 1;
}
if(endInt < 10){
endStr = "0" + endInt;
}
if(frontInt < 10){
frontStr = "0" + frontInt;
}
res = frontStr + endStr;
}
}
LinkedHashMap<String, Object> map = new LinkedHashMap<>();
map.put("invClassificationCode", inventoryCode);
map.put("serialNumber", res);
map.put("serialCode", inventoryCode + res);
CusInfoToOAUtil.getDataId(Util.getIntValue(serialNumberModelId, -1), map);
return res;
}
}

View File

@ -50,4 +50,11 @@ public interface CommonMapper {
"ON mp.id = mpd.mainId " +
"WHERE mp.modeid = #{modelId} AND mp.isSystem = 1 AND mp.iSSystemFlag = 1")
Map<String, Integer> getExpendConfigByModeId(@ParamMapper("modelId") int modelId);
@Select("select * from mode_triggerworkflowset where id = #{triggerId}")
Map<String, String> getConfigByTriggerId(@ParamMapper("triggerId") String triggerId);
@Select("select showcondition from mode_triggerworkflowset where id = #{triggerId}")
String getConditionByTriggerId(@ParamMapper("triggerId") String triggerId);
}

View File

@ -12,6 +12,8 @@ import org.apache.log4j.Logger;
import weaver.conn.RecordSet;
import weaver.formmode.data.ModeDataApproval;
import weaver.hrm.User;
import weaver.xiao.commons.config.entity.RequestMappingConfig;
import weaver.xiao.commons.config.service.DealWithMapping;
import weaver.xuanran.wang.common.annocation.CusDateFormat;
import weaver.xuanran.wang.common.annocation.ParamNotNull;
import weaver.xuanran.wang.common.mapper.CommonMapper;
@ -232,6 +234,16 @@ public class CommonUtil {
}
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2022/11/25 16:01
* @param list
* @return
**/
public static <T> List<List<T>> splitList(List<T> list) {
return splitList(list, SQL_IN_PAGE_SIZE);
}
/**
* <h1></h1>
* @author xuanran.wang
@ -337,6 +349,9 @@ public class CommonUtil {
* @return true/false
**/
public static boolean deleteDataByIds(List<String> ids, String tableName,int pageSize) {
if(CollectionUtils.isEmpty(ids)){
return true;
}
List<List<String>> lists = CommonUtil.splitList(ids, pageSize);
for (List<String> list : lists) {
boolean success = commonMapper.deleteModelDataByIds(tableName, list);
@ -526,4 +541,77 @@ public class CommonUtil {
return requestIds;
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2022/12/1 21:14
* @param modeId id
* @param dataIds id
* @param triggerWorkflowSetId id
**/
public static List<String> doCreateWorkFlow(int modeId, List<String> dataIds, int triggerWorkflowSetId){
if(modeId < 0){
throw new CustomerException("模块id不能小于0!");
}
if(triggerWorkflowSetId < 0){
throw new CustomerException("自定义数据审批id不能小于0!");
}
if(org.springframework.util.CollectionUtils.isEmpty(dataIds)){
logger.info("暂无数据要生成流程!");
return Collections.emptyList();
}
Map<String, Integer> expendConfig = commonMapper.getExpendConfigByModeId(modeId);
logger.info(Util.logStr("expendConfig {}", JSONObject.toJSONString(expendConfig)));
int expendId = expendConfig.get("id");
int formId = expendConfig.get("formId");
ArrayList<String> requestIds = new ArrayList<>();
if(expendId > 0 && triggerWorkflowSetId > 0){
for (String daId : dataIds) {
ModeDataApproval modeDataApproval = new ModeDataApproval();
modeDataApproval.setUser(new User(1));
modeDataApproval.setBillid(Util.getIntValue(daId));
modeDataApproval.setFormid(formId);
modeDataApproval.setModeid(modeId);
modeDataApproval.setTriggerWorkflowSetId(triggerWorkflowSetId);
modeDataApproval.setPageexpandid(expendId);
Map<String, String> resMap = modeDataApproval.approvalDataResult();
logger.info(Util.logStr("模块数据id : {}, 创建流程结果 : {}", daId, JSONObject.toJSONString(resMap)));
requestIds.add(Util.null2String(resMap.get("requestid")));
}
}
return requestIds;
}
/**
* <h1>id</h1>
* @author xuanran.wang
* @dateTime 2022/12/22 14:18
* @param modelId id
* @return
**/
public static String getModelTableNameById(int modelId){
if(modelId < 0){
throw new CustomerException("模块id不能小于0!");
}
return commonMapper.getModelNameByModelId(String.valueOf(modelId));
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2023/1/4 15:10
* @param requestMappingConfig
* @param tableName
* @return sql
**/
public static String getSelectSql( RequestMappingConfig requestMappingConfig, String tableName){
String cusWhere = Util.null2DefaultStr(requestMappingConfig.getCusWhereSql(), "");
if (StringUtils.isNotBlank(cusWhere)) {
cusWhere = " and " + DealWithMapping.sbc2dbcCase(cusWhere); // 全角转半角
}
return "select * from " + tableName + " where requestid = ? " + cusWhere;
}
}

View File

@ -16,6 +16,7 @@ import weaver.general.TimeUtil;
import weaver.xuanran.wang.common.mapper.CommonMapper;
import java.util.*;
import java.util.stream.Collectors;
/**
* @Author xuanran.wang
@ -26,7 +27,7 @@ public class CusInfoToOAUtil {
private static final ModeDataIdUpdate modeDataIdUpdate = ModeDataIdUpdate.getInstance();
private static final ModeRightInfo moderightinfo = new ModeRightInfo();
private static final Logger log = Util.getLogger();
public static final String TABLE_NAME_PLACEHOLDER = "#\\{tableName}";
private static final String TABLE_NAME_PLACEHOLDER = "#\\{tableName}";
/**
* <h1></h1>
@ -74,7 +75,7 @@ public class CusInfoToOAUtil {
String whereSql,
List<String> whereParams,
boolean needDel) {
return executeBatch(modelId, Collections.singletonList(new LinkedHashMap<>(params)), whereSql, whereParams, needDel).get(0);
return executeBatch(modelId, Collections.singletonList(new LinkedHashMap<>(params)), whereSql,Collections.singletonList(whereParams), needDel, Collections.emptyList()).get(0);
}
/**
@ -87,7 +88,7 @@ public class CusInfoToOAUtil {
**/
public static List<String> executeBatch( int modelId,
List<LinkedHashMap<String, Object>> params) {
return executeBatch(modelId, params, "", Collections.emptyList(), true);
return executeBatch(modelId, params, "", Collections.emptyList());
}
/**
@ -111,8 +112,13 @@ public class CusInfoToOAUtil {
if(StringUtils.isBlank(tableName)){
throw new CustomerException("模块id为 " + modelId + ", 在系统中暂没查询到对应表单!");
}
return executeBatch(modelId, tableName, params, whereSql, whereParams, true);
ArrayList<List<String>> lists = new ArrayList<>();
for (String param : whereParams) {
lists.add(new ArrayList<>(Collections.singleton(param)));
}
return executeBatch(modelId, tableName, params, whereSql, lists, true, Collections.emptyList());
}
/**
* <h1></h1>
* @author xuanran.wang
@ -124,11 +130,12 @@ public class CusInfoToOAUtil {
* @param needDel
* @return id
**/
public static List<String> executeBatch( int modelId,
List<LinkedHashMap<String, Object>> params,
String whereSql,
List<String> whereParams,
boolean needDel) {
public static List<String> executeBatch( int modelId,
List<LinkedHashMap<String, Object>> params,
String whereSql,
List<List<String>> whereParams,
boolean needDel,
List<LinkedHashMap<String, Object>> updateParams) {
if(modelId < 0){
throw new RuntimeException("建模模块id不能小于0!");
}
@ -136,7 +143,7 @@ public class CusInfoToOAUtil {
if(StringUtils.isBlank(tableName)){
throw new CustomerException("模块id为 " + modelId + ", 在系统中暂没查询到对应表单!");
}
return executeBatch(modelId, tableName, params, whereSql, whereParams, needDel);
return executeBatch(modelId, tableName, params, whereSql, whereParams, needDel, updateParams);
}
/**
@ -149,57 +156,75 @@ public class CusInfoToOAUtil {
* @param whereSql sql
* @param whereParams
* @param needDel
* @param updateParams
* @return id
**/
public static List<String> executeBatch( int modelId,
String tableName,
List<LinkedHashMap<String, Object>> params,
String whereSql,
List<String> whereParams,
boolean needDel) {
List<List<String>> whereParams,
boolean needDel,
List<LinkedHashMap<String, Object>> updateParams) {
// 如果要对模块数据中重复的进行更新则判断待插入的集合大小和判断重复的集合大小参数长度是否一致
if(StringUtils.isNotBlank(whereSql)){
if(CollectionUtils.isEmpty(whereParams) || CollectionUtils.isEmpty(params) || whereParams.size() != params.size()){
log.error(Util.logStr("params : {}", JSONObject.toJSONString(params)));
log.error(Util.logStr("whereSql : {}", whereSql));
log.error(Util.logStr("whereParams : {} ", JSONObject.toJSONString(whereParams)));
log.error(Util.logStr("updateParams : {} ", updateParams));
throw new CustomerException("使用批量更新时如果需要对重复数据进行更新,参数集合和判断重复参数集合大小必须相等!");
}
}
RecordSet rs = new RecordSet();
List<String> dataIds = new ArrayList<>();
List<Where> wheres = new ArrayList<>();
List<Where> paramsWheres = new ArrayList<>();
List<Where> updateWheres = new ArrayList<>();
whereSql = Util.sbc2dbcCase(whereSql);
whereSql = whereSql.replaceAll(TABLE_NAME_PLACEHOLDER, tableName);
// 需要插入的建模参数
List<LinkedHashMap<String, Object>> tempParams = new ArrayList<>();
// 如果建模中已经存在只想更新部分字段参数
List<LinkedHashMap<String, Object>> tempUpdateParams = new ArrayList<>();
for (int i = 0; i < params.size(); i++) {
int mainId = -1;
if(StringUtils.isNotBlank(whereSql)){
whereSql = Util.sbc2dbcCase(whereSql);
whereSql = whereSql.replaceAll(TABLE_NAME_PLACEHOLDER, tableName);
if (rs.executeQuery(whereSql, whereParams) && rs.next()) {
// 如果匹配到数据
if (rs.executeQuery(whereSql, whereParams.get(i)) && rs.next()) {
mainId = Util.getIntValue(rs.getString(1),-1);
updateWheres.add(Util.createPrepWhereImpl().whereAnd("id").whereEqual(mainId));
dataIds.add(String.valueOf(mainId));
if(!CollectionUtils.isEmpty(updateParams)){
tempUpdateParams.add(updateParams.get(i));
}else {
tempUpdateParams.add(params.get(i));
}
}else {
log.info("whereSql : " + whereSql);
log.info("参数 : " + whereParams);
log.info(Util.logStr("==== 未匹配到数据 ==== whereSql : {}, 参数 : {}", whereSql, JSONObject.toJSONString(whereParams.get(i))));
}
}
if(mainId < 0){
mainId = getNewIdByModelInfo(tableName, modelId);
paramsWheres.add(Util.createPrepWhereImpl().whereAnd("id").whereEqual(mainId));
dataIds.add(String.valueOf(mainId));
tempParams.add(params.get(i));
}
dataIds.add(String.valueOf(mainId));
wheres.add(Util.createPrepWhereImpl().whereAnd("id").whereEqual(mainId));
}
BatchSqlResultImpl batchSql = Util.createSqlBuilder().updateBatchSql(tableName, params, wheres);
String sqlStr = batchSql.getSqlStr();
List<List> batchList = batchSql.getBatchList();
if(!rs.executeBatchSql(sqlStr, batchList)){
log.error(Util.logStr("batchSql:{}", sqlStr));
log.error(Util.logStr("batchList:{}", JSONObject.toJSONString(batchList)));
log.error(Util.logStr("whereList:{}", JSONObject.toJSONString(wheres)));
try {
if(CollectionUtils.isNotEmpty(tempParams) && CollectionUtils.isNotEmpty(paramsWheres)){
execute(tableName, tempParams, paramsWheres);
}
if(CollectionUtils.isNotEmpty(tempUpdateParams) && CollectionUtils.isNotEmpty(updateWheres)){
execute(tableName, tempUpdateParams, updateWheres);
}
}catch (Exception e){
if(needDel){
if (!deleteModelDataByIds(String.valueOf(modelId), dataIds)) {
log.error(Util.logStr("删除数据失败!未删除数据集合:{}", JSONObject.toJSONString(dataIds)));
}
}
throw new CustomerException("执行批量更新sql失败!");
}
if(CollectionUtils.isEmpty(dataIds)){
throw new CustomerException("建模数据生成失败!");
throw new CustomerException(e.getMessage());
}
for (String dataId : dataIds) {
moderightinfo.rebuildModeDataShareByEdit(1, modelId, Integer.parseInt(dataId));
@ -207,6 +232,49 @@ public class CusInfoToOAUtil {
return dataIds;
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2022/11/23 17:00
* @param tableName
* @param params map
* @return id
**/
public static boolean executeDetailBatch(String tableName, List<LinkedHashMap<String, Object>> params){
RecordSet rs = new RecordSet();
BatchSqlResultImpl batchSql = Util.createSqlBuilder().insertBatchSql(tableName, params);
String sqlStr = batchSql.getSqlStr();
List<List> list = batchSql.getBatchList();
if (!rs.executeBatchSql(sqlStr, list)) {
throw new CustomerException(Util.logStr("明细数据插入失败! sql : {}, params : {}", sqlStr, JSONObject.toJSONString(list)));
}
return true;
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2022/12/15 10:53
* @param tableName
* @param params
* @param wheres where
**/
public static void execute(String tableName, List<LinkedHashMap<String, Object>> params, List<Where> wheres){
// log.info(Util.logStr("params : [{}],size : [{}]", JSONObject.toJSONString(params), params.size()));
// log.info(Util.logStr("wheres : [{}],size : [{}]", JSONObject.toJSONString(wheres), wheres.size()));
BatchSqlResultImpl batchSql = Util.createSqlBuilder().updateBatchSql(tableName, params, wheres);
String sqlStr = batchSql.getSqlStr();
List<List> batchList = batchSql.getBatchList();
RecordSet rs = new RecordSet();
if(!rs.executeBatchSql(sqlStr, batchList)){
log.error(Util.logStr("batchSql:{}", sqlStr));
log.error(Util.logStr("batchList:{}", JSONObject.toJSONString(batchList)));
log.error(Util.logStr("whereList:{}", JSONObject.toJSONString(wheres)));
throw new CustomerException("执行批量更新sql失败!请查看后台cus日志!");
}
}
/**
* <h1></h1>
* @author xuanran.wang
@ -219,6 +287,14 @@ public class CusInfoToOAUtil {
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();
//日期

View File

@ -0,0 +1,65 @@
package weaver.xuanran.wang.epdi.asset.action;
import aiyh.utils.Util;
import aiyh.utils.action.SafeCusBaseAction;
import aiyh.utils.annotation.PrintParamMark;
import aiyh.utils.annotation.RequiredMark;
import aiyh.utils.excention.CustomerException;
import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;
import weaver.hrm.User;
import weaver.soa.workflow.request.RequestInfo;
import weaver.xuanran.wang.epdi.asset.service.AssetDataPushService;
/**
* <h1>action</h1>
*
* @Author xuanran.wang
* @Date 2022/12/26 11:11
*/
public class AssetDataPushAction extends SafeCusBaseAction {
/**
* <h2></h2>
**/
@RequiredMark
@PrintParamMark
private String uniqueCode;
/**
* <h2></h2>
**/
@PrintParamMark
private String backField;
/**
* <h2>token</h2>
**/
@RequiredMark
@PrintParamMark
private String tokenUniqueCode;
/**
* <h2></h2>
* <p>
*
* </p>
**/
@PrintParamMark
private String tableField;
private final AssetDataPushService assetDataPushService = new AssetDataPushService();
@Override
public void doSubmit(String requestId, String billTable, int workflowId, User user, RequestInfo requestInfo) {
try {
log.info("----------------- AssetDataPushAction Begin " + requestId + " -----------------");
RecordSet updateRs = new RecordSet();
String backVal = assetDataPushService.dataPush(uniqueCode, tokenUniqueCode, requestId, backField);
// 如果接口响应字段值不为空并且表单回写字段不为空
if(StringUtils.isNotBlank(backVal) && StringUtils.isNotBlank(tableField)){
String updateSql = "update " + billTable + " set " + tableField + " = ? where requestid = ?";
if (!updateRs.executeUpdate(updateSql, backVal, requestId)) {
log.error(Util.logStr("更新表单sql : {}, 接口响应参数 : {}, 请求id : {}", backVal, requestId));
throw new CustomerException("接口数据回写表单失败!");
}
}
}catch (Exception e){
throw new CustomerException(Util.logStr("数据推送action异常 : {}", e.getMessage()));
}
}
}

View File

@ -0,0 +1,111 @@
package weaver.xuanran.wang.epdi.asset.service;
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 com.fasterxml.jackson.core.JsonProcessingException;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import weaver.xuanran.wang.epdi.datapush.eneity.MainRequestConfig;
import weaver.xuanran.wang.epdi.datapush.service.RequestPushService;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.util.Map;
/**
* <h1></h1>
*
* @Author xuanran.wang
* @Date 2022/12/26 11:13
*/
public class AssetDataPushService {
/**
* <h2></h2>
**/
private static final String MESSAGE_FIELD = "repmsg";
/**
* <h2></h2>
**/
private static final String SUCCESS_CODE = "1";
/**
* <h2></h2>
**/
private static final String SUCCESS_CODE_FIELD = "repcode";
private static final String TOKEN_FIELD = "token";
private final RequestPushService requestPushService = new RequestPushService();
private final HttpUtils httpUtils = new HttpUtils();
{
httpUtils.getGlobalCache().header.put("Content-Type", MediaType.APPLICATION_JSON); // 全局请求头
}
private final Logger log = Util.getLogger();
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2022/12/26 14:21
* @param uniqueCode
* @param tokenUniqueCode token
* @param requestId id
* @param backField
* @return
**/
public String dataPush(String uniqueCode, String tokenUniqueCode, String requestId, String backField){
String token = dataPush(tokenUniqueCode, requestId, TOKEN_FIELD);
log.info(Util.logStr("token : [{}]", token));
httpUtils.getGlobalCache().header.put("token", token);
return dataPush(uniqueCode, requestId, backField);
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2022/12/26 11:27
* @param uniqueCode
* @param requestId id
* @param backField
* @return
**/
private String dataPush(String uniqueCode, String requestId, String backField){
String res = "";
MainRequestConfig config = requestPushService.getRequestPushConfigByUniqueCode(uniqueCode);
Map<String, Object> requestParam = requestPushService.getRequestParam(config, requestId);
String url = config.getRequestUrl();
Map<String, String> headers = httpUtils.getGlobalCache().header;// 全局请
ResponeVo responseVo = null;
try {
responseVo = httpUtils.apiPost(url, requestParam);
} catch (IOException e) {
throw new CustomerException(Util.logStr("发送请求发生异常! : {}", e.getMessage())); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串
}
if (responseVo.getCode() != 200) { // 相应状态码
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(requestParam), JSON.toJSONString(headers), responseVo.getCode(), // 相应状态码
responseVo.getEntityString())); // 相应内容
throw new CustomerException(Util.logStr("can not fetch [{}]", url)); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串
}
Map<String, Object> response;
try {
response = responseVo.getEntityMap(); // 根据相应结果转化为map集合
} catch (JsonProcessingException e) {
log.error(Util.logStr("push data error, can not parse response to map" + // 构建日志字符串
"this response is [{}], url is [{}]request params is [{}] request heard is [{}];",
responseVo.getEntityString(), url, JSON.toJSONString(requestParam), JSON.toJSONString(headers))); // 相应内容
throw new CustomerException(Util.logStr("push data error, can not parse response to map")); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串
}
String successCode = Util.null2DefaultStr(response.get(SUCCESS_CODE_FIELD), "");
if (!successCode.equals(SUCCESS_CODE)) {
throw new CustomerException(Util.logStr("接口响应码不为 : [{}],接口响应信息: {}", successCode, Util.null2DefaultStr(response.get(MESSAGE_FIELD), ""))); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串
}
if(StringUtils.isNotBlank(backField)){
res = Util.null2DefaultStr(response.get(backField), "");
if (StringUtils.isBlank(res)) {
throw new CustomerException("获取接口中指定返回字段 [ " + backField+ " ] 为空, 请检查!"); // 自定义异常类 create 2022/3/9 2:20 PM
}
}
return res;
}
}

View File

@ -0,0 +1,94 @@
package weaver.xuanran.wang.epdi.datapush.constant;
/**
* <h1>uf_request_push</h1>
*
* @Author xuanran.wang
* @Date 2022/12/1 14:18
*/
public class RequestPushConstant {
/**
* <h2></h2>
**/
public static final String MODEL_TABLE_NAME = "uf_request_push";
/**
* <h2>-</h2>
**/
public static final String PARAM_NODE_TYPE_GENERAL = "0";
/**
* <h2>-</h2>
**/
public static final String PARAM_NODE_TYPE_OBJ = "1";
/**
* <h2>-</h2>
**/
public static final String PARAM_NODE_TYPE_LIST = "2";
/**
* <h2></h2>
**/
public static final String CONFIG_ENABLE = "0";
/**
* <h2>-String</h2>
**/
public static final String DATA_TYPE_STRING = "0";
/**
* <h2>-Int</h2>
**/
public static final String DATA_TYPE_INT = "1";
/**
* <h2>-Double</h2>
**/
public static final String DATA_TYPE_DOUBLE = "2";
/**
* <h2>-Date</h2>
**/
public static final String DATA_TYPE_DATE = "3";
/**
* <h2>-DateTime</h2>
**/
public static final String DATA_TYPE_DATE_TIME = "4";
/**
* <h2>-</h2>
**/
public static final String DATA_TYPE_CUS_DATE = "7";
/**
* <h2>-</h2>
**/
public static final String DATA_TYPE_TIME_TIMESTAMP = "8";
/**
* <h2>-</h2>
**/
public static final String CONVERT_RULES_TABLE_FIELD = "0";
/**
* <h2>-</h2>
**/
public static final String CONVERT_RULES_DEFAULT = "1";
/**
* <h2>-SQL</h2>
**/
public static final String CONVERT_RULES_NOW_TIME = "3";
/**
* <h2>-</h2>
**/
public static final String CONVERT_RULES_CUS_SQL = "4";
/**
* <h2>-requestId</h2>
**/
public static final String CONVERT_RULES_REQUEST_ID = "5";
/**
* <h2>-id</h2>
**/
public static final String CONVERT_RULES_DATA_ID = "6";
/**
* <h2></h2>
**/
public static final String DATASOURCE_MAIN_TABLE = "0";
/**
* <h2></h2>
**/
public static final String DATASOURCE_DETAIL_TABLE = "1";
/**
* <h2></h2>
**/
public static final String ROOT_NODE = "";
}

View File

@ -0,0 +1,27 @@
package weaver.xuanran.wang.epdi.datapush.eneity;
import lombok.Data;
import java.util.List;
/**
* <h1></h1>
*
* @Author xuanran.wang
* @Date 2022/12/23 16:20
*/
@Data
public class DetailRequestConfig {
private String paramName;
private String paramNodeType;
private String detailIndex;
private String parentName;
private String paramType;
private String getValueType;
private String valueContext;
private String workFlowField;
private String dataSource;
private String workFlowFieldName;
private List<DetailRequestConfig> detailRequestConfigList;
}

View File

@ -0,0 +1,24 @@
package weaver.xuanran.wang.epdi.datapush.eneity;
import lombok.Data;
import java.util.List;
/**
* <h1></h1>
*
* @Author xuanran.wang
* @Date 2022/12/23 16:20
*/
@Data
public class MainRequestConfig {
private String id;
private String uniqueCode;
private String workflow;
private String requestUrl;
private String cusSql;
private String enable;
private String tableName;
private List<DetailRequestConfig> detailRequestConfigList;
}

View File

@ -0,0 +1,50 @@
package weaver.xuanran.wang.epdi.datapush.mapper;
import aiyh.utils.annotation.recordset.CaseConversion;
import aiyh.utils.annotation.recordset.ParamMapper;
import aiyh.utils.annotation.recordset.Select;
import aiyh.utils.annotation.recordset.SqlMapper;
import weaver.xuanran.wang.epdi.datapush.constant.RequestPushConstant;
import weaver.xuanran.wang.epdi.datapush.eneity.DetailRequestConfig;
import weaver.xuanran.wang.epdi.datapush.eneity.MainRequestConfig;
import java.util.List;
/**
* <h1>mapper</h1>
*
* @Author xuanran.wang
* @Date 2022/12/1 14:35
*/
@SqlMapper
public interface RequestPushMapper {
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2022/12/1 14:39
* @return
**/
@Select("select a.*,b.tablename tableName " +
"from "+ RequestPushConstant.MODEL_TABLE_NAME +" a " +
"left join workflow_table_view b " +
"on a.workFlow = b.id " +
"where uniqueCode = #{uniqueCode} and enable = " + RequestPushConstant.CONFIG_ENABLE)
@CaseConversion(value = false)
MainRequestConfig getRequestPushMainConfig(@ParamMapper("uniqueCode") String uniqueCod);
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2022/12/1 14:40
* @param mainId id
* @return
**/
@Select("select a.*,b.fieldname workFlowFieldName " +
"from "+ RequestPushConstant.MODEL_TABLE_NAME + "_dt1 a " +
"left join workflow_field_table_view b " +
"on a.workFlowField = b.id " +
"where mainid = #{mainId} and enable = " + RequestPushConstant.CONFIG_ENABLE)
@CaseConversion(value = false)
List<DetailRequestConfig> getRequestPushDetailConfig(@ParamMapper("mainId") String mainId);
}

View File

@ -0,0 +1,401 @@
package weaver.xuanran.wang.epdi.datapush.service;
import aiyh.utils.Util;
import aiyh.utils.excention.CustomerException;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.util.Assert;
import weaver.conn.RecordSet;
import weaver.xuanran.wang.epdi.datapush.constant.RequestPushConstant;
import weaver.xuanran.wang.epdi.datapush.eneity.DetailRequestConfig;
import weaver.xuanran.wang.epdi.datapush.eneity.MainRequestConfig;
import weaver.xuanran.wang.epdi.datapush.mapper.RequestPushMapper;
import weaver.zwl.common.ToolUtil;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
/**
* <h1></h1>
*
* @Author xuanran.wang
* @Date 2022/12/23 16:20
*/
public class RequestPushService {
private final RequestPushMapper requestPushMapper = Util.getMapper(RequestPushMapper.class);
private String tempTableName = "";
private final ToolUtil toolUtil = new ToolUtil();
private final Logger logger = Util.getLogger();
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2022/12/1 15:09
* @param uniqueCode
* @return
**/
public MainRequestConfig getRequestPushConfigByUniqueCode(String uniqueCode){
MainRequestConfig requestPushMainConfig = requestPushMapper.getRequestPushMainConfig(uniqueCode);
Assert.notNull(requestPushMainConfig,"主表配置对象获取为空, 请检查!");
List<DetailRequestConfig> requestPushDetailConfig = requestPushMapper.getRequestPushDetailConfig(requestPushMainConfig.getId());
Assert.notEmpty(requestPushDetailConfig, "明细表配置集合获取为空, 请检查!");
requestPushMainConfig.setDetailRequestConfigList(requestPushDetailConfig);
return requestPushMainConfig;
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2022/12/23 17:17
* @param mainRequestConfig
* @param requestId id
* @return map
**/
public Map<String, Object> getRequestParam(MainRequestConfig mainRequestConfig, String requestId){
HashMap<String, Object> res = new HashMap<>();
// 请求配置的表
try {
List<DetailRequestConfig> configList = mainRequestConfig.getDetailRequestConfigList();
// 过滤根节点
List<DetailRequestConfig> rootNodeList = configList
.stream()
.filter(item -> RequestPushConstant.ROOT_NODE.equals(item.getParentName()))
.collect(Collectors.toList());
// 设置子节点
for (DetailRequestConfig detailRequestConfig : rootNodeList) {
setChildList(detailRequestConfig, configList);
}
String workflowType = mainRequestConfig.getWorkflow();
if(StringUtils.isBlank(workflowType)){
setObjValue(rootNodeList, res, null, null);
}else {
String mainTableName = mainRequestConfig.getTableName();
this.tempTableName = mainTableName;
RecordSet mainRs = new RecordSet();
String sql = "select * from " + mainTableName + " where requestid = ?";
if (mainRs.executeQuery(sql,requestId)) {
if (mainRs.next()) {
setObjValue(rootNodeList, res, mainRs, null);
}
}
}
}catch (Exception e){
throw new RuntimeException("执行getRequestParam发生异常 : " + e.getMessage());
}
return res;
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2022/12/23 17:16
* @param detailRequestConfig
* @param detailRequestConfigList
**/
private void setChildList(DetailRequestConfig detailRequestConfig, List<DetailRequestConfig> detailRequestConfigList){
try {
// 节点类型
String paramNodeType = detailRequestConfig.getParamNodeType();
// 参数名称
String paramName = detailRequestConfig.getParamName();
// 递归设置子节点
if(!RequestPushConstant.PARAM_NODE_TYPE_GENERAL.equals(paramNodeType)){
List<DetailRequestConfig> childList =
detailRequestConfigList.stream().filter(
config -> paramName.equals(config.getParentName())
).collect(Collectors.toList());
detailRequestConfig.setDetailRequestConfigList(childList);
for (DetailRequestConfig requestConfig : childList) {
setChildList(requestConfig, detailRequestConfigList);
}
}
}catch (Exception e){
throw new RuntimeException("执行setChildList发生异常 : " + e.getMessage());
}
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2022/12/23 17:25
* @param configList
* @param res map
* @param mainRs
* @param detailRs
**/
private void setObjValue(List<DetailRequestConfig> configList, HashMap<String, Object> res, RecordSet mainRs, RecordSet detailRs) {
try {
for (DetailRequestConfig requestConfig : configList) {
// 参数类型
String paramType = requestConfig.getParamNodeType();
String paramName = requestConfig.getParamName();
List<DetailRequestConfig> childConfigList = requestConfig.getDetailRequestConfigList();
// 集合
if (RequestPushConstant.PARAM_NODE_TYPE_LIST.equals(paramType)) {
List<Object> list = new ArrayList<>();
setListValue(requestConfig,childConfigList, list, mainRs);
res.put(paramName, list);
} else if (RequestPushConstant.PARAM_NODE_TYPE_OBJ.equals(paramType)) {
// 对象
HashMap<String, Object> map = new HashMap<>();
this.setObjValue(childConfigList, map, mainRs, detailRs);
}else{
// 普通对象
Object value = setCommonParamValue(requestConfig, mainRs, detailRs);
res.put(paramName, value);
}
}
}catch (Exception e){
throw new RuntimeException("执行setObjValue发生异常 : " + e.getMessage());
}
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2022/12/23 17:26
* @param detailRequestConfig
* @param childList
* @param list
* @param mainRs
**/
private void setListValue(DetailRequestConfig detailRequestConfig,
List<DetailRequestConfig> childList,
List<Object> list,
RecordSet mainRs) {
try {
// 子项数据来源
String dataSource = detailRequestConfig.getDataSource();
// 主表
if (RequestPushConstant.DATASOURCE_MAIN_TABLE.equals(dataSource)) {
HashMap<String, Object> map = new HashMap<>();
this.setObjValue(childList, map, mainRs, null);
list.add(map);
}else if(RequestPushConstant.DATASOURCE_DETAIL_TABLE.equals(dataSource)){
// 子表
int mainId = weaver.general.Util.getIntValue(mainRs.getString("id"));
String sql = "select * from " + tempTableName + "_dt" + detailRequestConfig.getDetailIndex() + " where mainid = " + mainId;
RecordSet detailRs = new RecordSet();
if(detailRs.executeQuery(sql)){
while (detailRs.next()) {
HashMap<String, Object> map = new HashMap<>();
this.setObjValue(childList, map, mainRs, detailRs);
list.add(map);
}
}
}
}catch (Exception e){
throw new RuntimeException("执行setListValue发生异常 : " + e.getMessage());
}
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2022/12/23 17:27
* @param detailRequestConfig
* @param mainRs
* @param detailRs
* @return
**/
private Object setCommonParamValue(DetailRequestConfig detailRequestConfig, RecordSet mainRs, RecordSet detailRs){
String paramType = detailRequestConfig.getParamType();
String getValueType = detailRequestConfig.getGetValueType();
String valueContext = detailRequestConfig.getValueContext();
String dataSource = detailRequestConfig.getDataSource();
String paramName = detailRequestConfig.getParamName();
String requestId = "";
int mainId = -1;
if(null != mainRs){
requestId = mainRs.getString("requestid");
mainId = Util.getIntValue(mainRs.getString("id"));
}
int detailId = -1;
if(null != detailRs){
detailId = Util.getIntValue(detailRs.getString("id"));
}
Object value = "";
switch (getValueType) {
// 流程字段
case RequestPushConstant.CONVERT_RULES_TABLE_FIELD: {
value = getRecordsetVal(detailRequestConfig, mainRs, detailRs);
}
break;
// 默认值
case RequestPushConstant.CONVERT_RULES_DEFAULT: {
value = getRecordsetVal(detailRequestConfig, mainRs, detailRs);
value = Util.null2String(valueContext)
.replace("{?requestid}", requestId)
.replace("{?}", String.valueOf(value));
}
break;
// 当前时间
case RequestPushConstant.CONVERT_RULES_NOW_TIME: {
value = new Date();
}
break;
// 自定义sql查询
case RequestPushConstant.CONVERT_RULES_CUS_SQL: {
String tempValue = Util.null2DefaultStr(getRecordsetVal(detailRequestConfig, mainRs, detailRs),"");
value = toolUtil.getValueByChangeRule(valueContext, tempValue, requestId, detailId);
}
break;
// requestId
case RequestPushConstant.CONVERT_RULES_REQUEST_ID: {
value = requestId;
}
break;
// 数据id
case RequestPushConstant.CONVERT_RULES_DATA_ID: {
if (RequestPushConstant.DATASOURCE_MAIN_TABLE.equals(dataSource)) {
value = mainId;
} else {
value = detailId;
}
}
break;
default:
throw new CustomerException("不支持的取值方式");
}
switch (paramType) {
// String类型
case RequestPushConstant.DATA_TYPE_STRING: {
value = Util.null2DefaultStr(value, "");
}
break;
// int类型
case RequestPushConstant.DATA_TYPE_INT: {
value = Util.getIntValue(Util.null2DefaultStr(value, ""),0);
}
break;
// double类型
case RequestPushConstant.DATA_TYPE_DOUBLE: {
value = Util.getDoubleValue(Util.null2DefaultStr(value, ""),0.00);
}
break;
// 日期类型
case RequestPushConstant.DATA_TYPE_DATE: {
if (Objects.isNull(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 CustomerException("时间处理异常:参数>>" + paramName);
}
}
break;
// 时间日期类型
case RequestPushConstant.DATA_TYPE_DATE_TIME: {
if (Objects.isNull(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 CustomerException("时间处理异常:参数>>" + paramName + " 异常信息:" + e);
}
}
break;
// 自定义时间格式化类型
case RequestPushConstant.DATA_TYPE_CUS_DATE: {
if (Objects.isNull(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 CustomerException("时间处理异常:参数>>" + paramName + " 异常信息:" + e.getMessage());
}
}
break;
// 时间戳类型
case RequestPushConstant.DATA_TYPE_TIME_TIMESTAMP: {
if (Objects.isNull(value)) {
value = "";
break;
}
try {
Date date = value instanceof Date ? (Date) value : parseDate(String.valueOf(value));
assert date != null;
value = date.getTime();
} catch (Exception e) {
throw new CustomerException("时间处理异常:参数>>" + paramName + " 异常信息:" + e.getMessage());
}
}
break;
default: return value;
}
return value;
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2022/12/23 17:42
* @param config
* @param mainRs
* @param detailRs
* @return
**/
public Object getRecordsetVal(DetailRequestConfig config, RecordSet mainRs, RecordSet detailRs){
String fieldName = config.getWorkFlowFieldName();
String dataSource = config.getDataSource();
if(StringUtils.isBlank(fieldName) || StringUtils.isBlank(dataSource)){
return "";
}
Object value = "";
if (RequestPushConstant.DATASOURCE_MAIN_TABLE.equals(dataSource)) {
value = Util.null2DefaultStr(mainRs.getString(fieldName),"");
} else {
value = Util.null2DefaultStr(detailRs.getString(fieldName),"");
}
return value;
}
/**
* <h1>Date</h1>
*
* @param dateStr
* @return
*/
private 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 CustomerException("无法将" + dateStr + "转换为日期对象!", e);
}
}
/**
*
*
* @param date
* @param tempStr
* @return
*/
private String diyDateFortMat(Date date, String tempStr) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(tempStr);
return simpleDateFormat.format(date);
}
}

View File

@ -5,7 +5,7 @@ import lombok.*;
import java.sql.Timestamp;
/**
* <h1></h1>
* <h1></h1>
*
* @Author xuanran.wang
* @Date 2022/12/1 14:01
@ -48,4 +48,16 @@ public class DataAsyncDetail {
* <h2></h2>
**/
private String dataSourceModelFiledName;
/**
* <h2></h2>
**/
private String updateCriteria;
/**
* <h2></h2>
**/
private String updateField;
/**
* <h2></h2>
**/
private String mainOrDetail;
}

View File

@ -22,5 +22,6 @@ public class DataAsyncMain {
private String cusWhere;
private String modelTypeTableName;
private String asyncTargetModelTableName;
private String detailIndex;
private List<DataAsyncDetail> dataAsyncDetailList;
}

View File

@ -76,4 +76,12 @@ public class DataAsyncConstant {
* <h2>-</h2>
**/
public static final String CONVERT_RULES_SPLIT_COPY = "5";
/**
* <h2></h2>
**/
public static final String MAIN_TABLE = "0";
/**
* <h2></h2>
**/
public static final String DETAIL_TABLE = "1";
}

View File

@ -30,9 +30,11 @@ public class CusDataToModelAsync extends BaseCronJob {
@Override
public void execute() {
try {
logger.info("------------ CusDataToModelAsync Begin ------------");
CommonUtil.checkParamNotNull(this);
DataAsyncMain dataAsyncConfigByUniqueCode = asyncConfigService.getDataAsyncConfigByUniqueCode(uniqueCode);
asyncConfigService.asyncModelData(dataAsyncConfigByUniqueCode, Util.getIntValue(modelId, -1));
logger.info("------------ CusDataToModelAsync End ------------");
}catch (Exception e){
logger.error(Util.logStr("执行数据同步计划任务失败!异常信息 : {}", e.getMessage()));
}

View File

@ -18,6 +18,4 @@ public interface DataAsyncMapper {
@CaseConversion(false)
RecordSet getRecordSetByCusSql(@SqlString String sql);
}

View File

@ -2,8 +2,12 @@ package weaver.xuanran.wang.saic_travel.model_data_async.service;
import aiyh.utils.Util;
import aiyh.utils.excention.CustomerException;
import aiyh.utils.zwl.common.ToolUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.jetbrains.annotations.NotNull;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import weaver.conn.RecordSet;
@ -62,17 +66,51 @@ public class DataAsyncConfigService {
}
logger.info("selectSql : " + selectSql);
List<LinkedHashMap<String, Object>> linkedHashMapList = new ArrayList<>();
StringBuilder updateWhereSql = new StringBuilder();
// 需要更新时候的参数集合
List<LinkedHashMap<String, Object>> updateLinkedList = new ArrayList<>();
// 判断是否更新sql的参数
List<List<String>> updateWhereParam = new ArrayList<>();
int splitCopy = -1;
String splitCopyFiledName = "";
// 复制个数
List<DataAsyncDetail> splitCopyList = asyncDetailList.stream().filter(item -> DataAsyncConstant.CONVERT_RULES_SPLIT_COPY.equals(item.getConvertRules())).collect(Collectors.toList());
DataAsyncDetail copyAsyncDetail = null;
if(!CollectionUtils.isEmpty(splitCopyList)){
DataAsyncDetail detail = splitCopyList.get(0);
copyAsyncDetail = detail;
splitCopy = Util.getIntValue(detail.getCusText(),-1);
splitCopyFiledName = Util.null2DefaultStr(detail.getAsyncModelTableField(),"");
}
// 更新数据条件
List<String> updateCriteriaList = asyncDetailList.stream()
.filter(item -> DataAsyncConstant.CONFIG_ENABLE.equals(item.getUpdateCriteria()))
.map(DataAsyncDetail::getAsyncModelTableField)
.collect(Collectors.toList());
// 更新字段
List<String> updateFieldList = asyncDetailList.stream()
.filter(item -> DataAsyncConstant.CONFIG_ENABLE.equals(item.getUpdateField()))
.map(DataAsyncDetail::getAsyncModelTableField)
.collect(Collectors.toList());
// 如果更新条件不为空那么就拼接更新sql
if(!CollectionUtils.isEmpty(updateCriteriaList)){
StringBuilder sqlSb = new StringBuilder();
for (int i = 0; i < updateCriteriaList.size(); i++) {
if(i != updateCriteriaList.size() -1 ){
sqlSb.append(updateCriteriaList.get(i)).append(" = ? and ");
}else {
sqlSb.append(updateCriteriaList.get(i)).append(" = ? ");
}
}
updateWhereSql.append("select id from #{tableName} where ").append(sqlSb);
}
while (rs.next()){
// 建模表插入参数
LinkedHashMap<String, Object> linkedHashMap = new LinkedHashMap<>();
// 如果数据存在更新参数集合
LinkedHashMap<String, Object> updateLinkedMap = new LinkedHashMap<>();
// 更新条件参数
LinkedHashMap<String, String> updateParam = new LinkedHashMap<>();
int tempCount = 0;
for (DataAsyncDetail dataAsyncDetail : asyncDetailList) {
String field = "";
@ -85,19 +123,49 @@ public class DataAsyncConfigService {
}break;
default:throw new CustomerException("暂不支持的数据来源");
}
// 同步建模字段
String asyncModelTableField = dataAsyncDetail.getAsyncModelTableField();
Object value = getFieldValue(rs, field, dataAsyncDetail, tempCount);
linkedHashMap.put(dataAsyncDetail.getAsyncModelTableField(), value);
// 把当前字段和值放到更新条件参数集合中
if(!CollectionUtils.isEmpty(updateCriteriaList) && updateCriteriaList.contains(asyncModelTableField)){
updateParam.put(asyncModelTableField, Util.null2DefaultStr(value,""));
}
// 需要更新时更新字段参数集合
if(!CollectionUtils.isEmpty(updateCriteriaList) && updateFieldList.contains(asyncModelTableField)){
updateLinkedMap.put(asyncModelTableField, value);
}
linkedHashMap.put(asyncModelTableField, value);
}
updateWhereParam.add(new ArrayList<>(updateParam.values()));
linkedHashMapList.add(linkedHashMap);
if(MapUtils.isNotEmpty(updateLinkedMap)){
updateLinkedList.add(updateLinkedMap);
}
// 记录复制
while (++tempCount < splitCopy) {
LinkedHashMap<String, Object> copyMap = new LinkedHashMap<>(linkedHashMap);
// 如果更新条件参数map不为空
if(MapUtils.isNotEmpty(updateLinkedMap)){
// 需要更新的参数map集合
LinkedHashMap<String, Object> copyUpdateLinkedMap = new LinkedHashMap<>(updateLinkedMap);
// 如果更新条件中包含拆分复制条件的
if(copyAsyncDetail != null && updateCriteriaList.contains(copyAsyncDetail.getAsyncModelTableField())){
updateParam.put(copyAsyncDetail.getAsyncModelTableField(), String.valueOf(tempCount));
}
// 将拆分复制的值加进去
if(copyAsyncDetail != null && updateFieldList.contains(copyAsyncDetail.getAsyncModelTableField())){
copyUpdateLinkedMap.put(splitCopyFiledName, tempCount);
}
updateLinkedList.add(copyUpdateLinkedMap);
updateWhereParam.add(new ArrayList<>(updateParam.values()));
}
copyMap.put(splitCopyFiledName, tempCount);
linkedHashMapList.add(copyMap);
}
}
return CusInfoToOAUtil.executeBatch(modelId, linkedHashMapList);
return CusInfoToOAUtil.executeBatch(modelId, linkedHashMapList, updateWhereSql.toString(), updateWhereParam, true, updateLinkedList);
}
/**
* <h1></h1>
* @author xuanran.wang
@ -108,7 +176,7 @@ public class DataAsyncConfigService {
* @param count
* @return
**/
public Object getFieldValue(RecordSet recordSet, String field, DataAsyncDetail dataAsyncDetail, int count){
public Object getFieldValue(RecordSet recordSet, String field, @NotNull DataAsyncDetail dataAsyncDetail, int count){
String convertRules = dataAsyncDetail.getConvertRules();
String dataType = dataAsyncDetail.getDataType();
String cusText = dataAsyncDetail.getCusText();
@ -131,12 +199,14 @@ public class DataAsyncConfigService {
// 自定义sql查询
case DataAsyncConstant.CONVERT_RULES_CUS_SQL: {
if(!StringUtils.isBlank(cusText)){
String cusSql = Util.sbc2dbcCase(cusText);
String where = "";
if(StringUtils.isNotBlank(field)){
where = Util.null2DefaultStr(recordSet.getString(field),"");
}
tempRs.executeQuery(cusSql, where);
String cusSql = Util.sbc2dbcCase(cusText)
.replace("?",where)
.replace("{main.id}", recordSet.getString("id"));
tempRs.executeQuery(cusSql);
if (!tempRs.next()) {
logger.error(Util.logStr("执行自定义sql失败!当前sql:{}, 当前参数:{}", cusSql, where));
break;
@ -146,6 +216,7 @@ public class DataAsyncConfigService {
}break;
case DataAsyncConstant.CONVERT_RULES_DATA_ID: {
value = recordSet.getString("id");
logger.info(Util.logStr("主数据Id : {}", value));
}break;
case DataAsyncConstant.CONVERT_RULES_SPLIT_COPY: {
value = count;
@ -232,30 +303,33 @@ public class DataAsyncConfigService {
* @return sql
**/
public String getSelectSql(DataAsyncMain asyncConfig){
String dataSource = asyncConfig.getDataSource();
String cusWhere = Util.null2DefaultStr(asyncConfig.getCusWhere(), "");
String dataSourceTableName = "";
List<DataAsyncDetail> asyncDetailList = asyncConfig.getDataAsyncDetailList();
String selectSql = "select ";
List<String> modelFieldList = new ArrayList<>();
// 判断数据来源拼接查询sql
switch (dataSource) {
case DataAsyncConstant.DATA_SOURCE_MODEL:{
modelFieldList = asyncDetailList.stream().map(DataAsyncDetail::getDataSourceModelFiledName).filter(StringUtils::isNotBlank).collect(Collectors.toList());
dataSourceTableName = asyncConfig.getModelTypeTableName();
}break;
case DataAsyncConstant.DATA_SOURCE_CUS_TABLE:{
modelFieldList = asyncDetailList.stream().map(DataAsyncDetail::getCusTableField).filter(StringUtils::isNotBlank).collect(Collectors.toList());
dataSourceTableName = asyncConfig.getCusTable();
}break;
default:throw new CustomerException("暂不支持的数据来源!");
}
// 拼接数据源查询sql
selectSql += StringUtils.join(modelFieldList, ",") + " from " + dataSourceTableName;
String selectSql = "select * from " + getTableName(asyncConfig);
if(StringUtils.isNotBlank(cusWhere)){
selectSql += " where " + cusWhere;
}
return selectSql;
}
/**
* <h1>sql</h1>
* @author xuanran.wang
* @dateTime 2022/12/2 12:56
* @param asyncConfig
* @return sql
**/
public String getTableName(DataAsyncMain asyncConfig){
// 判断数据来源拼接查询sql
switch (asyncConfig.getDataSource()) {
case DataAsyncConstant.DATA_SOURCE_MODEL:{
return asyncConfig.getModelTypeTableName();
}
case DataAsyncConstant.DATA_SOURCE_CUS_TABLE:{
return asyncConfig.getCusTable();
}
default:throw new CustomerException("暂不支持的数据来源!");
}
}
}

View File

@ -1,19 +1,25 @@
package weaver.xuanran.wang.schroeder.action;
import aiyh.utils.Util;
import aiyh.utils.action.CusBaseAction; // 基础的action实现一些基础的参数
import aiyh.utils.action.SafeCusBaseAction;
import aiyh.utils.annotation.RequiredMark;
import aiyh.utils.excention.CustomerException; // 自定义异常类 create 2022/3/9 2:20 PM
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPObject;
import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.hrm.User;
import weaver.soa.workflow.request.RequestInfo;
import weaver.workflow.request.RequestManager;
import weaver.xiao.commons.config.entity.RequestMappingConfig;
import weaver.xuanran.wang.common.util.CommonUtil;
import weaver.xuanran.wang.common.util.CusInfoToOAUtil;
import weaver.xuanran.wang.schroeder.before.interfaces.CusActionBeforeProcessor;
import weaver.xuanran.wang.schroeder.service.SchroederQRCodeService;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
@ -23,7 +29,7 @@ import java.util.stream.Collectors;
* @Author xuanran.wang
* @Date 2022/11/30 16:08
*/
public class PushSealTaskAction extends CusBaseAction { // 基础的action实现一些基础的参数
public class PushSealTaskAction extends SafeCusBaseAction { // 基础的action实现一些基础的参数
/**
* <h2></h2>
@ -47,43 +53,160 @@ public class PushSealTaskAction extends CusBaseAction { // 基础的action
* <h2>id</h2>
**/
@RequiredMark
private String modelId;
private String docLogModelId;
/**
* <h2>requestIdid</h2>
**/
@RequiredMark
private String requestIdLogModelId;
/**
* <h2></h2>
**/
@RequiredMark
private String filePeopleType;
/**
* <h2></h2>
**/
@RequiredMark
private String detailNo;
/**
* <h2></h2>
**/
@RequiredMark
private String successCode;
/**
* <h2></h2>
**/
@RequiredMark
private String backField;
/**
* <h2></h2>
**/
private String cusBeforeProcessor;
/**
* <h2></h2>
**/
private String type;
private final SchroederQRCodeService schroederQRCodeService = new SchroederQRCodeService(); // 施罗德业务方法 施罗德业务方法
@Override // action 提交流程业务处理方法 具体业务逻辑实现
public void doSubmit(String requestId, String billTable, int workflowId, User user, RequestManager requestManager) {
public void doSubmit(String requestId, String billTable, int workflowId, User user, RequestInfo requestInfo) {
log.info("---------- PushSealTaskSealValue Begin " + requestId + "----------");
RequestInfo requestInfo = requestInfoThreadLocal.get();
String scanNum = schroederQRCodeService.pushSealTask(onlyMark, billTable, requestId); // 推送数据创建任务 建模配置唯一标识
RecordSetTrans trans = requestManager.getRsTrans();
String delSql = "";
String mainId = "";
RecordSetTrans trans = new RecordSetTrans();
trans.setAutoCommit(false);
String updateSql = "update " + billTable + " set " + QRCodeField + " = ? where requestid = ?"; // 二维码来源字段
// 插入模块的参数集合
List<String> requestIdLogModelIdList = new ArrayList<>();
List<String> docLogModelIdList = new ArrayList<>();
// 前置接口做了添加明细表的操作 最后是否需要删除添加的明细
boolean del = false;
// 执行前置处理 默认添加一行明细
if(StringUtils.isNotBlank(cusBeforeProcessor)){
Map<String, String> pathParam = Util.parseCusInterfacePathParam(cusBeforeProcessor);
String classPath = pathParam.remove("_ClassPath");
del = executeBeforeProcessor(classPath, requestInfo, null, pathParam);
}
RecordSet mainRs = new RecordSet();
mainRs.executeQuery("select * from " + billTable + " where requestid = ?", requestId);
mainRs.next();
try{
mainId = mainRs.getString("id");
String detailTable = billTable + "_dt" + detailNo;
if(StringUtils.isNotBlank(mainId)){
delSql = "delete from " + detailTable + " where mainid = ? ";
}
try{
List<String> detailFileId = schroederQRCodeService.getDetailFileId(fileField, detailTable, mainId);
log.info(Util.logStr("明细docId集合 : {}", JSONObject.toJSONString(detailFileId)));
List<LinkedHashMap<String, Object>> docLogParamList = new ArrayList<>();
for (String docId : detailFileId) {
LinkedHashMap<String, Object> map = new LinkedHashMap<>();
map.put("docId", docId);
map.put("enable", 0);
docLogParamList.add(map);
}
log.info(Util.logStr("docLogParamList集合 : {}", JSONObject.toJSONString(docLogParamList)));
// 将docLog数据写入建模
docLogModelIdList = CusInfoToOAUtil.executeBatch(Util.getIntValue(docLogModelId, -1), docLogParamList);
// requestLog写入建模
LinkedHashMap<String, Object> map = new LinkedHashMap<>();
int count = schroederQRCodeService.getTaskIdByRequestId(requestId);
if(Util.getIntValue(String.valueOf(count),-1) < 0){
count = 1;
}else {
count += 1;
}
map.put("count", count);
map.put("cusRequestId", requestId);
requestIdLogModelIdList = CusInfoToOAUtil.executeBatch(Util.getIntValue(requestIdLogModelId, -1), Collections.singletonList(map));
}catch (Exception e){
throw new CustomerException(Util.logStr("数据写入建模异常!:{}", e.getMessage()));
}
String scanNum = schroederQRCodeService.pushSealTask(onlyMark, billTable, requestId, type, successCode, backField, filePeopleType); // 推送数据创建任务 建模配置唯一标识
String updateSql = "update " + billTable + " set " + QRCodeField + " = ? where requestid = ?"; // 二维码来源字段
if(!trans.executeUpdate(updateSql, scanNum, requestId)){
throw new CustomerException(Util.logStr("更新表单sql执行失败!sql : {}, 参数 scanNum : {}, requestId : {}", scanNum, requestId)); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串
}
// 获取明细表数据
List<Map<String, String>> detailList = getDetailTableValueByDetailNo(1, requestInfo);
List<String> docIds = detailList.stream()
.map(item -> Util.null2DefaultStr(item.get(fileField), ""))
.filter(StringUtils::isNotBlank).collect(Collectors.toList());
ArrayList<LinkedHashMap<String, Object>> list = new ArrayList<>();
for (String docId : docIds) {
LinkedHashMap<String, Object> map = new LinkedHashMap<>();
map.put("docId", docId);
map.put("enable", 0);
list.add(map);
}
// 将数据写入建模
CusInfoToOAUtil.executeBatch(Util.getIntValue(modelId, -1), list, "select 1 from #{tableName} where docId = ?", docIds);
}catch (Exception e){
CommonUtil.deleteDataByIds(requestIdLogModelIdList, Util.getIntValue(requestIdLogModelId,-1));
CommonUtil.deleteDataByIds(docLogModelIdList, Util.getIntValue(docLogModelId,-1));
trans.rollback();
throw new CustomerException(Util.logStr("执行提交方法异常:{}", e.getMessage())); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串
}finally {
log.info(Util.logStr("del: {}, sql: {}, mainId: {}", del, delSql, mainId));
if(del && StringUtils.isNotBlank(delSql)){
RecordSet rs = new RecordSet();
if(!rs.executeUpdate(delSql, mainId)){
log.error(Util.logStr("删除明细表失败! sql: {}, mainId: {}", delSql, mainId));
}
}
}
trans.commit();
}
/**
* <h2></h2>
*
* @param className
* @return
*/
private boolean executeBeforeProcessor(String className, RequestInfo requestInfo,
RequestMappingConfig requestMappingConfig,
Map<String, String> pathParam) {
Class<?> aClass;
try {
aClass = Class.forName(className);
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("未能找到自定义action前置置处理方法理接口" + className);
}
Constructor<?> constructor;
try {
constructor = aClass.getConstructor();
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException(className + "没有空参构造方法,无法获取构造方法对象!");
}
if (!CusActionBeforeProcessor.class.isAssignableFrom(aClass)) {
throw new IllegalArgumentException("自定义前置置处理接口:" + className + " 不是"
+ CusActionBeforeProcessor.class.getName() + "的子类或实现类!");
}
CusActionBeforeProcessor o;
try {
o = (CusActionBeforeProcessor) constructor.newInstance();
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new IllegalArgumentException("无法构造" + className + "对象!");
}
return o.beforeProcessor(requestInfo, requestMappingConfig, pathParam);
}
}

View File

@ -0,0 +1,45 @@
package weaver.xuanran.wang.schroeder.action;
import aiyh.utils.Util;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import weaver.xuanran.wang.schroeder.service.SchroederQRCodeService;
/**
* <h1>action</h1>
*
* @Author xuanran.wang
* @Date 2022/12/23 10:49
*/
public class SalesforceEndpointAction implements Action {
/**
* <h2></h2>
**/
private String onlyMark;
/**
* <h2></h2>
**/
private String successCode;
/**
* <h2></h2>
**/
private String type;
private final SchroederQRCodeService schroederQRCodeService = new SchroederQRCodeService();
@Override
public String execute(RequestInfo requestInfo) {
try {
String billTable = requestInfo.getRequestManager().getBillTableName();
String requestId = requestInfo.getRequestid();
schroederQRCodeService.pushSealTask(onlyMark, billTable, requestId,type, successCode,"","");
return Action.SUCCESS;
}catch (Exception e){
requestInfo.getRequestManager().setMessageid(String.valueOf(System.currentTimeMillis()));
requestInfo.getRequestManager().setMessagecontent(Util.logStr("执行提交方法异常:{}", e.getMessage()));
return Action.FAILURE_AND_CONTINUE;
}
}
}

View File

@ -0,0 +1,62 @@
package weaver.xuanran.wang.schroeder.before;
import aiyh.utils.Util;
import aiyh.utils.excention.CustomerException;
import aiyh.utils.sqlUtil.sqlResult.impl.PrepSqlResultImpl;
import com.alibaba.fastjson.JSONObject;
import org.apache.log4j.Logger;
import weaver.conn.RecordSet;
import weaver.soa.workflow.request.RequestInfo;
import weaver.xiao.commons.config.entity.RequestMappingConfig;
import weaver.xuanran.wang.schroeder.before.interfaces.CusActionBeforeProcessor;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* <h1></h1>
*
* @Author xuanran.wang
* @Date 2022/12/21 16:44
*/
public class PushSealTaskBeforeProcessor implements CusActionBeforeProcessor {
private final Logger logger = Util.getLogger();
/**
* weaver.xuanran.wang.schroeder.before.PushSealTaskBeforeProcessor?whereSql=`yyfs in (4,7)`&mapping=`yzzl:yzzl,htzyzcshj:htzyzcs,gzcshj:gzcs,frzcshj:frzcs`&detailNo=1
*/
@Override
public boolean beforeProcessor(RequestInfo requestInfo, RequestMappingConfig requestMappingConfig, Map<String, String> pathParam) {
String whereSql = pathParam.get("whereSql");
String tableName = requestInfo.getRequestManager().getBillTableName();
String sql = "select * from " + tableName + " where requestid = ? and " + whereSql;
RecordSet rs = new RecordSet();
// 如果主表数据符合插入条件
// mapping=sas:dashdjas,dhjsadh:dfhjs
logger.info(Util.logStr("前置接口 : sql : {}, 路径参数: {}", sql, JSONObject.toJSONString(pathParam)));
if(rs.executeQuery(sql, requestInfo.getRequestid()) && rs.next()){
HashMap<String, Object> detailMap = new HashMap<>();
String mapping = pathParam.get("mapping");
String detailNo = pathParam.get("detailNo");
String[] split = mapping.split(",");
for (String str : split) {
String[] map = str.split(":");
detailMap.put(map[1], Util.null2DefaultStr(rs.getString(map[0]),""));
}
detailMap.put("mainid", rs.getString("id"));
// 用印文件docId
detailMap.put(pathParam.get("fileField"),pathParam.get("fileFieldValue"));
PrepSqlResultImpl sqlResult = Util.createSqlBuilder().insertSql(tableName + "_dt" + detailNo, detailMap);
String sqlStr = sqlResult.getSqlStr();
List<Object> args = sqlResult.getArgs();
if (!rs.executeUpdate(sqlStr, args)) {
throw new CustomerException(Util.logStr("明细数据插入失败! sql : {}, params : {}", sqlStr, JSONObject.toJSONString(args)));
}
return true;
}
return false;
}
}

View File

@ -0,0 +1,23 @@
package weaver.xuanran.wang.schroeder.before.interfaces;
import weaver.soa.workflow.request.RequestInfo;
import weaver.xiao.commons.config.entity.RequestMappingConfig;
import java.util.Map;
/**
* <h1></h1>
*
* @Author xuanran.wang
* @Date 2022/12/21 16:40
*/
public interface CusActionBeforeProcessor {
/**
*
* @param requestInfo
* @param requestMappingConfig onlyMark
* @param pathParam
* @return
*/
boolean beforeProcessor(RequestInfo requestInfo, RequestMappingConfig requestMappingConfig, Map<String, String> pathParam);
}

View File

@ -6,12 +6,12 @@ import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import weaver.conn.ConnStatementDataSource;
import weaver.conn.RecordSet;
import weaver.xiao.commons.config.interfacies.CusInterfaceGetValue; // 自定义获取参数值
import weaver.zwl.common.ToolUtil; // 常用工具方法-公用类
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;
/**
* <h1></h1>
@ -20,14 +20,12 @@ import java.util.stream.Collectors;
* @Date 2022/12/2 16:10
*/
public class PushSealTaskSealValue implements CusInterfaceGetValue { // 自定义获取参数值
private final ToolUtil toolUtil = new ToolUtil(); // 常用工具方法-公用类 构造方法
private final Logger logger = Util.getLogger(); // 获取日志对象
@Override // 获取参数值
public Object execute(Map<String, Object> mainMap, Map<String, Object> detailMap, String currentValue, Map<String, String> pathParam) {
logger.info(Util.logStr("路径参数:[{}]", JSONObject.toJSONString(pathParam)));
logger.info("路径参数(字符串拼接) : " + JSONObject.toJSONString(pathParam));// 构建日志字符串
// 接口字段
String sealSnField = pathParam.get("sealSnField");
String sealNumField = pathParam.get("sealNumField");
@ -39,7 +37,6 @@ public class PushSealTaskSealValue implements CusInterfaceGetValue { // 自定
if(checkBlank(sealSnField, sealNumField, sealSnCusSql, sealNumCusSql)){
throw new CustomerException(Util.logStr("自定义类路径中必要参数为空,请检查!当前pathParam : {}", JSONObject.toJSONString(pathParam))); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串
}
logger.info(Util.logStr("当前值 : {}", currentValue)); // 构建日志字符串
// 如果为空返回空集合
if(StringUtils.isBlank(currentValue)){
return Collections.emptyList();
@ -48,11 +45,19 @@ public class PushSealTaskSealValue implements CusInterfaceGetValue { // 自定
int detailId = -1;
if(MapUtils.isNotEmpty(detailMap)){
detailId = Util.getIntValue(String.valueOf(detailMap.get("id")), -1);
if(detailId < 0){
detailId = Util.getIntValue(String.valueOf(detailMap.get("ID")), -1);
}
}
String requestId = String.valueOf(mainMap.get("requestid"));
if(StringUtils.isBlank(requestId)){
requestId = String.valueOf(mainMap.get("REQUESTID"));
}
logger.info(Util.logStr("requestId : {}, detailId : {}", requestId, detailId));
for (String val : currentValue.split(",")) {
// 印章类型转换执行自定义sql
String inSealVal = Util.null2DefaultStr(toolUtil.getValueByChangeRule(sealSnCusSql, val, String.valueOf(mainMap.get("requestid")), detailId),""); // 用数据库值,根据规则转换,获取其最终结果
String inSealNumVal = Util.null2DefaultStr(toolUtil.getValueByChangeRule(sealNumCusSql, val, String.valueOf(mainMap.get("requestid")), detailId),""); // 用数据库值,根据规则转换,获取其最终结果
String inSealVal = Util.null2DefaultStr(getValueByChangeRule(sealSnCusSql, val, requestId, detailId,""),""); // 用数据库值,根据规则转换,获取其最终结果
String inSealNumVal = Util.null2DefaultStr(getValueByChangeRule(sealNumCusSql, val, requestId, detailId,""),""); // 用数据库值,根据规则转换,获取其最终结果
HashMap<String, Object> map = new HashMap<>();
map.put(sealSnField, inSealVal);
map.put(sealNumField, inSealNumVal);
@ -61,6 +66,85 @@ public class PushSealTaskSealValue implements CusInterfaceGetValue { // 自定
return list;
}
/**
*
* @param cus_sql SQL
* @param value
* @param requestid ID
* @param detailKeyvalue
* @pram datasourceid ID
* @return
*/
public String getValueByChangeRule(String cus_sql,String value,String requestid,int detailKeyvalue,String datasourceid){
String endValue = "";
cus_sql = cus_sql.replace("&nbsp;", " ");
cus_sql = cus_sql.replace("{?dt.id}", String.valueOf(detailKeyvalue));
//参数进行替换
String sqlString = cus_sql.replace("{?requestid}", requestid);
sqlString = sqlString.replace("?", value);
sqlString = ToDBC(sqlString);
logger.info(Util.logStr("查询sql : {} ", sqlString));
try {
if(datasourceid != null && !"".equals(datasourceid)){
ConnStatementDataSource csds = new ConnStatementDataSource(datasourceid);
csds.setStatementSql(sqlString);
csds.executeQuery();
if(csds.next()){
endValue = weaver.general.Util.null2String(csds.getString(1));
}
csds.close();
}else{
RecordSet rs = new RecordSet();
if(rs.executeQuery(sqlString)){
if (rs.next()) {
endValue = weaver.general.Util.null2String(rs.getString(1));
logger.info(Util.logStr("执行自定义sql 返回结果 : {}", endValue));
}else {
logger.error("当前查询没有查询结果!");
}
}else {
logger.error("当前sql查询失败");
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return endValue;
}
/**
*
* @param input
* @return
*/
public String ToDBC(String input) {
char c[] = input.toCharArray();
for (int i = 0; i < c.length; i++) {
if (c[i] == '\u3000') {
c[i] = ' ';
} else if (c[i] > '\uFF00' && c[i] < '\uFF5F') {
c[i] = (char) (c[i] - 65248);
}
}
String returnString = new String(c);
return returnString;
}
public boolean checkBlank(String ... args){
return Arrays.stream(args).anyMatch(StringUtils::isBlank);
}

View File

@ -3,6 +3,7 @@ package weaver.xuanran.wang.schroeder.mapper;
import aiyh.utils.annotation.recordset.ParamMapper;
import aiyh.utils.annotation.recordset.Select;
import aiyh.utils.annotation.recordset.SqlMapper;
import com.icbc.api.internal.apache.http.impl.cookie.S;
import java.util.List;
import java.util.Map;
@ -38,8 +39,23 @@ public interface SchroederMapper {
* @return
**/
@Select("select $t{fileField} from $t{tableName} where mainid = #{mainId}")
List<Map<String, Object>> selectSealFileList(@ParamMapper("fileField") String fileField,
@ParamMapper("tableName") String tableName,
@ParamMapper("mainId") String mainId);
List<String> selectSealFileList(@ParamMapper("fileField") String fileField,
@ParamMapper("tableName") String tableName,
@ParamMapper("mainId") String mainId);
/**
* <h1>Id</h1>
* @author xuanran.wang
* @dateTime 2022/12/21 9:39
* @param cusRequestId id
* @return taskId
**/
@Select("select max(count) count " +
"from uf_request_task_log " +
"where cusRequestId = #{cusRequestId} " +
"group by cusRequestId")
Integer selectTaskId(@ParamMapper("cusRequestId") String cusRequestId);
@Select("select * from $t{tableName} where mainid = #{mainId}")
List<Map<String, Object>> detailList(@ParamMapper("tableName") String tableName,
@ParamMapper("mainId") String mainId);
}

View File

@ -7,27 +7,20 @@ import aiyh.utils.httpUtil.util.HttpUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.zxing.qrcode.encoder.QRCode;
import com.icbc.api.internal.apache.http.M;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.springframework.beans.BeanUtils;
import weaver.conn.RecordSet;
import weaver.mobile.plugin.ecology.QRCodeComInfo;
import weaver.xiao.commons.config.entity.RequestMappingConfig;
import weaver.xiao.commons.config.service.DealWithMapping;
import weaver.xuanran.wang.schroeder.mapper.SchroederMapper;
import javax.ws.rs.core.MediaType;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
@ -38,10 +31,6 @@ import java.util.stream.Collectors;
*/
public class SchroederQRCodeService {
private static final int SUCCESS_CODE = 200;
/**
* <h2></h2>
**/
private static final int SUCCESS_STATUS= 0;
/**
* <h2></h2>
**/
@ -54,119 +43,245 @@ public class SchroederQRCodeService {
* <h2></h2>
**/
private static final String STATUS_FIELD = "status";
/**
* <h2>get</h2>
**/
public static final String GET = "GET";
/**
* <h2>post</h2>
**/
public static final String POST = "POST";
/**
* <h2>requestId</h2>
**/
private final DealWithMapping dealWithMapping = new DealWithMapping();
private final Logger log = Util.getLogger(); // 获取日志对象
private final HttpUtils httpUtils = new HttpUtils();
{
httpUtils.getGlobalCache().header.put("Content-Type", MediaType.APPLICATION_JSON); // 全局请求头
}
private final SchroederMapper schroederMapper = Util.getMapper(SchroederMapper.class);
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2022/12/5 17:05
* @param onlyMark
* <h1></h1>
*
* @param onlyMark
* @param billTable
* @param requestId id
* @param type
* @param successCode
* @param backField
* @param filePeopleType filePeopleType
* @return
* @author xuanran.wang
* @dateTime 2022/12/5 17:05
**/
public String pushSealTask(String onlyMark, String billTable, String requestId){
String res = "";
public String pushSealTask(String onlyMark, String billTable,
String requestId, String type,
String successCode, String backField,String filePeopleType) {
RequestMappingConfig requestMappingConfig = dealWithMapping.treeDealWithUniqueCode(onlyMark); // 将配置参数通过唯一标识查询处理成树形结构
String cusWhere = Util.null2DefaultStr(requestMappingConfig.getCusWhereSql(),"");
if(StringUtils.isNotBlank(cusWhere)){
cusWhere = DealWithMapping.sbc2dbcCase(cusWhere); // 全角转半角
Map<String, Object> requestParam = getParamsMap(requestMappingConfig, billTable, requestId, filePeopleType);
String url = requestMappingConfig.getRequestUrl();
ResponeVo responeVo = null;
try {
switch (type){
case GET: {
responeVo = httpUtils.apiGet(url, requestParam, new HashMap<>());
}break;
case POST: {
responeVo = httpUtils.apiPost(url, requestParam);
}break;
default:throw new CustomerException("暂不支持的请求方式!");
}
} catch (IOException e) {
throw new CustomerException(Util.logStr("发送请求发生异常! : {}", e.getMessage())); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串
}
String selectMainSql = "select * from " + billTable + " where requestid = ? " + cusWhere;
log.info("查询主表数据sql { " + selectMainSql + " }, requestId { " + requestId + " }");
RecordSet recordSet = new RecordSet();
recordSet.executeQuery(selectMainSql, requestId);
if (recordSet.next()) {
dealWithMapping.setMainTable(billTable);
Map<String, Object> requestParam = dealWithMapping.getRequestParam(recordSet, requestMappingConfig);
// 如果明细数据存在骑缝章时候增加一行数据进去
changeRequestMap(requestParam, billTable + "_dt1", recordSet.getString("id"));
// 解析请求参数配置树,转换成请求参数
log.info(Util.logStr("请求json : {}", JSONObject.toJSONString(requestParam))); // 构建日志字符串
String url = requestMappingConfig.getRequestUrl();
ResponeVo responeVo = null;
try {
responeVo = httpUtils.apiPost(url, requestParam);
} catch (IOException e) {
throw new CustomerException(Util.logStr("发送印章请求发生异常! : {}", e.getMessage())); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串
}
Map<String, String> headers = httpUtils.getGlobalCache().header; // 全局请求头
if (responeVo.getCode() != 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(requestParam), JSON.toJSONString(headers), responeVo.getCode(), // 相应状态码
responeVo.getEntityString())); // 相应内容
throw new CustomerException(Util.logStr("can not fetch [{}]", url)); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串
}
Map<String, Object> response;
log.info(Util.logStr("this response is [{}]", responeVo.getEntityString())); // 构建日志字符串 相应内容
try {
response = responeVo.getEntityMap(); // 根据相应结果转化为map集合
log.info(Util.logStr("接口响应:{}", JSONObject.toJSONString(response))); // 构建日志字符串
} catch (JsonProcessingException e) {
log.error(Util.logStr("push data error, can not parse response to map" + // 构建日志字符串
"this response is [{}], url is [{}]request params is [{}] request heard is [{}];",
responeVo.getEntityString(), url, JSON.toJSONString(requestParam), JSON.toJSONString(headers))); // 相应内容
throw new CustomerException(Util.logStr("push data error, can not parse response to map")); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串
}
int status = (int) response.get(STATUS_FIELD);
if(SUCCESS_STATUS != status){
throw new CustomerException(Util.logStr("接口响应码不为0,接口响应信息:{}", Util.null2DefaultStr(response.get(MESSAGE_FIELD),""))); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串
}
res = Util.null2DefaultStr(response.get(SCAN_NUM_FIELD),"");
return parseResponseVo(responeVo, url, requestParam, successCode, backField);
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2022/12/23 11:25
* @param responseVo
* @param url
* @param requestParam
* @param successCode
* @param backField
* @return
**/
private String parseResponseVo(ResponeVo responseVo, String url,
Map<String, Object> requestParam,
String successCode, String backField){
String res = "";
Map<String, String> headers = httpUtils.getGlobalCache().header;// 全局请求头
if (responseVo.getCode() != 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(requestParam), JSON.toJSONString(headers), responseVo.getCode(), // 相应状态码
responseVo.getEntityString())); // 相应内容
throw new CustomerException(Util.logStr("can not fetch [{}]", url)); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串
}
if(StringUtils.isBlank(res)){
throw new CustomerException("获取接口中响应任务字段为空, 请检查!"); // 自定义异常类 create 2022/3/9 2:20 PM
Map<String, Object> response;
log.info(Util.logStr("this response is [{}]", responseVo.getEntityString())); // 构建日志字符串 相应内容
try {
response = responseVo.getEntityMap(); // 根据相应结果转化为map集合
} catch (JsonProcessingException e) {
log.error(Util.logStr("push data error, can not parse response to map" + // 构建日志字符串
"this response is [{}], url is [{}]request params is [{}] request heard is [{}];",
responseVo.getEntityString(), url, JSON.toJSONString(requestParam), JSON.toJSONString(headers))); // 相应内容
throw new CustomerException(Util.logStr("push data error, can not parse response to map")); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串
}
String status = Util.null2DefaultStr(response.get(STATUS_FIELD), "");
if (!successCode.equals(status)) {
throw new CustomerException(Util.logStr("接口响应码不为 : [{}],接口响应信息: {}", successCode, Util.null2DefaultStr(response.get(MESSAGE_FIELD), ""))); // 自定义异常类 create 2022/3/9 2:20 PM 构建日志字符串
}
if(StringUtils.isNotBlank(backField)){
res = Util.null2DefaultStr(response.get(backField), "");
if (StringUtils.isBlank(res)) {
throw new CustomerException("获取接口中响应任务字段为空, 请检查!"); // 自定义异常类 create 2022/3/9 2:20 PM
}
}
return res;
}
/**
* <h1></h1>
* <h1></h1>
* @author xuanran.wang
* @dateTime 2022/12/13 14:15
* @param requestParam
* @dateTime 2022/12/23 11:02
* @param requestMappingConfig
* @param billTable
* @param mainId id
* @param requestId id
* @param filePeopleType filePeopleType
* @return map
**/
public void changeRequestMap(Map<String, Object> requestParam, String billTable, String mainId){
public Map<String, Object> getParamsMap(RequestMappingConfig requestMappingConfig, String billTable, String requestId, String filePeopleType) {
String cusWhere = Util.null2DefaultStr(requestMappingConfig.getCusWhereSql(), "");
if (StringUtils.isNotBlank(cusWhere)) {
cusWhere = DealWithMapping.sbc2dbcCase(cusWhere); // 全角转半角
}
String selectMainSql = "select * from " + billTable + " where requestid = ? " + cusWhere;
log.info(Util.logStr("查询主表数据sql : {}, requestId : {}", selectMainSql, requestId));
RecordSet recordSet = new RecordSet();
recordSet.executeQuery(selectMainSql, requestId);
Map<String, Object> requestParam = new HashMap<>();
if (recordSet.next()) {
dealWithMapping.setMainTable(billTable);
requestParam = dealWithMapping.getRequestParam(recordSet, requestMappingConfig);
// 如果明细数据存在骑缝章时候增加一行数据进去
if (StringUtils.isNotBlank(filePeopleType)) {
changeRequestMap(requestParam, billTable + "_dt1", recordSet.getString("id"), filePeopleType);
}
}
return requestParam;
}
/**
* <h1></h1>
*
* @param requestParam
* @param billTable
* @param mainId id
* @author xuanran.wang
* @dateTime 2022/12/13 14:15
**/
public void changeRequestMap(Map<String, Object> requestParam, String billTable, String mainId, String filePeopleType) {
List<Map<String, Object>> files = (List<Map<String, Object>>) requestParam.get("file");
List<Map<String, Object>> detail1List = schroederMapper.selectSealTaskInfoList(billTable, mainId);
if(CollectionUtils.isEmpty(detail1List) || CollectionUtils.isEmpty(files)){
if (CollectionUtils.isEmpty(files)) {
return;
}
// 遍历明细数据
for (Map<String, Object> detailItem : detail1List) {
RecordSet detailRs = new RecordSet();
String sql = "select yywj,qfzzl,qfzcs from " + billTable + " where mainid = ? and sfjgqfz = 0";
if(!detailRs.executeQuery(sql, mainId)){
throw new CustomerException(Util.logStr("查询明细数据sql执行失败sql : {}, mainId : {}", sql, mainId));
}
// 貌似有bug 把mapper改成原生recordSet
while (detailRs.next()) {
// 用印文件
String sealFile = Util.null2String(detailItem.get("yywj"));
String sealFile = Util.null2String(detailRs.getString("yywj"));
if(StringUtils.isBlank(sealFile)){
sealFile = Util.null2String(detailRs.getString("YYWJ"));
}
// 从生成的请求参数map中开始匹配
String finalSealFile = sealFile;
List<Map<String, Object>> filterFiles = files.stream()
.filter(item -> {
String filePath = Util.null2DefaultStr(item.get("filePath"), "");
String docId = Util.null2DefaultStr(filePath.substring(filePath.lastIndexOf("=") + 1),"");
return sealFile.equals(docId);
String filePath = Util.null2DefaultStr(item.get("fileUrlPath"), "");
String docId = Util.null2DefaultStr(filePath.substring(filePath.lastIndexOf("=") + 1), "");
return finalSealFile.equals(docId);
})
.collect(Collectors.toList());
if(CollectionUtils.isNotEmpty(filterFiles)){
log.info(Util.logStr("filterFiles : {} ", JSONObject.toJSONString(finalSealFile)));
if (CollectionUtils.isNotEmpty(filterFiles)) {
// 只有一个能匹配
Map<String, Object> o = filterFiles.get(0);
HashMap<String, Object> tempMap = o.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> a, HashMap::new));
// 印章集合
List<HashMap<String, Object>> sealList = new ArrayList<>();
HashMap<String, Object> seal = new HashMap<>();
seal.put("sealSn",Util.null2DefaultStr(detailItem.get("qfzzl"),""));
seal.put("sealNum",Util.null2DefaultStr(detailItem.get("qfzcs"),"0"));
tempMap.put("seal", seal);
// 骑缝章总类
String qfzzl = Util.null2DefaultStr(detailRs.getString("qfzzl"),"");
if(StringUtils.isBlank(qfzzl)){
qfzzl = Util.null2DefaultStr(detailRs.getString("QFZZL"),"");
}
log.info(Util.logStr("骑缝章总类 : {}", qfzzl));
seal.put("sealSn", qfzzl);
String qfzcs = Util.null2DefaultStr(detailRs.getString("qfzcs"),"");
if(StringUtils.isBlank(qfzcs)){
qfzcs = Util.null2DefaultStr(detailRs.getString("QFZCS"),"");
}
log.info(Util.logStr("骑缝章次数 : {}", qfzcs));
seal.put("sealNum", Util.null2DefaultStr(qfzcs, "0"));
sealList.add(seal);
tempMap.put("seal", sealList);
tempMap.put("filePeopleType", filePeopleType);
files.add(tempMap);
}
}
}
/**
* <h1>taskId</h1>
*
* @return id
* @author xuanran.wang
* @dateTime 2022/12/21 9:42
**/
public Integer getTaskIdByRequestId(String requestId) {
return schroederMapper.selectTaskId(requestId);
}
/**
* <h1></h1>
*
* @param tableName
* @param mainId id
* @return
* @author xuanran.wang
* @dateTime 2022/12/21 18:03
**/
public List<Map<String, Object>> getDetailList(String tableName, String mainId) {
return schroederMapper.detailList(tableName, mainId);
}
/**
* <h1>1id</h1>
*
* @param fileField
* @param tableName
* @param mainId id
* @return
* @author xuanran.wang
* @dateTime 2022/12/21 18:03
**/
public List<String> getDetailFileId(String fileField,String tableName, String mainId) {
return schroederMapper.selectSealFileList(fileField,tableName, mainId);
}
}

View File

@ -0,0 +1,67 @@
package weaver.xuanran.wang.shyl.mq;
import aiyh.utils.Util;
import aiyh.utils.excention.CustomerException;
import org.apache.log4j.Logger;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
/**
* <h1>RocketMQListener</h1>
*
* @Author xuanran.wang
* @Date 2022/12/29 12:25
*/
public abstract class RocketMQConsumerListener extends HttpServlet {
private static final Logger log = Util.getLogger();
private String configName;
public RocketMQConsumerListener() {
}
public RocketMQConsumerListener(String configName) {
this.configName = configName;
}
@Override
public void init() throws ServletException {
super.init();
initialized();
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2022/12/29 21:48
**/
public void initialized() {
DefaultMQPushConsumer consumer = null;
log.info(Util.logStr("---- consumer : {} initialized start ----", configName));
try {
try {
// 根据配置文件初始化一个consumer对象
consumer = RocketMQFactory.getMQPushConsumer(configName, service());
}catch (Exception e){
throw new CustomerException(Util.logStr("the consumer init exception : {}", e.getMessage()));
}
try {
// 调用start()方法启动consumer
consumer.start();
}catch (Exception e){
throw new CustomerException(Util.logStr("the consumer start exception : {}", e.getMessage()));
}
log.info(Util.logStr("---- consumer : {} initialized end ----", configName));
}catch (Exception e){
log.info(Util.logStr("---- consumer : {} initialized error ----", configName));
log.error(Util.getErrString(e));
}
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2022/12/29 21:49
* @return MessageListenerConcurrently
**/
public abstract MessageListenerConcurrently service();
}

View File

@ -0,0 +1,120 @@
package weaver.xuanran.wang.shyl.mq;
import aiyh.utils.Util;
import aiyh.utils.excention.CustomerException;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;
import weaver.xuanran.wang.shyl.mq.constant.RocketMQConstant;
import weaver.xuanran.wang.shyl.mq.util.RocketUtil;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* <h1>rocketMQ</h1>
*
* @Author xuanran.wang
* @Date 2022/12/29 14:21
*/
public class RocketMQFactory {
/**
* <h2></h2>
**/
public static Map<String, Map<String,Object>> CONFIG_MAPS = new HashMap<>(16);
/**
* <h2>map</h2>
**/
private static Map<String, DefaultMQProducer> PRODUCER_MAP = new ConcurrentHashMap<>(16);
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2023/1/4 12:55
* @param configName
* @param messageListenerConcurrently
* @return
**/
public static DefaultMQPushConsumer getMQPushConsumer(String configName, MessageListenerConcurrently messageListenerConcurrently){
try {
Map<String, Object> configMap = getConfigMapByName(configName);
// 最大重试次数
int maxReconsumeTimes = Util.getIntValue(Util.null2String(configMap.get("MaxReconsumeTimes")), RocketMQConstant.DEFAULT_MAX_RECONSUME_TIMES);
// 声明一个消费者consumer需要传入一个组 weaver-consumer
DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(Util.null2String(configMap.get("ConsumerGroup")));
// 设置集群的NameServer地址多个地址之间以分号分隔 183.192.65.118:9876
consumer.setNamesrvAddr(Util.null2String(configMap.get("NameServer")));
// 设置consumer的消费策略
consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
// 集群模式消费,广播消费不会重试
consumer.setMessageModel(MessageModel.CLUSTERING);
// 设置最大重试次数默认是16次
consumer.setMaxReconsumeTimes(maxReconsumeTimes);
// 设置consumer所订阅的Topic和Tag*代表全部的Tag AUTH_CONSOLE_USERINFO_TOPIC
consumer.subscribe(Util.null2String(configMap.get("Topic")), Util.null2String(configMap.get("Tag")));
// Listener主要进行消息的逻辑处理,监听topic如果有消息就会立即去消费
consumer.registerMessageListener(messageListenerConcurrently);
return consumer;
}catch (Exception e){
throw new CustomerException(Util.logStr("consumer init error, now config name is : {} error : {}",configName, e.getMessage()));
}
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2023/1/4 12:59
* @param configName
* @return
**/
public static DefaultMQProducer getMQProducer(String configName){
DefaultMQProducer defaultMQProducer = null;
if(PRODUCER_MAP.containsKey(configName)){
return PRODUCER_MAP.get(configName);
}else {
synchronized (RocketMQFactory.class){
if(PRODUCER_MAP.containsKey(configName)){
return PRODUCER_MAP.get(configName);
}else {
Map<String, Object> configMap = getConfigMapByName(configName);
defaultMQProducer = new DefaultMQProducer();
// 发送消息最大超时时间 默认60000
int sendMsgTimeOut = Util.getIntValue(Util.null2String(configMap.get("sendMsgTimeOut")), RocketMQConstant.PRODUCER_SEND_MSG_TIME_OUT);
defaultMQProducer.setSendMsgTimeout(sendMsgTimeOut);
try {
defaultMQProducer.start();
}catch (MQClientException e){
throw new CustomerException("producer start error!");
}
// mq地址
defaultMQProducer.setNamesrvAddr(Util.null2String(configMap.get("NameServer")));
PRODUCER_MAP.put(configName, defaultMQProducer);
}
}
}
return defaultMQProducer;
}
/**
* <h1>map</h1>
* @author xuanran.wang
* @dateTime 2023/1/4 13:18
* @param configName
* @return map
**/
private synchronized static Map<String, Object> getConfigMapByName(String configName){
Map<String, Object> configMap = new HashMap<>();
if(!CONFIG_MAPS.containsKey(configName)){
configMap = RocketUtil.initMQConfigMap(configName);
CONFIG_MAPS.put(configName, configMap);
}
return configMap;
}
}

View File

@ -0,0 +1,31 @@
package weaver.xuanran.wang.shyl.mq.action;
import aiyh.utils.action.SafeCusBaseAction;
import aiyh.utils.annotation.RequiredMark;
import weaver.hrm.User;
import weaver.soa.workflow.request.RequestInfo;
/**
* <h1>action mq</h1>
*
* @author xuanran.wang
* @date 2023/1/4 14:47
*/
public class ProducerAction extends SafeCusBaseAction {
/**
* <h2>mq</h2>
**/
@RequiredMark
private String MQConfigName;
/**
* <h2></h2>
**/
@RequiredMark
private String onlyMark;
@Override
public void doSubmit(String requestId, String billTable, int workflowId, User user, RequestInfo requestInfo) {
}
}

View File

@ -0,0 +1,35 @@
package weaver.xuanran.wang.shyl.mq.constant;
import java.util.HashMap;
import java.util.Map;
/**
* <h1>RocketMQ</h1>
*
* @Author xuanran.wang
* @Date 2022/12/30 13:25
*/
public class RocketMQConstant {
public static final String CREATE_ACTION = "CREATE_ACTION";
public static final String UPDATE_ACTION = "UPDATE_ACTION";
public static final String DELETE_ACTION = "DELETE_ACTION";
public static final String PASSWORD_ACTION = "PASSWORD_ACTION";
public static final int DEFAULT_MAX_RECONSUME_TIMES = 5;
public static final String SEX_GIRL = "1";
public static final String SEX_BOY = "2";
public static final String STATUS_ENABLE = "1";
public static final String STATUS_NO_ENABLE = "4";
public static final String ID_TYPE_UNKNOWN = "0";
public static final String ID_TYPE_ID_CARD = "1";
public static final String ID_TYPE_PASSPORT = "3";
public static final String ID_TYPE_STU_CARD = "4";
public static final String ID_TYPE_SOLDIER_CARD = "5";
public static final String DEFAULT_PASSWORD = "1";
public static final int PRODUCER_SEND_MSG_TIME_OUT = 60000;
public static Map<String, String> SEX_MAPPING = new HashMap<>();
static {
SEX_MAPPING.put(SEX_BOY, "0");
}
}

View File

@ -0,0 +1,35 @@
package weaver.xuanran.wang.shyl.mq.consumer;
import aiyh.utils.Util;
import org.apache.log4j.Logger;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import weaver.xuanran.wang.shyl.mq.RocketMQConsumerListener;
import weaver.xuanran.wang.shyl.mq.service.impl.OrgServiceImpl;
import weaver.xuanran.wang.shyl.mq.util.RocketUtil;
import java.util.List;
/**
* <h1></h1>
*
* @Author xuanran.wang
* @Date 2022/12/29 14:35
*/
public class OrgConsumer extends RocketMQConsumerListener {
private static final Logger log = Util.getLogger();
private static final String CONFIG_NAME = "OrgConsumer";
private final OrgServiceImpl orgService = new OrgServiceImpl();
public OrgConsumer(){
super(CONFIG_NAME);
}
@Override
public MessageListenerConcurrently service() {
return (List<MessageExt> msg, ConsumeConcurrentlyContext consumeConcurrentlyContext) -> RocketUtil.execute(msg, consumeConcurrentlyContext, orgService, CONFIG_NAME);
}
}

View File

@ -0,0 +1,36 @@
package weaver.xuanran.wang.shyl.mq.consumer;
import aiyh.utils.Util;
import org.apache.log4j.Logger;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import weaver.xuanran.wang.shyl.mq.RocketMQConsumerListener;
import weaver.xuanran.wang.shyl.mq.service.impl.PassWordServiceImpl;
import weaver.xuanran.wang.shyl.mq.util.RocketUtil;
import java.util.List;
/**
* <h1></h1>
*
* @Author xuanran.wang
* @Date 2022/12/29 14:35
*/
public class PassWordConsumer extends RocketMQConsumerListener {
private static final Logger log = Util.getLogger();
public static final String CONFIG_NAME = "PassWordConsumer";
public PassWordConsumer(){
super(CONFIG_NAME);
}
private final PassWordServiceImpl passWordService = new PassWordServiceImpl();
@Override
public MessageListenerConcurrently service() {
return (List<MessageExt> msg, ConsumeConcurrentlyContext consumeConcurrentlyContext) -> RocketUtil.execute(msg, consumeConcurrentlyContext, passWordService, CONFIG_NAME);
}
}

View File

@ -0,0 +1,35 @@
package weaver.xuanran.wang.shyl.mq.consumer;
import aiyh.utils.Util;
import org.apache.log4j.Logger;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import weaver.xuanran.wang.shyl.mq.RocketMQConsumerListener;
import weaver.xuanran.wang.shyl.mq.service.impl.UserServiceImpl;
import weaver.xuanran.wang.shyl.mq.util.RocketUtil;
import java.util.List;
/**
* <h1></h1>
*
* @Author xuanran.wang
* @Date 2022/12/29 14:35
*/
public class UserInfoConsumer extends RocketMQConsumerListener {
private static final Logger log = Util.getLogger();
public static final String CONFIG_NAME = "UserInfoConsumer";
public UserInfoConsumer(){
super(CONFIG_NAME);
}
private final UserServiceImpl userInfoService = new UserServiceImpl();
@Override
public MessageListenerConcurrently service() {
return (List<MessageExt> msg, ConsumeConcurrentlyContext consumeConcurrentlyContext) -> RocketUtil.execute(msg, consumeConcurrentlyContext, userInfoService, CONFIG_NAME);
}
}

View File

@ -0,0 +1,44 @@
package weaver.xuanran.wang.shyl.mq.entity;
import lombok.Data;
/**
* <h1>mq</h1>
*
* @Author xuanran.wang
* @Date 2022/12/30 13:09
*/
@Data
public class MQMessage {
/**
* <h2>ID</h2>
**/
private String id;
/**
* <h2></h2>
* <p>
* AUTH_CONSOLE_USERINFO_TOPIC: ;
* AUTH_CONSOLE_ORG_TOPIC: ;
* AUTH_CONSOLE_USERINFO_PASSWORD_TOPIC:
* </p>
**/
private String topic;
/**
* <h2></h2>
* <p>
* CREATE_ACTION;
* UPDATE_ACTION: ;
* DELETE_ACTION: ;
* PASSWORD_ACTION:
* </p>
**/
private String actionType;
/**
* <h2></h2>
**/
private String sendTime;
/**
* <h2>,json ,()</h2>
**/
private String content;
}

View File

@ -0,0 +1,46 @@
package weaver.xuanran.wang.shyl.mq.entity;
import lombok.Data;
/**
* <h1></h1>
*
* @Author xuanran.wang
* @Date 2022/12/30 13:59
*/
@Data
public class ModifyPassWord {
/**
* <h2></h2>
**/
private String id;
/**
* <h2>ID</h2>
**/
private String uid;
/**
* <h2></h2>
**/
private String username;
/**
* <h2></h2>
**/
private String displayName;
/**
* <h2></h2>
**/
private String oldPassword;
/**
* <h2></h2>
**/
private String password;
/**
* <h2></h2>
**/
private String confirmPassword;
/**
* <h2></h2>
**/
private String decipherable;
}

View File

@ -0,0 +1,38 @@
package weaver.xuanran.wang.shyl.mq.entity;
import lombok.Data;
/**
* <h1></h1>
*
* @Author xuanran.wang
* @Date 2022/12/30 13:56
*/
@Data
public class Org {
/**
* <h2>ID</h2>
**/
private String id;
/**
* <h2></h2>
**/
private String orgCode;
/**
* <h2></h2>
**/
private String orgName;
/**
* <h2>ID</h2>
**/
private String parentId;
/**
* <h2></h2>
**/
private String sortIndex;
/**
* <h2></h2>
**/
private String status;
}

View File

@ -0,0 +1,61 @@
package weaver.xuanran.wang.shyl.mq.entity;
import lombok.Data;
/**
* <h1></h1>
*
* @Author xuanran.wang
* @Date 2022/12/30 13:52
*/
@Data
public class UserInfo {
/**
* <h2>ID</h2>
**/
private String id;
/**
* <h2></h2>
**/
private String userName;
/**
* <h2></h2>
**/
private String displayName;
/**
* <h2></h2>
**/
private String gender;
/**
* <h2></h2>
**/
private String birthDate;
/**
* <h2></h2>
**/
private String idType;
/**
* <h2></h2>
**/
private String idCardNo;
/**
* <h2></h2>
**/
private String email;
/**
* <h2></h2>
**/
private String mobile;
/**
* <h2>ID</h2>
**/
private String departmentId;
/**
* <h2></h2>
**/
private String department;
/**
* <h2></h2>
**/
private String status;
}

View File

@ -0,0 +1,75 @@
package weaver.xuanran.wang.shyl.mq.mapper;
import aiyh.utils.annotation.recordset.ParamMapper;
import aiyh.utils.annotation.recordset.Update;
import java.util.Map;
/**
* <h1>mapper</h1>
*
* @Author xuanran.wang
* @Date 2022/12/30 14:19
*/
public interface ConsumerMapper {
/**
* <h1>outKey</h1>
* @author xuanran.wang
* @dateTime 2022/12/30 14:33
* @return /
**/
@Update("update hrmresource set status = 5 where outkey = #{outKey}")
boolean updateUserStatusByOutKey(@ParamMapper("outKey") String outKey);
/**
* <h1>outKey</h1>
* @author xuanran.wang
* @dateTime 2022/12/30 14:33
* @param outKey id
* @return
**/
@Update("delete hrmdepartment where outkey = #{outKey}")
boolean deleteDepartmentByOutKey(@ParamMapper("outKey") String outKey);
/**
* <h1>outKey</h1>
* @author xuanran.wang
* @dateTime 2022/12/30 14:33
* @param outKey id
* @return map key : id, val : id
**/
@Update("select id departmentId, subcompanyid1 subCompanyId from hrmdepartment where outkey = #{outKey}")
Map<String, Integer> getDepInfoByOutKey(@ParamMapper("outKey") String outKey);
/**
* <h1>outKeyid</h1>
* @author xuanran.wang
* @dateTime 2022/12/30 14:33
* @param outKey id
* @return id
**/
@Update("select id from hrmresource where outkey = #{outKey}")
String getHrmIdByOutKey(@ParamMapper("outKey") String outKey);
/**
* <h1>outKeyoaid</h1>
* @author xuanran.wang
* @dateTime 2022/12/30 14:33
* @param outKey id
* @return id
**/
@Update("select id from hrmdepartment where outkey = #{outKey}")
String getDepIdByOutKey(@ParamMapper("outKey") String outKey);
/**
* <h1>outKeyoaid</h1>
* @author xuanran.wang
* @dateTime 2022/12/30 14:33
* @param id id
* @return true/false
**/
@Update("update hrmresource set password = #{password} where id = #{id}")
boolean updatePasswordById(@ParamMapper("id") String id,
@ParamMapper("password") String password);
}

View File

@ -0,0 +1,41 @@
package weaver.xuanran.wang.shyl.mq.service;
import aiyh.utils.Util;
import org.apache.log4j.Logger;
import weaver.conn.RecordSet;
import weaver.xuanran.wang.shyl.mq.mapper.ConsumerMapper;
import weaver.xuanran.wang.shyl.mq.service.interfaces.CreateAction;
import weaver.xuanran.wang.shyl.mq.service.interfaces.DeleteAction;
import weaver.xuanran.wang.shyl.mq.service.interfaces.PassWordAction;
import weaver.xuanran.wang.shyl.mq.service.interfaces.UpdateAction;
/**
* <h1></h1>
*
* @Author xuanran.wang
* @Date 2022/12/30 13:04
*/
public abstract class CusInfoActionService implements CreateAction, DeleteAction, UpdateAction, PassWordAction {
protected final RecordSet recordSet = new RecordSet();
protected final Logger logger = Util.getLogger();
/**
* <h2>consumer-mapper</h2>
**/
protected final ConsumerMapper consumerMapper = Util.getMapper(ConsumerMapper.class);
/**
* <h1>id</h1>
* @author xuanran.wang
* @dateTime 2023/01/03 10:50
* @return next id
**/
protected synchronized String getNextHrmId(){
recordSet.executeProc("HrmResourceMaxId_Get", "");
recordSet.next();
//新增的部门id
return Util.null2String(recordSet.getInt(1));
}
}

View File

@ -0,0 +1,42 @@
package weaver.xuanran.wang.shyl.mq.service;
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.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.shyl.mq.util.RocketUtil;
import java.util.HashMap;
import java.util.Map;
/**
* <h1></h1>
*
* @author xuanran.wang
* @date 2023/1/4 14:54
*/
public class ProducerService {
private final DealWithMapping dealWithMapping = new DealWithMapping();
public void pushWorkFlowToMQ(String configName, String onlyMark, String requestId, String tableName){
RequestMappingConfig requestMappingConfig = dealWithMapping.treeDealWithUniqueCode(onlyMark);
String selectMainSql = CommonUtil.getSelectSql(requestMappingConfig, tableName);
RecordSet recordSet = new RecordSet();
recordSet.executeQuery(selectMainSql, requestId);
Map<String, Object> requestParam = new HashMap<>();
if (recordSet.next()) {
dealWithMapping.setMainTable(tableName);
requestParam = dealWithMapping.getRequestParam(recordSet, requestMappingConfig);
}
if(MapUtils.isEmpty(requestParam)){
throw new CustomerException("convert workflow information to json error!");
}
RocketUtil.producerSendMsg(configName, JSONObject.toJSONString(requestParam));
}
}

View File

@ -0,0 +1,190 @@
package weaver.xuanran.wang.shyl.mq.service.impl;
import aiyh.utils.Util;
import aiyh.utils.excention.CustomerException;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import weaver.conn.RecordSet;
import weaver.general.TimeUtil;
import weaver.hrm.company.DepartmentComInfo;
import weaver.interfaces.hrm.HrmServiceManager;
import weaver.matrix.MatrixUtil;
import weaver.xuanran.wang.shyl.mq.entity.MQMessage;
import weaver.xuanran.wang.shyl.mq.entity.Org;
import weaver.xuanran.wang.shyl.mq.service.CusInfoActionService;
import java.util.ArrayList;
import java.util.List;
/**
* <h1></h1>
*
* @Author xuanran.wang
* @Date 2022/12/30 15:05
*/
public class OrgServiceImpl extends CusInfoActionService {
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2023/1/3 14:05
* @param message mq
* @return /
**/
@Override
public ConsumeConcurrentlyStatus cusCreateAction(MQMessage message) {
try {
String content = message.getContent();
Org org = JSONObject.parseObject(content, Org.class);
char separator = weaver.general.Util.getSeparator();
// 分部id
String subId = "";
RecordSet insertRs = new RecordSet();
if(StringUtils.isBlank(subId)){
throw new CustomerException("SubCompany can not be empty!");
}
//使用存储过程新增分部
String para = org.getOrgName() + separator + org.getOrgName() + separator +
"" + separator + "" + separator + subId + separator + org.getSortIndex() + separator + "";
insertRs.executeProc("HrmDepartment_Insert", para);
if (insertRs.next()) {
int depId = insertRs.getInt(1);
updateDepartmentInfo(String.valueOf(depId), subId, org);
}
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}catch (Exception e){
throw new CustomerException(Util.logStr("orgCreateAction error : {}", e.getMessage()));
}
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2023/1/3 13:59
* @param message mq
* @return /
**/
@Override
public ConsumeConcurrentlyStatus cusDeleteAction(MQMessage message) {
try {
String content = message.getContent();
Org org = JSONObject.parseObject(content, Org.class);
String id = org.getId();
if(StringUtils.isBlank(id)){
throw new CustomerException("userInfo id can not be empty!");
}
boolean success = consumerMapper.deleteDepartmentByOutKey(id);
if (!success) {
throw new CustomerException(Util.logStr("update user status error!"));
}
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}catch (Exception e){
throw new CustomerException(Util.logStr("orgDeleteAction execute error : [{}]!", e.getMessage()));
}
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2023/1/4 14:44
* @param message mq
* @return /
**/
@Override
public ConsumeConcurrentlyStatus cusUpdateAction(MQMessage message) {
try {
String content = message.getContent();
Org org = JSONObject.parseObject(content, Org.class);
String outKey = org.getId();
// 分部待明确
String subId = "";
String depId = consumerMapper.getDepIdByOutKey(outKey);
if(StringUtils.isBlank(depId)){
throw new CustomerException(Util.logStr("The department information data obtained by foreign key is empty!"));
}
updateDepartmentInfo(depId, subId, org);
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}catch (Exception e){
throw new CustomerException(Util.logStr("orgUpdateAction error : {}", e.getMessage()));
}
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2023/1/4 14:45
* @param depId id
* @param subId id
* @param org
**/
public void updateDepartmentInfo(String depId, String subId, Org org){
String insertSQL = "update hrmdepartment set created = ?, creater = ?, modified = ?, modifier = ?," +
" departmentcode = ?, tlevel = ?, showorder = ?, canceled = ?,departmentmark = ?, " +
" departmentname = ?, supdepid = ?, subcompanyid1 = ?, outkey = ? where id = ?";
RecordSet updateRs = new RecordSet();
List<Object> params = initDepartParam(String.valueOf(depId), subId, org);
if (!updateRs.executeUpdate(insertSQL, params)) {
throw new CustomerException(Util.logStr("insert HrmDepartment error sql : {}, params : {}", insertSQL, JSONObject.toJSONString(params)));
}
DepartmentComInfo dci = new DepartmentComInfo();
//清除全部部门缓存
dci.removeCompanyCache();
//新增单个部门缓存
HrmServiceManager hrmServiceManager = new HrmServiceManager();
hrmServiceManager.SynInstantDepartment(String.valueOf(depId), "2");
//同步分部数据到矩阵
MatrixUtil.updateDepartmentData("" + depId);
}
/**
* <h1>/</h1>
* @author xuanran.wang
* @dateTime 2023/1/3 13:34
* @param depId oaid
* @param org
* @return /
**/
private List<Object> initDepartParam(String depId, String subId, Org org){
List<Object> params = new ArrayList<>();
String currentTime = TimeUtil.getCurrentTimeString();
// 创建时间
params.add(currentTime);
// 创建人
params.add("1");
// 修改时间
params.add(currentTime);
// 修改人
params.add("1");
// 部门编码
params.add(org.getOrgCode());
// 层级结构
params.add(org.getSortIndex());
// 显示顺序
params.add(org.getSortIndex());
// 是否封存
params.add("0");
// 部门标识
params.add(org.getOrgName());
// 部门名称
params.add(org.getOrgName());
String parentId = org.getParentId();
// 父级部门id
String supDepId = "";
if(StringUtils.isNotBlank(parentId)){
supDepId = consumerMapper.getDepIdByOutKey(parentId);
}
params.add(supDepId);
// 分部
params.add(subId);
// out key
params.add(org.getId());
params.add(depId);
return params;
}
@Override
public ConsumeConcurrentlyStatus cusPassWordAction(MQMessage message) {
return null;
}
}

View File

@ -0,0 +1,52 @@
package weaver.xuanran.wang.shyl.mq.service.impl;
import aiyh.utils.Util;
import aiyh.utils.excention.CustomerException;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import weaver.xuanran.wang.shyl.mq.entity.MQMessage;
import weaver.xuanran.wang.shyl.mq.entity.ModifyPassWord;
import weaver.xuanran.wang.shyl.mq.service.CusInfoActionService;
/**
* <h1></h1>
*
* @author xuanran.wang
* @date 2023/1/3 16:07
*/
public class PassWordServiceImpl extends CusInfoActionService {
@Override
public ConsumeConcurrentlyStatus cusCreateAction(MQMessage message) {
return null;
}
@Override
public ConsumeConcurrentlyStatus cusDeleteAction(MQMessage message) {
return null;
}
@Override
public ConsumeConcurrentlyStatus cusPassWordAction(MQMessage message) {
try {
String content = message.getContent();
ModifyPassWord passWord = JSONObject.parseObject(content, ModifyPassWord.class);
String outKey = passWord.getId();
String hrmId = consumerMapper.getHrmIdByOutKey(outKey);
if(StringUtils.isBlank(hrmId)){
throw new CustomerException(Util.logStr("the userId is {} , no personnel information found in oa!", hrmId));
}
if (!consumerMapper.updatePasswordById(hrmId, Util.getEncrypt(passWord.getPassword()))) {
throw new CustomerException("update user password error!");
}
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
} catch (Exception e) {
throw new CustomerException(Util.logStr("passWordAction execute error : [{}]!", e.getMessage()));
}
}
@Override
public ConsumeConcurrentlyStatus cusUpdateAction(MQMessage message) {
return null;
}
}

View File

@ -0,0 +1,237 @@
package weaver.xuanran.wang.shyl.mq.service.impl;
import aiyh.utils.Util;
import aiyh.utils.excention.CustomerException;
import com.alibaba.fastjson.JSONObject;
import com.weaver.general.TimeUtil;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import weaver.conn.RecordSet;
import weaver.hrm.finance.SalaryManager;
import weaver.hrm.resource.ResourceComInfo;
import weaver.xiao.commons.utils.JsonResult;
import weaver.xuanran.wang.shyl.mq.constant.RocketMQConstant;
import weaver.xuanran.wang.shyl.mq.entity.MQMessage;
import weaver.xuanran.wang.shyl.mq.entity.UserInfo;
import weaver.xuanran.wang.shyl.mq.mapper.ConsumerMapper;
import weaver.xuanran.wang.shyl.mq.service.CusInfoActionService;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import static com.api.ecme.excel.HtmlLayoutOperate.user;
/**
* <h1></h1>
*
* @Author xuanran.wang
* @Date 2022/12/30 13:04
*/
public class UserServiceImpl extends CusInfoActionService {
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2023/1/3 13:37
* @param message mq
* @return /
**/
@Override
public ConsumeConcurrentlyStatus cusCreateAction(MQMessage message) {
try {
String content = message.getContent();
UserInfo userInfo = JSONObject.parseObject(content, UserInfo.class);
String userInfoDepartmentId = userInfo.getDepartmentId();
// 部门id
if(StringUtils.isBlank(userInfoDepartmentId)){
throw new CustomerException("userInfo userInfoDepartmentId can not be empty!");
}
Map<String, Integer> depInfoByOutKey = consumerMapper.getDepInfoByOutKey(userInfo.getDepartmentId());
if (MapUtils.isEmpty(depInfoByOutKey)) {
// 通过外键获取部门信息数据为空
throw new CustomerException("The department information data obtained by foreign key is empty!");
}
String nextHrmId = getNextHrmId();
List<Object> params = initHrmParam(nextHrmId, userInfo, depInfoByOutKey);
String departmentId = Util.null2DefaultStr(depInfoByOutKey.get("departmentId"), "");
String subCompanyId = Util.null2DefaultStr(depInfoByOutKey.get("subCompanyId"), "");
RecordSet insertRs = new RecordSet();
//使用sql新增人员
String insertSql = "insert into HrmResource(systemlanguage,workcode,departmentid,subcompanyid1," +
" status,createrid,createdate,lastmodid,lastmoddate,lastname,sex,loginid," +
" password,birthday,certificatenum,email, mobile,outkey,id) " +
" values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
if (insertRs.executeUpdate(insertSql, params)) {
char separator = Util.getSeparator();
Calendar todayCal = Calendar.getInstance();
String today = Util.add0(todayCal.get(Calendar.YEAR), 4) + "-" +
Util.add0(todayCal.get(Calendar.MONTH) + 1, 2) + "-" +
Util.add0(todayCal.get(Calendar.DAY_OF_MONTH), 2);
String userPara = "" + 1 + separator + today;
insertRs.executeProc("HrmResource_CreateInfo", "" + nextHrmId + separator + userPara + separator + userPara);
ResourceComInfo resourceComInfo = new ResourceComInfo();
resourceComInfo.addResourceInfoCache(nextHrmId);
SalaryManager salaryManager = new SalaryManager();
salaryManager.initResourceSalary(nextHrmId);
String para1 = "" + nextHrmId + separator + "" + separator + departmentId + separator + subCompanyId + separator + "0" + separator + "0";
insertRs.executeProc("HrmResource_Trigger_Insert", para1);
String sql_1 = ("insert into HrmInfoStatus (itemid,hrmid) values(1," + nextHrmId + ")");
insertRs.execute(sql_1);
String sql_2 = ("insert into HrmInfoStatus (itemid,hrmid) values(2," + nextHrmId + ")");
insertRs.execute(sql_2);
String sql_3 = ("insert into HrmInfoStatus (itemid,hrmid) values(3," + nextHrmId + ")");
insertRs.execute(sql_3);
String sql_10 = ("insert into HrmInfoStatus (itemid,hrmid) values(10," + nextHrmId + ")");
insertRs.execute(sql_10);
resourceComInfo.updateResourceInfoCache(nextHrmId);
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}else {
throw new CustomerException(Util.logStr("insert HrmResource error sql : {}, params : {}", insertSql, JSONObject.toJSONString(params)));
}
}catch (Exception e){
throw new CustomerException(Util.logStr("hrmCreateAction error : {}", e.getMessage()));
}
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2023/1/3 13:38
* @param message mq
* @return /
**/
@Override
public ConsumeConcurrentlyStatus cusDeleteAction(MQMessage message) {
try {
String content = message.getContent();
UserInfo userInfo = JSONObject.parseObject(content, UserInfo.class);
String id = userInfo.getId();
if(StringUtils.isBlank(id)){
throw new CustomerException("userInfo id can not be empty!");
}
boolean success = consumerMapper.updateUserStatusByOutKey(id);
if (!success) {
throw new CustomerException(Util.logStr("update user status error!"));
}
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
} catch (Exception e) {
throw new CustomerException(Util.logStr("hrmDeleteAction execute error : [{}]!", e.getMessage()));
}
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2023/1/3 13:39
* @param message mq
* @return /
**/
@Override
public ConsumeConcurrentlyStatus cusUpdateAction(MQMessage message) {
try {
String content = message.getContent();
UserInfo userInfo = JSONObject.parseObject(content, UserInfo.class);
String userInfoId = userInfo.getId();
String userInfoDepartmentId = userInfo.getDepartmentId();
// 接口人员id
if(StringUtils.isBlank(userInfoId)){
throw new CustomerException("userInfo id can not be empty!");
}
// 部门id
if(StringUtils.isBlank(userInfoDepartmentId)){
throw new CustomerException("userInfo userInfoDepartmentId can not be empty!");
}
// oa部门信息
Map<String, Integer> depInfoByOutKey = consumerMapper.getDepInfoByOutKey(userInfo.getDepartmentId());
if (MapUtils.isEmpty(depInfoByOutKey)) {
// 通过外键获取部门信息数据为空
throw new CustomerException("The department information data obtained by foreign key is empty!");
}
// oa人员id
String hrmId = consumerMapper.getHrmIdByOutKey(userInfoId);
if(StringUtils.isBlank(hrmId)){
throw new CustomerException(Util.logStr("userInfoId = [{}], No personnel information found in oa!", userInfoId));
}
//使用sql新增人员
String updateSql = "update HrmResource set systemlanguage = ?, workcode = ?, departmentid = ?, subcompanyid1 = ?," +
" status = ?,createrid = ?, createdate = ?, lastmodid = ? ,lastmoddate = ? ,lastname = ? ,sex = ?, loginid = ?, " +
" password = ?, birthday = ?,certificatenum = ?,email = ?, mobile = ? , outkey = ? where id = ? ";
List<Object> params = initHrmParam(hrmId, userInfo, depInfoByOutKey);
RecordSet updateRs = new RecordSet();
if(!updateRs.executeUpdate(updateSql, params)){
throw new CustomerException(Util.logStr("update HrmResource error sql : {}, params : {}", updateSql, JSONObject.toJSONString(params)));
}
ResourceComInfo resourceComInfo = new ResourceComInfo();
// 清空缓存
resourceComInfo.updateResourceInfoCache(hrmId);
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}catch (Exception e){
throw new CustomerException(Util.logStr("hrmUpdateAction execute error : [{}]!", e.getMessage()));
}
}
/**
* <h1>/</h1>
* @author xuanran.wang
* @dateTime 2023/1/3 13:34
* @param nextHrmId oaid
* @param userInfo mq
* @param depInfoByOutKey
* @return /
**/
private List<Object> initHrmParam(String nextHrmId, UserInfo userInfo, Map<String, Integer> depInfoByOutKey){
String password = Util.getEncrypt(RocketMQConstant.DEFAULT_PASSWORD);
String date = TimeUtil.getCurrentDateString();
ArrayList<Object> params = new ArrayList<>();
String userName = Util.null2DefaultStr(userInfo.getUserName(), "");
String departmentId = Util.null2DefaultStr(depInfoByOutKey.get("departmentId"), "");
String subCompanyId = Util.null2DefaultStr(depInfoByOutKey.get("subCompanyId"), "");
// 语言
params.add(7);
// 工号
params.add(userName);
// 部门id
params.add(departmentId);
// 分部id
params.add(subCompanyId);
// 状态
params.add(1);
// 创建人
params.add(1);
// 创建日期
params.add(date);
// 最后修改人
params.add(1);
// 最后修改日期
params.add(date);
// 人员名称
params.add(Util.null2DefaultStr(userInfo.getDisplayName(), ""));
// 性别 如果没传就默认男
params.add(RocketMQConstant.SEX_MAPPING.get(Util.null2DefaultStr(userInfo.getGender(), "1")));
// 登陆名
params.add(userName);
// 密码
params.add(password);
// 生日
params.add(Util.null2DefaultStr(userInfo.getBirthDate(), ""));
// 身份证号码
params.add(Util.null2DefaultStr(userInfo.getIdCardNo(), ""));
// 邮箱
params.add(Util.null2DefaultStr(userInfo.getEmail(), ""));
// 手机号
params.add(Util.null2DefaultStr(userInfo.getMobile(), ""));
// 用户out key
params.add(Util.null2DefaultStr(userInfo.getId(),""));
// oaId
params.add(nextHrmId);
return params;
}
@Override
public ConsumeConcurrentlyStatus cusPassWordAction(MQMessage message) {
return null;
}
}

View File

@ -0,0 +1,14 @@
package weaver.xuanran.wang.shyl.mq.service.interfaces;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import weaver.xuanran.wang.shyl.mq.entity.MQMessage;
/**
* <h1></h1>
*
* @Author xuanran.wang
* @Date 2022/12/30 13:00
*/
public interface CreateAction {
ConsumeConcurrentlyStatus cusCreateAction(MQMessage message);
}

View File

@ -0,0 +1,14 @@
package weaver.xuanran.wang.shyl.mq.service.interfaces;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import weaver.xuanran.wang.shyl.mq.entity.MQMessage;
/**
* <h1></h1>
*
* @Author xuanran.wang
* @Date 2022/12/30 13:02
*/
public interface DeleteAction {
ConsumeConcurrentlyStatus cusDeleteAction(MQMessage message);
}

View File

@ -0,0 +1,14 @@
package weaver.xuanran.wang.shyl.mq.service.interfaces;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import weaver.xuanran.wang.shyl.mq.entity.MQMessage;
/**
* <h1></h1>
*
* @Author xuanran.wang
* @Date 2022/12/30 13:03
*/
public interface PassWordAction {
ConsumeConcurrentlyStatus cusPassWordAction(MQMessage message);
}

View File

@ -0,0 +1,14 @@
package weaver.xuanran.wang.shyl.mq.service.interfaces;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import weaver.xuanran.wang.shyl.mq.entity.MQMessage;
/**
* <h1></h1>
*
* @Author xuanran.wang
* @Date 2022/12/30 13:01
*/
public interface UpdateAction {
ConsumeConcurrentlyStatus cusUpdateAction(MQMessage message);
}

View File

@ -0,0 +1,162 @@
package weaver.xuanran.wang.shyl.mq.util;
import aiyh.utils.Util;
import aiyh.utils.excention.CustomerException;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.apache.rocketmq.remoting.exception.RemotingException;
import weaver.xuanran.wang.shyl.mq.constant.RocketMQConstant;
import weaver.xuanran.wang.shyl.mq.RocketMQFactory;
import weaver.xuanran.wang.shyl.mq.entity.MQMessage;
import weaver.xuanran.wang.shyl.mq.service.CusInfoActionService;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
/**
* <h1>rocketMQ</h1>
*
* @Author xuanran.wang
* @Date 2022/12/29 21:03
*/
public class RocketUtil {
private static final Logger log = Util.getLogger();
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2022/12/29 12:53
**/
public static Map<String, Object> initMQConfigMap(String configName){
Map<String, Object> config = Util.getProperties2Map(configName);
if(MapUtils.isEmpty(config)){
throw new CustomerException(Util.logStr("please check /filesystem/prop/prop2map {}.properties file is exist!", configName));
}
for (Map.Entry<String, Object> entry : config.entrySet()) {
String key = Util.null2DefaultStr(entry.getKey(),"");
String value = Util.null2DefaultStr(entry.getValue(),"");
if(StringUtils.isBlank(key) || StringUtils.isBlank(value)){
throw new CustomerException(Util.logStr("the config file key is empty or key = {} value is empty!", key));
}
}
log.info(Util.logStr("ConfigName : {} , MQConfig : {} ",configName, JSONObject.toJSONString(config)));
return config;
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2022/12/30 13:34
* @param msg mq
* @param consumeConcurrentlyContext
* @param cusInfoActionService
* @param configName
* @return mq
**/
public static ConsumeConcurrentlyStatus execute(List<MessageExt> msg, ConsumeConcurrentlyContext consumeConcurrentlyContext,
CusInfoActionService cusInfoActionService, String configName){
Map<String, Object> configMap = RocketMQFactory.CONFIG_MAPS.get(configName);
log.info(Util.logStr("{} service config is {}", configName, JSONObject.toJSONString(configMap)));
int maxReconsumeTimes = Util.getIntValue(Util.null2String(configMap.get("MaxReconsumeTimes")),RocketMQConstant.DEFAULT_MAX_RECONSUME_TIMES);
try {
if (CollectionUtils.isNotEmpty(msg)) {
MessageExt messageExt = msg.get(0);
String msgBody;
MQMessage mqMessage;
try {
msgBody = new String(messageExt.getBody(), StandardCharsets.UTF_8);
if(StringUtils.isBlank(msgBody)){
throw new CustomerException("MQ msgBody is empty!");
}
mqMessage = JSONObject.parseObject(msgBody, MQMessage.class);
// 业务主体
String content = Util.null2DefaultStr(mqMessage.getContent(),"");
if(StringUtils.isBlank(content)){
throw new CustomerException(Util.logStr("the messageId : {}, content is empty!", Util.null2DefaultStr(mqMessage.getId(), "")));
}
log.info(Util.logStr("MQMessage : {} ", mqMessage));
// 业务类型
String actionType = mqMessage.getActionType();
switch (actionType){
case RocketMQConstant.CREATE_ACTION:{
return cusInfoActionService.cusCreateAction(mqMessage);
}
case RocketMQConstant.UPDATE_ACTION:{
return cusInfoActionService.cusUpdateAction(mqMessage);
}
case RocketMQConstant.DELETE_ACTION:{
return cusInfoActionService.cusDeleteAction(mqMessage);
}
case RocketMQConstant.PASSWORD_ACTION:{
return cusInfoActionService.cusPassWordAction(mqMessage);
}
default: throw new CustomerException(Util.logStr("current actionType : [{}] is not supported!", actionType));
}
}catch (Exception e){
throw new CustomerException(Util.logStr("parse msgBody to Message error current msgBody is {}, the error is {}", msg, e.getMessage()));
}
}else {
log.error("the msgList is empty!");
}
} catch (Exception e) {
// 如果重试达到最大还是异常那么先返回成功 oa将错误日志记录到日志中
if (msg.get(0).getReconsumeTimes() == maxReconsumeTimes) {
//TODO
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
} else {
return ConsumeConcurrentlyStatus.RECONSUME_LATER;
}
}
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
/**
* <h1>mq</h1>
* @author xuanran.wang
* @dateTime 2023/1/4 14:30
* @param configName
* @param msg
**/
public static void producerSendMsg(String configName, String msg) {
// 先从本地缓存中获取生产者对象
DefaultMQProducer producer = RocketMQFactory.getMQProducer(configName);
// 获取配置信息
Map<String, Object> configMap = RocketMQFactory.CONFIG_MAPS.get(configName);
// 队列名
String topic = Util.null2DefaultStr(configMap.get("Topic"),"");
// tag
String tag = Util.null2DefaultStr(configMap.get("Tag"),"");
Message message;
try {
message = new Message(topic, tag, msg.getBytes(RemotingHelper.DEFAULT_CHARSET));
}catch (Exception e){
throw new CustomerException(Util.logStr("init message error : {} !", e.getMessage()));
}
SendResult result;
try {
result = producer.send(message);
} catch (MQClientException | RemotingException | MQBrokerException | InterruptedException e) {
throw new CustomerException(Util.logStr("producer send message error!", e.getMessage()));
}
SendStatus sendStatus = result.getSendStatus();
// 如果成功
if(SendStatus.SEND_OK.equals(sendStatus)){
log.error(Util.logStr("producer send message call back status is not ok! the message is {}, the status is {}.", msg, sendStatus));
}
}
}

View File

@ -2,6 +2,7 @@ package weaver.xuanran.wang.traffic_bank.waco_first.service;
import aiyh.utils.Util;
import aiyh.utils.excention.CustomerException;
import com.alibaba.fastjson.JSONObject;
import com.jcraft.jsch.ChannelSftp;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
@ -103,9 +104,11 @@ public class WacoDataPushOAService {
for (Info info : infos) {
List<String> docDetailParam = new ArrayList<>();
Map<String, Object> param = getParamsMapByInfo(secCategory, info, docDetailParam);
logger.info("param : " + JSONObject.toJSONString(param));
String dataId = CusInfoToOAUtil.getDataId(modelId, param,
whereSql,
Collections.singletonList(info.getInfoId()));
logger.info("dataId : " + JSONObject.toJSONString(dataId));
ids.add(dataId);
docDetailContentParams.add(docDetailParam);
}

View File

@ -4,6 +4,7 @@ import aiyh.utils.Util;
import basetest.BaseTest;
import com.api.xuanran.wang.ambofo.checkuser.service.CheckUserService;
import org.junit.Test;
import weaver.interfaces.encode.AuthorizationBasic4OAuth2;
/**
* <h1></h1>
@ -24,4 +25,12 @@ public class CheckUserTest extends BaseTest {
log.error(Util.getErrString(e));
}
}
@Test
public void testPA(){
String clientId = "ai-689bbdb3c4834b15af692540c62dc126";
String clientSecret = "7o88qSgOx0SOCQxR9xFGUm0n";
AuthorizationBasic4OAuth2 auth2 = new AuthorizationBasic4OAuth2();
log.info(auth2.encode(clientId + ":" + clientSecret));
}
}

View File

@ -0,0 +1,31 @@
package xuanran.wang.epdi.datapush;
import basetest.BaseTest;
import com.alibaba.fastjson.JSONObject;
import org.junit.Test;
import weaver.xuanran.wang.epdi.datapush.eneity.MainRequestConfig;
import weaver.xuanran.wang.epdi.datapush.service.RequestPushService;
import java.util.Map;
/**
* <h1></h1>
*
* @Author xuanran.wang
* @Date 2022/12/26 10:14
*/
public class RequestDataPush extends BaseTest {
private final RequestPushService requestDataPush = new RequestPushService();
@Test
public void testCreatesJson(){
String requestId = "798800";
String tableName = "";
String uniqueCode = "token";
MainRequestConfig config = requestDataPush.getRequestPushConfigByUniqueCode(uniqueCode);
Map<String, Object> requestParam = requestDataPush.getRequestParam(config, requestId);
log.info("请求参数: " + JSONObject.toJSONString(requestParam));
}
}

View File

@ -1,17 +1,25 @@
package xuanran.wang.saic_travel.model_data_async;
import aiyh.utils.ApiResult;
import aiyh.utils.Util;
import aiyh.utils.excention.CustomerException;
import basetest.BaseTest;
import com.alibaba.fastjson.JSONObject;
import com.api.xuanran.wang.saic_travel.model_create_workflow.service.CreateWorkFlowService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import weaver.conn.RecordSet;
import weaver.formmode.data.ModeDataApproval;
import weaver.general.Util;
import weaver.general.TimeUtil;
import weaver.hrm.User;
import weaver.xuanran.wang.common.mapper.CommonMapper;
import weaver.xuanran.wang.common.util.CommonUtil;
import weaver.xuanran.wang.saic_travel.model_data_async.config.eneity.DataAsyncMain;
import weaver.xuanran.wang.saic_travel.model_data_async.service.DataAsyncConfigService;
import java.util.*;
import java.util.stream.Collectors;
/**
* <h1></h1>
@ -21,7 +29,8 @@ import java.util.*;
*/
public class AsyncTest extends BaseTest {
private DataAsyncConfigService dataAsyncConfigService = new DataAsyncConfigService();
private final CommonMapper commonMapper = Util.getMapper(CommonMapper.class);
private final CreateWorkFlowService createWorkFlowService = new CreateWorkFlowService();
@Test
public void testGetConfig(){
// DataAsyncMain hrmAsyncTest = dataAsyncConfigService.getDataAsyncConfigByUniqueCode("hrmAsyncTest");
@ -45,24 +54,71 @@ public class AsyncTest extends BaseTest {
@Test
public void testAsync(){
// try {
// DataAsyncMain config = dataAsyncConfigService.getDataAsyncConfigByUniqueCode("wacoTest");
// List<String> data = dataAsyncConfigService.asyncModelData(config, 109);
// log.info("生成的数据id : " + JSONObject.toJSONString(data));
// }catch (Exception e){
// log.error("生成建模数据异常 : " + e.getMessage());
try {
DataAsyncMain config = dataAsyncConfigService.getDataAsyncConfigByUniqueCode("hrmAsyncTest");
List<String> data = dataAsyncConfigService.asyncModelData(config, 109);
log.info("生成的数据id : " + JSONObject.toJSONString(data));
}catch (Exception e){
log.error("生成建模数据异常 : " + e.getMessage());
}
// String choiceData = "2357,2358,2274,2275";
// String triggerWorkflowSetId = "4";
// // 勾选的数据集合
// List<String> dataList = Arrays.stream(choiceData.split(",")).collect(Collectors.toList());
// RecordSet rs = new RecordSet();
// List<List<String>> splitList = CommonUtil.splitList(dataList);
// String name = commonMapper.getModelNameByModelId(String.valueOf(109));
// for (List<String> list : splitList) {
// List<Integer> ids = list.stream().map(item -> aiyh.utils.Util.getIntValue(item, -1)).collect(Collectors.toList());
// if(CollectionUtils.isEmpty(ids)){
// continue;
// }
// }
// String sql = "select id from " + name;
// for (String id : triggerWorkflowSetId.split(",")) {
// String condition = commonMapper.getConditionByTriggerId(id);
// if(StringUtils.isNotBlank(condition)){
// sql += " where " + condition;
// }
// log.info(aiyh.utils.Util.logStr("查询数据sql : {}", sql));
// List<String> filterIds = filterIds(sql);
// List<String> dataIds = dataList.stream().filter(filterIds::contains).collect(Collectors.toList());
// List<String> requestIds = CommonUtil.doCreateWorkFlow(109, dataIds, aiyh.utils.Util.getIntValue(id, -1)); // 通过数据审批生成流程
// List<String> errorData = new ArrayList<>();
// for (int i = 0; i < requestIds.size(); i++) {
// if (aiyh.utils.Util.getIntValue(requestIds.get(i), -1) < 0) {
// errorData.add(dataList.get(i));
// }
// }
// log.error(Util.logStr("执行创建流程失败集合: {}",JSONObject.toJSONString(errorData))); // 构建日志字符串
// }
// List<String> list = CommonUtil.doCreateWorkFlow(109, data);
// log.info("触发成功 : " + JSONObject.toJSONString(list));
log.info("select hr.email from HrmResource hr where status in (0,1,2,3) AND "+ Util.getSubINClause("1,3,323,124,544","id","in") + " and " + Util.getSubINClause("1","id","not in"));
log.info(Util.getSubINClause("1,3,323,124,544","id","in",2));
// log.info("select hr.email from HrmResource hr where status in (0,1,2,3) AND "+ Util.getSubINClause("1,3,323,124,544","id","in") + " and " + Util.getSubINClause("1","id","not in"));
// log.info(Util.getSubINClause("1,3,323,124,544","id","in",2));
}
public List<String> filterIds(String sql){
RecordSet rs = new RecordSet();
ArrayList<String> res = new ArrayList<>();
if (rs.executeQuery(sql)) {
while (rs.next()){
res.add(Util.null2DefaultStr(rs.getString(1),""));
}
}
return res;
}
@Test
public void testNotNull(){
String str = "jssjhgdkjs?docId={?}&{$requestid}";
System.out.println(str.replace("{?}", "123")
.replace("{$requestid}", "12194283"));
public void testNotNull() {
try {
String datas = "2600,2601,2602,2603,2599,2598";
String gys = createWorkFlowService.supplierCusCreateWorkFlow("6", "109", "gys", datas, 110);
log.info(" gys : " + gys);
}catch (Exception e){
log.error("e => " + e.getMessage());
}
}
public boolean checkNull(String ... args){

View File

@ -1,9 +1,9 @@
package xuanran.wang.schroeder.download_file;
import aiyh.utils.Util;
import aiyh.utils.sqlUtil.sqlResult.impl.PrepSqlResultImpl;
import basetest.BaseTest;
import com.alibaba.fastjson.JSONObject;
import com.api.xuanran.wang.schroeder.download_file.mapper.DownLoadFileMapper;
import com.icbc.api.internal.apache.http.impl.cookie.S;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
@ -31,19 +31,6 @@ import java.util.stream.Collectors;
* @Date 2022/12/7 11:58
*/
public class DownLoadFileTest extends BaseTest {
private final DownLoadFileMapper downLoadFileMapper = Util.getMapper(DownLoadFileMapper.class);
@Test
public void testSelectFileInfo() throws IOException {
Map<String, Object> fileInfo = downLoadFileMapper.selectDocInfoByDocId("95");
log.info("map " + fileInfo);
String fileName = Util.null2String(fileInfo.get("fileName"));
int imageFileId = Util.getIntValue(Util.null2DefaultStr(fileInfo.get("imageFileId"),""), -1);
log.info("imageFileId " + imageFileId);
InputStream is = ImageFileManager.getInputStreamById(imageFileId);
log.info(null == is);
}
@Test
public void testImageFileInputSteam(){
@ -154,4 +141,49 @@ public class DownLoadFileTest extends BaseTest {
String resultString = text.replaceAll("2", replacement);
log.info("resultString " + resultString);
}
@Test
public void testBefore(){
Map<String, String> pathParam = Util.parseCusInterfacePathParam("weaver.xuanran.wang.schroeder.before.PushSealTaskBeforeProcessor?whereSql=`yyfs in (4,7)`&mapping=`yzzl:yzzl,htzyzcshj:htzyzcs,gzcshj:gzcs,frzcshj:frzcs`&detailNo=1");
HashMap<String, Object> detailMap = new HashMap<>();
String mapping = pathParam.get("mapping");
String detailNo = pathParam.get("detailNo");
String[] split = mapping.split(",");
for (String str : split) {
String[] map = str.split(":");
detailMap.put(map[1], map[0]);
}
detailMap.put("mainid", "1");
PrepSqlResultImpl sqlResult = Util.createSqlBuilder().insertSql("121212" + "_dt" + detailNo, detailMap);
String sqlStr = sqlResult.getSqlStr();
List<Object> args = sqlResult.getArgs();
log.info("sqlStr : " + sqlStr);
log.info("args : " + args);
}
@Test
public void testUrl(){
String serialNumber = "0199";
String front = serialNumber.substring(0,2);
String end = serialNumber.substring(2);
log.info("front " + front);
log.info("end " + end);
int frontInt = Util.getIntValue(front);
int endInt = Util.getIntValue(end);
log.info("frontInt " + frontInt);
log.info("endInt " + endInt);
String endStr = "";
String frontStr = "";
if(++endInt >= 100){
frontInt += 1;
endInt = 1;
}
if(endInt < 10){
endStr = "0" + endInt;
}
if(frontInt < 10){
frontStr = "0" + frontInt;
}
log.info(frontStr + endStr);
}
}

View File

@ -72,7 +72,7 @@ public class WacoFirstTest extends BaseTest {
public void testFinally() throws IOException {
String currentDate = TimeUtil.getCurrentDateString();
String WACO_TEMP_PATH = "WACO" + File.separator + "temp" + File.separator;
String fileName = currentDate.replaceAll("-","") + ".zip";
String fileName = "20221208.zip";
String zipOATempPath = GCONST.getSysFilePath() + WACO_TEMP_PATH + fileName;
try {
String tempFolder = GCONST.getSysFilePath() + WACO_TEMP_PATH;

View File

@ -34,5 +34,6 @@
+ [建模开发文档](https://e-cloudstore.com/doc.html?appId=e783a1d75a784d9b97fbd40fdf569f7d)
+ [支持ecode复写的组件版本信息整理](https://e-cloudstore.com/doc.html?appId=f353923a8d2d42948235e7bbbd5f8912)
+ [ecode常见问题](https://e-cloudstore.com/doc.html?appId=25fb364617c44ca3aa007581db3e4269)
+ [ecode权限说明](https://e-cloudstore.com/doc.html?appId=e6f85c66d5514aa2aa9242a0cea303d7)
+ [前端开发规范](https://e-cloudstore.com/doc.html?appId=36f4cc525d7444ee9291e6dfaeb0a632)
+ [e9组件库](https://cloudstore.e-cology.cn/#/pc/doc/common-index)

View File

@ -46,14 +46,14 @@ public interface Action {
```
常量 | 值 | 说明
---|---|---
SUCCESS | "1" | 成功标识,继续流程提交或执行下一个附加操作
FAILURE_AND_CONTINUE | "0" | 失败标识,阻断流程提交
| 常量 | 值 | 说明 |
|----------------------|-----|-----------------------|
| SUCCESS | "1" | 成功标识,继续流程提交或执行下一个附加操作 |
| FAILURE_AND_CONTINUE | "0" | 失败标识,阻断流程提交 |
方法 | 说明
---|---
String execute(RequestInfo request); | action实现逻辑执行时调用此方法
| 方法 | 说明 |
|--------------------------------------|---------------------|
| String execute(RequestInfo request); | action实现逻辑执行时调用此方法 |
实现示例
@ -148,7 +148,7 @@ public String execute(RequestInfo info){
int formid=RequestManager.getFormid();
//是否为单据
int isbill=RequestManager.getIsbill();
//获取数据库主表名
//获取数据库主表名 (低版本中 该值有可能获取到的值为空)
String tableName=isbill==1?"workflow_form":RequestManager.getBillTableName();
return Action.SUCCESS;
}
@ -236,7 +236,7 @@ public class SQLExecuteActionDemo implements Action {
rs.executeQuery("select amount from formtable_main_16 where requestid = ?",requestId);
//获取金额字段的值
if(rs.next()){
amount=rs.getFloat(1);
amount=rs.getFloat(1);
}
/*************2.直接查询数据库获取表单值***************/
@ -244,20 +244,20 @@ public class SQLExecuteActionDemo implements Action {
Map<String, String> mainDatas=new HashMap<>();
Property[]properties=request.getMainTableInfo().getProperty();
for(Property propertie:properties){
mainDatas.put(propertie.getName(),propertie.getValue());
mainDatas.put(propertie.getName(),propertie.getValue());
}
amount=Util.getFloatValue(Util.null2String(mainDatas.get("amount")));
//金额字段值大于10000阻断流程提交
if(amount>10000){
RequestManager requestManager=request.getRequestManager();
requestManager.setMessagecontent("不允许提交金额大于10000的流程");
return FAILURE_AND_CONTINUE;
RequestManager requestManager=request.getRequestManager();
requestManager.setMessagecontent("不允许提交金额大于10000的流程");
return FAILURE_AND_CONTINUE;
}
return SUCCESS;
}
}
```
4、强制收回触发action回滚
@ -270,12 +270,12 @@ public String execute(RequestInfo request){
//对应节点强制收回,则回滚数据
if(request.getRequestManager().getNodeid()==123){
RecordSet rs=new RecordSet();
rs.executeUpdate("delete from uf_fix_log where requestid = ?",requestId);
RecordSet rs=new RecordSet();
rs.executeUpdate("delete from uf_fix_log where requestid = ?",requestId);
}
return SUCCESS;
}
}
```
@ -438,14 +438,66 @@ public class OperatorActionTest implements OperatorAction {
7、流程提交失败调用action回滚逻辑E9+2006KB支持
8、节点附加操作执行失败问题的简单排查
> 查看日志文件 /ecology/log/integration/integration_流程提交日期.log 文件中根据requestid进行搜索会有详细的接口后附加操作的相关日志。
### 第一个定时任务
> 维护人员:
> 维护人员:weilin.zhu
> 必须继承weaver.interfaces.schedule.BaseCronJob类实现execute() 方法。
``` java
import weaver.interfaces.schedule.BaseCronJob;
/**
* <p>第一个计划任务</p>
*/
public class FirstTask extends BaseCronJob {
/**
* 自定义参数 必须有getter、setter方法否则无法取到配置值
*/
private String cusParam = "";
/**
* 重写父类方法
*/
@Override
public void execute() {
//具体的业务逻辑
}
public String getCusParam() {
return cusParam;
}
public void setCusParam(String cusParam) {
this.cusParam = cusParam;
}
}
```
### 第一个restful接口
> 维护人员:
> 维护人员weilin.zhu
> 1、API接口必须写在 com.api /om.cloudstore 文件夹下这样才能被扫描到。若系统有统一待办的非标功能放在weaver.rest目录下也是可以的。
>
> 2、但是这里我们这边要求大家放到 com.api 目录下,我们编写的接口,请求地址前面默认会加上/api。例@Path("/getUserInfo"),请求地址应为/api/getUserInfo
>
> 3、若编写的api供外部系统调用必须将api的请求地址放在配置文件的白名单中否则异构系统无法直接调用。
> 关于API白名单说明
>
> 配置文件ecology/WEB-INF/prop/weaver_session_filter.properties
>
> 配置说明在unchecksessionurl=后面添加自定义接口请求地址
> 示例代码:
```java
```
### 如何操作数据库